my-ai-chat-framework 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,13 +1,11 @@
1
1
  (function(global, factory) {
2
2
  typeof exports === "object" && typeof module !== "undefined" ? factory(exports) : typeof define === "function" && define.amd ? define(["exports"], factory) : (global = typeof globalThis !== "undefined" ? globalThis : global || self, factory(global.AIChatFramework = {}));
3
3
  })(this, function(exports) {
4
- Object.defineProperties(exports, {
5
- __esModule: { value: true },
6
- [Symbol.toStringTag]: { value: "Module" }
7
- });
4
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
8
5
  //#region src/core/EventEmitter.js
9
6
  /**
10
7
  * 极简事件发射器
8
+ * 支持同步/异步事件,handler 返回 Promise 时自动 await
11
9
  */
12
10
  var EventEmitter = class {
13
11
  constructor() {
@@ -24,6 +22,9 @@
24
22
  if (handlers.length) this._events.set(event, handlers);
25
23
  else this._events.delete(event);
26
24
  }
25
+ /**
26
+ * 同步触发事件
27
+ */
27
28
  emit(event, data) {
28
29
  if (!this._events.has(event)) return;
29
30
  for (const handler of this._events.get(event)) try {
@@ -32,6 +33,18 @@
32
33
  console.error(`事件 ${event} 处理出错:`, err);
33
34
  }
34
35
  }
36
+ /**
37
+ * 异步触发事件,逐个 await handler
38
+ * handler 返回 Promise 时自动等待
39
+ */
40
+ async emitAsync(event, data) {
41
+ if (!this._events.has(event)) return;
42
+ for (const handler of this._events.get(event)) try {
43
+ await handler(data);
44
+ } catch (err) {
45
+ console.error(`事件 ${event} 处理出错:`, err);
46
+ }
47
+ }
35
48
  };
36
49
  //#endregion
37
50
  //#region src/core/MessageStore.js
@@ -42,6 +55,10 @@
42
55
  * id?: string,
43
56
  * role: 'user'|'assistant'|'system'|'tool',
44
57
  * content: string,
58
+ * images?: Array<string>, // 图片引用(URL / id),框架不存储图片数据
59
+ * _ephemeral?: boolean, // 临时消息:仅底部连续时参与请求,续写后转正
60
+ * _complete?: boolean, // 流式是否完成(false=未完成/中断)
61
+ * prefix?: boolean, // 前缀续写标记
45
62
  * toolCalls?: Array,
46
63
  * toolCallId?: string,
47
64
  * timestamp?: number,
@@ -91,6 +108,22 @@
91
108
  metadata
92
109
  });
93
110
  }
111
+ /**
112
+ * 快速添加一次性的、带续写标记的 assistant 消息
113
+ * 适用于思维链引导、临时注入等场景
114
+ * @param {string} content — 引导内容
115
+ * @param {Object} [options] — { reasoningContent, prefix }
116
+ * @returns {Object} 添加的消息
117
+ */
118
+ addOnceAssistant(content, options = {}) {
119
+ return this.add({
120
+ role: "assistant",
121
+ content,
122
+ reasoningContent: options.reasoningContent,
123
+ prefix: options.prefix !== false,
124
+ _ephemeral: true
125
+ });
126
+ }
94
127
  getLast() {
95
128
  return this._messages[this._messages.length - 1] || null;
96
129
  }
@@ -109,151 +142,1172 @@
109
142
  if (lastAssistantIndex >= 0) return this._messages.splice(lastAssistantIndex + 1);
110
143
  return [];
111
144
  }
145
+ /**
146
+ * 撤回到指定消息 id 的上一个用户消息,删除两者之间的所有消息
147
+ * 适用于重发
148
+ * @param {string} id — 目标消息 id
149
+ * @returns {Array} 被删除的消息列表
150
+ */
151
+ undoToPreviousUser(id) {
152
+ let targetIndex = -1;
153
+ let previousUserIndex = -1;
154
+ for (let i = this._messages.length - 1; i >= 0; i--) {
155
+ if (this._messages[i].id === id) targetIndex = i;
156
+ if (targetIndex >= 0 && this._messages[i].role === "user") {
157
+ previousUserIndex = i;
158
+ break;
159
+ }
160
+ }
161
+ if (targetIndex >= 0 && previousUserIndex >= 0) return this._messages.splice(previousUserIndex + 1, targetIndex - previousUserIndex);
162
+ return [];
163
+ }
164
+ /**
165
+ * 更新消息:按 id 查找并合并 changes,不新增消息
166
+ * @param {string} id — 消息 id
167
+ * @param {Object} changes — 要合并的字段
168
+ * @returns {Object|null} 更新后的消息,未找到返回 null
169
+ */
170
+ update(id, changes) {
171
+ for (const msg of this._messages) if (msg.id === id) {
172
+ Object.assign(msg, changes);
173
+ msg.timestamp = changes.timestamp || Date.now();
174
+ return msg;
175
+ }
176
+ return null;
177
+ }
178
+ };
179
+ //#endregion
180
+ //#region src/core/SystemPromptStore.js
181
+ /**
182
+ * SystemPromptStore — 系统提示词存储
183
+ *
184
+ * 职责:管理多条 system prompt 的增删改查与开关
185
+ * 与 MessageStore 分离,因为 system prompt 是"AI 行为准则",不是对话事件
186
+ *
187
+ * 每条记录格式:
188
+ * {
189
+ * id: string,
190
+ * content: string,
191
+ * enabled: boolean,
192
+ * timestamp: number
193
+ * }
194
+ */
195
+ var SystemPromptStore = class {
196
+ constructor() {
197
+ this._prompts = [];
198
+ this._idCounter = 0;
199
+ }
200
+ /**
201
+ * 添加一条 system prompt
202
+ * @param {string} content — 提示词内容
203
+ * @param {boolean} [enabled=true] — 是否启用
204
+ * @returns {Object} 添加的记录
205
+ */
206
+ add(content, enabled = true) {
207
+ if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
208
+ const record = {
209
+ id: `sys_${Date.now()}_${++this._idCounter}`,
210
+ content: content.trim(),
211
+ enabled: Boolean(enabled),
212
+ timestamp: Date.now()
213
+ };
214
+ this._prompts.push(record);
215
+ return record;
216
+ }
217
+ /**
218
+ * 删除指定索引的 system prompt
219
+ * @param {number} index
220
+ * @returns {Object} 被删除的记录
221
+ */
222
+ remove(index) {
223
+ if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
224
+ return this._prompts.splice(index, 1)[0];
225
+ }
226
+ /**
227
+ * 切换指定索引的启用/禁用状态
228
+ * @param {number} index
229
+ * @returns {boolean} 切换后的状态
230
+ */
231
+ toggle(index) {
232
+ if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
233
+ this._prompts[index].enabled = !this._prompts[index].enabled;
234
+ return this._prompts[index].enabled;
235
+ }
236
+ /**
237
+ * 更新指定索引的 content
238
+ * @param {number} index
239
+ * @param {string} content
240
+ */
241
+ update(index, content) {
242
+ if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
243
+ if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
244
+ this._prompts[index].content = content.trim();
245
+ this._prompts[index].timestamp = Date.now();
246
+ }
247
+ /**
248
+ * 清空并用一条 content 替换(便捷方法,常用于 config.system = '...')
249
+ * @param {string} content
250
+ */
251
+ set(content) {
252
+ this._prompts = [];
253
+ if (content && typeof content === "string" && content.trim()) this.add(content, true);
254
+ }
255
+ /**
256
+ * 按 enabled 筛选后,转为适配器可用的格式
257
+ * @returns {Array<{role:'system', content:string}>}
258
+ */
259
+ getEnabled() {
260
+ return this._prompts.filter((p) => p.enabled).map((p) => ({
261
+ role: "system",
262
+ content: p.content
263
+ }));
264
+ }
265
+ /**
266
+ * 返回所有记录(含 enabled 状态,用于 UI 展示)
267
+ * @returns {Array}
268
+ */
269
+ getAll() {
270
+ return [...this._prompts];
271
+ }
272
+ /**
273
+ * 清空所有 system prompt
274
+ */
275
+ clear() {
276
+ this._prompts = [];
277
+ }
278
+ };
279
+ //#endregion
280
+ //#region src/core/Errors.js
281
+ /**
282
+ * 自定义错误类
283
+ * 用于区分不同类型的错误,方便用户通过 `error.name` 或 `instanceof` 处理
284
+ */
285
+ var APIError = class extends Error {
286
+ /**
287
+ * @param {string} message - 错误消息(通常来自 API 响应)
288
+ * @param {number} statusCode - HTTP 状态码
289
+ * @param {any} originalError - 原始错误对象或相关信息
290
+ * @param {string} responseText - 原始响应文本(如果有)
291
+ */
292
+ constructor(message, statusCode, originalError, responseText) {
293
+ super(message);
294
+ this.name = "APIError";
295
+ this.statusCode = statusCode;
296
+ this.originalError = originalError;
297
+ this.responseText = responseText;
298
+ }
299
+ };
300
+ var NetworkError = class extends Error {
301
+ /**
302
+ * @param {string} message - 错误消息
303
+ * @param {any} originalError - 原始错误对象或相关信息
304
+ */
305
+ constructor(message, originalError) {
306
+ super(message);
307
+ this.name = "NetworkError";
308
+ this.originalError = originalError;
309
+ }
310
+ };
311
+ var ConfigurationError = class extends Error {
312
+ /**
313
+ * @param {string} message - 错误消息
314
+ */
315
+ constructor(message) {
316
+ super(message);
317
+ this.name = "ConfigurationError";
318
+ }
319
+ };
320
+ var ParsingError = class extends Error {
321
+ /**
322
+ * @param {string} message - 错误消息
323
+ * @param {any} originalError - 原始错误对象或相关信息
324
+ * @param {string} responseText - 原始响应文本(如果有)
325
+ **/
326
+ constructor(message, originalError, responseText) {
327
+ super(message);
328
+ this.name = "ParsingError";
329
+ this.originalError = originalError;
330
+ this.responseText = responseText;
331
+ }
332
+ };
333
+ //#endregion
334
+ //#region src/core/Pipeline.js
335
+ /**
336
+ * Pipeline —— 极简顺序管道(v3.0 提案 · 阶段 1)
337
+ *
338
+ * 三个概念(对照 pipeline-demo.html):
339
+ * - 小车 ctx —— 本次请求的全部"状态",车间之间只通过它交接
340
+ * - 车间 stage —— { name, run(ctx) },只干一件事,不认别的车间
341
+ * - 调度 run() —— for + await,顺序执行(线性,无"回程";洋葱能力留给阶段 2 的 after 车间)
342
+ */
343
+ var Pipeline = class {
344
+ constructor() {
345
+ this._stages = [];
346
+ }
347
+ /**
348
+ * 注册一个车间(追加到末尾)。
349
+ * @param {{name: string, run: (ctx: object) => void | Promise<void>}} stage
350
+ * @returns {Pipeline} this,支持链式
351
+ */
352
+ register(stage) {
353
+ if (!stage || typeof stage.run !== "function") throw new TypeError("Pipeline.register: stage 需要 { name, run(ctx) },运行 run 必须是函数");
354
+ this._stages.push(stage);
355
+ return this;
356
+ }
357
+ /** 按名字移除车间(移除不存在的名字是安全的) */
358
+ unregister(name) {
359
+ this._stages = this._stages.filter((s) => s.name !== name);
360
+ return this;
361
+ }
362
+ /** 列出当前车间名(调试用) */
363
+ names() {
364
+ return this._stages.map((s) => s.name);
365
+ }
366
+ /** 把小车开过所有车间;返回 ctx(车间可改 ctx 上的字段) */
367
+ async run(ctx) {
368
+ for (const stage of this._stages) await stage.run(ctx);
369
+ return ctx;
370
+ }
112
371
  };
