@auipage/agent 0.1.0-alpha.5 → 0.2.0-alpha.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.
package/dist/index.js CHANGED
@@ -1,4 +1,4 @@
1
- /*! @auipage/agent v0.1.0-alpha.5 */
1
+ /*! @auipage/agent v0.2.0-alpha.0 */
2
2
  (function (global, factory) {
3
3
  typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
4
  typeof define === 'function' && define.amd ? define(['exports'], factory) :
@@ -27,6 +27,7 @@
27
27
  return this;
28
28
  }
29
29
 
30
+ // #doc:emit
30
31
  emit(event, ...args) {
31
32
  const list = this._events[event];
32
33
  if (!list || list.length === 0) return false;
@@ -35,12 +36,12 @@
35
36
  try {
36
37
  fn.apply(null, args);
37
38
  } catch (e) {
38
- // 单个监听器异常不影响其它监听器
39
- // 用 queueMicrotask 抛到全局,避免污染 emit 调用栈
40
- queueMicrotask(() => { throw e; });
39
+ // 单个监听器异常不影响其它监听器,也不再冒泡成进程级异常
40
+ console.error(e);
41
41
  }
42
42
  }
43
43
  return true;
44
+ // #end
44
45
  }
45
46
  }
46
47
 
@@ -49,12 +50,44 @@
49
50
  class Response extends Emitter {
50
51
  constructor() {
51
52
  super();
53
+ // #doc:state
52
54
  this.status = 0;
53
55
  this.headers = {};
54
56
  this.ok = false;
55
57
  this._done = false; // 标记是否已经 end/error,防止重复触发
56
58
  this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
57
59
  this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
60
+ this._cancel = null; // 由 createFetch 注入,用于中断底层请求
61
+ this._errorPending = null; // 消费者还没来得及注册时就发生的错误,注册后补发
62
+ // #end
63
+ }
64
+
65
+ // 注册监听;error 是一次性终态,注册时若已发生则补发
66
+ // #doc:replay
67
+ on(event, listener) {
68
+ super.on(event, listener);
69
+ if (event === 'error' && this._errorPending) {
70
+ const err = this._errorPending;
71
+ this._errorPending = null;
72
+ // 异步补发,避免在注册栈里同步回调
73
+ queueMicrotask(() => this.emit('error', err));
74
+ }
75
+ return this;
76
+ // #end
77
+ }
78
+
79
+ // 主动取消请求,失败统一从 error 事件返回
80
+ cancel() {
81
+ if (this._cancel) this._cancel();
82
+ return this;
83
+ }
84
+
85
+ // 统一读取响应头:浏览器是 Headers 对象,Node 是普通对象
86
+ header(name) {
87
+ const headers = this.headers;
88
+ if (!headers) return undefined;
89
+ if (typeof headers.get === 'function') return headers.get(name) ?? undefined;
90
+ return headers[name];
58
91
  }
59
92
 
60
93
  // 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
@@ -62,6 +95,7 @@
62
95
  if (this._done && type !== 'error') return;
63
96
 
64
97
  // SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
98
+ // #doc:sse
65
99
  if (type === 'data' && this._sseMode) {
66
100
  this._sseBuffer += payload;
67
101
 
@@ -76,6 +110,7 @@
76
110
  }
77
111
  }
78
112
  return;
113
+ // #end
79
114
  }
80
115
 
81
116
  if (type === 'end') {
@@ -89,27 +124,43 @@
89
124
  }
90
125
  this._done = true;
91
126
  }
92
- if (type === 'error') this._done = true;
127
+ if (type === 'error') {
128
+ this._done = true;
129
+ const listeners = this._events && this._events['error'];
130
+ if (!listeners || listeners.length === 0) {
131
+ // 消费者还没注册监听,先缓存,注册时补发
132
+ this._errorPending = payload;
133
+ return;
134
+ }
135
+ }
93
136
 
94
137
  this.emit(type, payload);
95
138
  }
96
139
 
97
140
  // 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
