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