113
372
  //#endregion
114
373
  //#region src/core/ChatService.js
115
374
  /**
116
- * 核心聊天服务
117
- * 极简设计:只负责消息存储、事件发射、插件管理、请求委托
375
+ * @typedef {Object} ChatAdapter 适配器协议(v3.0:写同级适配器只需实现这 4+1 个方法)
376
+ * @property {Function} buildRequest (messages, config, systemPrompts) => requestBody
377
+ * @property {Function} send (body, config, opts) => Promise<apiResponse>
378
+ * @property {Function} stream (body, config, onProgress, onDone, opts) => Promise<void>
379
+ * @property {Function} parseResponse (apiResponse) => assistantMessage
380
+ * @property {Function} [getRequestDefaults] () => 默认请求参数(可选)
381
+ * @property {Function} [install] (chatService, options) 插件式安装(可选)
382
+ */
383
+ /**
384
+ * @typedef {Object} PipelineContext 管道小车 ctx(public pipe 车间可见/可改的全部字段)
385
+ * @property {Object} options 原始请求选项
386
+ * @property {*} userInput 用户输入(可为 undefined)
387
+ * @property {boolean} addUser 是否已新增/将新增用户消息
388
+ * @property {MessageStore} messages 消息列表(可读可改:push / unshift / update)
389
+ * @property {SystemPromptStore} systemPrompts 系统提示词(可读可改)
390
+ * @property {Object} config 合并后的请求级配置(prepareInput 后生效)
391
+ * @property {boolean} isStream 本次是否流式
392
+ * @property {Function|null} onProgress 流式进度回调
393
+ * @property {Function|null} onDone 流式完成回调
394
+ * @property {string|null} mergeToEntry 续写目标 id(null = 普通发送)
395
+ * @property {*} body 请求体(buildRequest 后产出)
396
+ * @property {*} result 最终结果(send 后产出)
118
397
  */
