my-ai-chat-framework 2.7.0 → 4.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.
@@ -143,6 +143,25 @@
143
143
  return [];
144
144
  }
145
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
+ /**
146
165
  * 更新消息:按 id 查找并合并 changes,不新增消息
147
166
  * @param {string} id — 消息 id
148
167
  * @param {Object} changes — 要合并的字段
@@ -158,6 +177,69 @@
158
177
  }
159
178
  };
160
179
  //#endregion
180
+ //#region src/core/Errors.js
181
+ /**
182
+ * 自定义错误类
183
+ * 用于区分不同类型的错误,方便用户通过 `error.name` 或 `instanceof` 处理
184
+ */
185
+ var APIError = class extends Error {
186
+ /**
187
+ * @param {string} message - 错误消息(通常来自 API 响应)
188
+ * @param {number} statusCode - HTTP 状态码
189
+ * @param {any} originalError - 原始错误对象或相关信息
190
+ * @param {string} responseText - 原始响应文本(如果有)
191
+ */
192
+ constructor(message, statusCode, originalError, responseText) {
193
+ super(message);
194
+ this.name = "APIError";
195
+ this.statusCode = statusCode;
196
+ this.originalError = originalError;
197
+ this.responseText = responseText;
198
+ }
199
+ };
200
+ var NetworkError = class extends Error {
201
+ /**
202
+ * @param {string} message - 错误消息
203
+ * @param {any} originalError - 原始错误对象或相关信息
204
+ */
205
+ constructor(message, originalError) {
206
+ super(message);
207
+ this.name = "NetworkError";
208
+ this.originalError = originalError;
209
+ }
210
+ };
211
+ var ConfigurationError = class extends Error {
212
+ /**
213
+ * @param {string} message - 错误消息
214
+ */
215
+ constructor(message) {
216
+ super(message);
217
+ this.name = "ConfigurationError";
218
+ }
219
+ };
220
+ var ValidationError = class extends ConfigurationError {
221
+ /**
222
+ * @param {string} message - 错误消息
223
+ */
224
+ constructor(message) {
225
+ super(message);
226
+ this.name = "ValidationError";
227
+ }
228
+ };
229
+ var ParsingError = class extends Error {
230
+ /**
231
+ * @param {string} message - 错误消息
232
+ * @param {any} originalError - 原始错误对象或相关信息
233
+ * @param {string} responseText - 原始响应文本(如果有)
234
+ **/
235
+ constructor(message, originalError, responseText) {
236
+ super(message);
237
+ this.name = "ParsingError";
238
+ this.originalError = originalError;
239
+ this.responseText = responseText;
240
+ }
241
+ };
242
+ //#endregion
161
243
  //#region src/core/SystemPromptStore.js
162
244
  /**
163
245
  * SystemPromptStore — 系统提示词存储
@@ -185,7 +267,7 @@
185
267
  * @returns {Object} 添加的记录
186
268
  */
187
269
  add(content, enabled = true) {
188
- if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
270
+ if (!content || typeof content !== "string" || !content.trim()) throw new ValidationError("[SystemPromptStore] content 必须是非空字符串");
189
271
  const record = {
190
272
  id: `sys_${Date.now()}_${++this._idCounter}`,
191
273
  content: content.trim(),
@@ -201,7 +283,7 @@
201
283
  * @returns {Object} 被删除的记录
202
284
  */
203
285
  remove(index) {
204
- if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
286
+ if (index < 0 || index >= this._prompts.length) throw new ValidationError(`[SystemPromptStore] 索引越界: ${index}`);
205
287
  return this._prompts.splice(index, 1)[0];
206
288
  }
207
289
  /**
@@ -210,7 +292,7 @@
210
292
  * @returns {boolean} 切换后的状态
211
293
  */
212
294
  toggle(index) {
213
- if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
295
+ if (index < 0 || index >= this._prompts.length) throw new ValidationError(`[SystemPromptStore] 索引越界: ${index}`);
214
296
  this._prompts[index].enabled = !this._prompts[index].enabled;
215
297
  return this._prompts[index].enabled;
216
298
  }
@@ -220,8 +302,8 @@
220
302
  * @param {string} content
221
303
  */
222
304
  update(index, content) {
223
- if (index < 0 || index >= this._prompts.length) throw new Error(`[SystemPromptStore] 索引越界: ${index}`);
224
- if (!content || typeof content !== "string" || !content.trim()) throw new Error("[SystemPromptStore] content 必须是非空字符串");
305
+ if (index < 0 || index >= this._prompts.length) throw new ValidationError(`[SystemPromptStore] 索引越界: ${index}`);
306
+ if (!content || typeof content !== "string" || !content.trim()) throw new ValidationError("[SystemPromptStore] content 必须是非空字符串");
225
307
  this._prompts[index].content = content.trim();
226
308
  this._prompts[index].timestamp = Date.now();
227
309
  }
@@ -258,151 +340,337 @@
258
340
  }
259
341
  };
260
342
  //#endregion
261
- //#region src/core/Errors.js
343
+ //#region src/core/Pipeline.js
262
344
  /**
263
- * 自定义错误类
264
- * 用于区分不同类型的错误,方便用户通过 `error.name` 或 `instanceof` 处理
345
+ * Pipeline —— 极简顺序管道(v3.0 提案 · 阶段 1)
346
+ *
347
+ * 三个概念(对照 pipeline-demo.html):
348
+ * - 小车 ctx —— 本次请求的全部"状态",车间之间只通过它交接
349
+ * - 车间 stage —— { name, run(ctx) },只干一件事,不认别的车间
350
+ * - 调度 run() —— for + await,顺序执行(线性,无"回程";洋葱能力留给阶段 2 的 after 车间)
265
351
  */
