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