398
+ /**
399
+ * @typedef {Object} PipeStage 车间(v3.0 公开扩展单元)
400
+ * @property {string} name 车间名(唯一,不能与内部车间重名)
401
+ * @property {string} [phase] 'beforeSend'(默认)| 'afterSend'
402
+ * @property {Function} run (ctx: PipelineContext) => void | Promise<void>
403
+ */
404
+ var SESSION_CONFIG_KEYS = [
405
+ "model",
406
+ "temperature",
407
+ "maxTokens",
408
+ "modelParams",
409
+ "system",
410
+ "retry",
411
+ "ephemeralContinue"
412
+ ];
119
413
  var ChatService = class extends EventEmitter {
120
414
  constructor(config = {}) {
121
415
  super();
122
- this.config = {
123
- apiKey: config.apiKey || "",
124
- model: config.model || "gpt-3.5-turbo",
125
- ...config
126
- };
416
+ this.config = { ...config };
127
417
  this.messages = new MessageStore();
128
- this._plugins = [];
418
+ this.systemPrompts = new SystemPromptStore();
129
419
  this._adapter = null;
130
- this._pendingRequest = null;
420
+ this._abortController = null;
421
+ this._isGenerating = false;
422
+ this._hooks = new EventEmitter();
423
+ this._processResponse = null;
424
+ const model = this.config.model || this.config.modelParams?.model;
425
+ if (!model || typeof model !== "string" || !model.trim()) throw new ConfigurationError("缺少 model 配置");
426
+ this._assertValidConfig(this.config);
427
+ if (typeof config.system === "string" && config.system.trim()) this.systemPrompts.set(config.system);
428
+ if (config.adapter) this.setAdapter(config.adapter);
429
+ this._userStages = [];
430
+ this._pipeline = this._buildPipeline();
131
431
  }
132
432
  /**
133
- * 加载插件
134
- * @param {object} plugin - 必须包含 install 方法
433
+ * 校验配置中的可校验字段(model 必填由构造器负责,这里只校验存在性)
434
+ * @throws {ConfigurationError}
135
435
  */
136
- use(plugin) {
137
- if (typeof plugin.install === "function") {
138
- plugin.install(this);
139
- this._plugins.push(plugin);
140
- } else throw new Error("插件必须提供 install 方法");
436
+ _assertValidConfig(cfg) {
437
+ const temperature = cfg.modelParams?.temperature ?? cfg.temperature;
438
+ if (temperature !== void 0 && (typeof temperature !== "number" || temperature < 0 || temperature > 2)) throw new ConfigurationError(`temperature 必须在 0-2 之间,当前值: ${temperature}`);
439
+ const maxTokens = cfg.modelParams?.maxTokens ?? cfg.maxTokens;
440
+ if (maxTokens !== void 0 && (typeof maxTokens !== "number" || maxTokens < 1 || !Number.isInteger(maxTokens))) throw new ConfigurationError(`maxTokens 必须为正整数,当前值: ${maxTokens}`);
441
+ const model = cfg.model ?? cfg.modelParams?.model;
442
+ if (model !== void 0 && (typeof model !== "string" || !model.trim())) throw new ConfigurationError("model 必须是非空字符串");
443
+ }
444
+ use(plugin, options = {}) {
445
+ plugin.install(this, options);
141
446
  return this;
142
447
  }
143
448
  /**
144
- * 设置 API 适配器
449
+ * 往请求管道里挂一个"车间"。
450
+ * - phase 'beforeSend'(默认):在内部 beforeRequest 钩子之后、构建请求体之前执行
451
+ * - phase 'afterSend' :在内部发送(流式/非流式)完成、结果落位之后执行(可改 ctx.result)
452
+ * 不注册任何车间 = 行为与版本 2.8.x 完全一致。
453
+ * @param {PipeStage} stage
454
+ * @returns {ChatService} this
455
+ * @throws {ConfigurationError} 参数非法 / 名字被占用 / 与内部车间重名
145
456
  */
457
+ pipe(stage) {
458
+ if (!stage || typeof stage !== "object" || typeof stage.run !== "function") throw new ConfigurationError("pipe: 需要 { name, phase?, run(ctx) },run 必须是函数");
459
+ if (typeof stage.name !== "string" || !stage.name.trim()) throw new ConfigurationError("pipe: 需要 name(车间名,非空字符串)");
460
+ if ([
461
+ "prepareInput",
462
+ "beforeSend",
463
+ "autoContinue",
464
+ "buildRequest",
465
+ "send"
466
+ ].includes(stage.name)) throw new ConfigurationError(`pipe: "${stage.name}" 是内部车间名,请换一个名字`);
467
+ if (this._userStages.some((s) => s.name === stage.name)) throw new ConfigurationError(`pipe: 车间 "${stage.name}" 已存在,请先 chat.unpipe("${stage.name}")`);
468
+ const phase = stage.phase === "afterSend" ? "afterSend" : "beforeSend";
469
+ this._userStages.push({
470
+ name: stage.name,
471
+ phase,
472
+ run: stage.run
473
+ });
474
+ this._rebuildPipeline();
475
+ return this;
476
+ }
477
+ /** 移除一个用户车间(移除不存在的名字是安全的)。@returns {ChatService} this */
478
+ unpipe(name) {
479
+ const before = this._userStages.length;
480
+ this._userStages = this._userStages.filter((s) => s.name !== name);
481
+ if (this._userStages.length !== before) this._rebuildPipeline();
482
+ return this;
483
+ }
484
+ /** 查看当前管道里所有车间名(调试/说明用,含内部车间) */
485
+ get pipelineStages() {
486
+ return this._pipeline.names();
487
+ }
488
+ /** 重建内部管道:内部 5 车间 + 用户车间按 phase 插入 */
489
+ _buildPipeline() {
490
+ const p = new Pipeline();
491
+ p.register({
492
+ name: "prepareInput",
493
+ run: (ctx) => this._stagePrepareInput(ctx)
494
+ });
495
+ p.register({
496
+ name: "beforeSend",
497
+ run: (ctx) => this._stageBeforeSend(ctx)
498
+ });
499
+ for (const s of this._userStages) if (s.phase === "beforeSend") p.register({
500
+ name: s.name,
501
+ run: (ctx) => s.run(ctx)
502
+ });
503
+ p.register({
504
+ name: "autoContinue",
505
+ run: (ctx) => this._stageAutoContinue(ctx)
506
+ });
507
+ p.register({
508
+ name: "buildRequest",
509
+ run: (ctx) => this._stageBuildRequest(ctx)
510
+ });
511
+ p.register({
512
+ name: "send",
513
+ run: (ctx) => this._stageSend(ctx)
514
+ });
515
+ for (const s of this._userStages) if (s.phase === "afterSend") p.register({
516
+ name: s.name,
517
+ run: (ctx) => s.run(ctx)
518
+ });
519
+ return p;
520
+ }
521
+ _rebuildPipeline() {
522
+ this._pipeline = this._buildPipeline();
523
+ }
146
524
  setAdapter(adapter) {
525
+ assertAdapter(adapter);
147
526
  this._adapter = adapter;
148
- return this;
527
+ }
528
+ abort() {
529
+ if (this._abortController) this._abortController.abort();
530
+ }
531
+ get isGenerating() {
532
+ return this._isGenerating;
533
+ }
534
+ async continueLast() {
535
+ const target = this._prepareContinue();
536
+ this.messages.update(target.id, { prefix: true });
537
+ try {
538
+ await this._request({
539
+ addUser: false,
540
+ isStream: false,
541
+ mergeToEntry: target.id
542
+ });
543
+ this.messages.update(target.id, {
544
+ _complete: true,
545
+ prefix: void 0,
546
+ _ephemeral: false
547
+ });
548
+ return target;
549
+ } catch (err) {
550
+ this.messages.update(target.id, {
551
+ _complete: true,
552
+ prefix: void 0,
553
+ _ephemeral: false
554
+ });
555
+ if (err.name === "AbortError") {
556
+ this.emit("aborted", { timestamp: Date.now() });
557
+ return target;
558
+ }
559
+ throw err;
560
+ }
561
+ }
562
+ async continueLastStream(onProgress, onDone) {
563
+ const target = this._prepareContinue();
564
+ this.messages.update(target.id, { prefix: true });
565
+ const baseLen = (target.content || "").length;
566
+ try {
567
+ await this._request({
568
+ addUser: false,
569
+ isStream: true,
570
+ mergeToEntry: target.id,
571
+ onProgress: (chunk) => {
572
+ if (onProgress) onProgress({
573
+ ...chunk,
574
+ content: (chunk.content || "").slice(baseLen)
575
+ });
576
+ },
577
+ onDone: (final) => {
578
+ if (onDone) onDone(final);
579
+ }
580
+ });
581
+ this.messages.update(target.id, {
582
+ _complete: true,
583
+ prefix: void 0,
584
+ _ephemeral: false
585
+ });
586
+ return target;
587
+ } catch (err) {
588
+ this.messages.update(target.id, {
589
+ _complete: true,
590
+ prefix: void 0,
591
+ _ephemeral: false
592
+ });
593
+ if (err.name === "AbortError") {
594
+ this.emit("aborted", { timestamp: Date.now() });
595
+ return target;
596
+ }
597
+ throw err;
598
+ }
599
+ }
600
+ _prepareContinue() {
601
+ const msgs = this.messages.getAll();
602
+ const last = msgs[msgs.length - 1];
603
+ if (last && (last.role === "assistant" || last._ephemeral)) return last;
604
+ throw new Error("最后一条消息不是 assistant,无法续写");
149
605
  }
150
606
  /**
151
- * 发送消息(非流式)
152
- * @param {string|object} input - 字符串或消息对象
607
+ * 运行时修改配置(仅会话层字段)。
608
+ *
609
+ * 白名单:model / temperature / maxTokens / modelParams / system / retry / ephemeralContinue。
610
+ * - 运输层(apiKey/baseUrl/headers):归适配器,要改就换适配器实例
611
+ * - 请求参数默认值:走适配器工厂 options 或请求级覆盖(chat.send(x, params))
612
+ * - 能力表:归 modelRegistry 插件
613
+ *
614
+ * 与构造器一样经过校验,不能注入非法值。
615
+ * @throws {ConfigurationError} 非白名单字段或非法值
153
616
  */
154
- async send(input) {
155
- const userMsg = typeof input === "string" ? {
156
- role: "user",
157
- content: input
158
- } : {
159
- role: "user",
160
- ...input
617
+ updateConfig(partial) {
618
+ for (const key of Object.keys(partial)) if (!SESSION_CONFIG_KEYS.includes(key)) throw new ConfigurationError(`updateConfig 不支持修改 "${key}"。允许的会话层字段: ${SESSION_CONFIG_KEYS.join(", ")}`);
619
+ this._assertValidConfig(partial);
620
+ Object.assign(this.config, partial);
621
+ if (typeof partial.system === "string") this.systemPrompts.set(partial.system);
622
+ this.emit("config-updated", {
623
+ changes: partial,
624
+ timestamp: Date.now()
625
+ });
626
+ }
627
+ /**
628
+ * 合并请求参数(近者优先):
629
+ * 适配器默认(getRequestDefaults) ← 会话配置(this.config) ← 本次覆盖(params)
630
+ * modelParams 深层合并;平铺便捷键(temperature/maxTokens/reasoningEffort)自动折叠进 modelParams
631
+ */
632
+ _mergeRequestConfig(params = {}) {
633
+ const adapterDefaults = this._adapter?.getRequestDefaults?.() || {};
634
+ const requestConfig = {
635
+ ...adapterDefaults,
636
+ ...this.config,
637
+ ...params
161
638
  };
162
- this.messages.add(userMsg);
163
- this.emit("sending", userMsg);
164
- const requestBody = this._adapter.buildRequest(this.messages.getAll(), this.config);
165
- const response = await this._adapter.send(requestBody, this.config);
166
- const assistantMsg = this._adapter.parseResponse(response);
639
+ const modelParams = {
640
+ ...adapterDefaults.modelParams || {},
641
+ ...this.config.modelParams || {},
642
+ ...params.modelParams || {}
643
+ };
644
+ for (const key of [
645
+ "temperature",
646
+ "maxTokens",
647
+ "reasoningEffort"
648
+ ]) {
649
+ const value = params[key] ?? this.config[key] ?? adapterDefaults[key];
650
+ if (value !== void 0) modelParams[key] = value;
651
+ }
652
+ requestConfig.modelParams = modelParams;
653
+ return requestConfig;
654
+ }
655
+ /**
656
+ * 内部调度(v3.0 提案 · 阶段 1):造一辆小车 ctx,开过内部管道,返回结果。
657
+ * 行为与旧版 _request 完全一致,只是把固定线拆成了车间(见 _stage* 方法)。
658
+ *
659
+ * ctx 字段(车间可见):
660
+ * options —— 原始请求选项
661
+ * userInput —— 用户输入
662
+ * addUser —— 是否新增用户消息
663
+ * messages —— MessageStore(可读可改)
664
+ * systemPrompts —— SystemPromptStore
665
+ * config —— 合并后的请求级配置(prepareInput 车间产出)
666
+ * isStream —— 本次是否流式
667
+ * onProgress —— 流式进度回调(可为 null)
668
+ * onDone —— 流式完成回调(可为 null)
669
+ * mergeToEntry —— 续写目标 id(空 = 普通发送)
670
+ * body —— adapter 构建出的请求体(buildRequest 车间产出)
671
+ * result —— 最终结果(send 车间产出)
672
+ */
673
+ async _request(options = {}) {
674
+ const ctx = {
675
+ options,
676
+ userInput: options.userInput,
677
+ addUser: options.addUser !== false,
678
+ messages: this.messages,
679
+ systemPrompts: this.systemPrompts,
680
+ config: null,
681
+ isStream: !!options.isStream,
682
+ onProgress: options.onProgress || null,
683
+ onDone: options.onDone || null,
684
+ mergeToEntry: options.mergeToEntry || null,
685
+ body: null,
686
+ result: null
687
+ };
688
+ try {
689
+ await this._pipeline.run(ctx);
690
+ return ctx.result;
691
+ } catch (error) {
692
+ if (error.name === "AbortError") throw error;
693
+ this.emit("error", {
694
+ error,
695
+ timestamp: Date.now()
696
+ });
697
+ throw error;
698
+ }
699
+ }
700
+ /** 车间 1:加用户消息 → 合并请求参数 → 广播 sending */
701
+ async _stagePrepareInput(ctx) {
702
+ this._addUserMessage(ctx.userInput, ctx.addUser);
703
+ ctx.config = this._mergeRequestConfig(ctx.options.params);
704
+ this.emit("sending", {
705
+ addUser: ctx.addUser,
706
+ userInput: ctx.userInput,
707
+ timestamp: Date.now()
708
+ });
709
+ }
710
+ /** 车间 2:发送前钩子(兼容桥:事件钩子照发;阶段 4 会迁到 beforeSend 公开位置) */
711
+ async _stageBeforeSend(ctx) {
712
+ await this._hooks.emitAsync("beforeRequest", {
713
+ messages: ctx.messages,
714
+ config: ctx.config,
715
+ options: ctx.options
716
+ });
717
+ }
718
+ /** 车间 3:自动续写检测(ephemeralContinue 时,底部若有 prefix 消息则续写) */
719
+ async _stageAutoContinue(ctx) {
720
+ if (this.config.ephemeralContinue && !ctx.mergeToEntry) {
721
+ const msgs = ctx.messages.getAll();
722
+ const last = msgs[msgs.length - 1];
723
+ if (last && last.prefix && (last.role === "assistant" || last._ephemeral)) ctx.mergeToEntry = last.id;
724
+ }
725
+ }
726
+ /** 车间 4:构建请求体 */
727
+ async _stageBuildRequest(ctx) {
728
+ ctx.body = this._adapter.buildRequest(ctx.messages.getAll(), ctx.config, ctx.systemPrompts.getEnabled());
729
+ }
730
+ /** 车间 5:发送(流式/非流式 + 重试 + 占位消息 + _processResponse 工具钩子) */
731
+ async _stageSend(ctx) {
732
+ const retryCfg = this.config.retry || {};
733
+ ctx.result = await this._withRetry(ctx.body, {
734
+ isStream: ctx.isStream,
735
+ onProgress: ctx.onProgress,
736
+ onDone: ctx.onDone,
737
+ mergeToEntry: ctx.mergeToEntry,
738
+ config: ctx.config,
739
+ maxRetries: retryCfg.maxRetries ?? 0,
740
+ retryDelay: retryCfg.retryDelay ?? 1e3
741
+ });
742
+ }
743
+ _addUserMessage(userInput, addUser) {
744
+ if (addUser && userInput !== void 0) {
745
+ const msg = typeof userInput === "string" ? {
746
+ role: "user",
747
+ content: userInput
748
+ } : {
749
+ role: "user",
750
+ ...userInput
751
+ };
752
+ this.messages.add(msg);
753
+ }
754
+ }
755
+ /** retry 循环,占位消息只 push 一次 */
756
+ async _withRetry(body, { isStream, onProgress, onDone, mergeToEntry, config, maxRetries, retryDelay }) {
757
+ let lastError = null;
758
+ const adapterOptions = { signal: this._abortController?.signal };
759
+ let placeholder = null;
760
+ let base = null;
761
+ if (isStream) {
762
+ if (mergeToEntry) {
763
+ placeholder = this.messages.getAll().find((m) => m.id === mergeToEntry);
764
+ if (placeholder) base = {
765
+ content: placeholder.content || "",
766
+ reasoning: placeholder.reasoningContent || ""
767
+ };
768
+ }
769
+ if (!placeholder) placeholder = this.messages.add({
770
+ role: "assistant",
771
+ content: "",
772
+ _complete: false
773
+ });
774
+ }
775
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
776
+ if (attempt > 0) {
777
+ this.emit("retry", {
778
+ attempt,
779
+ maxRetries,
780
+ lastError,
781
+ timestamp: Date.now()
782
+ });
783
+ await new Promise((r) => setTimeout(r, retryDelay));
784
+ }
785
+ try {
786
+ this._isGenerating = true;
787
+ if (isStream) return await this._stream(body, adapterOptions, {
788
+ placeholder,
789
+ base,
790
+ mergeToEntry,
791
+ onProgress,
792
+ onDone,
793
+ config
794
+ });
795
+ else {
796
+ const resp = await this._adapter.send(body, config, adapterOptions);
797
+ let result = this._handleResult(this._adapter.parseResponse(resp), mergeToEntry);
798
+ if (this._processResponse && !mergeToEntry) result = await this._processResponse(result, { isStream: false });
799
+ return result;
800
+ }
801
+ } catch (error) {
802
+ lastError = error;
803
+ if (error.name === "AbortError" || this._abortController?.signal.aborted) {
804
+ this._isGenerating = false;
805
+ throw error;
806
+ }
807
+ if (error instanceof NetworkError && attempt < maxRetries) continue;
808
+ this._isGenerating = false;
809
+ throw error;
810
+ }
811
+ }
812
+ this._isGenerating = false;
813
+ throw lastError;
814
+ }
815
+ /**
816
+ * 流式处理:ChatService 维护占位消息,adapter 只负责解析 SSE
817
+ *
818
+ * 参数说明:
819
+ * - placeholder:流式期间实时更新的目标消息(续写时 = target 本身,普通发送时 = 新建的空消息)
820
+ * - base:续写时保存的旧内容快照,用于和 API 新内容拼接
821
+ * - mergeToEntry:续写目标的 id,有值时走续写逻辑
822
+ * - onProgress:外部回调,每收到一个 chunk 触发
823
+ * - onDone:流结束回调
824
+ */
825
+ async _stream(body, adapterOptions, { placeholder, base, mergeToEntry, onProgress, onDone, config }) {
826
+ let finalMsg = null;
827
+ await this._adapter.stream(body, config, (snap) => {
828
+ placeholder.content = mergeToEntry && base ? base.content + (snap.content || "") : snap.content || "";
829
+ if (snap.reasoningContent) placeholder.reasoningContent = mergeToEntry && base ? base.reasoning + snap.reasoningContent : snap.reasoningContent;
830
+ if (snap.toolCalls) placeholder.toolCalls = [...snap.toolCalls];
831
+ this.emit("stream-progress", snap);
832
+ if (onProgress) onProgress(snap);
833
+ }, async (final) => {
834
+ finalMsg = final;
835
+ if (this._processResponse && !mergeToEntry) finalMsg = await this._processResponse(finalMsg, {
836
+ isStream: true,
837
+ onProgress,
838
+ onDone
839
+ });
840
+ if (mergeToEntry && base) {
841
+ const changes = {
842
+ content: base.content + (final.content || ""),
843
+ _complete: true,
844
+ _ephemeral: false,
845
+ prefix: void 0
846
+ };
847
+ if (final.reasoningContent) changes.reasoningContent = base.reasoning + final.reasoningContent;
848
+ if (final.toolCalls) changes.toolCalls = final.toolCalls;
849
+ this.messages.update(mergeToEntry, changes);
850
+ const updated = this.messages.getAll().find((m) => m.id === mergeToEntry);
851
+ this.emit("message", updated);
852
+ if (onDone) onDone(updated);
853
+ } else {
854
+ placeholder._complete = true;
855
+ this.emit("message", finalMsg);
856
+ if (onDone) onDone(finalMsg);
857
+ }
858
+ }, adapterOptions);
859
+ return mergeToEntry || finalMsg;
860
+ }
861
+ /** 非流式结果落位 */
862
+ _handleResult(assistantMsg, mergeToEntry) {
863
+ if (mergeToEntry) {
864
+ const entry = this.messages.getAll().find((m) => m.id === mergeToEntry);
865
+ if (!entry) {
866
+ this.messages.add(assistantMsg);
867
+ this.emit("message", assistantMsg);
868
+ return assistantMsg;
869
+ }
870
+ const changes = {
871
+ content: (entry.content || "") + (assistantMsg.content || ""),
872
+ _complete: true,
873
+ _ephemeral: false,
874
+ prefix: void 0
875
+ };
876
+ if (assistantMsg.reasoningContent) changes.reasoningContent = (entry.reasoningContent || "") + assistantMsg.reasoningContent;
877
+ if (assistantMsg.toolCalls) changes.toolCalls = assistantMsg.toolCalls;
878
+ this.messages.update(mergeToEntry, changes);
879
+ const updated = this.messages.getAll().find((m) => m.id === mergeToEntry);
880
+ this.emit("message", updated);
881
+ return updated;
882
+ }
167
883
  this.messages.add(assistantMsg);
168
884
  this.emit("message", assistantMsg);
169
885
  return assistantMsg;
170
886
  }
171
887
  /**
172
- * 流式发送消息
173
- * @param {string|object} input
174
- * @param {function} onProgress - 每次收到数据块时调用,参数为累积的当前消息对象
175
- * @param {function} onDone - 完成时调用,参数为最终消息对象
888
+ * 发送消息。
889
+ * @param {string|Object} userInput - 用户输入
890
+ * @param {Object} [params] - 请求级参数覆盖(model/temperature/modelParams 等,仅本次生效)
176
891
  */
177
- async stream(input, onProgress, onDone) {
178
- const userMsg = typeof input === "string" ? {
179
- role: "user",
180
- content: input
181
- } : {
182
- role: "user",
183
- ...input
184
- };
185
- this.messages.add(userMsg);
186
- this.emit("sending", userMsg);
187
- const requestBody = this._adapter.buildRequest(this.messages.getAll(), this.config);
188
- let accumulated = {
189
- role: "assistant",
190
- content: ""
191
- };
192
- await this._adapter.stream(requestBody, this.config, (chunk) => {
193
- if (chunk.content) accumulated.content += chunk.content;
194
- if (chunk.toolCalls) accumulated.toolCalls = chunk.toolCalls;
195
- if (chunk.reasoningContent) accumulated.reasoningContent = chunk.reasoningContent;
196
- this.emit("stream-progress", { ...accumulated });
197
- if (onProgress) onProgress({ ...accumulated });
198
- }, (finalMessage) => {
199
- this.messages.add(finalMessage);
200
- this.emit("message", finalMessage);
201
- if (onDone) onDone(finalMessage);
202
- });
892
+ async send(userInput, params) {
893
+ this._abortController = new AbortController();
894
+ try {
895
+ return await this._request({
896
+ userInput,
897
+ addUser: true,
898
+ isStream: false,
899
+ params
900
+ });
901
+ } catch (err) {
902
+ if (err.name === "AbortError") {
903
+ this.emit("aborted", { timestamp: Date.now() });
904
+ return;
905
+ }
906
+ throw err;
907
+ } finally {
908
+ this._abortController = null;
909
+ this._isGenerating = false;
910
+ }
203
911
  }
204
912
  /**
205
- * 注册工具(由工具调用插件实现)
206
- * 这里只留一个空方法,插件会覆盖它
913
+ * 流式发送。
914
+ * @param {string|Object} userInput - 用户输入
915
+ * @param {Object} [params] - 请求级参数覆盖(仅本次生效)
916
+ * @param {Function} [onProgress] - 流式进度回调
917
+ * @param {Function} [onDone] - 流式完成回调
207
918
  */
208
- registerTool(name, description, executor) {
209
- throw new Error("工具调用插件未加载,请先使用 use(toolCallingPlugin)");
919
+ async stream(userInput, params, onProgress, onDone) {
920
+ if (typeof params === "function") {
921
+ onDone = onProgress;
922
+ onProgress = params;
923
+ params = void 0;
924
+ }
925
+ this._abortController = new AbortController();
926
+ try {
927
+ return await this._request({
928
+ userInput,
929
+ addUser: true,
930
+ isStream: true,
931
+ onProgress,
932
+ onDone,
933
+ params
934
+ });
935
+ } catch (err) {
936
+ if (err.name === "AbortError") {
937
+ this.emit("aborted", { timestamp: Date.now() });
938
+ return;
939
+ }
940
+ throw err;
941
+ } finally {
942
+ this._abortController = null;
943
+ this._isGenerating = false;
944
+ }
945
+ }
946
+ /**
947
+ * 重发当前消息(不加用户消息)。
948
+ * @param {Object} [params] - 请求级参数覆盖(仅本次生效)
949
+ */
950
+ async sendExisting(params) {
951
+ this._abortController = new AbortController();
952
+ try {
953
+ return await this._request({
954
+ addUser: false,
955
+ isStream: false,
956
+ params
957
+ });
958
+ } catch (err) {
959
+ if (err.name === "AbortError") {
960
+ this.emit("aborted", { timestamp: Date.now() });
961
+ return;
962
+ }
963
+ throw err;
964
+ } finally {
965
+ this._abortController = null;
966
+ this._isGenerating = false;
967
+ }
968
+ }
969
+ /**
970
+ * 流式重发(不加用户消息)。
971
+ * @param {Object} [params] - 请求级参数覆盖(仅本次生效)
972
+ * @param {Function} [onProgress] - 流式进度回调
973
+ * @param {Function} [onDone] - 流式完成回调
974
+ */
975
+ async sendExistingStream(params, onProgress, onDone) {
976
+ if (typeof params === "function") {
977
+ onDone = onProgress;
978
+ onProgress = params;
979
+ params = void 0;
980
+ }
981
+ this._abortController = new AbortController();
982
+ try {
983
+ return await this._request({
984
+ addUser: false,
985
+ isStream: true,
986
+ onProgress,
987
+ onDone,
988
+ params
989
+ });
990
+ } catch (err) {
991
+ if (err.name === "AbortError") {
992
+ this.emit("aborted", { timestamp: Date.now() });
993
+ return;
994
+ }
995
+ throw err;
996
+ } finally {
997
+ this._abortController = null;
998
+ this._isGenerating = false;
999
+ }
210
1000
  }
211
1001
  };
1002
+ /**
1003
+ * 校验 adapter 是否满足协议(v3.0 · 阶段 3)。
1004
+ * 缺少必要方法时抛 ConfigurationError,并列出缺少的方法名——写"同级适配器"不再靠猜。
1005
+ * @param {*} adapter
1006
+ * @throws {ConfigurationError}
1007
+ */
1008
+ function assertAdapter(adapter) {
1009
+ if (!adapter || typeof adapter !== "object") throw new ConfigurationError("setAdapter: adapter 必须是对象(如 openaiAdapter / createOpenAIAdapter() 实例)");
1010
+ const missing = [
1011
+ "buildRequest",
1012
+ "send",
1013
+ "stream",
1014
+ "parseResponse"
1015
+ ].filter((k) => typeof adapter[k] !== "function");
1016
+ if (missing.length) throw new ConfigurationError(`setAdapter: adapter 缺少必要方法: ${missing.join(", ")}(协议见 ChatService.js 顶部的 @typedef ChatAdapter)`);
1017
+ }
1018
+ //#endregion
1019
+ //#region src/utils/url.js
1020
+ /**
1021
+ * URL 工具函数
1022
+ */
1023
+ /**
1024
+ * 拼接 baseUrl 和 path
1025
+ * 注意:path 应以 '/' 开头,否则会替换 baseUrl 的最后一段
1026
+ * @param {string} baseUrl - 基础 URL(如 https://api.deepseek.com)
1027
+ * @param {string} path - 路径(如 /v1/chat/completions)
1028
+ * @returns {string} 完整的 URL
1029
+ */
1030
+ function joinUrl(baseUrl, path) {
1031
+ return baseUrl.replace(/\/$/, "") + (path.startsWith("/") ? path : "/" + path);
1032
+ }
1033
+ //#endregion
1034
+ //#region src/utils/typeCheck.js
1035
+ /**
1036
+ * 类型判断工具
1037
+ */
1038
+ /**
1039
+ * 判断一个值是否为字符串
1040
+ * @param {any} value - 要检查的值
1041
+ * @returns {boolean} 如果是字符串则返回 true
1042
+ */
1043
+ function isString(value) {
1044
+ return typeof value === "string";
1045
+ }
1046
+ //#endregion
1047
+ //#region src/utils/MessageFormatter.js
1048
+ /**
1049
+ * MessageFormatter — 可注册的消息格式转换器
1050
+ *
1051
+ * 职责:
1052
+ * 1. 内置 OpenA I兼容格式的转换逻辑
1053
+ * 2. 支持 register(name, fn) 注册自定义格式(如 Anthropic、Gemini 等)
1054
+ * 3. 统一处理 capabilities 过滤(reasoning、vision 等)
1055
+ * 4. 所有适配器通过此工具获取 API 消息数组,消除重复代码
1056
+ *
1057
+ * 用法:
1058
+ * import { MessageFormatter } from 'my-ai-chat-framework';
1059
+ *
1060
+ * // 使用内置格式
1061
+ * const msgs = MessageFormatter.format({
1062
+ * messages, systemPrompts, capabilities, resolveImage
1063
+ * }); // 默认 'openai'
1064
+ *
1065
+ * // 注册自定义格式
1066
+ * MessageFormatter.register('anthropic', ({ messages, systemPrompts, capabilities }) => {
1067
+ * // 返回 Anthropic 格式的消息数组
1068
+ * });
1069
+ */
1070
+ var IS_URL = /^https?:\/\//i;
1071
+ function defaultResolveImage(imageId) {
1072
+ if (IS_URL.test(imageId)) return { url: imageId };
1073
+ return null;
1074
+ }
1075
+ function buildMultimodalContent(textContent, images, resolveImage) {
1076
+ const content = [{
1077
+ type: "text",
1078
+ text: textContent
1079
+ }];
1080
+ for (const ref of images) {
1081
+ const resolved = resolveImage(ref);
1082
+ if (!resolved) continue;
1083
+ if (resolved.url) content.push({
1084
+ type: "image_url",
1085
+ image_url: { url: resolved.url }
1086
+ });
1087
+ else if (resolved.data) {
1088
+ const mime = resolved.mimeType || "image/png";
1089
+ content.push({
1090
+ type: "image_url",
1091
+ image_url: { url: `data:${mime};base64,${resolved.data}` }
1092
+ });
1093
+ }
1094
+ }
1095
+ return content;
1096
+ }
1097
+ /** OpenAI 兼容格式 */
1098
+ function toOpenAI({ messages, systemPrompts, capabilities, resolveImage }) {
1099
+ const rImg = typeof resolveImage === "function" ? resolveImage : defaultResolveImage;
1100
+ const result = [];
1101
+ for (const sp of systemPrompts) if (sp?.content && isString(sp.content) && sp.content.trim()) result.push({
1102
+ role: "system",
1103
+ content: sp.content.trim()
1104
+ });
1105
+ let ephemEnd = messages.length;
1106
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i]._ephemeral) ephemEnd = i;
1107
+ else break;
1108
+ for (let i = 0; i < messages.length; i++) {
1109
+ const msg = messages[i];
1110
+ if (msg._ephemeral) {
1111
+ if (i < ephemEnd) continue;
1112
+ }
1113
+ if (msg.role === "system" && !msg._ephemeral) continue;
1114
+ if (msg.role === "tool") {
1115
+ result.push({
1116
+ role: "tool",
1117
+ content: msg.content || "",
1118
+ tool_call_id: msg.toolCallId
1119
+ });
1120
+ continue;
1121
+ }
1122
+ if (msg.role === "assistant" && msg.toolCalls?.length) {
1123
+ const entry = {
1124
+ role: "assistant",
1125
+ content: msg.content || "",
1126
+ tool_calls: msg.toolCalls
1127
+ };
1128
+ if (msg.prefix) entry.prefix = true;
1129
+ if (capabilities?.reasoning && msg.reasoningContent) entry.reasoning_content = msg.reasoningContent;
1130
+ result.push(entry);
1131
+ continue;
1132
+ }
1133
+ const hasText = msg.content && isString(msg.content) && msg.content.trim();
1134
+ const hasImages = msg.images && Array.isArray(msg.images) && msg.images.length > 0;
1135
+ if (!hasText && !hasImages) {
1136
+ if (msg.role === "assistant" && msg.prefix) {
1137
+ const prefixEntry = {
1138
+ role: "assistant",
1139
+ content: "",
1140
+ prefix: true
1141
+ };
1142
+ if (capabilities?.reasoning && msg.reasoningContent) prefixEntry.reasoning_content = msg.reasoningContent;
1143
+ result.push(prefixEntry);
1144
+ }
1145
+ continue;
1146
+ }
1147
+ const entry = { role: msg.role };
1148
+ if (hasImages) {
1149
+ if (!capabilities?.vision) throw new Error("[MessageFormatter] 消息包含图片但模型不支持视觉(capabilities.vision=false)。请切换模型或移除图片。");
1150
+ entry.content = buildMultimodalContent(msg.content || "", msg.images, rImg);
1151
+ } else entry.content = msg.content;
1152
+ if (msg.prefix) entry.prefix = true;
1153
+ result.push(entry);
1154
+ }
1155
+ return result;
1156
+ }
1157
+ var MessageFormatter = {
1158
+ _formats: new Map([["openai", toOpenAI]]),
1159
+ register(name, fn) {
1160
+ if (!name || typeof name !== "string" || !name.trim()) throw new Error("[MessageFormatter] 格式名称必须是非空字符串");
1161
+ if (typeof fn !== "function") throw new Error("[MessageFormatter] 转换函数必须是 function");
1162
+ this._formats.set(name.trim(), fn);
1163
+ },
1164
+ unregister(name) {
1165
+ if (name === "openai") throw new Error("[MessageFormatter] 内置格式 \"openai\" 不可移除");
1166
+ this._formats.delete(name);
1167
+ },
1168
+ listFormats() {
1169
+ return [...this._formats.keys()];
1170
+ },
1171
+ format(options = {}) {
1172
+ const formatName = options.format || "openai";
1173
+ const fn = this._formats.get(formatName);
1174
+ if (!fn) throw new Error(`[MessageFormatter] 未知格式 "${formatName}"。可用格式: ${[...this._formats.keys()].join(", ")}`);
1175
+ return fn({
1176
+ messages: options.messages || [],
1177
+ systemPrompts: options.systemPrompts || [],
1178
+ capabilities: options.capabilities || {},
1179
+ resolveImage: options.resolveImage
1180
+ });
1181
+ }
1182
+ };
1183
+ function assembleMessages(options = {}) {
1184
+ return MessageFormatter.format({
1185
+ ...options,
1186
+ format: "openai"
1187
+ });
1188
+ }
212
1189
  //#endregion
213
1190
  //#region src/adapters/openai.js
214
1191
  /**
215
1192
  * OpenAI 兼容 API 适配器
216
1193
  * 支持 DeepSeek 等完全兼容 OpenAI 接口的服务
217
1194
  */
1195
+ var TRANSPORT_KEYS = [
1196
+ "apiKey",
1197
+ "baseUrl",
1198
+ "apiUrl",
1199
+ "path",
1200
+ "headers"
1201
+ ];
218
1202
  var openaiAdapter = {
219
1203
  name: "openai",
220
- install(chatService) {
1204
+ install(chatService, options = {}) {
1205
+ if (this._transport) this._transport = {
1206
+ ...this._transport,
1207
+ ...options
1208
+ };
221
1209
  chatService.setAdapter(this);
222
1210
  },
223
- buildRequest(messages, config) {
224
- const apiMessages = messages.map((msg) => {
225
- const base = {
226
- role: msg.role,
227
- content: msg.content
228
- };
229
- if (msg.role === "assistant" && msg.toolCalls) base.tool_calls = msg.toolCalls;
230
- if (msg.role === "tool" && msg.toolCallId) base.tool_call_id = msg.toolCallId;
231
- return base;
232
- });
233
- return {
234
- model: config.model,
235
- messages: apiMessages,
236
- temperature: config.temperature ?? .7,
237
- max_tokens: config.maxTokens ?? 2e3,
1211
+ _resolveConfig(config) {
1212
+ const transport = this._transport || {};
1213
+ const resolved = {
1214
+ ...config,
1215
+ ...transport
1216
+ };
1217
+ if (transport.modelParams) resolved.modelParams = {
1218
+ ...transport.modelParams,
1219
+ ...config.modelParams || {}
1220
+ };
1221
+ return resolved;
1222
+ },
1223
+ getRequestDefaults() {
1224
+ if (!this._transport) return {};
1225
+ const defaults = {};
1226
+ for (const [key, value] of Object.entries(this._transport)) if (!TRANSPORT_KEYS.includes(key) && value !== void 0) defaults[key] = value;
1227
+ return defaults;
1228
+ },
1229
+ buildRequest(messages, config, systemPrompts = []) {
1230
+ config = this._resolveConfig(config);
1231
+ const model = config.model || config.modelParams?.model;
1232
+ if (!model) throw new Error("Missing required config: model (either at top level or in modelParams)");
1233
+ const mp = config.modelParams || {};
1234
+ const temperature = mp.temperature ?? config.temperature ?? .7;
1235
+ const maxTokens = mp.maxTokens ?? config.maxTokens ?? 2e3;
1236
+ const reasoningEffort = mp.reasoningEffort ?? config.reasoningEffort;
1237
+ const requestBody = {
1238
+ model,
1239
+ messages: MessageFormatter.format({
1240
+ messages,
1241
+ systemPrompts,
1242
+ capabilities: config.capabilities || {},
1243
+ resolveImage: config.resolveImage,
1244
+ format: config.messageFormat
1245
+ }),
1246
+ temperature,
1247
+ max_tokens: maxTokens,
238
1248
  stream: false
239
1249
  };
1250
+ if (mp.topP !== void 0) requestBody.top_p = mp.topP;
1251
+ if (mp.frequencyPenalty !== void 0) requestBody.frequency_penalty = mp.frequencyPenalty;
1252
+ if (mp.presencePenalty !== void 0) requestBody.presence_penalty = mp.presencePenalty;
1253
+ if (mp.stop !== void 0) requestBody.stop = mp.stop;
1254
+ if (mp.responseFormat !== void 0) requestBody.response_format = mp.responseFormat;
1255
+ if (mp.seed !== void 0) requestBody.seed = mp.seed;
1256
+ if (config.tools && Array.isArray(config.tools) && config.tools.length > 0) {
1257
+ requestBody.tools = config.tools;
1258
+ requestBody.tool_choice = "auto";
1259
+ }
1260
+ if (reasoningEffort !== void 0) requestBody.reasoning_effort = reasoningEffort;
1261
+ const consumedKeys = new Set([
1262
+ "model",
1263
+ "temperature",
1264
+ "maxTokens",
1265
+ "reasoningEffort",
1266
+ "topP",
1267
+ "frequencyPenalty",
1268
+ "presencePenalty",
1269
+ "stop",
1270
+ "responseFormat",
1271
+ "seed"
1272
+ ]);
1273
+ for (const [key, value] of Object.entries(mp)) if (!consumedKeys.has(key) && value !== void 0) requestBody[key] = value;
1274
+ return requestBody;
240
1275
  },
241
- async send(requestBody, config) {
242
- const response = await fetch(config.apiUrl || "https://api.openai.com/v1/chat/completions", {
243
- method: "POST",
244
- headers: {
1276
+ _getUrl(config) {
1277
+ config = config || {};
1278
+ const { apiUrl, baseUrl, path } = config;
1279
+ const defaultPath = "/chat/completions";
1280
+ if (apiUrl && isString(apiUrl)) return apiUrl;
1281
+ if (baseUrl && isString(baseUrl)) return joinUrl(baseUrl, path && isString(path) ? path : defaultPath);
1282
+ return "https://api.openai.com/v1/chat/completions";
1283
+ },
1284
+ async send(requestBody, config, options = {}) {
1285
+ try {
1286
+ config = this._resolveConfig(config);
1287
+ const url = this._getUrl(config);
1288
+ const headers = {
245
1289
  "Content-Type": "application/json",
246
- "Authorization": `Bearer ${config.apiKey}`
247
- },
248
- body: JSON.stringify(requestBody)
249
- });
250
- if (!response.ok) {
251
- const error = await response.text();
252
- throw new Error(`API 请求失败: ${response.status} ${error}`);
1290
+ "Authorization": `Bearer ${config.apiKey}`,
1291
+ ...config.headers || {},
1292
+ ...options.headers || {}
1293
+ };
1294
+ const response = await fetch(url, {
1295
+ method: "POST",
1296
+ headers,
1297
+ body: JSON.stringify(requestBody),
1298
+ signal: options.signal
1299
+ });
1300
+ if (!response.ok) await this.handleErrorResponse(response);
1301
+ return await response.json();
1302
+ } catch (error) {
1303
+ if (error instanceof APIError) throw error;
1304
+ if (error.name === "AbortError") throw error;
1305
+ if (error.name === "TypeError" && error.message.includes("fetch")) throw new NetworkError(`Request failed: ${error.message}`, error);
1306
+ throw error;
253
1307
  }
254
- return await response.json();
255
1308
  },
256
1309
  parseResponse(apiResponse) {
1310
+ 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));
257
1311
  const msg = apiResponse.choices[0].message;
258
1312
  const internal = {
259
1313
  role: msg.role,
@@ -263,32 +1317,44 @@
263
1317
  if (msg.reasoning_content) internal.reasoningContent = msg.reasoning_content;
264
1318
  return internal;
265
1319
  },
266
- async stream(requestBody, config, onProgress, onDone) {
1320
+ async stream(requestBody, config, onProgress, onDone, options = {}) {
1321
+ config = this._resolveConfig(config);
267
1322
  const streamBody = {
268
1323
  ...requestBody,
269
1324
  stream: true
270
1325
  };
271
- const response = await fetch(config.apiUrl || "https://api.openai.com/v1/chat/completions", {
272
- method: "POST",
273
- headers: {
274
- "Content-Type": "application/json",
275
- "Authorization": `Bearer ${config.apiKey}`,
276
- "Accept": "text/event-stream"
277
- },
278
- body: JSON.stringify(streamBody)
279
- });
280
- if (!response.ok) {
281
- const error = await response.text();
282
- throw new Error(`流式请求失败: ${response.status} ${error}`);
1326
+ const url = this._getUrl(config);
1327
+ let response;
1328
+ const headers = {
1329
+ "Content-Type": "application/json",
1330
+ "Authorization": `Bearer ${config.apiKey}`,
1331
+ "Accept": "text/event-stream",
1332
+ ...config.headers || {},
1333
+ ...options.headers || {}
1334
+ };
1335
+ try {
1336
+ response = await fetch(url, {
1337
+ method: "POST",
1338
+ headers,
1339
+ body: JSON.stringify(streamBody),
1340
+ signal: options.signal
1341
+ });
1342
+ } catch (error) {
1343
+ if (error.name === "AbortError") throw error;
1344
+ if (error.name === "TypeError" && error.message.includes("fetch")) throw new NetworkError(`Stream request failed: ${error.message}`, error);
1345
+ throw error;
283
1346
  }
1347
+ if (!response.ok) await this.handleErrorResponse(response);
284
1348
  const reader = response.body.getReader();
285
1349
  const decoder = new TextDecoder();
286
1350
  let buffer = "";
287
1351
  let accumulated = {
288
1352
  role: "assistant",
289
- content: ""
1353
+ content: "",
1354
+ reasoningContent: ""
290
1355
  };
291
1356
  while (true) {
1357
+ if (options.signal?.aborted) break;
292
1358
  const { done, value } = await reader.read();
293
1359
  if (done) break;
294
1360
  buffer += decoder.decode(value, { stream: true });
@@ -296,22 +1362,34 @@
296
1362
  buffer = lines.pop();
297
1363
  for (const line of lines) {
298
1364
  const dataLine = line.replace(/^data: /, "").trim();
299
- if (!dataLine || dataLine === "[DONE]") continue;
1365
+ if (!dataLine) continue;
1366
+ if (dataLine === "[DONE]") break;
300
1367
  try {
301
1368
  const delta = JSON.parse(dataLine).choices?.[0]?.delta;
302
1369
  if (!delta) continue;
303
- const update = {
304
- role: delta.role || "assistant",
305
- content: delta.content || ""
306
- };
307
- if (delta.tool_calls) update.toolCalls = delta.tool_calls;
308
- if (delta.reasoning_content) update.reasoningContent = delta.reasoning_content;
309
- if (update.content) accumulated.content += update.content;
310
- if (update.toolCalls) accumulated.toolCalls = update.toolCalls;
311
- if (update.reasoningContent) accumulated.reasoningContent = update.reasoningContent;
1370
+ if (delta.content) accumulated.content += delta.content;
1371
+ if (delta.tool_calls) {
1372
+ if (!accumulated.toolCalls) accumulated.toolCalls = [];
1373
+ for (const toolCallDelta of delta.tool_calls) {
1374
+ const index = toolCallDelta.index;
1375
+ if (!accumulated.toolCalls[index]) accumulated.toolCalls[index] = {
1376
+ id: "",
1377
+ type: "function",
1378
+ function: {
1379
+ name: "",
1380
+ arguments: ""
1381
+ }
1382
+ };
1383
+ if (toolCallDelta.id) accumulated.toolCalls[index].id = toolCallDelta.id;
1384
+ if (toolCallDelta.type) accumulated.toolCalls[index].type = toolCallDelta.type;
1385
+ if (toolCallDelta.function?.name) accumulated.toolCalls[index].function.name += toolCallDelta.function.name;
1386
+ if (toolCallDelta.function?.arguments) accumulated.toolCalls[index].function.arguments += toolCallDelta.function.arguments;
1387
+ }
1388
+ }
1389
+ if (delta.reasoning_content) accumulated.reasoningContent += delta.reasoning_content;
312
1390
  onProgress({ ...accumulated });
313
1391
  } catch (e) {
314
- console.warn("解析流式数据块失败:", e, dataLine);
1392
+ console.warn("stream parsing failed :", e, dataLine);
315
1393
  }
316
1394
  }
317
1395
  }
@@ -321,81 +1399,211 @@
321
1399
  toolCalls: accumulated.toolCalls,
322
1400
  reasoningContent: accumulated.reasoningContent
323
1401
  });
1402
+ },
1403
+ async handleErrorResponse(response) {
1404
+ let errorText = await response.text();
1405
+ let errorMessage = `HTTP ${response.status}`;
1406
+ try {
1407
+ const errorJson = JSON.parse(errorText);
1408
+ errorMessage = errorJson.error?.message || errorJson.message || errorText.slice(0, 200);
1409
+ } catch (e) {
1410
+ errorMessage = errorText.length > 200 ? errorText.slice(0, 200) + "..." : errorText;
1411
+ }
1412
+ throw new APIError(errorMessage, response.status, null, errorText);
324
1413
  }
325
1414
  };
1415
+ /**
1416
+ * 创建 OpenAI 兼容适配器实例(工厂)。
1417
+ *
1418
+ * 与单例 openaiAdapter 的区别:每个实例自持一份运输配置(apiKey/baseUrl/apiUrl/path/headers),
1419
+ * 互不干扰——解决"同一适配器装到多个 ChatService 互相覆盖"的单例陷阱。
1420
+ *
1421
+ * 用法:
1422
+ * const adapter = createOpenAIAdapter({ apiKey, baseUrl, modelParams: { temperature: 0.8 } });
1423
+ * const chat = new ChatService({ adapter, model: 'deepseek-chat' });
1424
+ * chat.use(adapter); // 或直接 new ChatService({ adapter })
1425
+ *
1426
+ * 非运输键(model/modelParams/messageFormat/resolveImage/capabilities 等)会作为
1427
+ * "请求默认参数"供会话层合并,单次请求仍可覆盖。
1428
+ */
1429
+ function createOpenAIAdapter(options = {}) {
1430
+ return {
1431
+ ...openaiAdapter,
1432
+ _transport: { ...options }
1433
+ };
1434
+ }
326
1435
  //#endregion
327
1436
  //#region src/plugins/tool-calling.js
328
1437
  /**
329
1438
  * 工具调用插件
330
- * 拦截消息中的 tool_calls,执行注册的工具,并将结果插入对话,然后继续请求
1439
+ * 功能:拦截助手消息中的 tool_calls,执行对应的工具,将结果作为 tool 消息加入对话,
1440
+ * 然后自动继续对话(通过 sendExisting / sendExistingStream),直到没有新的工具调用。
1441
+ *
1442
+ * 设计要点:
1443
+ * - 支持普通请求和流式请求(通过 isStream 标志区分)
1444
+ * - 支持多次工具调用循环(maxIterations 防止无限循环)
1445
+ * - 并行执行工具
1446
+ * - 工具执行失败时,仍然返回错误信息给 AI,而不是中断整个流程
1447
+ * - 触发 tool-error 事件,方便用户监听工具执行异常
1448
+ *
1449
+ * 注意:请使用 createToolCallingPlugin() 工厂创建实例。
1450
+ * 默认导出的 toolCallingPlugin 是兼容用的模块级单例,装到多个 ChatService
1451
+ * 实例会互相覆盖(executor 表、工具定义、配置),新代码不要直接用单例。
331
1452
  */
332
- var toolCallingPlugin = {
333
- name: "tool-calling",
334
- maxIterations: 5,
335
- install(chatService) {
336
- this.chatService = chatService;
337
- this._tools = /* @__PURE__ */ new Map();
338
- chatService.registerTool = (name, description, executor) => {
339
- this._tools.set(name, {
340
- executor,
341
- description
1453
+ var toolCallingPlugin = createToolCallingPlugin();
1454
+ /**
1455
+ * 创建工具调用插件实例(工厂)。
1456
+ * @param {Object} [options] — { timeout, maxIterations }
1457
+ */
1458
+ function createToolCallingPlugin(options = {}) {
1459
+ return {
1460
+ name: "tool-calling",
1461
+ maxIterations: options.maxIterations || 5,
1462
+ _options: { ...options },
1463
+ _tools: /* @__PURE__ */ new Map(),
1464
+ _toolDefs: [],
1465
+ chatService: null,
1466
+ install(chatService, options = {}) {
1467
+ this._options = {
1468
+ ...this._options,
1469
+ ...options
1470
+ };
1471
+ this.chatService = chatService;
1472
+ chatService.pipe({
1473
+ name: "tool-calling-inject",
1474
+ phase: "beforeSend",
1475
+ run: ({ config }) => {
1476
+ if (this._toolDefs.length) config.tools = this._toolDefs;
1477
+ }
342
1478
  });
343
- return chatService;
344
- };
345
- const originalSend = chatService.send;
346
- chatService.send = async (input) => {
347
- return this._handleWithTools(originalSend, input, false);
348
- };
349
- const originalStream = chatService.stream;
350
- chatService.stream = async (input, onProgress, onDone) => {
351
- return this._handleWithTools(originalStream, input, true, onProgress, onDone);
352
- };
353
- },
354
- async _handleWithTools(originalMethod, input, isStream, onProgress, onDone) {
355
- const self = this;
356
- const chat = this.chatService;
357
- let iteration = 0;
358
- async function processResponse(initialResponse) {
359
- let lastResponse = initialResponse;
360
- while (iteration < self.maxIterations) {
361
- const toolCalls = lastResponse?.toolCalls;
362
- if (!toolCalls || toolCalls.length === 0) break;
363
- iteration++;
364
- const toolResults = [];
365
- for (const call of toolCalls) {
366
- const toolName = call.function?.name;
367
- const args = JSON.parse(call.function?.arguments || "{}");
368
- const tool = self._tools.get(toolName);
369
- if (!tool) {
370
- console.warn(`未找到工具: ${toolName}`);
371
- toolResults.push({
372
- tool_call_id: call.id,
373
- error: `工具 ${toolName} 未注册`,
374
- success: false
375
- });
376
- continue;
377
- }
378
- try {
379
- const result = await tool.executor(args);
380
- toolResults.push({
381
- tool_call_id: call.id,
382
- content: typeof result === "string" ? result : JSON.stringify(result),
383
- success: true
384
- });
385
- } catch (err) {
386
- console.error(`工具 ${toolName} 执行失败:`, err);
387
- toolResults.push({
388
- tool_call_id: call.id,
389
- error: err.message,
390
- success: false
391
- });
1479
+ /**
1480
+ * 注册工具
1481
+ * @param {string} name - 工具名称(唯一标识)
1482
+ * @param {string} description - 工具描述(告诉 AI 何时调用)
1483
+ * @param {Function} executor - 异步执行函数,接收参数对象,返回结果(字符串或对象)
1484
+ * @param {Object} parameters - JSON Schema 参数定义(可选,默认为空对象)
1485
+ * @returns {ChatService} 返回 chatService 实例,支持链式调用
1486
+ */
1487
+ chatService.registerTool = (name, description, executor, parameters = {}) => {
1488
+ this._tools.set(name, {
1489
+ executor,
1490
+ description
1491
+ });
1492
+ const toolDefinition = {
1493
+ type: "function",
1494
+ function: {
1495
+ name,
1496
+ description,
1497
+ parameters: {
1498
+ type: "object",
1499
+ properties: parameters,
1500
+ required: Object.keys(parameters).filter((key) => parameters[key]?.required)
1501
+ }
392
1502
  }
1503
+ };
1504
+ if (!this._toolDefs.find((t) => t.function.name === name)) this._toolDefs.push(toolDefinition);
1505
+ return chatService;
1506
+ };
1507
+ chatService.pipe({
1508
+ name: "tool-calling-loop",
1509
+ phase: "afterSend",
1510
+ run: async (ctx) => {
1511
+ ctx.result = await this._handleWithTools(ctx.result, ctx.isStream, ctx.onProgress || void 0, ctx.onDone || void 0);
393
1512
  }
394
- for (const tr of toolResults) chat.messages.addTool(tr.content || tr.error, tr.tool_call_id);
395
- if (isStream) {
396
- chat.messages.getLast();
397
- await new Promise((resolve) => {
398
- originalStream.call(chat, null, (chunk) => {
1513
+ });
1514
+ },
1515
+ async _handleWithTools(initialResponse, isStream, onProgress, onDone) {
1516
+ const self = this;
1517
+ const chat = this.chatService;
1518
+ let iteration = 0;
1519
+ /**
1520
+ * 递归处理工具调用
1521
+ * @param {Object} initialResponse - 初始 AI 响应(可能是第一次请求的响应)
1522
+ * @returns {Promise<Object>} 最终 AI 响应(不含 tool_calls)
1523
+ */
1524
+ async function processResponse(initialResponse) {
1525
+ let lastResponse = initialResponse;
1526
+ while (iteration < self.maxIterations) {
1527
+ const toolCalls = lastResponse?.toolCalls;
1528
+ if (!toolCalls || toolCalls.length === 0) break;
1529
+ iteration++;
1530
+ const toolResults = await Promise.all(toolCalls.map(async (call) => {
1531
+ const toolName = call.function?.name;
1532
+ let args;
1533
+ try {
1534
+ args = JSON.parse(call.function?.arguments || "{}");
1535
+ } catch (parseErr) {
1536
+ chat.emit("tool-error", {
1537
+ toolName: toolName || "unknown",
1538
+ error: parseErr,
1539
+ toolCallId: call.id,
1540
+ stage: "parse",
1541
+ timestamp: Date.now()
1542
+ });
1543
+ return {
1544
+ tool_call_id: call.id,
1545
+ error: `参数解析失败: ${parseErr.message}`,
1546
+ success: false
1547
+ };
1548
+ }
1549
+ const tool = self._tools.get(toolName);
1550
+ if (!tool) {
1551
+ chat.emit("tool-error", {
1552
+ toolName,
1553
+ error: /* @__PURE__ */ new Error(`Tool not registered: ${toolName}`),
1554
+ toolCallId: call.id,
1555
+ stage: "lookup",
1556
+ timestamp: Date.now()
1557
+ });
1558
+ return {
1559
+ tool_call_id: call.id,
1560
+ error: `工具 ${toolName} 未注册`,
1561
+ success: false
1562
+ };
1563
+ }
1564
+ try {
1565
+ const toolTimeout = self._options.timeout ?? chat.config.toolTimeout;
1566
+ let execPromise = tool.executor(args);
1567
+ if (toolTimeout && typeof toolTimeout === "number" && toolTimeout > 0) {
1568
+ const timeoutErr = /* @__PURE__ */ new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
1569
+ timeoutErr.name = "ToolTimeoutError";
1570
+ const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(timeoutErr), toolTimeout));
1571
+ execPromise = Promise.race([execPromise, timeoutPromise]);
1572
+ }
1573
+ const result = await execPromise;
1574
+ chat.emit("tool-success", {
1575
+ toolName,
1576
+ result,
1577
+ toolCallId: call.id,
1578
+ timestamp: Date.now()
1579
+ });
1580
+ return {
1581
+ tool_call_id: call.id,
1582
+ content: typeof result === "string" ? result : JSON.stringify(result),
1583
+ success: true
1584
+ };
1585
+ } catch (err) {
1586
+ const stage = err.name === "ToolTimeoutError" ? "timeout" : "execute";
1587
+ chat.emit("tool-error", {
1588
+ toolName,
1589
+ error: err,
1590
+ toolCallId: call.id,
1591
+ stage,
1592
+ timestamp: Date.now()
1593
+ });
1594
+ return {
1595
+ tool_call_id: call.id,
1596
+ error: err.message,
1597
+ success: false
1598
+ };
1599
+ }
1600
+ }));
1601
+ for (const tr of toolResults) {
1602
+ const content = tr.success ? tr.content : tr.error || "工具执行失败";
1603
+ chat.messages.addTool(content, tr.tool_call_id);
1604
+ }
1605
+ if (isStream) await new Promise((resolve) => {
1606
+ chat.sendExistingStream((chunk) => {
399
1607
  if (onProgress) onProgress(chunk);
400
1608
  lastResponse = chunk;
401
1609
  }, (final) => {
@@ -403,39 +1611,214 @@
403
1611
  resolve();
404
1612
  });
405
1613
  });
406
- } else {
407
- const reqBody = chat._adapter.buildRequest(chat.messages.getAll(), chat.config);
408
- const apiResp = await chat._adapter.send(reqBody, chat.config);
409
- lastResponse = chat._adapter.parseResponse(apiResp);
1614
+ else lastResponse = await chat.sendExisting();
410
1615
  }
1616
+ return lastResponse;
411
1617
  }
412
- return lastResponse;
1618
+ return await processResponse(initialResponse);
413
1619
  }
414
- if (isStream) {
415
- let finalMessage;
416
- await originalMethod.call(chat, input, (chunk) => {
417
- if (onProgress) onProgress(chunk);
418
- }, async (final) => {
419
- finalMessage = await processResponse(final);
420
- if (onDone) onDone(finalMessage);
421
- });
422
- } else return await processResponse(await originalMethod.call(chat, input));
1620
+ };
1621
+ }
1622
+ //#endregion
1623
+ //#region src/plugins/model-registry.js
1624
+ /**
1625
+ * model-registry 插件
1626
+ *
1627
+ * 职责:
1628
+ * 1. 内置常用模型的能力标签表(model → capabilities 映射)
1629
+ * 2. 安装时自动根据 config.model 查表,写入 config.capabilities
1630
+ * 3. 监听 config-updated 事件,切换模型时自动同步能力
1631
+ * 4. 提供 chat.registerModel(),允许用户追加/覆盖自定义模型
1632
+ *
1633
+ * 能力标签字段(全部可选,缺失视为 false / 未知):
1634
+ * {
1635
+ * reasoning: boolean — 是否返回 reasoning_content(思维链)
1636
+ * vision: boolean — 是否支持图片输入
1637
+ * toolCalling: boolean — 是否支持 function calling
1638
+ * streaming: boolean — 是否支持流式传输
1639
+ * maxInputTokens: number — 最大输入 token 数
1640
+ * maxOutputTokens: number — 最大输出 token 数
1641
+ * }
1642
+ *
1643
+ * 使用:
1644
+ * chat.use(modelRegistryPlugin);
1645
+ * // config.capabilities 现在已自动填充
1646
+ * chat.registerModel('my-custom-model', { toolCalling: true });
1647
+ */
1648
+ var BUILTIN_MODELS = {
1649
+ "deepseek-chat": {
1650
+ reasoning: false,
1651
+ vision: false,
1652
+ toolCalling: true,
1653
+ streaming: true,
1654
+ maxInputTokens: 128e3,
1655
+ maxOutputTokens: 8192
1656
+ },
1657
+ "deepseek-reasoner": {
1658
+ reasoning: true,
1659
+ vision: false,
1660
+ toolCalling: true,
1661
+ streaming: true,
1662
+ maxInputTokens: 128e3,
1663
+ maxOutputTokens: 8192
1664
+ },
1665
+ "gpt-4o": {
1666
+ reasoning: false,
1667
+ vision: true,
1668
+ toolCalling: true,
1669
+ streaming: true,
1670
+ maxInputTokens: 128e3,
1671
+ maxOutputTokens: 16384
1672
+ },
1673
+ "gpt-4o-mini": {
1674
+ reasoning: false,
1675
+ vision: true,
1676
+ toolCalling: true,
1677
+ streaming: true,
1678
+ maxInputTokens: 128e3,
1679
+ maxOutputTokens: 16384
1680
+ },
1681
+ "gpt-3.5-turbo": {
1682
+ reasoning: false,
1683
+ vision: false,
1684
+ toolCalling: true,
1685
+ streaming: true,
1686
+ maxInputTokens: 16385,
1687
+ maxOutputTokens: 4096
1688
+ },
1689
+ "o1": {
1690
+ reasoning: true,
1691
+ vision: false,
1692
+ toolCalling: false,
1693
+ streaming: false,
1694
+ maxInputTokens: 2e5,
1695
+ maxOutputTokens: 1e5
1696
+ },
1697
+ "o3-mini": {
1698
+ reasoning: true,
1699
+ vision: false,
1700
+ toolCalling: true,
1701
+ streaming: true,
1702
+ maxInputTokens: 2e5,
1703
+ maxOutputTokens: 1e5
1704
+ },
1705
+ "claude-3.5-sonnet": {
1706
+ reasoning: false,
1707
+ vision: true,
1708
+ toolCalling: true,
1709
+ streaming: true,
1710
+ maxInputTokens: 2e5,
1711
+ maxOutputTokens: 8192
1712
+ },
1713
+ "claude-3.5-haiku": {
1714
+ reasoning: false,
1715
+ vision: true,
1716
+ toolCalling: true,
1717
+ streaming: true,
1718
+ maxInputTokens: 2e5,
1719
+ maxOutputTokens: 8192
423
1720
  }
424
1721
  };
425
- //#endregion
426
- //#region src/index.js
427
- var src_default = {
428
- ChatService,
429
- MessageStore,
430
- EventEmitter,
431
- openaiAdapter,
432
- toolCallingPlugin
1722
+ var DEFAULT_CAPABILITIES = {
1723
+ streaming: true,
1724
+ toolCalling: false,
1725
+ reasoning: false,
1726
+ vision: false
433
1727
  };
1728
+ /**
1729
+ * 注意:请使用 createModelRegistryPlugin() 工厂创建实例。
1730
+ * 默认导出的 modelRegistryPlugin 是兼容用的模块级单例,装到多个 ChatService
1731
+ * 实例会互相覆盖(注册表、实例引用),新代码不要直接用单例。
1732
+ */
1733
+ var modelRegistryPlugin = createModelRegistryPlugin();
1734
+ /**
1735
+ * 创建模型能力注册表插件实例(工厂)。
1736
+ * @param {Object} [options] — { models: { '模型名': capabilities } }(合并进内置表)
1737
+ */
1738
+ function createModelRegistryPlugin(options = {}) {
1739
+ return {
1740
+ name: "model-registry",
1741
+ _options: { ...options },
1742
+ _registry: new Map([...Object.entries(BUILTIN_MODELS), ...Object.entries(options.models || {})]),
1743
+ chat: null,
1744
+ install(chatService, options = {}) {
1745
+ this._options = {
1746
+ ...this._options,
1747
+ ...options
1748
+ };
1749
+ this.chat = chatService;
1750
+ /**
1751
+ * 注册/覆盖一个模型的能力标签
1752
+ * @param {string} name — 模型名称
1753
+ * @param {Object} capabilities — 能力标签对象(部分字段即可,未提供的取默认值)
1754
+ * @returns {ChatService}
1755
+ */
1756
+ chatService.registerModel = (name, capabilities = {}) => {
1757
+ if (!name || typeof name !== "string" || !name.trim()) throw new Error("[model-registry] 模型名称必须是非空字符串");
1758
+ const merged = {
1759
+ ...DEFAULT_CAPABILITIES,
1760
+ ...capabilities
1761
+ };
1762
+ this._registry.set(name.trim(), merged);
1763
+ if (chatService.config.model === name.trim()) this._syncCapabilities();
1764
+ return chatService;
1765
+ };
1766
+ /**
1767
+ * 列出所有已注册的模型名称
1768
+ * @returns {Array<string>}
1769
+ */
1770
+ chatService.listModels = () => {
1771
+ return [...this._registry.keys()];
1772
+ };
1773
+ this._syncCapabilities();
1774
+ chatService.pipe({
1775
+ name: "model-registry-caps",
1776
+ phase: "beforeSend",
1777
+ run: ({ config }) => {
1778
+ if (!config.model) return;
1779
+ const caps = this._registry.get(config.model);
1780
+ if (caps) config.capabilities = { ...caps };
1781
+ }
1782
+ });
1783
+ chatService.on("config-updated", ({ changes }) => {
1784
+ if ("model" in changes) this._syncCapabilities();
1785
+ if ("capabilities" in changes && !("model" in changes)) {
1786
+ const current = this._lookupCapabilities();
1787
+ if (current) chatService.config.capabilities = {
1788
+ ...current,
1789
+ ...changes.capabilities
1790
+ };
1791
+ }
1792
+ });
1793
+ },
1794
+ _lookupCapabilities() {
1795
+ const model = this.chat.config.model;
1796
+ if (!model) return null;
1797
+ return this._registry.get(model) || null;
1798
+ },
1799
+ _syncCapabilities() {
1800
+ const caps = this._lookupCapabilities();
1801
+ if (caps) this.chat.config.capabilities = { ...caps };
1802
+ }
1803
+ };
1804
+ }
434
1805
  //#endregion
1806
+ exports.APIError = APIError;
435
1807
  exports.ChatService = ChatService;
1808
+ exports.ConfigurationError = ConfigurationError;
436
1809
  exports.EventEmitter = EventEmitter;
1810
+ exports.MessageFormatter = MessageFormatter;
437
1811
  exports.MessageStore = MessageStore;
438
- exports.default = src_default;
1812
+ exports.NetworkError = NetworkError;
1813
+ exports.ParsingError = ParsingError;
1814
+ exports.Pipeline = Pipeline;
1815
+ exports.SystemPromptStore = SystemPromptStore;
1816
+ exports.assembleMessages = assembleMessages;
1817
+ exports.assertAdapter = assertAdapter;
1818
+ exports.createModelRegistryPlugin = createModelRegistryPlugin;
1819
+ exports.createOpenAIAdapter = createOpenAIAdapter;
1820
+ exports.createToolCallingPlugin = createToolCallingPlugin;
1821
+ exports.modelRegistryPlugin = modelRegistryPlugin;
439
1822
  exports.openaiAdapter = openaiAdapter;
440
1823
  exports.toolCallingPlugin = toolCallingPlugin;
441
1824
  });