141
+ // #doc:extract
98
142
  _extractSSEData(raw) {
99
143
  const dataLines = [];
100
144
  for (const line of raw.split('\n')) {
101
145
  if (line.startsWith('data:')) {
102
- dataLines.push(line.replace(/^data:\s*/, ''));
146
+ dataLines.push(line.replace(/^data:\s*/, '').replace(/\r$/, ''));
103
147
  }
104
148
  }
105
149
  if (dataLines.length === 0) return null;
106
150
  return dataLines.join('\n');
151
+ // #end
107
152
  }
108
153
  }
109
154
 
110
155
  // fetch 工厂:注入 adapter,返回对外的 fetch 函数
111
156
 
157
+ // 只有普通对象才自动 JSON 序列化,ArrayBufferView / Blob / FormData 等保持原样
158
+ function isPlainBody(body) {
159
+ return Object.prototype.toString.call(body) === '[object Object]';
160
+ }
161
+
112
162
  function createFetch(adapter) {
163
+ // #doc:factory
113
164
  return function fetch(options) {
114
165
  // 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
115
166
  return new Promise((resolve, reject) => {
@@ -118,13 +169,32 @@
118
169
  return;
119
170
  }
120
171
 
172
+ // 请求体是普通对象时自动序列化,避免 Node 端 req.write(object) 抛 TypeError
173
+ if (isPlainBody(options.body)) {
174
+ options = Object.assign({}, options, { body: JSON.stringify(options.body) });
175
+ }
176
+
121
177
  const response = new Response();
178
+ const controller = typeof AbortController === 'function' ? new AbortController() : null;
179
+ let timer = null;
180
+ let failed = false;
181
+
182
+ response._cancel = () => { if (controller) controller.abort(); };
122
183
 
123
184
  // adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
124
185
  // 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
125
186
  queueMicrotask(() => resolve(response));
187
+ // #end
188
+
189
+ const clearTimer = () => {
190
+ if (timer) {
191
+ clearTimeout(timer);
192
+ timer = null;
193
+ }
194
+ };
126
195
 
127
- adapter(options, {
196
+ // #doc:hooks
197
+ const hooks = {
128
198
  onResponse(meta) {
129
199
  if (meta && typeof meta.status === 'number') {
130
200
  response.status = meta.status;
@@ -142,19 +212,68 @@
142
212
  response._sseMode = true;
143
213
  }
144
214
  }
215
+
216
+ // 非 2xx 单独通知:不占用 error 事件、不锁 _done,错误体照常投递
217
+ if (response.status >= 400) {
218
+ response.emit('http-error', { status: response.status, headers: response.headers });
219
+ }
145
220
  },
146
221
  onData(chunk) {
147
222
  response._push('data', chunk);
148
223
  },
149
224
  onEnd() {
225
+ clearTimer();
150
226
  response._push('end');
151
227
  },
152
228
  onError(err) {
229
+ if (failed) return;
230
+ failed = true;
231
+ clearTimer();
153
232
  // 错误同时通过 error 事件 和 catch 暴露,避免遗漏
154
233
  response._push('error', err);
155
234
  reject(err);
156
235
  }
157
- });
236
+ };
237
+ // #end
238
+
239
+ // #doc:abort
240
+ const abortWith = (err) => {
241
+ if (controller) controller.abort();
242
+ hooks.onError(err);
243
+ };
244
+
245
+ // 超时:到点先中断底层请求,再走统一错误通道
246
+ if (options.timeout > 0) {
247
+ timer = setTimeout(() => {
248
+ timer = null;
249
+ abortWith(new Error('fetch: 请求超时(' + options.timeout + 'ms)'));
250
+ }, options.timeout);
251
+ }
252
+
253
+ // 外部 signal
254
+ if (options.signal) {
255
+ if (options.signal.aborted) {
256
+ abortWith(new Error('fetch: 请求已取消'));
257
+ return;
258
+ }
259
+ options.signal.addEventListener('abort', () => {
260
+ abortWith(new Error('fetch: 请求已取消'));
261
+ });
262
+ }
263
+
264
+ // 把内部 controller 的 signal 交给 adapter,adapter 可据此中断底层请求
265
+ const requestOptions = controller ? Object.assign({}, options, { signal: controller.signal }) : options;
266
+
267
+ let ret;
268
+ try {
269
+ ret = adapter(requestOptions, hooks);
270
+ } catch (err) {
271
+ hooks.onError(err);
272
+ return;
273
+ }
274
+ // adapter 允许返回 Promise,失败也要走同一条错误通道
275
+ if (ret && typeof ret.then === 'function') ret.then(null, hooks.onError);
276
+ // #end
158
277
  });