266
- var APIError = class extends Error {
267
- /**
268
- * @param {string} message - 错误消息(通常来自 API 响应)
269
- * @param {number} statusCode - HTTP 状态码
270
- * @param {any} originalError - 原始错误对象或相关信息
271
- * @param {string} responseText - 原始响应文本(如果有)
272
- */
273
- constructor(message, statusCode, originalError, responseText) {
274
- super(message);
275
- this.name = "APIError";
276
- this.statusCode = statusCode;
277
- this.originalError = originalError;
278
- this.responseText = responseText;
352
+ var Pipeline = class {
353
+ constructor() {
354
+ this._stages = [];
279
355
  }
280
- };
281
- var NetworkError = class extends Error {
282
356
  /**
283
- * @param {string} message - 错误消息
284
- * @param {any} originalError - 原始错误对象或相关信息
357
+ * 注册一个车间(追加到末尾)。
358
+ * @param {{name: string, run: (ctx: object) => void | Promise<void>}} stage
359
+ * @returns {Pipeline} this,支持链式
285
360
  */
286
- constructor(message, originalError) {
287
- super(message);
288
- this.name = "NetworkError";
289
- this.originalError = originalError;
361
+ register(stage) {
362
+ if (!stage || typeof stage.run !== "function") throw new TypeError("Pipeline.register: stage 需要 { name, run(ctx) },运行 run 必须是函数");
363
+ this._stages.push(stage);
364
+ return this;
290
365
  }
291
- };
292
- var ConfigurationError = class extends Error {
293
- /**
294
- * @param {string} message - 错误消息
295
- */
296
- constructor(message) {
297
- super(message);
298
- this.name = "ConfigurationError";
366
+ /** 按名字移除车间(移除不存在的名字是安全的) */
367
+ unregister(name) {
368
+ this._stages = this._stages.filter((s) => s.name !== name);
369
+ return this;
299
370
  }
300
- };
301
- var ParsingError = class extends Error {
302
- /**
303
- * @param {string} message - 错误消息
304
- * @param {any} originalError - 原始错误对象或相关信息
305
- * @param {string} responseText - 原始响应文本(如果有)
306
- **/
307
- constructor(message, originalError, responseText) {
308
- super(message);
309
- this.name = "ParsingError";
310
- this.originalError = originalError;
311
- this.responseText = responseText;
371
+ /** 列出当前车间名(调试用) */
372
+ names() {
373
+ return this._stages.map((s) => s.name);
374
+ }
375
+ /** 把小车开过所有车间;返回 ctx(车间可改 ctx 上的字段) */
376
+ async run(ctx) {
377
+ for (const stage of this._stages) await stage.run(ctx);
378
+ return ctx;
312
379
  }
313
380
  };
314
381
  //#endregion
315
382
  //#region src/core/ChatService.js
383
+ /**
384
+ * @typedef {Object} ChatAdapter 适配器协议(v3.0:写同级适配器只需实现这 4+1 个方法)
385
+ * @property {Function} buildRequest (messages, config, systemPrompts) => requestBody
386
+ * @property {Function} send (body, config, opts) => Promise<apiResponse>
387
+ * @property {Function} stream (body, config, onProgress, onDone, opts) => Promise<void>
388
+ * @property {Function} parseResponse (apiResponse) => assistantMessage
389
+ * @property {Function} [getRequestDefaults] () => 默认请求参数(可选)
390
+ * @property {Function} [install] (chatService, options) 插件式安装(可选)
391
+ */
392
+ /**
393
+ * @typedef {Object} PipelineContext 管道小车 ctx(public pipe 车间可见/可改的全部字段)
394
+ * @property {Object} options 原始请求选项
395
+ * @property {*} userInput 用户输入(可为 undefined)
396
+ * @property {boolean} addUser 是否已新增/将新增用户消息
397
+ * @property {MessageStore} messages 消息列表(可读可改:push / unshift / update)
398
+ * @property {SystemPromptStore} systemPrompts 系统提示词(可读可改)
399
+ * @property {Object} config 合并后的请求级配置(prepareInput 后生效)
400
+ * @property {boolean} isStream 本次是否流式
401
+ * @property {Function|null} onProgress 流式进度回调
402
+ * @property {Function|null} onDone 流式完成回调
403
+ * @property {string|null} mergeToEntry 续写目标 id(null = 普通发送)
404
+ * @property {*} body 请求体(buildRequest 后产出)
405
+ * @property {*} result 最终结果(send 后产出)
406
+ */
407
+ /**
408
+ * @typedef {Object} PipeStage 车间(v3.0 公开扩展单元)
409
+ * @property {string} name 车间名(唯一,不能与内部车间重名)
410
+ * @property {string} [phase] 'beforeSend'(默认)| 'afterSend'
411
+ * @property {Function} run (ctx: PipelineContext) => void | Promise<void>
412
+ */
413
+ var SESSION_CONFIG_KEYS = [
414
+ "model",
415
+ "temperature",
416
+ "maxTokens",
417
+ "modelParams",
418
+ "system",
419
+ "retry"
420
+ ];
421
+ var INTERNAL_STAGES = [
422
+ "prepareInput",
423
+ "beforeSend",
424
+ "autoContinue",
425
+ "buildRequest",
426
+ "send"
427
+ ];
316
428
  var ChatService = class extends EventEmitter {
317
429
  constructor(config = {}) {
318
430
  super();
319
431
  this.config = { ...config };
320
- this.messages = new MessageStore();
432
+ if (config.store) {
433
+ if (typeof config.store.getAll !== "function" || typeof config.store.add !== "function") throw new ValidationError("store 必须实现 MessageStore 的接口(至少 getAll / add / update)");
434
+ this.messages = config.store;
435
+ } else this.messages = new MessageStore();
321
436
  this.systemPrompts = new SystemPromptStore();
322
437
  this._adapter = null;
323
- this._abortController = null;
324
- this._isGenerating = false;
325
- this._hooks = new EventEmitter();
326
- this._processResponse = null;
438
+ this._activeRequests = /* @__PURE__ */ new Map();
439
+ this._requestSeq = 0;
327
440
  const model = this.config.model || this.config.modelParams?.model;
328
441
  if (!model || typeof model !== "string" || !model.trim()) throw new ConfigurationError("缺少 model 配置");
329
- const temperature = this.config.modelParams?.temperature ?? this.config.temperature;
442
+ this._assertValidConfig(this.config);
443
+ if (typeof config.system === "string" && config.system.trim()) this.systemPrompts.set(config.system);
444
+ if (config.adapter) this.setAdapter(config.adapter);
445
+ this._userStages = [];
446
+ this._stageOverrides = /* @__PURE__ */ new Map();
447
+ this._disabledStages = /* @__PURE__ */ new Set();
448
+ this._extraConfigKeys = /* @__PURE__ */ new Map();
449
+ this.plugins = {};
450
+ this._pipeline = this._buildPipeline();
451
+ }
452
+ /**
453
+ * 校验配置中的可校验字段(model 必填由构造器负责,这里只校验存在性)
454
+ * @throws {ConfigurationError}
455
+ */
456
+ _assertValidConfig(cfg) {
457
+ const temperature = cfg.modelParams?.temperature ?? cfg.temperature;
330
458
  if (temperature !== void 0 && (typeof temperature !== "number" || temperature < 0 || temperature > 2)) throw new ConfigurationError(`temperature 必须在 0-2 之间,当前值: ${temperature}`);
331
- const maxTokens = this.config.modelParams?.maxTokens ?? this.config.maxTokens;
459
+ const maxTokens = cfg.modelParams?.maxTokens ?? cfg.maxTokens;
332
460
  if (maxTokens !== void 0 && (typeof maxTokens !== "number" || maxTokens < 1 || !Number.isInteger(maxTokens))) throw new ConfigurationError(`maxTokens 必须为正整数,当前值: ${maxTokens}`);
333
- if (typeof config.system === "string" && config.system.trim()) this.systemPrompts.set(config.system);
461
+ const model = cfg.model ?? cfg.modelParams?.model;
462
+ if (model !== void 0 && (typeof model !== "string" || !model.trim())) throw new ConfigurationError("model 必须是非空字符串");
334
463
  }
335
- use(plugin) {
336
- plugin.install(this);
464
+ /**
465
+ * 安装插件。
466
+ * - 插件实现 `install(chat, options)`
467
+ * - 若 install 返回一个对象,会挂到 **`chat.plugins[plugin.name]`**(v4.0 命名空间,插件之间不会撞名)
468
+ * - 插件要提供卸载时,自己在返回值里带 `uninstall()`(或调用 `plugin.uninstall(chat)`)
469
+ * @returns {ChatService} this
470
+ */
471
+ use(plugin, options = {}) {
472
+ const api = plugin.install(this, options);
473
+ if (plugin.name && api && typeof api === "object") this.plugins[plugin.name] = api;
337
474
  return this;
338
475
  }
339
- setAdapter(adapter) {
340
- this._adapter = adapter;
476
+ /**
477
+ * 往请求管道里挂一个"车间"。
478
+ * - phase 'beforeSend'(默认):在内部 beforeRequest 钩子之后、构建请求体之前执行
479
+ * - phase 'afterSend' :在内部发送(流式/非流式)完成、结果落位之后执行(可改 ctx.result)
480
+ * 不注册任何车间 = 行为与版本 2.8.x 完全一致。
481
+ * @param {PipeStage} stage
482
+ * @returns {ChatService} this
483
+ * @throws {ConfigurationError} 参数非法 / 名字被占用 / 与内部车间重名
484
+ */
485
+ pipe(stage) {
486
+ if (!stage || typeof stage !== "object" || typeof stage.run !== "function") throw new ConfigurationError("pipe: 需要 { name, phase?, run(ctx) },run 必须是函数");
487
+ if (typeof stage.name !== "string" || !stage.name.trim()) throw new ConfigurationError("pipe: 需要 name(车间名,非空字符串)");
488
+ if (INTERNAL_STAGES.includes(stage.name)) throw new ConfigurationError(`pipe: "${stage.name}" 是内部车间名,请换一个名字`);
489
+ if (this._userStages.some((s) => s.name === stage.name)) throw new ConfigurationError(`pipe: 车间 "${stage.name}" 已存在,请先 chat.unpipe("${stage.name}")`);
490
+ const phase = stage.phase === "afterSend" ? "afterSend" : "beforeSend";
491
+ this._userStages.push({
492
+ name: stage.name,
493
+ phase,
494
+ run: stage.run
495
+ });
496
+ this._rebuildPipeline();
497
+ return this;
341
498
  }
342
- abort() {
343
- if (this._abortController) this._abortController.abort();
499
+ /** 移除一个用户车间(移除不存在的名字是安全的)。@returns {ChatService} this */
500
+ unpipe(name) {
501
+ const before = this._userStages.length;
502
+ this._userStages = this._userStages.filter((s) => s.name !== name);
503
+ if (this._userStages.length !== before) this._rebuildPipeline();
504
+ return this;
344
505
  }
345
- get isGenerating() {
346
- return this._isGenerating;
506
+ /** 查看当前管道里所有车间名(调试/说明用,含内部车间) */
507
+ get pipelineStages() {
508
+ return this._pipeline.names();
347
509
  }
348
- async continueLast() {
349
- const target = this._prepareContinue();
350
- this.messages.update(target.id, { prefix: true });
351
- try {
352
- await this._request({
353
- addUser: false,
354
- isStream: false,
355
- mergeToEntry: target.id
510
+ /** 内部步骤名(顺序即执行顺序):prepareInput / beforeSend / autoContinue / buildRequest / send */
511
+ get internalStages() {
512
+ return [...INTERNAL_STAGES];
513
+ }
514
+ /** 内部步骤的默认实现表 */
515
+ _defaultStageRuns() {
516
+ return {
517
+ prepareInput: (ctx) => this._stagePrepareInput(ctx),
518
+ beforeSend: (ctx) => this._stageBeforeSend(ctx),
519
+ autoContinue: (ctx) => this._stageAutoContinue(ctx),
520
+ buildRequest: (ctx) => this._stageBuildRequest(ctx),
521
+ send: (ctx) => this._stageSend(ctx)
522
+ };
523
+ }
524
+ /**
525
+ * 用你自己的实现**顶替**某个内部步骤。框架不再执行该步的默认行为。
526
+ * 例:`chat.replaceStage('send', async (ctx) => { ctx.result = await 我的发送(ctx.body) })`
527
+ * 想"包一层"默认实现:先 `const base = chat.getStage('send')`,再在自己的函数里调用它。
528
+ * @param {string} name 步骤名(见 internalStages)
529
+ * @param {Function} run (ctx) => void | Promise<void>
530
+ * @throws {ConfigurationError} 步骤名未知 / run 不是函数
531
+ */
532
+ replaceStage(name, run) {
533
+ if (!INTERNAL_STAGES.includes(name)) throw new ConfigurationError(`replaceStage: 未知的内部步骤 "${name}"。可选: ${INTERNAL_STAGES.join(", ")}`);
534
+ if (typeof run !== "function") throw new ConfigurationError("replaceStage: 第二个参数必须是函数 (ctx) => void | Promise<void>");
535
+ this._stageOverrides.set(name, run);
536
+ this._rebuildPipeline();
537
+ return this;
538
+ }
539
+ /** 撤销替换,恢复该步骤的默认实现(不影响 unstage 的关闭状态) */
540
+ restoreStage(name) {
541
+ if (!INTERNAL_STAGES.includes(name)) throw new ConfigurationError(`restoreStage: 未知的内部步骤 "${name}"。可选: ${INTERNAL_STAGES.join(", ")}`);
542
+ this._stageOverrides.delete(name);
543
+ this._rebuildPipeline();
544
+ return this;
545
+ }
546
+ /**
547
+ * **关闭**某个内部步骤(从管道里移除,不再执行)。
548
+ * 例:`chat.unstage('autoContinue')` —— 彻底不要"自动续写检测"这一步。
549
+ * 警告:关闭 prepareInput / buildRequest / send 会让流程失去必要产物(如 ctx.body)。
550
+ */
551
+ unstage(name) {
552
+ if (!INTERNAL_STAGES.includes(name)) throw new ConfigurationError(`unstage: 未知的内部步骤 "${name}"。可选: ${INTERNAL_STAGES.join(", ")}`);
553
+ this._disabledStages.add(name);
554
+ this._rebuildPipeline();
555
+ return this;
556
+ }
557
+ /** 重新启用被 unstage 关闭的步骤 */
558
+ restage(name) {
559
+ if (!INTERNAL_STAGES.includes(name)) throw new ConfigurationError(`restage: 未知的内部步骤 "${name}"。可选: ${INTERNAL_STAGES.join(", ")}`);
560
+ this._disabledStages.delete(name);
561
+ this._rebuildPipeline();
562
+ return this;
563
+ }
564
+ /** 取得某个内部步骤的默认实现(用于"包一层":做自己的事,再调用它) */
565
+ getStage(name) {
566
+ if (!INTERNAL_STAGES.includes(name)) throw new ConfigurationError(`getStage: 未知的内部步骤 "${name}"。可选: ${INTERNAL_STAGES.join(", ")}`);
567
+ return this._defaultStageRuns()[name];
568
+ }
569
+ /**
570
+ * 重建内部管道:内部步骤(可被 replaceStage 顶替 / 被 unstage 关闭)+ 用户车间按 phase 插入
571
+ * 顺序:prepareInput → beforeSend → [用户 beforeSend 车间] → autoContinue → buildRequest → send → [用户 afterSend 车间]
572
+ */
573
+ _buildPipeline() {
574
+ const p = new Pipeline();
575
+ const defaults = this._defaultStageRuns();
576
+ const insertUsers = (phase) => {
577
+ for (const s of this._userStages) if (s.phase === phase) p.register({
578
+ name: s.name,
579
+ run: (ctx) => s.run(ctx)
356
580
  });
357
- this.messages.update(target.id, {
358
- _complete: true,
359
- prefix: void 0,
360
- _ephemeral: void 0
581
+ };
582
+ for (const name of INTERNAL_STAGES) {
583
+ if (!this._disabledStages.has(name)) p.register({
584
+ name,
585
+ run: this._stageOverrides.get(name) || defaults[name]
361
586
  });
362
- return target;
363
- } catch (err) {
364
- this.messages.update(target.id, { prefix: void 0 });
365
- throw err;
587
+ if (name === "beforeSend") insertUsers("beforeSend");
588
+ if (name === "send") insertUsers("afterSend");
366
589
  }
590
+ return p;
367
591
  }
368
- async continueLastStream(onProgress, onDone) {
369
- const target = this._prepareContinue();
370
- console.log("[DEBUG] continueLastStream target.id:", target.id);
371
- this.messages.update(target.id, { prefix: true });
372
- const baseLen = (target.content || "").length;
373
- try {
374
- await this._request({
375
- addUser: false,
376
- isStream: true,
377
- mergeToEntry: target.id,
378
- onProgress: (chunk) => {
379
- if (onProgress) onProgress({
380
- ...chunk,
381
- content: (chunk.content || "").slice(baseLen)
382
- });
383
- },
384
- onDone: (final) => {
385
- if (onDone) onDone(final);
386
- }
387
- });
388
- this.messages.update(target.id, {
389
- _complete: true,
390
- prefix: void 0,
391
- _ephemeral: void 0
392
- });
393
- return target;
394
- } catch (err) {
395
- this.messages.update(target.id, { prefix: void 0 });
396
- throw err;
592
+ _rebuildPipeline() {
593
+ this._pipeline = this._buildPipeline();
594
+ }
595
+ setAdapter(adapter) {
596
+ assertAdapter(adapter);
597
+ this._adapter = adapter;
598
+ }
599
+ /**
600
+ * 中断请求(v4.0:按请求隔离)。
601
+ * - 不传参数:中断**所有**活跃请求(旧版只会中断"最后一个",多请求时会中断错的那个)
602
+ * - 传 requestId:只中断那一个(id 见 `chat.activeRequests`)
603
+ */
604
+ abort(requestId) {
605
+ if (requestId) {
606
+ const controller = this._activeRequests.get(requestId);
607
+ if (controller) controller.abort();
608
+ return;
609
+ }
610
+ for (const controller of this._activeRequests.values()) controller.abort();
611
+ }
612
+ /** 是否有请求正在生成中 */
613
+ get isGenerating() {
614
+ return this._activeRequests.size > 0;
615
+ }
616
+ /** 当前活跃请求的 id 列表(调试 / 精确中断用) */
617
+ get activeRequests() {
618
+ return [...this._activeRequests.keys()];
619
+ }
620
+ /** 内部:登记一个请求,返回 { id, signal } */
621
+ _beginRequest() {
622
+ const id = "req_" + ++this._requestSeq;
623
+ const controller = new AbortController();
624
+ this._activeRequests.set(id, controller);
625
+ return {
626
+ id,
627
+ signal: controller.signal
628
+ };
629
+ }
630
+ /** 内部:注销一个请求 */
631
+ _endRequest(id) {
632
+ this._activeRequests.delete(id);
633
+ }
634
+ /**
635
+ * 注册"运行时可改的配置字段"(v4.0)。
636
+ * 让插件自带配置(如 continuation 的 autoContinue)不必回头改核心白名单。
637
+ * @param {string[]|Object<string, Function>} keys 字段名数组,或 { 字段名: 校验器(value)=>boolean }
638
+ * @returns {ChatService} this
639
+ * @throws {ConfigurationError} 字段名非法 / 校验器不是函数
640
+ */
641
+ registerConfigKeys(keys) {
642
+ const entries = Array.isArray(keys) ? keys.map((k) => [k, null]) : Object.entries(keys || {});
643
+ for (const [key, validator] of entries) {
644
+ if (typeof key !== "string" || !key.trim()) throw new ConfigurationError("registerConfigKeys: 字段名必须是非空字符串");
645
+ if (validator != null && typeof validator !== "function") throw new ConfigurationError(`registerConfigKeys: "${key}" 的校验器必须是函数`);
646
+ this._extraConfigKeys.set(key.trim(), validator || null);
397
647
  }
648
+ return this;
649
+ }
650
+ /** 注销运行时可改字段(插件卸载时调用)@returns {ChatService} this */
651
+ unregisterConfigKeys(keys) {
652
+ for (const k of Array.isArray(keys) ? keys : [keys]) this._extraConfigKeys.delete(k);
653
+ return this;
398
654
  }
399
- _prepareContinue() {
400
- const msgs = this.messages.getAll();
401
- const last = msgs[msgs.length - 1];
402
- if (last && (last.role === "assistant" || last._ephemeral)) return last;
403
- throw new Error("最后一条消息不是 assistant,无法续写");
655
+ /** 当前允许在运行时修改的配置字段(内置基础字段 + 插件注册) */
656
+ get configKeys() {
657
+ return [...SESSION_CONFIG_KEYS, ...this._extraConfigKeys.keys()];
404
658
  }
659
+ /**
660
+ * 运行时修改配置(仅"可改字段":内置基础字段 + 插件注册字段)。
661
+ *
662
+ * - 运输层(apiKey/baseUrl/headers):归适配器,要改就换适配器实例
663
+ * - 请求参数默认值:走适配器工厂 options 或请求级覆盖(chat.send(x, params))
664
+ * - 插件自有配置:插件用 `registerConfigKeys` 登记后才可改(工厂 options 仍是首选)
665
+ *
666
+ * 与构造器一样经过校验,不能注入非法值。
667
+ * @throws {ConfigurationError} 非白名单字段、非法值、或插件校验器拒绝
668
+ */
405
669
  updateConfig(partial) {
670
+ const allowed = this.configKeys;
671
+ for (const key of Object.keys(partial)) if (!allowed.includes(key)) throw new ConfigurationError(`updateConfig 不支持修改 "${key}"。允许的字段: ${allowed.join(", ")}`);
672
+ this._assertValidConfig(partial);
673
+ for (const [key, validator] of this._extraConfigKeys) if (validator && key in partial && validator(partial[key]) === false) throw new ConfigurationError(`updateConfig: 字段 "${key}" 的值不合法: ${JSON.stringify(partial[key])}`);
406
674
  Object.assign(this.config, partial);
407
675
  if (typeof partial.system === "string") this.systemPrompts.set(partial.system);
408
676
  this.emit("config-updated", {
@@ -410,36 +678,73 @@
410
678
  timestamp: Date.now()
411
679
  });
412
680
  }
413
- async _request(options) {
414
- let { userInput, addUser = true, isStream = false, onProgress, onDone, mergeToEntry } = options;
415
- this.emit("sending", {
416
- addUser,
417
- userInput,
418
- timestamp: Date.now()
419
- });
420
- this._addUserMessage(userInput, addUser);
421
- await this._hooks.emitAsync("beforeRequest", {
422
- messages: this.messages,
423
- config: this.config,
424
- options
425
- });
426
- if (this.config.ephemeralContinue && !mergeToEntry) {
427
- const msgs = this.messages.getAll();
428
- const last = msgs[msgs.length - 1];
429
- if (last && last.prefix && (last.role === "assistant" || last._ephemeral)) mergeToEntry = last.id;
681
+ /**
682
+ * 合并请求参数(近者优先):
683
+ * 适配器默认(getRequestDefaults) ← 会话配置(this.config) ← 本次覆盖(params)
684
+ * modelParams 深层合并;平铺便捷键(temperature/maxTokens/reasoningEffort)自动折叠进 modelParams
685
+ */
686
+ _mergeRequestConfig(params = {}) {
687
+ const adapterDefaults = this._adapter?.getRequestDefaults?.() || {};
688
+ const requestConfig = {
689
+ ...adapterDefaults,
690
+ ...this.config,
691
+ ...params
692
+ };
693
+ const modelParams = {
694
+ ...adapterDefaults.modelParams || {},
695
+ ...this.config.modelParams || {},
696
+ ...params.modelParams || {}
697
+ };
698
+ for (const key of [
699
+ "temperature",
700
+ "maxTokens",
701
+ "reasoningEffort"
702
+ ]) {
703
+ const value = params[key] ?? this.config[key] ?? adapterDefaults[key];
704
+ if (value !== void 0) modelParams[key] = value;
430
705
  }
431
- const body = this._adapter.buildRequest(this.messages.getAll(), this.config, this.systemPrompts.getEnabled());
432
- const retryCfg = this.config.retry || {};
706
+ requestConfig.modelParams = modelParams;
707
+ return requestConfig;
708
+ }
709
+ /**
710
+ * 内部调度(v3.0 提案 · 阶段 1):造一辆小车 ctx,开过内部管道,返回结果。
711
+ * 行为与旧版 _request 完全一致,只是把固定线拆成了车间(见 _stage* 方法)。
712
+ *
713
+ * ctx 字段(车间可见):
714
+ * options —— 原始请求选项
715
+ * userInput —— 用户输入
716
+ * addUser —— 是否新增用户消息
717
+ * messages —— MessageStore(可读可改)
718
+ * systemPrompts —— SystemPromptStore
719
+ * config —— 合并后的请求级配置(prepareInput 车间产出)
720
+ * isStream —— 本次是否流式
721
+ * onProgress —— 流式进度回调(可为 null)
722
+ * onDone —— 流式完成回调(可为 null)
723
+ * mergeToEntry —— 续写目标 id(空 = 普通发送)
724
+ * body —— adapter 构建出的请求体(buildRequest 车间产出)
725
+ * result —— 最终结果(send 车间产出)
726
+ */
727
+ async _request(options = {}) {
728
+ const ctx = {
729
+ options,
730
+ userInput: options.userInput,
731
+ addUser: options.addUser !== false,
732
+ messages: this.messages,
733
+ systemPrompts: this.systemPrompts,
734
+ config: null,
735
+ isStream: !!options.isStream,
736
+ onProgress: options.onProgress || null,
737
+ onDone: options.onDone || null,
738
+ mergeToEntry: options.mergeToEntry || null,
739
+ signal: options.signal || null,
740
+ body: null,
741
+ result: null
742
+ };
433
743
  try {
434
- return await this._withRetry(body, {
435
- isStream,
436
- onProgress,
437
- onDone,
438
- mergeToEntry,
439
- maxRetries: retryCfg.maxRetries ?? 0,
440
- retryDelay: retryCfg.retryDelay ?? 1e3
441
- });
744
+ await this._pipeline.run(ctx);
745
+ return ctx.result;
442
746
  } catch (error) {
747
+ if (error.name === "AbortError") throw error;
443
748
  this.emit("error", {
444
749
  error,
445
750
  timestamp: Date.now()
@@ -447,6 +752,47 @@
447
752
  throw error;
448
753
  }
449
754
  }
755
+ /** 车间 1:加用户消息 → 合并请求参数 → 广播 sending */
756
+ async _stagePrepareInput(ctx) {
757
+ this._addUserMessage(ctx.userInput, ctx.addUser);
758
+ ctx.config = this._mergeRequestConfig(ctx.options.params);
759
+ this.emit("sending", {
760
+ addUser: ctx.addUser,
761
+ userInput: ctx.userInput,
762
+ timestamp: Date.now()
763
+ });
764
+ }
765
+ /**
766
+ * 车间 2:发送前 —— **v4.0 起默认什么都不做**。
767
+ * 需要在这里做事的(注入、改写消息/配置):`chat.replaceStage('beforeSend', fn)`
768
+ * 或挂一个 `chat.pipe({ phase: 'beforeSend' })` 车间(在它之后执行)。
769
+ * 旧的 `_hooks.on('beforeRequest')` 兼容桥已于 v4.0 移除。
770
+ */
771
+ async _stageBeforeSend(ctx) {}
772
+ /**
773
+ * 车间 3:自动续写检测 —— **v4.0 起默认什么都不做**。
774
+ * 续写是玩法:需要它的装上 continuation 插件,由插件 replaceStage('autoContinue', ...) 接管。
775
+ * 步骤名与位置保留,方便插件替换、也方便使用者 `unstage('autoContinue')` 明确移除。
776
+ */
777
+ async _stageAutoContinue(ctx) {}
778
+ /** 车间 4:构建请求体 */
779
+ async _stageBuildRequest(ctx) {
780
+ ctx.body = this._adapter.buildRequest(ctx.messages.getAll(), ctx.config, ctx.systemPrompts.getEnabled());
781
+ }
782
+ /** 车间 5:发送(流式/非流式 + 重试 + 占位消息 + _processResponse 工具钩子) */
783
+ async _stageSend(ctx) {
784
+ const retryCfg = this.config.retry || {};
785
+ ctx.result = await this._withRetry(ctx.body, {
786
+ isStream: ctx.isStream,
787
+ onProgress: ctx.onProgress,
788
+ onDone: ctx.onDone,
789
+ mergeToEntry: ctx.mergeToEntry,
790
+ config: ctx.config,
791
+ maxRetries: retryCfg.maxRetries ?? 0,
792
+ retryDelay: retryCfg.retryDelay ?? 1e3,
793
+ signal: ctx.signal
794
+ });
795
+ }
450
796
  _addUserMessage(userInput, addUser) {
451
797
  if (addUser && userInput !== void 0) {
452
798
  const msg = typeof userInput === "string" ? {
@@ -460,9 +806,9 @@
460
806
  }
461
807
  }
462
808
  /** retry 循环,占位消息只 push 一次 */
463
- async _withRetry(body, { isStream, onProgress, onDone, mergeToEntry, maxRetries, retryDelay }) {
809
+ async _withRetry(body, { isStream, onProgress, onDone, mergeToEntry, config, maxRetries, retryDelay, signal }) {
464
810
  let lastError = null;
465
- const adapterOptions = { signal: this._abortController?.signal };
811
+ const adapterOptions = { signal };
466
812
  let placeholder = null;
467
813
  let base = null;
468
814
  if (isStream) {
@@ -490,54 +836,53 @@
490
836
  await new Promise((r) => setTimeout(r, retryDelay));
491
837
  }
492
838
  try {
493
- this._isGenerating = true;
494
839
  if (isStream) return await this._stream(body, adapterOptions, {
495
840
  placeholder,
496
841
  base,
497
842
  mergeToEntry,
498
843
  onProgress,
499
- onDone
844
+ onDone,
845
+ config
500
846
  });
501
847
  else {
502
- const resp = await this._adapter.send(body, this.config, adapterOptions);
503
- let result = this._handleResult(this._adapter.parseResponse(resp), mergeToEntry);
504
- if (this._processResponse && !mergeToEntry) result = await this._processResponse(result, { isStream: false });
505
- return result;
848
+ const resp = await this._adapter.send(body, config, adapterOptions);
849
+ return this._handleResult(this._adapter.parseResponse(resp), mergeToEntry);
506
850
  }
507
851
  } catch (error) {
508
852
  lastError = error;
509
- if (error.name === "AbortError" || this._abortController?.signal.aborted) {
510
- this._isGenerating = false;
511
- throw error;
512
- }
853
+ if (error.name === "AbortError" || signal?.aborted) throw error;
513
854
  if (error instanceof NetworkError && attempt < maxRetries) continue;
514
- this._isGenerating = false;
515
855
  throw error;
516
856
  }
517
857
  }
518
- this._isGenerating = false;
519
858
  throw lastError;
520
859
  }
521
- /** 流式:ChatService 维护占位,adapter 只管解析 */
522
- async _stream(body, adapterOptions, { placeholder, base, mergeToEntry, onProgress, onDone }) {
860
+ /**
861
+ * 流式处理:ChatService 维护占位消息,adapter 只负责解析 SSE
862
+ *
863
+ * 参数说明:
864
+ * - placeholder:流式期间实时更新的目标消息(续写时 = target 本身,普通发送时 = 新建的空消息)
865
+ * - base:续写时保存的旧内容快照,用于和 API 新内容拼接
866
+ * - mergeToEntry:续写目标的 id,有值时走续写逻辑
867
+ * - onProgress:外部回调,每收到一个 chunk 触发
868
+ * - onDone:流结束回调
869
+ */
870
+ async _stream(body, adapterOptions, { placeholder, base, mergeToEntry, onProgress, onDone, config }) {
523
871
  let finalMsg = null;
524
- await this._adapter.stream(body, this.config, (snap) => {
525
- placeholder.content = snap.content || "";
526
- if (snap.reasoningContent) placeholder.reasoningContent = snap.reasoningContent;
872
+ await this._adapter.stream(body, config, (snap, delta) => {
873
+ placeholder.content = mergeToEntry && base ? base.content + (snap.content || "") : snap.content || "";
874
+ if (snap.reasoningContent) placeholder.reasoningContent = mergeToEntry && base ? base.reasoning + snap.reasoningContent : snap.reasoningContent;
527
875
  if (snap.toolCalls) placeholder.toolCalls = [...snap.toolCalls];
528
876
  this.emit("stream-progress", snap);
529
- if (onProgress) onProgress(snap);
877
+ if (onProgress) onProgress(snap, delta);
530
878
  }, async (final) => {
531
879
  finalMsg = final;
532
- if (this._processResponse && !mergeToEntry) finalMsg = await this._processResponse(finalMsg, {
533
- isStream: true,
534
- onProgress,
535
- onDone
536
- });
537
880
  if (mergeToEntry && base) {
538
881
  const changes = {
539
882
  content: base.content + (final.content || ""),
540
- _complete: true
883
+ _complete: true,
884
+ _ephemeral: false,
885
+ prefix: void 0
541
886
  };
542
887
  if (final.reasoningContent) changes.reasoningContent = base.reasoning + final.reasoningContent;
543
888
  if (final.toolCalls) changes.toolCalls = final.toolCalls;
@@ -564,7 +909,9 @@
564
909
  }
565
910
  const changes = {
566
911
  content: (entry.content || "") + (assistantMsg.content || ""),
567
- _complete: true
912
+ _complete: true,
913
+ _ephemeral: false,
914
+ prefix: void 0
568
915
  };
569
916
  if (assistantMsg.reasoningContent) changes.reasoningContent = (entry.reasoningContent || "") + assistantMsg.reasoningContent;
570
917
  if (assistantMsg.toolCalls) changes.toolCalls = assistantMsg.toolCalls;
@@ -577,61 +924,148 @@
577
924
  this.emit("message", assistantMsg);
578
925
  return assistantMsg;
579
926
  }
580
- async send(userInput) {
581
- this._abortController = new AbortController();
927
+ /**
928
+ * 发送消息。
929
+ * @param {string|Object} userInput - 用户输入
930
+ * @param {Object} [params] - 请求级参数覆盖(model/temperature/modelParams 等,仅本次生效)
931
+ */
932
+ async send(userInput, params) {
933
+ const { id, signal } = this._beginRequest();
582
934
  try {
583
935
  return await this._request({
584
936
  userInput,
585
937
  addUser: true,
586
- isStream: false
938
+ isStream: false,
939
+ params,
940
+ signal
587
941
  });
942
+ } catch (err) {
943
+ if (err.name === "AbortError") {
944
+ this.emit("aborted", { timestamp: Date.now() });
945
+ return;
946
+ }
947
+ throw err;
588
948
  } finally {
589
- this._abortController = null;
590
- this._isGenerating = false;
949
+ this._endRequest(id);
591
950
  }
592
951
  }
593
- async stream(userInput, onProgress, onDone) {
594
- this._abortController = new AbortController();
952
+ /**
953
+ * 流式发送。
954
+ * @param {string|Object} userInput - 用户输入
955
+ * @param {Object} [params] - 请求级参数覆盖(仅本次生效)
956
+ * @param {Function} [onProgress] - 流式进度回调
957
+ * @param {Function} [onDone] - 流式完成回调
958
+ */
959
+ async stream(userInput, params, onProgress, onDone) {
960
+ if (typeof params === "function") {
961
+ onDone = onProgress;
962
+ onProgress = params;
963
+ params = void 0;
964
+ }
965
+ const { id, signal } = this._beginRequest();
595
966
  try {
596
967
  return await this._request({
597
968
  userInput,
598
969
  addUser: true,
599
970
  isStream: true,
600
971
  onProgress,
601
- onDone
972
+ onDone,
973
+ params,
974
+ signal
602
975
  });
976
+ } catch (err) {
977
+ if (err.name === "AbortError") {
978
+ this.emit("aborted", { timestamp: Date.now() });
979
+ return;
980
+ }
981
+ throw err;
603
982
  } finally {
604
- this._abortController = null;
605
- this._isGenerating = false;
983
+ this._endRequest(id);
606
984
  }
607
985
  }
608
- async sendExisting() {
609
- this._abortController = new AbortController();
986
+ /**
987
+ * 重发当前消息(不加用户消息)。
988
+ * @param {Object} [params] - 请求级参数覆盖(仅本次生效)
989
+ * @param {Object} [options] - { mergeToEntry } 可选:把结果合并进指定的已有消息(续写等场景)
990
+ */
991
+ async sendExisting(params, options = {}) {
992
+ const mergeToEntry = options?.mergeToEntry || null;
993
+ const { id, signal } = this._beginRequest();
610
994
  try {
611
995
  return await this._request({
612
996
  addUser: false,
613
- isStream: false
997
+ isStream: false,
998
+ params,
999
+ mergeToEntry,
1000
+ signal
614
1001
  });
1002
+ } catch (err) {
1003
+ if (err.name === "AbortError") {
1004
+ this.emit("aborted", { timestamp: Date.now() });
1005
+ return;
1006
+ }
1007
+ throw err;
615
1008
  } finally {
616
- this._abortController = null;
617
- this._isGenerating = false;
1009
+ this._endRequest(id);
618
1010
  }
619
1011
  }
620
- async sendExistingStream(onProgress, onDone) {
621
- this._abortController = new AbortController();
1012
+ /**
1013
+ * 流式重发(不加用户消息)。
1014
+ * @param {Object} [params] - 请求级参数覆盖(仅本次生效)
1015
+ * @param {Object} [options] - { mergeToEntry } 可选:把结果合并进指定的已有消息
1016
+ * @param {Function} [onProgress] - 流式进度回调
1017
+ * @param {Function} [onDone] - 流式完成回调
1018
+ */
1019
+ async sendExistingStream(params, options, onProgress, onDone) {
1020
+ if (typeof params === "function") {
1021
+ onDone = options;
1022
+ onProgress = params;
1023
+ options = {};
1024
+ params = void 0;
1025
+ } else if (typeof options === "function") {
1026
+ onDone = onProgress;
1027
+ onProgress = options;
1028
+ options = {};
1029
+ }
1030
+ const mergeToEntry = options?.mergeToEntry || null;
1031
+ const { id, signal } = this._beginRequest();
622
1032
  try {
623
1033
  return await this._request({
624
1034
  addUser: false,
625
1035
  isStream: true,
626
1036
  onProgress,
627
- onDone
1037
+ onDone,
1038
+ params,
1039
+ mergeToEntry,
1040
+ signal
628
1041
  });
1042
+ } catch (err) {
1043
+ if (err.name === "AbortError") {
1044
+ this.emit("aborted", { timestamp: Date.now() });
1045
+ return;
1046
+ }
1047
+ throw err;
629
1048
  } finally {
630
- this._abortController = null;
631
- this._isGenerating = false;
1049
+ this._endRequest(id);
632
1050
  }
633
1051
  }
634
1052
  };
1053
+ /**
1054
+ * 校验 adapter 是否满足协议(v3.0 · 阶段 3)。
1055
+ * 缺少必要方法时抛 ConfigurationError,并列出缺少的方法名——写"同级适配器"不再靠猜。
1056
+ * @param {*} adapter
1057
+ * @throws {ConfigurationError}
1058
+ */
1059
+ function assertAdapter(adapter) {
1060
+ if (!adapter || typeof adapter !== "object") throw new ConfigurationError("setAdapter: adapter 必须是对象(如 openaiAdapter / createOpenAIAdapter() 实例)");
1061
+ const missing = [
1062
+ "buildRequest",
1063
+ "send",
1064
+ "stream",
1065
+ "parseResponse"
1066
+ ].filter((k) => typeof adapter[k] !== "function");
1067
+ if (missing.length) throw new ConfigurationError(`setAdapter: adapter 缺少必要方法: ${missing.join(", ")}(协议见 ChatService.js 顶部的 @typedef ChatAdapter)`);
1068
+ }
635
1069
  //#endregion
636
1070
  //#region src/utils/url.js
637
1071
  /**
@@ -663,26 +1097,23 @@
663
1097
  //#endregion
664
1098
  //#region src/utils/MessageFormatter.js
665
1099
  /**
666
- * MessageFormatter — 可注册的消息格式转换器
1100
+ * MessageFormatter — 可注册的消息格式转换器 + 可注册的过滤器链(v4.0)
667
1101
  *
668
1102
  * 职责:
669
- * 1. 内置 OpenA I兼容格式的转换逻辑
1103
+ * 1. 内置 OpenAI 兼容格式的转换逻辑
670
1104
  * 2. 支持 register(name, fn) 注册自定义格式(如 Anthropic、Gemini 等)
671
- * 3. 统一处理 capabilities 过滤(reasoning、vision 等)
672
- * 4. 所有适配器通过此工具获取 API 消息数组,消除重复代码
1105
+ * 3. v4.0:消息"保留 / 丢弃"规则改为可注册的过滤器链(registerFilter)
1106
+ * —— 原来硬编码在格式里的 ephemeral / system / 空内容规则,现在都是过滤器;
1107
+ * 业务插件(如 continuation)可以同名覆盖内置过滤器,接管规则。
673
1108
  *
674
1109
  * 用法:
675
1110
  * import { MessageFormatter } from 'my-ai-chat-framework';
676
1111
  *
677
1112
  * // 使用内置格式
678
- * const msgs = MessageFormatter.format({
679
- * messages, systemPrompts, capabilities, resolveImage
680
- * }); // 默认 'openai'
1113
+ * const msgs = MessageFormatter.format({ messages, systemPrompts, capabilities, resolveImage });
681
1114
  *
682
- * // 注册自定义格式
683
- * MessageFormatter.register('anthropic', ({ messages, systemPrompts, capabilities }) => {
684
- * // 返回 Anthropic 格式的消息数组
685
- * });
1115
+ * // 注册自己的过滤器(决定哪些消息进入请求)
1116
+ * MessageFormatter.registerFilter('my-rule', (msg, ctx) => msg.role === 'system' ? null : msg);
686
1117
  */
687
1118
  var IS_URL = /^https?:\/\//i;
688
1119
  function defaultResolveImage(imageId) {
@@ -711,7 +1142,23 @@
711
1142
  }
712
1143
  return content;
713
1144
  }
714
- /** OpenAI 兼容格式 */
1145
+ /** system 角色消息不进对话数组(system 由 systemPrompts 统一置顶) */
1146
+ function filterSystemDrop(msg) {
1147
+ if (msg.role === "system" && !msg._ephemeral) return null;
1148
+ return msg;
1149
+ }
1150
+ /** 空内容清理:无文本、无图片的消息丢弃(tool、带 toolCalls 的 assistant、prefix 空消息例外) */
1151
+ function filterEmptyDrop(msg) {
1152
+ if (msg.role === "system" || msg.role === "tool") return msg;
1153
+ if (msg.role === "assistant" && msg.toolCalls?.length) return msg;
1154
+ const hasText = msg.content && isString(msg.content) && msg.content.trim();
1155
+ const hasImages = Array.isArray(msg.images) && msg.images.length > 0;
1156
+ if (!hasText && !hasImages) {
1157
+ if (msg.role === "assistant" && msg.prefix) return msg;
1158
+ return null;
1159
+ }
1160
+ return msg;
1161
+ }
715
1162
  function toOpenAI({ messages, systemPrompts, capabilities, resolveImage }) {
716
1163
  const rImg = typeof resolveImage === "function" ? resolveImage : defaultResolveImage;
717
1164
  const result = [];
@@ -719,15 +1166,8 @@
719
1166
  role: "system",
720
1167
  content: sp.content.trim()
721
1168
  });
722
- let ephemEnd = messages.length;
723
- for (let i = messages.length - 1; i >= 0; i--) if (messages[i]._ephemeral) ephemEnd = i;
724
- else break;
725
- for (let i = 0; i < messages.length; i++) {
726
- const msg = messages[i];
727
- if (msg._ephemeral) {
728
- if (i < ephemEnd) continue;
729
- }
730
- if (msg.role === "system" && !msg._ephemeral) continue;
1169
+ const kept = MessageFormatter._runFilters(messages, capabilities || {});
1170
+ for (const msg of kept) {
731
1171
  if (msg.role === "tool") {
732
1172
  result.push({
733
1173
  role: "tool",
@@ -763,7 +1203,7 @@
763
1203
  }
764
1204
  const entry = { role: msg.role };
765
1205
  if (hasImages) {
766
- if (!capabilities?.vision) throw new Error("[MessageFormatter] 消息包含图片但模型不支持视觉(capabilities.vision=false)。请切换模型或移除图片。");
1206
+ if (!capabilities?.vision) throw new ValidationError("[MessageFormatter] 消息包含图片但模型不支持视觉(capabilities.vision=false)。请切换模型或移除图片。");
767
1207
  entry.content = buildMultimodalContent(msg.content || "", msg.images, rImg);
768
1208
  } else entry.content = msg.content;
769
1209
  if (msg.prefix) entry.prefix = true;
@@ -773,22 +1213,71 @@
773
1213
  }
774
1214
  var MessageFormatter = {
775
1215
  _formats: new Map([["openai", toOpenAI]]),
1216
+ _filters: /* @__PURE__ */ new Map(),
1217
+ _filterOrder: 0,
776
1218
  register(name, fn) {
777
- if (!name || typeof name !== "string" || !name.trim()) throw new Error("[MessageFormatter] 格式名称必须是非空字符串");
778
- if (typeof fn !== "function") throw new Error("[MessageFormatter] 转换函数必须是 function");
1219
+ if (!name || typeof name !== "string" || !name.trim()) throw new ValidationError("[MessageFormatter] 格式名称必须是非空字符串");
1220
+ if (typeof fn !== "function") throw new ValidationError("[MessageFormatter] 转换函数必须是 function");
779
1221
  this._formats.set(name.trim(), fn);
780
1222
  },
781
1223
  unregister(name) {
782
- if (name === "openai") throw new Error("[MessageFormatter] 内置格式 \"openai\" 不可移除");
1224
+ if (name === "openai") throw new ValidationError("[MessageFormatter] 内置格式 \"openai\" 不可移除");
783
1225
  this._formats.delete(name);
784
1226
  },
785
1227
  listFormats() {
786
1228
  return [...this._formats.keys()];
787
1229
  },
1230
+ registerFilter(name, fn, options = {}) {
1231
+ if (!name || typeof name !== "string" || !name.trim()) throw new ValidationError("[MessageFormatter] 过滤器名称必须是非空字符串");
1232
+ if (typeof fn !== "function") throw new ValidationError("[MessageFormatter] 过滤器必须是 function");
1233
+ const key = name.trim();
1234
+ const priority = typeof options.priority === "number" ? options.priority : 100;
1235
+ const prev = this._filters.get(key);
1236
+ this._filters.set(key, {
1237
+ name: key,
1238
+ fn,
1239
+ priority,
1240
+ order: ++this._filterOrder
1241
+ });
1242
+ return prev ? prev.fn : void 0;
1243
+ },
1244
+ unregisterFilter(name) {
1245
+ return this._filters.delete(name);
1246
+ },
1247
+ listFilters() {
1248
+ return [...this._filters.values()].sort((a, b) => a.priority - b.priority || a.order - b.order).map((f) => ({
1249
+ name: f.name,
1250
+ priority: f.priority
1251
+ }));
1252
+ },
1253
+ _runFilters(messages, capabilities = {}) {
1254
+ if (this._filters.size === 0) return [...messages];
1255
+ const list = [...this._filters.values()].sort((a, b) => a.priority - b.priority || a.order - b.order);
1256
+ const out = [];
1257
+ for (let i = 0; i < messages.length; i++) {
1258
+ let msg = messages[i];
1259
+ const ctx = {
1260
+ index: i,
1261
+ total: messages.length,
1262
+ messages,
1263
+ capabilities
1264
+ };
1265
+ let dropped = false;
1266
+ for (const f of list) {
1267
+ msg = f.fn(msg, ctx);
1268
+ if (msg === null || msg === void 0) {
1269
+ dropped = true;
1270
+ break;
1271
+ }
1272
+ }
1273
+ if (!dropped) out.push(msg);
1274
+ }
1275
+ return out;
1276
+ },
788
1277
  format(options = {}) {
789
1278
  const formatName = options.format || "openai";
790
1279
  const fn = this._formats.get(formatName);
791
- if (!fn) throw new Error(`[MessageFormatter] 未知格式 "${formatName}"。可用格式: ${[...this._formats.keys()].join(", ")}`);
1280
+ if (!fn) throw new ValidationError(`[MessageFormatter] 未知格式 "${formatName}"。可用格式: ${[...this._formats.keys()].join(", ")}`);
792
1281
  return fn({
793
1282
  messages: options.messages || [],
794
1283
  systemPrompts: options.systemPrompts || [],
@@ -797,6 +1286,8 @@
797
1286
  });
798
1287
  }
799
1288
  };
1289
+ MessageFormatter.registerFilter("system-drop", filterSystemDrop, { priority: 900 });
1290
+ MessageFormatter.registerFilter("empty-drop", filterEmptyDrop, { priority: 910 });
800
1291
  function assembleMessages(options = {}) {
801
1292
  return MessageFormatter.format({
802
1293
  ...options,
@@ -809,17 +1300,48 @@
809
1300
  * OpenAI 兼容 API 适配器
810
1301
  * 支持 DeepSeek 等完全兼容 OpenAI 接口的服务
811
1302
  */
1303
+ var TRANSPORT_KEYS = [
1304
+ "apiKey",
1305
+ "baseUrl",
1306
+ "apiUrl",
1307
+ "path",
1308
+ "headers"
1309
+ ];
812
1310
  var openaiAdapter = {
813
1311
  name: "openai",
814
- install(chatService) {
1312
+ install(chatService, options = {}) {
1313
+ if (this._transport) this._transport = {
1314
+ ...this._transport,
1315
+ ...options
1316
+ };
815
1317
  chatService.setAdapter(this);
816
1318
  },
1319
+ _resolveConfig(config) {
1320
+ const transport = this._transport || {};
1321
+ const resolved = {
1322
+ ...config,
1323
+ ...transport
1324
+ };
1325
+ if (transport.modelParams) resolved.modelParams = {
1326
+ ...transport.modelParams,
1327
+ ...config.modelParams || {}
1328
+ };
1329
+ return resolved;
1330
+ },
1331
+ getRequestDefaults() {
1332
+ if (!this._transport) return {};
1333
+ const defaults = {};
1334
+ for (const [key, value] of Object.entries(this._transport)) if (!TRANSPORT_KEYS.includes(key) && value !== void 0) defaults[key] = value;
1335
+ return defaults;
1336
+ },
817
1337
  buildRequest(messages, config, systemPrompts = []) {
1338
+ config = this._resolveConfig(config);
818
1339
  const model = config.model || config.modelParams?.model;
819
- if (!model) throw new Error("Missing required config: model (either at top level or in modelParams)");
820
- const temperature = config.modelParams?.temperature ?? config.temperature ?? .7;
821
- const maxTokens = config.modelParams?.maxTokens ?? config.maxTokens ?? 2e3;
822
- const reasoningEffort = config.modelParams?.reasoningEffort ?? config.reasoningEffort;
1340
+ if (!model) throw new ConfigurationError("Missing required config: model (either at top level or in modelParams)");
1341
+ const mp = config.modelParams || {};
1342
+ const temperature = mp.temperature ?? config.temperature;
1343
+ const maxTokens = mp.maxTokens ?? config.maxTokens;
1344
+ const reasoningEffort = mp.reasoningEffort ?? config.reasoningEffort;
823
1345
  const requestBody = {
824
1346
  model,
825
1347
  messages: MessageFormatter.format({
@@ -829,15 +1351,34 @@
829
1351
  resolveImage: config.resolveImage,
830
1352
  format: config.messageFormat
831
1353
  }),
832
- temperature,
833
- max_tokens: maxTokens,
834
1354
  stream: false
835
1355
  };
1356
+ if (temperature !== void 0) requestBody.temperature = temperature;
1357
+ if (maxTokens !== void 0) requestBody.max_tokens = maxTokens;
1358
+ if (mp.topP !== void 0) requestBody.top_p = mp.topP;
1359
+ if (mp.frequencyPenalty !== void 0) requestBody.frequency_penalty = mp.frequencyPenalty;
1360
+ if (mp.presencePenalty !== void 0) requestBody.presence_penalty = mp.presencePenalty;
1361
+ if (mp.stop !== void 0) requestBody.stop = mp.stop;
1362
+ if (mp.responseFormat !== void 0) requestBody.response_format = mp.responseFormat;
1363
+ if (mp.seed !== void 0) requestBody.seed = mp.seed;
836
1364
  if (config.tools && Array.isArray(config.tools) && config.tools.length > 0) {
837
1365
  requestBody.tools = config.tools;
838
1366
  requestBody.tool_choice = "auto";
839
1367
  }
840
- if (reasoningEffort && model === "deepseek-reasoner") requestBody.reasoning_effort = reasoningEffort;
1368
+ if (reasoningEffort !== void 0) requestBody.reasoning_effort = reasoningEffort;
1369
+ const consumedKeys = new Set([
1370
+ "model",
1371
+ "temperature",
1372
+ "maxTokens",
1373
+ "reasoningEffort",
1374
+ "topP",
1375
+ "frequencyPenalty",
1376
+ "presencePenalty",
1377
+ "stop",
1378
+ "responseFormat",
1379
+ "seed"
1380
+ ]);
1381
+ for (const [key, value] of Object.entries(mp)) if (!consumedKeys.has(key) && value !== void 0) requestBody[key] = value;
841
1382
  return requestBody;
842
1383
  },
843
1384
  _getUrl(config) {
@@ -850,6 +1391,7 @@
850
1391
  },
851
1392
  async send(requestBody, config, options = {}) {
852
1393
  try {
1394
+ config = this._resolveConfig(config);
853
1395
  const url = this._getUrl(config);
854
1396
  const headers = {
855
1397
  "Content-Type": "application/json",
@@ -884,6 +1426,7 @@
884
1426
  return internal;
885
1427
  },
886
1428
  async stream(requestBody, config, onProgress, onDone, options = {}) {
1429
+ config = this._resolveConfig(config);
887
1430
  const streamBody = {
888
1431
  ...requestBody,
889
1432
  stream: true
@@ -918,22 +1461,37 @@
918
1461
  content: "",
919
1462
  reasoningContent: ""
920
1463
  };
1464
+ let reachedDone = false;
921
1465
  while (true) {
922
1466
  if (options.signal?.aborted) break;
923
1467
  const { done, value } = await reader.read();
924
1468
  if (done) break;
925
1469
  buffer += decoder.decode(value, { stream: true });
926
- const lines = buffer.split(/\n\n/);
927
- buffer = lines.pop();
928
- for (const line of lines) {
929
- const dataLine = line.replace(/^data: /, "").trim();
930
- if (!dataLine) continue;
931
- if (dataLine === "[DONE]") break;
1470
+ let sepMatch;
1471
+ const EVENT_SEP = /\r?\n\r?\n/;
1472
+ while ((sepMatch = EVENT_SEP.exec(buffer)) !== null) {
1473
+ const rawEvent = buffer.slice(0, sepMatch.index);
1474
+ buffer = buffer.slice(sepMatch.index + sepMatch[0].length);
1475
+ const dataPayload = rawEvent.split(/\r?\n/).filter((l) => l.startsWith("data:")).map((l) => l.slice(5).replace(/^ /, "")).join("\n");
1476
+ if (!dataPayload) continue;
1477
+ if (dataPayload.trim() === "[DONE]") {
1478
+ reachedDone = true;
1479
+ break;
1480
+ }
932
1481
  try {
933
- const delta = JSON.parse(dataLine).choices?.[0]?.delta;
1482
+ const delta = JSON.parse(dataPayload).choices?.[0]?.delta;
934
1483
  if (!delta) continue;
935
- if (delta.content) accumulated.content += delta.content;
1484
+ const deltaInfo = {
1485
+ content: "",
1486
+ reasoningContent: "",
1487
+ toolCalls: null
1488
+ };
1489
+ if (delta.content) {
1490
+ accumulated.content += delta.content;
1491
+ deltaInfo.content = delta.content;
1492
+ }
936
1493
  if (delta.tool_calls) {
1494
+ const newCalls = [];
937
1495
  if (!accumulated.toolCalls) accumulated.toolCalls = [];
938
1496
  for (const toolCallDelta of delta.tool_calls) {
939
1497
  const index = toolCallDelta.index;
@@ -949,14 +1507,23 @@
949
1507
  if (toolCallDelta.type) accumulated.toolCalls[index].type = toolCallDelta.type;
950
1508
  if (toolCallDelta.function?.name) accumulated.toolCalls[index].function.name += toolCallDelta.function.name;
951
1509
  if (toolCallDelta.function?.arguments) accumulated.toolCalls[index].function.arguments += toolCallDelta.function.arguments;
1510
+ newCalls.push({
1511
+ index,
1512
+ delta: toolCallDelta
1513
+ });
952
1514
  }
1515
+ deltaInfo.toolCalls = newCalls;
953
1516
  }
954
- if (delta.reasoning_content) accumulated.reasoningContent += delta.reasoning_content;
955
- onProgress({ ...accumulated });
1517
+ if (delta.reasoning_content) {
1518
+ accumulated.reasoningContent += delta.reasoning_content;
1519
+ deltaInfo.reasoningContent = delta.reasoning_content;
1520
+ }
1521
+ onProgress({ ...accumulated }, deltaInfo);
956
1522
  } catch (e) {
957
- console.warn("stream parsing failed :", e, dataLine);
1523
+ console.warn("stream parsing failed :", e, dataPayload);
958
1524
  }
959
1525
  }
1526
+ if (reachedDone) break;
960
1527
  }
961
1528
  onDone({
962
1529
  role: "assistant",
@@ -977,165 +1544,246 @@
977
1544
  throw new APIError(errorMessage, response.status, null, errorText);
978
1545
  }
979
1546
  };
1547
+ /**
1548
+ * 创建 OpenAI 兼容适配器实例(工厂)。
1549
+ *
1550
+ * 与单例 openaiAdapter 的区别:每个实例自持一份运输配置(apiKey/baseUrl/apiUrl/path/headers),
1551
+ * 互不干扰——解决"同一适配器装到多个 ChatService 互相覆盖"的单例陷阱。
1552
+ *
1553
+ * 用法:
1554
+ * const adapter = createOpenAIAdapter({ apiKey, baseUrl, modelParams: { temperature: 0.8 } });
1555
+ * const chat = new ChatService({ adapter, model: 'deepseek-chat' });
1556
+ * chat.use(adapter); // 或直接 new ChatService({ adapter })
1557
+ *
1558
+ * 非运输键(model/modelParams/messageFormat/resolveImage/capabilities 等)会作为
1559
+ * "请求默认参数"供会话层合并,单次请求仍可覆盖。
1560
+ */
1561
+ function createOpenAIAdapter(options = {}) {
1562
+ return {
1563
+ ...openaiAdapter,
1564
+ _transport: { ...options }
1565
+ };
1566
+ }
980
1567
  //#endregion
981
1568
  //#region src/plugins/tool-calling.js
982
1569
  /**
983
1570
  * 工具调用插件
984
1571
  * 功能:拦截助手消息中的 tool_calls,执行对应的工具,将结果作为 tool 消息加入对话,
985
1572
  * 然后自动继续对话(通过 sendExisting / sendExistingStream),直到没有新的工具调用。
986
- *
1573
+ *
987
1574
  * 设计要点:
988
1575
  * - 支持普通请求和流式请求(通过 isStream 标志区分)
989
1576
  * - 支持多次工具调用循环(maxIterations 防止无限循环)
990
- * - 串行执行工具(可后续升级为并行)
1577
+ * - 并行执行工具
991
1578
  * - 工具执行失败时,仍然返回错误信息给 AI,而不是中断整个流程
992
1579
  * - 触发 tool-error 事件,方便用户监听工具执行异常
1580
+ *
1581
+ * 注意:请使用 createToolCallingPlugin() 工厂创建实例。
1582
+ * 默认导出的 toolCallingPlugin 是兼容用的模块级单例,装到多个 ChatService
1583
+ * 实例会互相覆盖(executor 表、工具定义、配置),新代码不要直接用单例。
1584
+ */
1585
+ var toolCallingPlugin = createToolCallingPlugin();
1586
+ /**
1587
+ * 创建工具调用插件实例(工厂)。
1588
+ * @param {Object} [options] — { timeout?, maxIterations? }
1589
+ * - 两者**默认都不限制**:不传就是"循环到没有工具调用为止 / 不超时"
1590
+ * - 想限制才传(这是使用者的选择,不是框架替你做的决定)
993
1591
  */
994
- var toolCallingPlugin = {
995
- name: "tool-calling",
996
- maxIterations: 5,
997
- install(chatService) {
998
- this.chatService = chatService;
999
- this._tools = /* @__PURE__ */ new Map();
1000
- if (!chatService.config.tools) chatService.config.tools = [];
1001
- /**
1002
- * 注册工具
1003
- * @param {string} name - 工具名称(唯一标识)
1004
- * @param {string} description - 工具描述(告诉 AI 何时调用)
1005
- * @param {Function} executor - 异步执行函数,接收参数对象,返回结果(字符串或对象)
1006
- * @param {Object} parameters - JSON Schema 参数定义(可选,默认为空对象)
1007
- * @returns {ChatService} 返回 chatService 实例,支持链式调用
1008
- */
1009
- chatService.registerTool = (name, description, executor, parameters = {}) => {
1010
- this._tools.set(name, {
1011
- executor,
1012
- description
1592
+ function createToolCallingPlugin(options = {}) {
1593
+ return {
1594
+ name: "tool-calling",
1595
+ maxIterations: options.maxIterations ?? Infinity,
1596
+ _options: { ...options },
1597
+ _tools: /* @__PURE__ */ new Map(),
1598
+ _toolDefs: [],
1599
+ chatService: null,
1600
+ install(chatService, options = {}) {
1601
+ this._options = {
1602
+ ...this._options,
1603
+ ...options
1604
+ };
1605
+ this.chatService = chatService;
1606
+ chatService.pipe({
1607
+ name: "tool-calling-inject",
1608
+ phase: "beforeSend",
1609
+ run: ({ config }) => {
1610
+ if (this._toolDefs.length) config.tools = this._toolDefs;
1611
+ }
1013
1612
  });
1014
- const toolDefinition = {
1015
- type: "function",
1016
- function: {
1017
- name,
1018
- description,
1019
- parameters: {
1020
- type: "object",
1021
- properties: parameters,
1022
- required: Object.keys(parameters).filter((key) => parameters[key]?.required)
1613
+ /**
1614
+ * 注册工具
1615
+ * @param {string} name - 工具名称(唯一标识)
1616
+ * @param {string} description - 工具描述(告诉 AI 何时调用)
1617
+ * @param {Function} executor - 异步执行函数,接收参数对象,返回结果(字符串或对象)
1618
+ * @param {Object} parameters - JSON Schema 参数定义(可选,默认为空对象)
1619
+ * @returns {ChatService} 返回 chatService 实例,支持链式调用
1620
+ */
1621
+ const registerTool = (name, description, executor, parameters = {}) => {
1622
+ this._tools.set(name, {
1623
+ executor,
1624
+ description
1625
+ });
1626
+ const properties = {};
1627
+ const requiredKeys = [];
1628
+ for (const [key, def] of Object.entries(parameters || {})) {
1629
+ const { required: isRequired, ...schema } = def || {};
1630
+ properties[key] = schema;
1631
+ if (isRequired) requiredKeys.push(key);
1632
+ }
1633
+ const toolDefinition = {
1634
+ type: "function",
1635
+ function: {
1636
+ name,
1637
+ description,
1638
+ parameters: {
1639
+ type: "object",
1640
+ properties,
1641
+ required: requiredKeys
1642
+ }
1023
1643
  }
1644
+ };
1645
+ if (!this._toolDefs.find((t) => t.function.name === name)) this._toolDefs.push(toolDefinition);
1646
+ return chatService;
1647
+ };
1648
+ chatService.pipe({
1649
+ name: "tool-calling-loop",
1650
+ phase: "afterSend",
1651
+ run: async (ctx) => {
1652
+ ctx.result = await this._handleWithTools(ctx.result, ctx.isStream, ctx.onProgress || void 0, ctx.onDone || void 0);
1024
1653
  }
1654
+ });
1655
+ return {
1656
+ registerTool,
1657
+ tools: this._tools,
1658
+ uninstall: (c) => this.uninstall(c)
1025
1659
  };
1026
- if (!chatService.config.tools.find((t) => t.function.name === name)) chatService.config.tools.push(toolDefinition);
1027
- return chatService;
1028
- };
1029
- chatService._processResponse = async (response, { isStream, onProgress, onDone }) => {
1030
- return this._handleWithTools(response, isStream, onProgress, onDone);
1031
- };
1032
- },
1033
- async _handleWithTools(initialResponse, isStream, onProgress, onDone) {
1034
- const self = this;
1035
- const chat = this.chatService;
1036
- let iteration = 0;
1037
- /**
1038
- * 递归处理工具调用
1039
- * @param {Object} initialResponse - 初始 AI 响应(可能是第一次请求的响应)
1040
- * @returns {Promise<Object>} 最终 AI 响应(不含 tool_calls)
1041
- */
1042
- async function processResponse(initialResponse) {
1043
- let lastResponse = initialResponse;
1044
- while (iteration < self.maxIterations) {
1045
- const toolCalls = lastResponse?.toolCalls;
1046
- if (!toolCalls || toolCalls.length === 0) break;
1047
- iteration++;
1048
- const toolResults = await Promise.all(toolCalls.map(async (call) => {
1049
- const toolName = call.function?.name;
1050
- let args;
1051
- try {
1052
- args = JSON.parse(call.function?.arguments || "{}");
1053
- } catch (parseErr) {
1054
- chat.emit("tool-error", {
1055
- toolName: toolName || "unknown",
1056
- error: parseErr,
1057
- toolCallId: call.id,
1058
- stage: "parse",
1059
- timestamp: Date.now()
1060
- });
1061
- return {
1062
- tool_call_id: call.id,
1063
- error: `参数解析失败: ${parseErr.message}`,
1064
- success: false
1065
- };
1066
- }
1067
- const tool = self._tools.get(toolName);
1068
- if (!tool) {
1069
- chat.emit("tool-error", {
1070
- toolName,
1071
- error: /* @__PURE__ */ new Error(`Tool not registered: ${toolName}`),
1072
- toolCallId: call.id,
1073
- stage: "lookup",
1074
- timestamp: Date.now()
1075
- });
1076
- return {
1077
- tool_call_id: call.id,
1078
- error: `工具 ${toolName} 未注册`,
1079
- success: false
1080
- };
1081
- }
1082
- try {
1083
- const toolTimeout = chat.config.toolTimeout;
1084
- let execPromise = tool.executor(args);
1085
- if (toolTimeout && typeof toolTimeout === "number" && toolTimeout > 0) {
1086
- const timeoutErr = /* @__PURE__ */ new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
1087
- timeoutErr.name = "ToolTimeoutError";
1088
- const timeoutPromise = new Promise((_, reject) => setTimeout(() => reject(timeoutErr), toolTimeout));
1089
- execPromise = Promise.race([execPromise, timeoutPromise]);
1660
+ },
1661
+ uninstall(chat) {
1662
+ if (!chat) return chat;
1663
+ chat.unpipe?.("tool-calling-inject");
1664
+ chat.unpipe?.("tool-calling-loop");
1665
+ if (chat.plugins && chat.plugins["tool-calling"]) delete chat.plugins["tool-calling"];
1666
+ return chat;
1667
+ },
1668
+ async _handleWithTools(initialResponse, isStream, onProgress, onDone) {
1669
+ const self = this;
1670
+ const chat = this.chatService;
1671
+ let iteration = 0;
1672
+ /**
1673
+ * 递归处理工具调用
1674
+ * @param {Object} initialResponse - 初始 AI 响应(可能是第一次请求的响应)
1675
+ * @returns {Promise<Object>} 最终 AI 响应(不含 tool_calls)
1676
+ */
1677
+ async function processResponse(initialResponse) {
1678
+ let lastResponse = initialResponse;
1679
+ while (iteration < self.maxIterations) {
1680
+ const toolCalls = lastResponse?.toolCalls;
1681
+ if (!toolCalls || toolCalls.length === 0) break;
1682
+ iteration++;
1683
+ const toolResults = await Promise.all(toolCalls.map(async (call) => {
1684
+ const toolName = call.function?.name;
1685
+ let args;
1686
+ try {
1687
+ args = JSON.parse(call.function?.arguments || "{}");
1688
+ } catch (parseErr) {
1689
+ chat.emit("tool-error", {
1690
+ toolName: toolName || "unknown",
1691
+ error: parseErr,
1692
+ toolCallId: call.id,
1693
+ stage: "parse",
1694
+ timestamp: Date.now()
1695
+ });
1696
+ return {
1697
+ tool_call_id: call.id,
1698
+ error: `参数解析失败: ${parseErr.message}`,
1699
+ success: false
1700
+ };
1090
1701
  }
1091
- const result = await execPromise;
1092
- chat.emit("tool-success", {
1093
- toolName,
1094
- result,
1095
- toolCallId: call.id,
1096
- timestamp: Date.now()
1097
- });
1098
- return {
1099
- tool_call_id: call.id,
1100
- content: typeof result === "string" ? result : JSON.stringify(result),
1101
- success: true
1102
- };
1103
- } catch (err) {
1104
- const stage = err.name === "ToolTimeoutError" ? "timeout" : "execute";
1105
- chat.emit("tool-error", {
1106
- toolName,
1107
- error: err,
1108
- toolCallId: call.id,
1109
- stage,
1110
- timestamp: Date.now()
1111
- });
1112
- return {
1113
- tool_call_id: call.id,
1114
- error: err.message,
1115
- success: false
1116
- };
1702
+ const tool = self._tools.get(toolName);
1703
+ if (!tool) {
1704
+ chat.emit("tool-error", {
1705
+ toolName,
1706
+ error: /* @__PURE__ */ new Error(`Tool not registered: ${toolName}`),
1707
+ toolCallId: call.id,
1708
+ stage: "lookup",
1709
+ timestamp: Date.now()
1710
+ });
1711
+ return {
1712
+ tool_call_id: call.id,
1713
+ error: `工具 ${toolName} 未注册`,
1714
+ success: false
1715
+ };
1716
+ }
1717
+ try {
1718
+ const toolTimeout = self._options.timeout;
1719
+ let result;
1720
+ if (typeof toolTimeout === "number" && toolTimeout > 0) {
1721
+ const controller = new AbortController();
1722
+ const timeoutErr = /* @__PURE__ */ new Error(`工具 ${toolName} 执行超时 (${toolTimeout}ms)`);
1723
+ timeoutErr.name = "ToolTimeoutError";
1724
+ let timer;
1725
+ const timeoutPromise = new Promise((_, reject) => {
1726
+ timer = setTimeout(() => {
1727
+ controller.abort();
1728
+ reject(timeoutErr);
1729
+ }, toolTimeout);
1730
+ });
1731
+ const execPromise = Promise.resolve().then(() => tool.executor(args, { signal: controller.signal }));
1732
+ execPromise.catch(() => {});
1733
+ try {
1734
+ result = await Promise.race([execPromise, timeoutPromise]);
1735
+ } finally {
1736
+ clearTimeout(timer);
1737
+ }
1738
+ } else result = await tool.executor(args);
1739
+ chat.emit("tool-success", {
1740
+ toolName,
1741
+ result,
1742
+ toolCallId: call.id,
1743
+ timestamp: Date.now()
1744
+ });
1745
+ return {
1746
+ tool_call_id: call.id,
1747
+ content: typeof result === "string" ? result : JSON.stringify(result),
1748
+ success: true
1749
+ };
1750
+ } catch (err) {
1751
+ const stage = err.name === "ToolTimeoutError" ? "timeout" : "execute";
1752
+ chat.emit("tool-error", {
1753
+ toolName,
1754
+ error: err,
1755
+ toolCallId: call.id,
1756
+ stage,
1757
+ timestamp: Date.now()
1758
+ });
1759
+ return {
1760
+ tool_call_id: call.id,
1761
+ error: err.message,
1762
+ success: false
1763
+ };
1764
+ }
1765
+ }));
1766
+ for (const tr of toolResults) {
1767
+ const content = tr.success ? tr.content : tr.error || "工具执行失败";
1768
+ chat.messages.addTool(content, tr.tool_call_id);
1117
1769
  }
1118
- }));
1119
- for (const tr of toolResults) {
1120
- const content = tr.success ? tr.content : tr.error || "工具执行失败";
1121
- chat.messages.addTool(content, tr.tool_call_id);
1122
- }
1123
- if (isStream) await new Promise((resolve) => {
1124
- chat.sendExistingStream((chunk) => {
1125
- if (onProgress) onProgress(chunk);
1126
- lastResponse = chunk;
1127
- }, (final) => {
1128
- lastResponse = final;
1129
- resolve();
1770
+ if (isStream) await new Promise((resolve) => {
1771
+ chat.sendExistingStream((chunk) => {
1772
+ if (onProgress) onProgress(chunk);
1773
+ lastResponse = chunk;
1774
+ }, (final) => {
1775
+ lastResponse = final;
1776
+ resolve();
1777
+ });
1130
1778
  });
1131
- });
1132
- else lastResponse = await chat.sendExisting();
1779
+ else lastResponse = await chat.sendExisting();
1780
+ }
1781
+ return lastResponse;
1133
1782
  }
1134
- return lastResponse;
1783
+ return await processResponse(initialResponse);
1135
1784
  }
1136
- return await processResponse(initialResponse);
1137
- }
1138
- };
1785
+ };
1786
+ }
1139
1787
  //#endregion
1140
1788
  //#region src/plugins/model-registry.js
1141
1789
  /**
@@ -1242,56 +1890,225 @@
1242
1890
  reasoning: false,
1243
1891
  vision: false
1244
1892
  };
1245
- var modelRegistryPlugin = {
1246
- name: "model-registry",
1247
- install(chatService) {
1248
- this.chat = chatService;
1249
- this._registry = new Map(Object.entries(BUILTIN_MODELS));
1250
- /**
1251
- * 注册/覆盖一个模型的能力标签
1252
- * @param {string} name — 模型名称
1253
- * @param {Object} capabilities — 能力标签对象(部分字段即可,未提供的取默认值)
1254
- * @returns {ChatService}
1255
- */
1256
- chatService.registerModel = (name, capabilities = {}) => {
1257
- if (!name || typeof name !== "string" || !name.trim()) throw new Error("[model-registry] 模型名称必须是非空字符串");
1258
- const merged = {
1259
- ...DEFAULT_CAPABILITIES,
1260
- ...capabilities
1893
+ /**
1894
+ * 注意:请使用 createModelRegistryPlugin() 工厂创建实例。
1895
+ * 默认导出的 modelRegistryPlugin 是兼容用的模块级单例,装到多个 ChatService
1896
+ * 实例会互相覆盖(注册表、实例引用),新代码不要直接用单例。
1897
+ */
1898
+ var modelRegistryPlugin = createModelRegistryPlugin();
1899
+ /**
1900
+ * 创建模型能力注册表插件实例(工厂)。
1901
+ * @param {Object} [options] — { models: { '模型名': capabilities } }(合并进内置表)
1902
+ */
1903
+ function createModelRegistryPlugin(options = {}) {
1904
+ return {
1905
+ name: "model-registry",
1906
+ _options: { ...options },
1907
+ _registry: new Map([...Object.entries(BUILTIN_MODELS), ...Object.entries(options.models || {})]),
1908
+ chat: null,
1909
+ install(chatService, options = {}) {
1910
+ this._options = {
1911
+ ...this._options,
1912
+ ...options
1261
1913
  };
1262
- this._registry.set(name.trim(), merged);
1263
- if (chatService.config.model === name.trim()) this._syncCapabilities();
1264
- return chatService;
1265
- };
1266
- /**
1267
- * 列出所有已注册的模型名称
1268
- * @returns {Array<string>}
1269
- */
1270
- chatService.listModels = () => {
1271
- return [...this._registry.keys()];
1272
- };
1273
- this._syncCapabilities();
1274
- chatService.on("config-updated", ({ changes }) => {
1275
- if ("model" in changes) this._syncCapabilities();
1276
- if ("capabilities" in changes && !("model" in changes)) {
1277
- const current = this._lookupCapabilities();
1278
- if (current) chatService.config.capabilities = {
1279
- ...current,
1280
- ...changes.capabilities
1914
+ this.chat = chatService;
1915
+ /**
1916
+ * 注册/覆盖一个模型的能力标签
1917
+ * @param {string} name — 模型名称
1918
+ * @param {Object} capabilities — 能力标签对象(部分字段即可,未提供的取默认值)
1919
+ * @returns {ChatService}
1920
+ */
1921
+ const registerModel = (name, capabilities = {}) => {
1922
+ if (!name || typeof name !== "string" || !name.trim()) throw new ValidationError("[model-registry] 模型名称必须是非空字符串");
1923
+ const merged = {
1924
+ ...DEFAULT_CAPABILITIES,
1925
+ ...capabilities
1281
1926
  };
1282
- }
1283
- });
1284
- },
1285
- _lookupCapabilities() {
1286
- const model = this.chat.config.model;
1287
- if (!model) return null;
1288
- return this._registry.get(model) || null;
1289
- },
1290
- _syncCapabilities() {
1291
- const caps = this._lookupCapabilities();
1292
- if (caps) this.chat.config.capabilities = { ...caps };
1293
- }
1294
- };
1927
+ this._registry.set(name.trim(), merged);
1928
+ if (chatService.config.model === name.trim()) this._syncCapabilities();
1929
+ return chatService;
1930
+ };
1931
+ /**
1932
+ * 列出所有已注册的模型名称
1933
+ * @returns {Array<string>}
1934
+ */
1935
+ const listModels = () => {
1936
+ return [...this._registry.keys()];
1937
+ };
1938
+ this._syncCapabilities();
1939
+ chatService.pipe({
1940
+ name: "model-registry-caps",
1941
+ phase: "beforeSend",
1942
+ run: ({ config }) => {
1943
+ if (!config.model) return;
1944
+ const caps = this._registry.get(config.model);
1945
+ if (caps) config.capabilities = { ...caps };
1946
+ }
1947
+ });
1948
+ chatService.on("config-updated", ({ changes }) => {
1949
+ if ("model" in changes) this._syncCapabilities();
1950
+ if ("capabilities" in changes && !("model" in changes)) {
1951
+ const current = this._lookupCapabilities();
1952
+ if (current) chatService.config.capabilities = {
1953
+ ...current,
1954
+ ...changes.capabilities
1955
+ };
1956
+ }
1957
+ });
1958
+ return {
1959
+ registerModel,
1960
+ listModels,
1961
+ uninstall: (c) => this.uninstall(c)
1962
+ };
1963
+ },
1964
+ uninstall(chat = this.chat) {
1965
+ if (!chat) return chat;
1966
+ chat.unpipe?.("model-registry-caps");
1967
+ if (chat.plugins && chat.plugins["model-registry"]) delete chat.plugins["model-registry"];
1968
+ return chat;
1969
+ },
1970
+ _lookupCapabilities() {
1971
+ const model = this.chat.config.model;
1972
+ if (!model) return null;
1973
+ return this._registry.get(model) || null;
1974
+ },
1975
+ _syncCapabilities() {
1976
+ const caps = this._lookupCapabilities();
1977
+ if (caps) this.chat.config.capabilities = { ...caps };
1978
+ }
1979
+ };
1980
+ }
1981
+ //#endregion
1982
+ //#region src/plugins/continuation.js
1983
+ /**
1984
+ * continuation 插件(v4.0)
1985
+ *
1986
+ * 「续写 / 临时消息」这套玩法住在这里 —— 核心不认识它,装上才有:
1987
+ * 1. 续写检测(替换核心的 autoContinue 步骤):底部若有带 prefix 标记的消息,就把结果合并回它
1988
+ * 2. ephemeral 过滤器:临时消息只有"位于底部连续段"时才发给 API
1989
+ * 3. continueLast / continueLastStream 两个 API
1990
+ * 4. uninstall():把自己装的东西全部还原(步骤、过滤器、方法)
1991
+ *
1992
+ * 用法:
1993
+ * import { createContinuationPlugin } from 'my-ai-chat-framework';
1994
+ * chat.use(createContinuationPlugin({ autoContinue: true }));
1995
+ *
1996
+ * // 模拟思维链:注入一条临时引导,结果合并回上一条 assistant,不留痕
1997
+ * chat.messages.addOnceAssistant('(内心:他肯定又要熬夜)');
1998
+ * await chat.stream('在吗');
1999
+ */
2000
+ /**
2001
+ * ephemeral 规则:只有底部连续的临时消息保留,其余丢弃(与 v3.x 核心内置行为一致)。
2002
+ * 导出以便使用者直接注册到 MessageFormatter(不使用插件时也能用这条规则)。
2003
+ */
2004
+ function ephemeralFilterRule(msg, { index, messages }) {
2005
+ if (!msg._ephemeral) return msg;
2006
+ let start = messages.length;
2007
+ for (let i = messages.length - 1; i >= 0; i--) if (messages[i]._ephemeral) start = i;
2008
+ else break;
2009
+ return index >= start ? msg : null;
2010
+ }
2011
+ /**
2012
+ * 找续写目标:最后一条必须是 assistant 或临时消息(否则抛错)。
2013
+ * @param {object} chat ChatService 实例
2014
+ */
2015
+ function prepareContinue(chat) {
2016
+ const msgs = chat.messages.getAll();
2017
+ const last = msgs[msgs.length - 1];
2018
+ if (last && (last.role === "assistant" || last._ephemeral)) return last;
2019
+ throw new ValidationError("最后一条消息不是 assistant,无法续写");
2020
+ }
2021
+ /** 续写结束后的"转正" */
2022
+ function finalize(chat, targetId) {
2023
+ chat.messages.update(targetId, {
2024
+ _complete: true,
2025
+ prefix: void 0,
2026
+ _ephemeral: false
2027
+ });
2028
+ }
2029
+ /**
2030
+ * 创建续写插件实例(工厂)
2031
+ * @param {Object} [options] — { autoContinue?: boolean } 是否自动识别底部 prefix 消息并合并(默认 false)
2032
+ */
2033
+ function createContinuationPlugin(options = {}) {
2034
+ return {
2035
+ name: "continuation",
2036
+ _options: {
2037
+ autoContinue: false,
2038
+ ...options
2039
+ },
2040
+ _prevEphemeralFilter: void 0,
2041
+ _installedOn: null,
2042
+ install(chat) {
2043
+ this._installedOn = chat;
2044
+ if (typeof chat.registerConfigKeys === "function") chat.registerConfigKeys({ autoContinue: (v) => typeof v === "boolean" });
2045
+ chat.replaceStage("autoContinue", (ctx) => {
2046
+ if (!(chat.config.autoContinue ?? this._options.autoContinue)) return;
2047
+ if (ctx.mergeToEntry) return;
2048
+ const last = ctx.messages.getLast();
2049
+ if (last && last.prefix && (last.role === "assistant" || last._ephemeral)) ctx.mergeToEntry = last.id;
2050
+ });
2051
+ this._prevEphemeralFilter = MessageFormatter.registerFilter("ephemeral", ephemeralFilterRule, { priority: 100 });
2052
+ const continueLast = async () => {
2053
+ const target = prepareContinue(chat);
2054
+ chat.messages.update(target.id, { prefix: true });
2055
+ try {
2056
+ await chat.sendExisting(void 0, { mergeToEntry: target.id });
2057
+ finalize(chat, target.id);
2058
+ return target;
2059
+ } catch (err) {
2060
+ finalize(chat, target.id);
2061
+ if (err.name === "AbortError") {
2062
+ chat.emit("aborted", { timestamp: Date.now() });
2063
+ return target;
2064
+ }
2065
+ throw err;
2066
+ }
2067
+ };
2068
+ const continueLastStream = async (onProgress, onDone) => {
2069
+ const target = prepareContinue(chat);
2070
+ chat.messages.update(target.id, { prefix: true });
2071
+ const baseLen = (target.content || "").length;
2072
+ try {
2073
+ await chat.sendExistingStream(void 0, { mergeToEntry: target.id }, (chunk) => {
2074
+ if (onProgress) onProgress({
2075
+ ...chunk,
2076
+ content: (chunk.content || "").slice(baseLen)
2077
+ });
2078
+ }, (final) => {
2079
+ if (onDone) onDone(final);
2080
+ });
2081
+ finalize(chat, target.id);
2082
+ return target;
2083
+ } catch (err) {
2084
+ finalize(chat, target.id);
2085
+ if (err.name === "AbortError") {
2086
+ chat.emit("aborted", { timestamp: Date.now() });
2087
+ return target;
2088
+ }
2089
+ throw err;
2090
+ }
2091
+ };
2092
+ return {
2093
+ continueLast,
2094
+ continueLastStream,
2095
+ uninstall: () => this.uninstall(chat)
2096
+ };
2097
+ },
2098
+ uninstall(chat = this._installedOn) {
2099
+ if (!chat) return chat;
2100
+ if (typeof chat.restoreStage === "function") chat.restoreStage("autoContinue");
2101
+ if (this._prevEphemeralFilter) MessageFormatter.registerFilter("ephemeral", this._prevEphemeralFilter, { priority: 100 });
2102
+ else MessageFormatter.unregisterFilter("ephemeral");
2103
+ if (chat.plugins && chat.plugins["continuation"]) delete chat.plugins["continuation"];
2104
+ if (typeof chat.unregisterConfigKeys === "function") chat.unregisterConfigKeys(["autoContinue"]);
2105
+ this._installedOn = null;
2106
+ return chat;
2107
+ }
2108
+ };
2109
+ }
2110
+ /** 兼容用单例(多实例场景请用工厂) */
2111
+ var continuationPlugin = createContinuationPlugin();
1295
2112
  //#endregion
1296
2113
  exports.APIError = APIError;
1297
2114
  exports.ChatService = ChatService;
@@ -1301,8 +2118,16 @@
1301
2118
  exports.MessageStore = MessageStore;
1302
2119
  exports.NetworkError = NetworkError;
1303
2120
  exports.ParsingError = ParsingError;
2121
+ exports.Pipeline = Pipeline;
1304
2122
  exports.SystemPromptStore = SystemPromptStore;
2123
+ exports.ValidationError = ValidationError;
1305
2124
  exports.assembleMessages = assembleMessages;
2125
+ exports.assertAdapter = assertAdapter;
2126
+ exports.continuationPlugin = continuationPlugin;
2127
+ exports.createContinuationPlugin = createContinuationPlugin;
2128
+ exports.createModelRegistryPlugin = createModelRegistryPlugin;
2129
+ exports.createOpenAIAdapter = createOpenAIAdapter;
2130
+ exports.createToolCallingPlugin = createToolCallingPlugin;
1306
2131
  exports.modelRegistryPlugin = modelRegistryPlugin;
1307
2132
  exports.openaiAdapter = openaiAdapter;
1308
2133
  exports.toolCallingPlugin = toolCallingPlugin;