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