159
278
  };
160
279
  }
@@ -162,14 +281,14 @@
162
281
  // 浏览器环境适配器:基于原生 fetch + ReadableStream
163
282
  // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
164
283
  function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
165
- const { url, method = 'GET', headers = {}, body } = options;
284
+ const { url, method = 'GET', headers = {}, body, signal } = options;
166
285
 
167
286
  if (typeof fetch !== 'function') {
168
287
  onError(new Error('Global fetch is not available in this environment'));
169
288
  return;
170
289
  }
171
290
 
172
- fetch(url, { method, headers, body })
291
+ fetch(url, { method, headers, body, signal })
173
292
  .then(async (res) => {
174
293
  if (typeof onResponse === 'function') {
175
294
  onResponse({
@@ -184,6 +303,7 @@
184
303
  return;
185
304
  }
186
305
 
306
+ // #doc:read
187
307
  const reader = res.body.getReader();
188
308
  const decoder = new TextDecoder('utf-8');
189
309
 
@@ -200,6 +320,7 @@
200
320
  }
201
321
  // value 是 Uint8Array,解码为字符串
202
322
  onData(decoder.decode(value, { stream: true }));
323
+ // #end
203
324
  }
204
325
  } catch (err) {
205
326
  onError(err);
@@ -214,13 +335,15 @@
214
335
  // 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
215
336
  // 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
216
337
  async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
338
+ // #doc:lazy
217
339
  const [{ default: http }, { default: https }, { URL }] = await Promise.all([
218
340
  import('http'),
219
341
  import('https'),
220
342
  import('url')
221
343
  ]);
344
+ // #end
222
345
 
223
- const { url, method = 'GET', headers = {}, body } = options;
346
+ const { url, method = 'GET', headers = {}, body, signal } = options;
224
347
 
225
348
  let parsed;
226
349
  try {
@@ -241,6 +364,7 @@
241
364
  headers
242
365
  };
243
366
 
367
+ // #doc:req
244
368
  const req = lib.request(reqOptions, (res) => {
245
369
  // 把 status / headers 同步给 Response(若上游关心)
246
370
  if (typeof onResponse === 'function') {
@@ -257,6 +381,20 @@
257
381
  });
258
382
 
259
383
  req.on('error', (err) => onError(err));
384
+ // #end
385
+
386
+ // 取消 / 超时:直接中断底层请求,错误从 req 的 error 事件返回
387
+ // #doc:abort
388
+ if (signal) {
389
+ if (signal.aborted) {
390
+ onError(new Error('请求已取消'));
391
+ return;
392
+ }
393
+ signal.addEventListener('abort', () => {
394
+ req.destroy(new Error('请求已取消'));
395
+ // #end
396
+ });
397
+ }
260
398
 
261
399
  if (body != null) {
262
400
  req.write(body);
@@ -267,29 +405,71 @@
267
405
  // 入口:环境判断 + 选择 adapter,构造并导出 fetch
268
406
 
269
407
  // 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
408
+ // #doc:pick
270
409
  const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
271
410
 
272
411
  const adapter = isBrowser ? browserAdapter : nodeAdapter;
273
412
 
274
413
  const fetch$1 = createFetch(adapter);
275
414
 
276
- // 字符串转JSON
277
- // 适配LLM返回数据格式
278
- function parseString (value) {
279
- value = value.trim().replace(/^data: /, "").replace(/data: \[DONE\]$/, "");
415
+ // 字符串转 JSON,适配 LLM 返回的各种流式格式:
416
+ // 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
417
+ function stripDataPrefix(text) {
418
+ return text.replace(/^data:\s*/, "");
419
+ }
280
420
 
281
- if (/\r{0,1}\n\r{0,1}\ndata: /.test(value)) {
282
- return JSON.parse("[" + (value.split(/\r{0,1}\n\r{0,1}\ndata: /)).join(",") + "]");
283
- } else if (value === "[DONE]") {
284
- return [];
421
+ function tryParse(text) {
422
+ try {
423
+ return { value: JSON.parse(text) };
424
+ } catch (e) {
425
+ return null;
285
426
  }
427
+ }
286
428
 
287
- let result = JSON.parse(value);
288
- if (result.error) throw result.error;
429
+ function parseOne(text, origin) {
430
+ const parsed = tryParse(stripDataPrefix(text.trim()));
431
+ if (!parsed) throw new SyntaxError("模型返回无法解析:" + String(origin).slice(0, 120));
432
+ return parsed.value;
433
+ }
289
434
 
435
+ // 错误响应体({"error":{...}})直接抛出,交给调用方转成 reject
436
+ function checkError(result) {
437
+ if (Array.isArray(result)) {
438
+ for (const item of result) {
439
+ if (item && item.error) throw item.error;
440
+ }
441
+ return result;
442
+ }
443
+ if (result && result.error) throw result.error;
290
444
  return result;
291
445
  }
292
446
 
447
+ function parseString (value) {
448
+ let text = String(value == null ? "" : value).trim();
449
+
450
+ // 结束标记:可能单独出现,也可能紧跟在最后一条事件后面
451
+ // #doc:done
452
+ text = text.replace(/data:\s*\[DONE\]$/, "").trim();
453
+ if (text === "" || text === "[DONE]") return [];
454
+ // #end
455
+
456
+ // 单条:带 data: 前缀或裸 JSON
457
+ let single = tryParse(stripDataPrefix(text)) || tryParse(text);
458
+ if (single) return checkError(single.value);
459
+
460
+ // 多条 SSE 事件,以 "\n\ndata: " 分隔
461
+ // #doc:multi
462
+ const parts = text.split(/\r?\n\r?\ndata: /);
463
+ if (parts.length > 1) return checkError(parts.map(part => parseOne(part, text)));
464
+ // #end
465
+
466
+ // NDJSON:逐行 JSON(跳过空行和 ":" 注释行)
467
+ const lines = text.split(/\r?\n/).filter(line => line.trim() && !line.trim().startsWith(":"));
468
+ if (lines.length > 1) return checkError(lines.map(line => parseOne(line, text)));
469
+
470
+ throw new SyntaxError("模型返回无法解析:" + text.slice(0, 120));
471
+ }
472
+
293
473
  // 解析 LLM 返回的推理内容(reasoning / reasoning_content)
294
474
  // 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
295
475
  function parseReasoning(reasoning, content) {
@@ -308,12 +488,14 @@
308
488
 
309
489
  // 计算文本尾部与标签前缀的最长匹配长度
310
490
  // 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
491
+ // #doc:partial
311
492
  function partialTagLength(text, tag) {
312
493
  const max = Math.min(tag.length - 1, text.length);
313
494
  for (let len = max; len > 0; len--) {
314
495
  if (text.endsWith(tag.slice(0, len))) return len;
315
496
  }
316
497
  return 0;
498
+ // #end
317
499
  }
318
500
 
319
501
  // 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
@@ -369,9 +551,65 @@
369
551
  return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
370
552
  }
371
553
 
554
+ // 新调用的槽位:保留原始字段形状,只保证 function.arguments 是字符串
555
+ function normalizeCall(toolCall) {
556
+ const fn = toolCall.function || {};
557
+ return {
558
+ ...toolCall,
559
+ function: {
560
+ ...fn,
561
+ arguments: typeof fn.arguments === "string" ? fn.arguments : ""
562
+ }
563
+ };
564
+ }
565
+
566
+ // 续片:按 index 优先归并,否则追加到最后一个槽位
567
+ // #doc:merge
568
+ function mergeToolCall(state, toolCall) {
569
+ if (!state._toolSlots) state._toolSlots = new Map();
570
+
571
+ const calls = state.tool_calls;
572
+ const index = typeof toolCall.index === "number" ? toolCall.index : null;
573
+ const hasId = typeof toolCall.id === "string" && toolCall.id !== "";
574
+
575
+ // 带 id 视为新调用;同 id 重复下发时复用已有槽位
576
+ if (hasId) {
577
+ const exist = calls.find(call => call.id === toolCall.id);
578
+ if (exist) {
579
+ appendArguments(exist, toolCall);
580
+ return;
581
+ }
582
+ const slot = normalizeCall(toolCall);
583
+ calls.push(slot);
584
+ if (index !== null) state._toolSlots.set(index, slot);
585
+ return;
586
+ }
587
+
588
+ let slot = index !== null ? state._toolSlots.get(index) : null;
589
+ if (!slot && calls.length) slot = calls[calls.length - 1];
590
+
591
+ // 首片就没有 id:建占位槽位,后续分片补齐参数
592
+ if (!slot) {
593
+ slot = normalizeCall(toolCall);
594
+ calls.push(slot);
595
+ if (index !== null) state._toolSlots.set(index, slot);
596
+ return;
597
+ }
598
+
599
+ appendArguments(slot, toolCall);
600
+ // #end
601
+ }
602
+
603
+ function appendArguments(slot, toolCall) {
604
+ const fn = toolCall.function || {};
605
+ if (fn.name && !slot.function.name) slot.function.name = fn.name;
606
+ if (typeof fn.arguments === "string") slot.function.arguments += fn.arguments;
607
+ }
608
+
372
609
  // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
373
- // 返回累积的 { content, tool_calls }
374
610
  function handleChoices(choices, { logback, thinkback }, state) {
611
+ if (!Array.isArray(choices)) return;
612
+
375
613
  for (let i = 0; i < choices.length; i++) {
376
614
  const delta = choices[i].delta;
377
615
 
@@ -396,14 +634,10 @@
396
634
  }
397
635
  }
398
636
 
399
- // 工具调用
400
- if (delta.tool_calls) {
637
+ // 工具调用分片
638
+ if (Array.isArray(delta.tool_calls)) {
401
639
  for (const toolCall of delta.tool_calls) {
402
- if (toolCall.id) {
403
- state.tool_calls.push(toolCall);
404
- } else {
405
- state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
406
- }
640
+ mergeToolCall(state, toolCall);
407
641
  }
408
642
  }
409
643
  }
@@ -419,69 +653,164 @@
419
653
  }
420
654
  }
421
655
 
656
+ // 统一把各种错误形态收敛成 Error,保证 Promise 一定 settle
657
+ function toError(value, fallback) {
658
+ if (value instanceof Error) return value;
659
+ if (value && typeof value.message === "string") return new Error(value.message);
660
+ try {
661
+ return new Error(String(value));
662
+ } catch (e) {
663
+ return new Error(fallback || "模型请求失败");
664
+ }
665
+ }
666
+
667
+ // HTTP 错误:尽量带出响应体里的 error.message,方便定位
668
+ function errorFromHttp(meta, body) {
669
+ const status = meta && meta.status;
670
+ let detail = "";
671
+
672
+ if (body) {
673
+ try {
674
+ const parsed = JSON.parse(body);
675
+ const raw = parsed && parsed.error;
676
+ detail = (raw && (raw.message || raw)) || "";
677
+ } catch (e) {
678
+ detail = String(body).slice(0, 200);
679
+ }
680
+ if (detail && typeof detail !== "string") detail = JSON.stringify(detail);
681
+ }
682
+
683
+ return new Error("模型服务返回 HTTP " + status + (detail ? ":" + detail : ""));
684
+ }
685
+
422
686
  function completions(params, logback, thinkback) {
423
687
  return new Promise((resolve, reject) => {
424
688
 
689
+ // #doc:state
425
690
  const state = { content: "", tool_calls: [] };
426
691
  const callbacks = { logback, thinkback };
427
692
 
428
693
  let buffer = "";
694
+ let httpError = null;
695
+ let streamError = null;
696
+ let settled = false;
697
+
698
+ const finish = (fn, value) => {
699
+ if (settled) return;
700
+ settled = true;
701
+ fn(value);
702
+ };
703
+ const fail = value => finish(reject, toError(value, "模型请求失败"));
704
+ // #end
705
+
706
+ // #doc:body
707
+ const body = {
708
+ model: this.model,
709
+ messages: params.messages,
710
+ tools: params.tools ? params.tools.map(tool => tool.description) : [],
711
+ stream: params.stream,
712
+ };
713
+ const temperature = params.temperature != null ? params.temperature : this.temperature;
714
+ const topP = params.topP != null ? params.topP : this.topP;
715
+ const maxTokens = params.maxTokens != null ? params.maxTokens : this.maxTokens;
716
+ if (temperature != null) body.temperature = temperature;
717
+ if (topP != null) body.top_p = topP;
718
+ if (maxTokens != null) body.max_tokens = maxTokens;
719
+ // #end
429
720
 
430
721
  fetch$1({
431
- url: `${this.baseURL}/chat/completions`,
722
+ url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
432
723
  method: "POST",
433
724
  headers: {
434
725
  "Authorization": `Bearer ${this.apiKey}`,
435
726
  "Content-Type": "application/json",
436
727
  },
437
- body: JSON.stringify({
438
- model: this.model,
439
- messages: params.messages,
440
- tools: params.tools ? params.tools.map(tool => tool.description) : [],
441
- stream: params.stream,
442
- })
728
+ body: JSON.stringify(body),
729
+ timeout: params.timeout != null ? params.timeout : this.timeout,
730
+ signal: params.signal
731
+ // #end
443
732
  }).then(res => {
444
733
 
734
+ // 非 2xx:非流式等错误体读完再判,流式直接中断
735
+ res.on("http-error", meta => {
736
+ httpError = meta;
737
+ if (params.stream) fail(errorFromHttp(meta));
738
+ });
739
+
445
740
  // 数据流
741
+ // #doc:stream
446
742
  res.on("data", chunk => {
447
- if (params.stream) {
448
- const parsed = parseString(chunk.toString());
449
- if (Array.isArray(parsed)) {
450
- for (const item of parsed) {
451
- handleChoices(item.choices, callbacks, state);
452
- }
453
- } else {
454
- handleChoices(parsed.choices, callbacks, state);
455
- }
456
- } else {
743
+ if (settled) return;
744
+ if (!params.stream) {
457
745
  buffer += chunk;
746
+ return;
747
+ }
748
+ let parsed;
749
+ try {
750
+ parsed = parseString(chunk.toString());
751
+ } catch (e) {
752
+ streamError = e;
753
+ fail(e);
754
+ // #end
755
+ return;
756
+ }
757
+ try {
758
+ const items = Array.isArray(parsed) ? parsed : [parsed];
759
+ for (const item of items) handleChoices(item.choices, callbacks, state);
760
+ } catch (e) {
761
+ fail(e);
458
762
  }
459
763
  });
460
764
 
461
765
  // 结束
462
766
  res.on("end", () => {
463
767
  if (!params.stream) {
464
- handleChoices(
465
- [{ delta: parseString(buffer).choices[0].message }],
466
- callbacks,
467
- state
468
- );
768
+ if (httpError) {
769
+ fail(errorFromHttp(httpError, buffer));
770
+ return;
771
+ }
772
+ try {
773
+ const parsed = parseString(buffer);
774
+ const choices = parsed && parsed.choices;
775
+ if (!choices || !choices[0] || !choices[0].message) {
776
+ throw new Error("模型响应缺少 choices[0].message");
777
+ }
778
+ handleChoices([{ delta: choices[0].message }], callbacks, state);
779
+ } catch (e) {
780
+ fail(e);
781
+ return;
782
+ }
783
+ } else if (streamError) {
784
+ fail(streamError);
785
+ return;
786
+ } else if (httpError) {
787
+ fail(errorFromHttp(httpError));
788
+ return;
469
789
  }
790
+
470
791
  // 冲刷 <think> 标签截断残留
471
792
  flushThinkBuffer(state, callbacks);
472
- resolve({ content: state.content, tool_calls: state.tool_calls });
793
+ finish(resolve, { content: state.content, tool_calls: state.tool_calls });
473
794
  });
474
795
 
475
- res.on("error", err => reject(err));
476
- }).catch(err => reject(err));
796
+ res.on("error", err => fail(err));
797
+ }).catch(err => fail(err));
477
798
 
478
799
  });
479
800
  }
480
801
 
802
+ // #doc:ctor
481
803
  function Model(fields) {
482
804
  this.model = fields.model;
483
805
  this.apiKey = fields.apiKey;
484
806
  this.baseURL = fields.baseURL;
807
+
808
+ // 可选请求参数:显式传入才写进请求体,保持旧行为不变
809
+ this.temperature = fields.temperature;
810
+ this.topP = fields.topP;
811
+ this.maxTokens = fields.maxTokens;
812
+ this.timeout = fields.timeout;
813
+ // #end
485
814
  }
486
815
 
487
816
  Model.prototype.completions = completions;
@@ -496,27 +825,36 @@
496
825
  */
497
826
  function callFuns(_this, tool_calls) {
498
827
 
499
- const tasks = tool_calls.map(call => {
500
- const tool = _this.tools.find(
501
- t => t.description.function.name === call.function.name
828
+ // #doc:map
829
+ const tasks = (tool_calls || []).map(call => {
830
+ const fn = (call && call.function) || {};
831
+ const tool = (_this.tools || []).find(
832
+ t => t.description.function.name === fn.name
502
833
  );
503
834
 
504
835
  if (!tool) {
505
- return Promise.resolve("工具" + call.function.name + "不存在");
836
+ return Promise.resolve("工具" + fn.name + "不存在");
837
+ }
838
+
839
+ if (typeof tool.execute !== "function") {
840
+ return Promise.resolve("工具" + fn.name + "缺少 execute");
506
841
  }
507
842
 
508
- let result;
843
+ let args;
509
844
  try {
510
- result = tool.execute(JSON.parse(call.function.arguments));
845
+ // 无参工具:arguments 为空字符串或缺失时按 {} 处理
846
+ args = typeof fn.arguments === "string" && fn.arguments.trim() ? JSON.parse(fn.arguments) : {};
511
847
  } catch (e) {
512
848
  return Promise.resolve("参数解析失败:" + e);
513
849
  }
514
850
 
515
- if (result instanceof Promise) {
516
- // 工具内部报错也不要阻断对话,转成字符串继续往下走
517
- return result.catch(e => "运行出错:" + e);
851
+ try {
852
+ // 工具内部报错(含同步抛错)也不要阻断对话,转成字符串继续往下走
853
+ return Promise.resolve(tool.execute(args)).catch(e => "运行出错:" + e);
854
+ } catch (e) {
855
+ return Promise.resolve("运行出错:" + e);
856
+ // #end
518
857
  }
519
- return Promise.resolve(result);
520
858
  });
521
859
 
522
860
  return Promise.all(tasks);
@@ -556,11 +894,17 @@
556
894
  */
557
895
  async function runConversation(_this, messages, logback, thinkback) {
558
896
 
559
- while (true) {
897
+ // maxSteps 为 0 表示不限制
898
+ // #doc:loop
899
+ const maxSteps = _this.maxSteps > 0 ? _this.maxSteps : Infinity;
900
+
901
+ for (let step = 1; step <= maxSteps; step++) {
902
+
560
903
  const result = await _this.model.completions({
561
904
  messages,
562
905
  tools: _this.tools,
563
906
  stream: _this.stream,
907
+ signal: _this.signal || void 0,
564
908
  }, logback, thinkback);
565
909
 
566
910
  const hasToolCalls = appendAssistantMessage(messages, result);
@@ -574,7 +918,10 @@
574
918
  result.tool_calls.forEach((call, i) => {
575
919
  messages.push(toToolMessage(call, toolResults[i]));
576
920
  });
921
+ // #end
577
922
  }
923
+
924
+ throw new Error("工具调用步骤超过 maxSteps 上限:" + _this.maxSteps);
578
925
  }
579
926
 
580
927
  function initOption(setOption, defaultOption) {
@@ -589,21 +936,30 @@
589
936
  this.ms = ms;
590
937
  }
591
938
 
592
- CreateTool.prototype.create = function ({ description, execute }) {
939
+ /**
940
+ * 包装一个工具。
941
+ *
942
+ * @param {object} input description + 可选 execute(缺省即前端工具)
943
+ * @param {object} [options] { timeout } 前端工具等待页面回传的超时毫秒数,0 表示不限制
944
+ */
945
+ CreateTool.prototype.create = function ({ description, execute }, options) {
593
946
  let _this = this;
947
+ const timeout = options && options.timeout > 0 ? options.timeout : 0;
948
+
594
949
  return {
595
950
  description,
596
951
  execute: async function (args) {
597
952
  let toolInfo = {
598
953
  type: "tool-call",
599
954
  status: "pending",
600
- id: Date.now().toString()+"_"+Math.random().toString(36).substring(2).toUpperCase(),
955
+ id: Date.now().toString() + "_" + Math.random().toString(36).substring(2).toUpperCase(),
601
956
  name: description.function.name,
602
957
  caller: execute ? "backend" : "frontend",
603
958
  args
604
959
  };
605
960
 
606
961
  // 后端工具调用
962
+ // #doc:backend
607
963
  if (execute) {
608
964
  _this.ms.send(toolInfo); // 开始调用工具
609
965
 
@@ -621,39 +977,91 @@
621
977
  result
622
978
  }, toolInfo));
623
979
 
980
+ // 失败继续抛出,由 callFuns 统一转成给模型的错误文本
981
+ if (status === "error") throw result;
982
+
624
983
  return result;
984
+ // #end
625
985
  }
626
986
 
627
987
  // 前端工具调用
628
- else {
629
- let _resolve = null;
630
- globalThis[toolInfo.id] = function (result) {
631
- _resolve(result);
632
- delete globalThis[toolInfo.id];
633
- };
988
+ let settle = null;
989
+ let timer = null;
634
990
 
635
- _this.ms.send(toolInfo); // 开始调用工具
991
+ const done = () => {
992
+ if (timer) { clearTimeout(timer); timer = null; }
993
+ delete globalThis[toolInfo.id];
994
+ };
995
+
996
+ // 先建好 Promise 再推事件,避免页面同步回传时 _resolve 还不存在
997
+ const waiting = new Promise((resolve, reject) => {
998
+ settle = { resolve, reject };
999
+ });
1000
+
1001
+ globalThis[toolInfo.id] = function (result, status) {
1002
+ if (!settle) return;
1003
+ const current = settle;
1004
+ settle = null;
1005
+ done();
1006
+ if (status === "error") current.reject(result);
1007
+ else current.resolve(result);
1008
+ };
1009
+
1010
+ if (timeout > 0) {
1011
+ timer = setTimeout(() => {
1012
+ if (!settle) return;
1013
+ const current = settle;
1014
+ settle = null;
1015
+ done();
1016
+ current.reject(new Error("前端工具调用超时:" + description.function.name));
1017
+ }, timeout);
1018
+ }
636
1019
 
637
- return new Promise((resolve, reject) => {
638
- _resolve = resolve;
639
- });
1020
+ try {
1021
+ _this.ms.send(toolInfo); // 开始调用工具
1022
+ } catch (error) {
1023
+ settle = null;
1024
+ done();
1025
+ throw error;
640
1026
  }
1027
+
1028
+ return waiting;
641
1029
  }
642
1030
  };
643
1031
  };
644
1032
 
645
1033
  function Agent(option) {
1034
+ option = option || {};
1035
+
1036
+ // #doc:ctor
646
1037
  this.model = new Model(option.model);
647
1038
  this.tools = option.tools || [];
648
1039
  this.systemPrompt = option.systemPrompt || "";
649
1040
  this.stream = option.stream || false;
1041
+
1042
+ // 工具调用循环上限,0 表示不限制
1043
+ this.maxSteps = option.maxSteps > 0 ? option.maxSteps : 0;
1044
+
1045
+ // 取消信号,透传给每次模型请求
1046
+ this.signal = option.signal || null;
1047
+ // #end
650
1048
  }
651
1049
 
652
1050
  Agent.prototype.generate = function (messages, logback, thinkback) {
653
- if (this.systemPrompt) messages.unshift({
654
- role: "system",
655
- content: this.systemPrompt
656
- });
1051
+ if (!Array.isArray(messages)) messages = [];
1052
+
1053
+ // 注入 system 提示词;首条已是同内容时跳过,避免复用同一数组时累积(原地修改,保持契约)
1054
+ // #doc:system
1055
+ if (this.systemPrompt) {
1056
+ let first = messages[0];
1057
+ if (!first || first.role !== "system" || first.content !== this.systemPrompt) {
1058
+ messages.unshift({
1059
+ role: "system",
1060
+ content: this.systemPrompt
1061
+ });
1062
+ }
1063
+ }
1064
+ // #end
657
1065
 
658
1066
  return runConversation(this, messages, logback, thinkback);
659
1067
  };