@auipage/model 0.1.0 → 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,489 +1,818 @@
1
- /*! @auipage/model v0.1.0 */
1
+ /*! @auipage/model 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) :
5
5
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.auipage_model = {}));
6
6
  })(this, (function (exports) { 'use strict';
7
7
 
8
- // 极简 EventEmitter:on / off / emit,供 Response 复用
9
- class Emitter {
10
- constructor() {
11
- this._events = Object.create(null);
12
- }
13
-
14
- on(event, listener) {
15
- if (typeof listener !== 'function') return this;
16
- const list = this._events[event] || (this._events[event] = []);
17
- list.push(listener);
18
- return this;
19
- }
20
-
21
- off(event, listener) {
22
- const list = this._events[event];
23
- if (!list) return this;
24
- const idx = list.indexOf(listener);
25
- if (idx >= 0) list.splice(idx, 1);
26
- if (list.length === 0) delete this._events[event];
27
- return this;
28
- }
29
-
30
- emit(event, ...args) {
31
- const list = this._events[event];
32
- if (!list || list.length === 0) return false;
33
- // 复制一份再触发,避免 off 回调过程中影响本次派发
34
- for (const fn of list.slice()) {
35
- try {
36
- fn.apply(null, args);
37
- } catch (e) {
38
- // 单个监听器异常不影响其它监听器
39
- // 用 queueMicrotask 抛到全局,避免污染 emit 调用栈
40
- queueMicrotask(() => { throw e; });
41
- }
42
- }
43
- return true;
44
- }
8
+ // 极简 EventEmitter:on / off / emit,供 Response 复用
9
+ class Emitter {
10
+ constructor() {
11
+ this._events = Object.create(null);
12
+ }
13
+
14
+ on(event, listener) {
15
+ if (typeof listener !== 'function') return this;
16
+ const list = this._events[event] || (this._events[event] = []);
17
+ list.push(listener);
18
+ return this;
19
+ }
20
+
21
+ off(event, listener) {
22
+ const list = this._events[event];
23
+ if (!list) return this;
24
+ const idx = list.indexOf(listener);
25
+ if (idx >= 0) list.splice(idx, 1);
26
+ if (list.length === 0) delete this._events[event];
27
+ return this;
28
+ }
29
+
30
+ // #doc:emit
31
+ emit(event, ...args) {
32
+ const list = this._events[event];
33
+ if (!list || list.length === 0) return false;
34
+ // 复制一份再触发,避免 off 回调过程中影响本次派发
35
+ for (const fn of list.slice()) {
36
+ try {
37
+ fn.apply(null, args);
38
+ } catch (e) {
39
+ // 单个监听器异常不影响其它监听器,也不再冒泡成进程级异常
40
+ console.error(e);
41
+ }
42
+ }
43
+ return true;
44
+ // #end
45
+ }
45
46
  }
46
47
 
47
- // Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
48
-
49
- class Response extends Emitter {
50
- constructor() {
51
- super();
52
- this.status = 0;
53
- this.headers = {};
54
- this.ok = false;
55
- this._done = false; // 标记是否已经 end/error,防止重复触发
56
- this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
57
- this._sseBuffer = ''; // SSE 缓冲区,处理 chunk 边界
58
- }
59
-
60
- // 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
61
- _push(type, payload) {
62
- if (this._done && type !== 'error') return;
63
-
64
- // SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
65
- if (type === 'data' && this._sseMode) {
66
- this._sseBuffer += payload;
67
-
68
- // 按 \n\n 分割出完整事件,最后一段可能不完整
69
- const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
70
- this._sseBuffer = parts.pop();
71
-
72
- for (const part of parts) {
73
- const payload = this._extractSSEData(part);
74
- if (payload !== null) {
75
- this.emit('data', payload);
76
- }
77
- }
78
- return;
79
- }
80
-
81
- if (type === 'end') {
82
- // SSE 模式下,flush 缓冲区残留
83
- if (this._sseMode && this._sseBuffer.trim()) {
84
- const payload = this._extractSSEData(this._sseBuffer);
85
- if (payload !== null) {
86
- this.emit('data', payload);
87
- }
88
- this._sseBuffer = '';
89
- }
90
- this._done = true;
91
- }
92
- if (type === 'error') this._done = true;
93
-
94
- this.emit(type, payload);
95
- }
96
-
97
- // 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
98
- _extractSSEData(raw) {
99
- const dataLines = [];
100
- for (const line of raw.split('\n')) {
101
- if (line.startsWith('data:')) {
102
- dataLines.push(line.replace(/^data:\s*/, ''));
103
- }
104
- }
105
- if (dataLines.length === 0) return null;
106
- return dataLines.join('\n');
107
- }
48
+ // Response:暴露 on/off 事件机制,承载 status / headers / 流式 data/end/error
49
+
50
+ class Response extends Emitter {
51
+ constructor() {
52
+ super();
53
+ // #doc:state
54
+ this.status = 0;
55
+ this.headers = {};
56
+ this.ok = false;
57
+ this._done = false; // 标记是否已经 end/error,防止重复触发
58
+ this._sseMode = false; // SSE 模式:按 \n\n 分割事件,提取 data: 字段原始字符串
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];
91
+ }
92
+
93
+ // 提供一个统一入口让 adapter 推数据,屏蔽 Emitter 的细节
94
+ _push(type, payload) {
95
+ if (this._done && type !== 'error') return;
96
+
97
+ // SSE 模式:缓冲 + 按 \n\n 分割,提取 data: 字段原始字符串
98
+ // #doc:sse
99
+ if (type === 'data' && this._sseMode) {
100
+ this._sseBuffer += payload;
101
+
102
+ // 按 \n\n 分割出完整事件,最后一段可能不完整
103
+ const parts = this._sseBuffer.split(/\r{0,1}\n\r{0,1}\n/);
104
+ this._sseBuffer = parts.pop();
105
+
106
+ for (const part of parts) {
107
+ const payload = this._extractSSEData(part);
108
+ if (payload !== null) {
109
+ this.emit('data', payload);
110
+ }
111
+ }
112
+ return;
113
+ // #end
114
+ }
115
+
116
+ if (type === 'end') {
117
+ // SSE 模式下,flush 缓冲区残留
118
+ if (this._sseMode && this._sseBuffer.trim()) {
119
+ const payload = this._extractSSEData(this._sseBuffer);
120
+ if (payload !== null) {
121
+ this.emit('data', payload);
122
+ }
123
+ this._sseBuffer = '';
124
+ }
125
+ this._done = true;
126
+ }
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
+ }
136
+
137
+ this.emit(type, payload);
138
+ }
139
+
140
+ // 从一个 SSE 事件块中提取 data: 字段内容(去掉前缀,多行用 \n 拼接)
141
+ // #doc:extract
142
+ _extractSSEData(raw) {
143
+ const dataLines = [];
144
+ for (const line of raw.split('\n')) {
145
+ if (line.startsWith('data:')) {
146
+ dataLines.push(line.replace(/^data:\s*/, '').replace(/\r$/, ''));
147
+ }
148
+ }
149
+ if (dataLines.length === 0) return null;
150
+ return dataLines.join('\n');
151
+ // #end
152
+ }
108
153
  }
109
154
 
110
- // fetch 工厂:注入 adapter,返回对外的 fetch 函数
111
-
112
- function createFetch(adapter) {
113
- return function fetch(options) {
114
- // 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
115
- return new Promise((resolve, reject) => {
116
- if (!options || !options.url) {
117
- reject(new Error('fetch: options.url is required'));
118
- return;
119
- }
120
-
121
- const response = new Response();
122
-
123
- // adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
124
- // 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
125
- queueMicrotask(() => resolve(response));
126
-
127
- adapter(options, {
128
- onResponse(meta) {
129
- if (meta && typeof meta.status === 'number') {
130
- response.status = meta.status;
131
- response.ok = meta.status >= 200 && meta.status < 300;
132
- }
133
- if (meta && meta.headers) {
134
- response.headers = meta.headers;
135
-
136
- // 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
137
- const contentType =
138
- (typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
139
- meta.headers['content-type'] ||
140
- '';
141
- if (contentType.includes('text/event-stream')) {
142
- response._sseMode = true;
143
- }
144
- }
145
- },
146
- onData(chunk) {
147
- response._push('data', chunk);
148
- },
149
- onEnd() {
150
- response._push('end');
151
- },
152
- onError(err) {
153
- // 错误同时通过 error 事件 和 catch 暴露,避免遗漏
154
- response._push('error', err);
155
- reject(err);
156
- }
157
- });
158
- });
159
- };
155
+ // fetch 工厂:注入 adapter,返回对外的 fetch 函数
156
+
157
+ // 只有普通对象才自动 JSON 序列化,ArrayBufferView / Blob / FormData 等保持原样
158
+ function isPlainBody(body) {
159
+ return Object.prototype.toString.call(body) === '[object Object]';
160
160
  }
161
161
 
162
- // 浏览器环境适配器:基于原生 fetch + ReadableStream
163
- // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
164
- function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
165
- const { url, method = 'GET', headers = {}, body } = options;
166
-
167
- if (typeof fetch !== 'function') {
168
- onError(new Error('Global fetch is not available in this environment'));
169
- return;
170
- }
171
-
172
- fetch(url, { method, headers, body })
173
- .then(async (res) => {
174
- if (typeof onResponse === 'function') {
175
- onResponse({
176
- status: res.status || 0,
177
- headers: res.headers || {}
178
- });
179
- }
180
-
181
- // 没有 body(例如 204)直接结束
182
- if (!res.body) {
183
- onEnd();
184
- return;
185
- }
186
-
187
- const reader = res.body.getReader();
188
- const decoder = new TextDecoder('utf-8');
189
-
190
- // 循环读取流直到 done
191
- // 用 async IIFE 形式启动,错误统一走 onError
192
- (async () => {
193
- try {
194
- // eslint-disable-next-line no-constant-condition
195
- while (true) {
196
- const { value, done } = await reader.read();
197
- if (done) {
198
- onEnd();
199
- return;
200
- }
201
- // value 是 Uint8Array,解码为字符串
202
- onData(decoder.decode(value, { stream: true }));
203
- }
204
- } catch (err) {
205
- onError(err);
206
- }
207
- })();
208
- })
209
- .catch((err) => onError(err));
162
+ function createFetch(adapter) {
163
+ // #doc:factory
164
+ return function fetch(options) {
165
+ // 必须返回 Promise<response>,让调用方能 .then(res => res.on(...))
166
+ return new Promise((resolve, reject) => {
167
+ if (!options || !options.url) {
168
+ reject(new Error('fetch: options.url is required'));
169
+ return;
170
+ }
171
+
172
+ // 请求体是普通对象时自动序列化,避免 Node 端 req.write(object) 抛 TypeError
173
+ if (isPlainBody(options.body)) {
174
+ options = Object.assign({}, options, { body: JSON.stringify(options.body) });
175
+ }
176
+
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(); };
183
+
184
+ // adapter 调用前先把 response 交出去,确保 .then(res => ...) 里能立刻 on(...) 注册监听
185
+ // 用 queueMicrotask 推后一拍,避免同步 resolve 后用户立刻注册的监听错过首个 data
186
+ queueMicrotask(() => resolve(response));
187
+ // #end
188
+
189
+ const clearTimer = () => {
190
+ if (timer) {
191
+ clearTimeout(timer);
192
+ timer = null;
193
+ }
194
+ };
195
+
196
+ // #doc:hooks
197
+ const hooks = {
198
+ onResponse(meta) {
199
+ if (meta && typeof meta.status === 'number') {
200
+ response.status = meta.status;
201
+ response.ok = meta.status >= 200 && meta.status < 300;
202
+ }
203
+ if (meta && meta.headers) {
204
+ response.headers = meta.headers;
205
+
206
+ // 自动检测 SSE:浏览器 Headers 对象用 get(),Node 的 plain object 用 []
207
+ const contentType =
208
+ (typeof meta.headers.get === 'function' && meta.headers.get('content-type')) ||
209
+ meta.headers['content-type'] ||
210
+ '';
211
+ if (contentType.includes('text/event-stream')) {
212
+ response._sseMode = true;
213
+ }
214
+ }
215
+
216
+ // 非 2xx 单独通知:不占用 error 事件、不锁 _done,错误体照常投递
217
+ if (response.status >= 400) {
218
+ response.emit('http-error', { status: response.status, headers: response.headers });
219
+ }
220
+ },
221
+ onData(chunk) {
222
+ response._push('data', chunk);
223
+ },
224
+ onEnd() {
225
+ clearTimer();
226
+ response._push('end');
227
+ },
228
+ onError(err) {
229
+ if (failed) return;
230
+ failed = true;
231
+ clearTimer();
232
+ // 错误同时通过 error 事件 和 catch 暴露,避免遗漏
233
+ response._push('error', err);
234
+ reject(err);
235
+ }
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
277
+ });
278
+ };
210
279
  }
211
280
 
212
- // Node 环境适配器:基于 http / https,天然流式输出
213
- // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
214
- // 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
215
- // 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
216
- async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
217
- const [{ default: http }, { default: https }, { URL }] = await Promise.all([
218
- import('http'),
219
- import('https'),
220
- import('url')
221
- ]);
222
-
223
- const { url, method = 'GET', headers = {}, body } = options;
224
-
225
- let parsed;
226
- try {
227
- parsed = new URL(url);
228
- } catch (e) {
229
- onError(e);
230
- return;
231
- }
232
-
233
- const isHttps = parsed.protocol === 'https:';
234
- const lib = isHttps ? https : http;
235
-
236
- const reqOptions = {
237
- method,
238
- hostname: parsed.hostname,
239
- port: parsed.port || (isHttps ? 443 : 80),
240
- path: parsed.pathname + parsed.search,
241
- headers
242
- };
243
-
244
- const req = lib.request(reqOptions, (res) => {
245
- // 把 status / headers 同步给 Response(若上游关心)
246
- if (typeof onResponse === 'function') {
247
- onResponse({
248
- status: res.statusCode || 0,
249
- headers: res.headers || {}
250
- });
251
- }
252
-
253
- res.setEncoding('utf8');
254
- res.on('data', (chunk) => onData(chunk));
255
- res.on('end', () => onEnd());
256
- res.on('error', (err) => onError(err));
257
- });
258
-
259
- req.on('error', (err) => onError(err));
260
-
261
- if (body != null) {
262
- req.write(body);
263
- }
264
- req.end();
281
+ // 浏览器环境适配器:基于原生 fetch + ReadableStream
282
+ // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
283
+ function browserAdapter(options, { onData, onEnd, onError, onResponse }) {
284
+ const { url, method = 'GET', headers = {}, body, signal } = options;
285
+
286
+ if (typeof fetch !== 'function') {
287
+ onError(new Error('Global fetch is not available in this environment'));
288
+ return;
289
+ }
290
+
291
+ fetch(url, { method, headers, body, signal })
292
+ .then(async (res) => {
293
+ if (typeof onResponse === 'function') {
294
+ onResponse({
295
+ status: res.status || 0,
296
+ headers: res.headers || {}
297
+ });
298
+ }
299
+
300
+ // 没有 body(例如 204)直接结束
301
+ if (!res.body) {
302
+ onEnd();
303
+ return;
304
+ }
305
+
306
+ // #doc:read
307
+ const reader = res.body.getReader();
308
+ const decoder = new TextDecoder('utf-8');
309
+
310
+ // 循环读取流直到 done
311
+ // 用 async IIFE 形式启动,错误统一走 onError
312
+ (async () => {
313
+ try {
314
+ // eslint-disable-next-line no-constant-condition
315
+ while (true) {
316
+ const { value, done } = await reader.read();
317
+ if (done) {
318
+ onEnd();
319
+ return;
320
+ }
321
+ // value 是 Uint8Array,解码为字符串
322
+ onData(decoder.decode(value, { stream: true }));
323
+ // #end
324
+ }
325
+ } catch (err) {
326
+ onError(err);
327
+ }
328
+ })();
329
+ })
330
+ .catch((err) => onError(err));
265
331
  }
266
332
 
267
- // 入口:环境判断 + 选择 adapter,构造并导出 fetch
268
-
269
- // 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
270
- const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
271
-
272
- const adapter = isBrowser ? browserAdapter : nodeAdapter;
273
-
333
+ // Node 环境适配器:基于 http / https,天然流式输出
334
+ // adapter 协议:(options, { onData, onEnd, onError, onResponse }) => void
335
+ // 运行时不通过顶层 import 静态拉取 node 内置模块,而是 await import 按需加载,
336
+ // 避免在浏览器 / bundler 解析阶段触发对 'http' / 'https' / 'url' 的静态分析。
337
+ async function nodeAdapter(options, { onData, onEnd, onError, onResponse }) {
338
+ // #doc:lazy
339
+ const [{ default: http }, { default: https }, { URL }] = await Promise.all([
340
+ import('http'),
341
+ import('https'),
342
+ import('url')
343
+ ]);
344
+ // #end
345
+
346
+ const { url, method = 'GET', headers = {}, body, signal } = options;
347
+
348
+ let parsed;
349
+ try {
350
+ parsed = new URL(url);
351
+ } catch (e) {
352
+ onError(e);
353
+ return;
354
+ }
355
+
356
+ const isHttps = parsed.protocol === 'https:';
357
+ const lib = isHttps ? https : http;
358
+
359
+ const reqOptions = {
360
+ method,
361
+ hostname: parsed.hostname,
362
+ port: parsed.port || (isHttps ? 443 : 80),
363
+ path: parsed.pathname + parsed.search,
364
+ headers
365
+ };
366
+
367
+ // #doc:req
368
+ const req = lib.request(reqOptions, (res) => {
369
+ // 把 status / headers 同步给 Response(若上游关心)
370
+ if (typeof onResponse === 'function') {
371
+ onResponse({
372
+ status: res.statusCode || 0,
373
+ headers: res.headers || {}
374
+ });
375
+ }
376
+
377
+ res.setEncoding('utf8');
378
+ res.on('data', (chunk) => onData(chunk));
379
+ res.on('end', () => onEnd());
380
+ res.on('error', (err) => onError(err));
381
+ });
382
+
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
+ }
398
+
399
+ if (body != null) {
400
+ req.write(body);
401
+ }
402
+ req.end();
403
+ }
404
+
405
+ // 入口:环境判断 + 选择 adapter,构造并导出 fetch
406
+
407
+ // 浏览器存在 window / document;Node 不存在。SSR 环境需要 polyfill 时也能正确走 nodeAdapter
408
+ // #doc:pick
409
+ const isBrowser = typeof window !== 'undefined' && typeof window.document !== 'undefined';
410
+
411
+ const adapter = isBrowser ? browserAdapter : nodeAdapter;
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\]$/, "");
280
-
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 [];
285
- }
286
-
287
- let result = JSON.parse(value);
288
- if (result.error) throw result.error;
289
-
290
- return result;
415
+ // 字符串转 JSON,适配 LLM 返回的各种流式格式:
416
+ // 单条 JSON(含 pretty-printed 的多行)、带 "data: " 前缀的 SSE、多条 SSE 事件、NDJSON
417
+ function stripDataPrefix(text) {
418
+ return text.replace(/^data:\s*/, "");
419
+ }
420
+
421
+ function tryParse(text) {
422
+ try {
423
+ return { value: JSON.parse(text) };
424
+ } catch (e) {
425
+ return null;
426
+ }
291
427
  }
292
428
 
293
- // 解析 LLM 返回的推理内容(reasoning / reasoning_content)
294
- // 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
295
- function parseReasoning(reasoning, content) {
296
- if (!/<\/think>/.test(reasoning)) return reasoning;
297
-
298
- const parts = reasoning.split("</think>");
299
- const thinkPart = parts[0].replace("<think>", "");
300
- return {
301
- reasoning: thinkPart,
302
- content: parts[1] + (content || "")
303
- };
304
- }
305
-
306
- const OPEN = "<think>";
307
- const CLOSE = "</think>";
308
-
309
- // 计算文本尾部与标签前缀的最长匹配长度
310
- // 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
311
- function partialTagLength(text, tag) {
312
- const max = Math.min(tag.length - 1, text.length);
313
- for (let len = max; len > 0; len--) {
314
- if (text.endsWith(tag.slice(0, len))) return len;
315
- }
316
- return 0;
317
- }
318
-
319
- // 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
320
- // 这里把它剥离出来:思考片段归 thinkback,其余归正文
321
- // 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
322
- // 返回 { thinking, content }
323
- function extractThink(content, state) {
324
- const buf = (state.thinkBuf || "") + content;
325
- state.thinkBuf = "";
326
-
327
- // 正处于思考块内:寻找 </think>
328
- if (state.inThink) {
329
- const end = buf.indexOf(CLOSE);
330
- if (end === -1) {
331
- const hold = partialTagLength(buf, CLOSE);
332
- state.thinkBuf = buf.slice(buf.length - hold);
333
- return { thinking: buf.slice(0, buf.length - hold), content: "" };
334
- }
335
- state.inThink = false;
336
- const rest = extractThink(buf.slice(end + CLOSE.length), state);
337
- return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
338
- }
339
-
340
- // 正常正文:寻找 <think>
341
- const start = buf.indexOf(OPEN);
342
- if (start === -1) {
343
- const hold = partialTagLength(buf, OPEN);
344
- state.thinkBuf = buf.slice(buf.length - hold);
345
- return { thinking: "", content: buf.slice(0, buf.length - hold) };
346
- }
347
-
348
- const end = buf.indexOf(CLOSE, start);
349
- if (end !== -1) {
350
- const rest = extractThink(buf.slice(end + CLOSE.length), state);
351
- return {
352
- thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
353
- content: buf.slice(0, start) + rest.content
354
- };
355
- }
356
-
357
- // 有 <think> 无 </think>:进入思考态
358
- state.inThink = true;
359
- const body = buf.slice(start + OPEN.length);
360
- const hold = partialTagLength(body, CLOSE);
361
- state.thinkBuf = body.slice(body.length - hold);
362
- return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
363
- }
364
-
365
- // 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
366
- function flushThink(state) {
367
- const buf = state.thinkBuf || "";
368
- state.thinkBuf = "";
369
- return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
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;
370
433
  }
371
434
 
372
- // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
373
- // 返回累积的 { content, tool_calls }
374
- function handleChoices(choices, { logback, thinkback }, state) {
375
- for (let i = 0; i < choices.length; i++) {
376
- const delta = choices[i].delta;
377
-
378
- // 推理内容(reasoning / reasoning_content 字段)
379
- let reasoning = delta.reasoning || delta.reasoning_content;
380
- if (reasoning) {
381
- const parsed = parseReasoning(reasoning, delta.content);
382
- if (typeof parsed === "object") {
383
- reasoning = parsed.reasoning;
384
- delta.content = parsed.content;
385
- }
386
- if (thinkback) thinkback(reasoning);
387
- }
388
-
389
- // 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
390
- if (delta.content) {
391
- const extracted = extractThink(delta.content, state);
392
- if (extracted.thinking && thinkback) thinkback(extracted.thinking);
393
- if (extracted.content) {
394
- if (logback) logback(extracted.content);
395
- state.content += extracted.content;
396
- }
397
- }
398
-
399
- // 工具调用
400
- if (delta.tool_calls) {
401
- 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
- }
407
- }
408
- }
409
- }
410
- }
411
-
412
- // 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
413
- function flushThinkBuffer(state, { logback, thinkback }) {
414
- const flushed = flushThink(state);
415
- if (flushed.thinking && thinkback) thinkback(flushed.thinking);
416
- if (flushed.content) {
417
- if (logback) logback(flushed.content);
418
- state.content += flushed.content;
419
- }
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;
444
+ return result;
420
445
  }
421
446
 
422
- function completions(params, logback, thinkback) {
423
- return new Promise((resolve, reject) => {
424
-
425
- const state = { content: "", tool_calls: [] };
426
- const callbacks = { logback, thinkback };
427
-
428
- let buffer = "";
429
-
430
- fetch$1({
431
- url: `${this.baseURL}/chat/completions`,
432
- method: "POST",
433
- headers: {
434
- "Authorization": `Bearer ${this.apiKey}`,
435
- "Content-Type": "application/json",
436
- },
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
- })
443
- }).then(res => {
444
-
445
- // 数据流
446
- 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 {
457
- buffer += chunk;
458
- }
459
- });
460
-
461
- // 结束
462
- res.on("end", () => {
463
- if (!params.stream) {
464
- handleChoices(
465
- [{ delta: parseString(buffer).choices[0].message }],
466
- callbacks,
467
- state
468
- );
469
- }
470
- // 冲刷 <think> 标签截断残留
471
- flushThinkBuffer(state, callbacks);
472
- resolve({ content: state.content, tool_calls: state.tool_calls });
473
- });
474
-
475
- res.on("error", err => reject(err));
476
- }).catch(err => reject(err));
477
-
478
- });
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
+
473
+ // 解析 LLM 返回的推理内容(reasoning / reasoning_content)
474
+ // 将 <think>...</think> 形式的内容从 reasoning 字段中剥离出来
475
+ function parseReasoning(reasoning, content) {
476
+ if (!/<\/think>/.test(reasoning)) return reasoning;
477
+
478
+ const parts = reasoning.split("</think>");
479
+ const thinkPart = parts[0].replace("<think>", "");
480
+ return {
481
+ reasoning: thinkPart,
482
+ content: parts[1] + (content || "")
483
+ };
484
+ }
485
+
486
+ const OPEN = "<think>";
487
+ const CLOSE = "</think>";
488
+
489
+ // 计算文本尾部与标签前缀的最长匹配长度
490
+ // 用于标签可能被截断在 chunk 边界的情况(如收到 "</thi")
491
+ // #doc:partial
492
+ function partialTagLength(text, tag) {
493
+ const max = Math.min(tag.length - 1, text.length);
494
+ for (let len = max; len > 0; len--) {
495
+ if (text.endsWith(tag.slice(0, len))) return len;
496
+ }
497
+ return 0;
498
+ // #end
499
+ }
500
+
501
+ // 部分模型(如 MiniMax-M3)会把思考过程以 <think>...</think> 形式混在 content 中
502
+ // 这里把它剥离出来:思考片段归 thinkback,其余归正文
503
+ // 流式时标签可能分散在多个 chunk,依赖 state.inThink / state.thinkBuf 跨 chunk 记录状态
504
+ // 返回 { thinking, content }
505
+ function extractThink(content, state) {
506
+ const buf = (state.thinkBuf || "") + content;
507
+ state.thinkBuf = "";
508
+
509
+ // 正处于思考块内:寻找 </think>
510
+ if (state.inThink) {
511
+ const end = buf.indexOf(CLOSE);
512
+ if (end === -1) {
513
+ const hold = partialTagLength(buf, CLOSE);
514
+ state.thinkBuf = buf.slice(buf.length - hold);
515
+ return { thinking: buf.slice(0, buf.length - hold), content: "" };
516
+ }
517
+ state.inThink = false;
518
+ const rest = extractThink(buf.slice(end + CLOSE.length), state);
519
+ return { thinking: buf.slice(0, end) + rest.thinking, content: rest.content };
520
+ }
521
+
522
+ // 正常正文:寻找 <think>
523
+ const start = buf.indexOf(OPEN);
524
+ if (start === -1) {
525
+ const hold = partialTagLength(buf, OPEN);
526
+ state.thinkBuf = buf.slice(buf.length - hold);
527
+ return { thinking: "", content: buf.slice(0, buf.length - hold) };
528
+ }
529
+
530
+ const end = buf.indexOf(CLOSE, start);
531
+ if (end !== -1) {
532
+ const rest = extractThink(buf.slice(end + CLOSE.length), state);
533
+ return {
534
+ thinking: buf.slice(start + OPEN.length, end) + rest.thinking,
535
+ content: buf.slice(0, start) + rest.content
536
+ };
537
+ }
538
+
539
+ // 有 <think> 无 </think>:进入思考态
540
+ state.inThink = true;
541
+ const body = buf.slice(start + OPEN.length);
542
+ const hold = partialTagLength(body, CLOSE);
543
+ state.thinkBuf = body.slice(body.length - hold);
544
+ return { thinking: body.slice(0, body.length - hold), content: buf.slice(0, start) };
545
+ }
546
+
547
+ // 流结束时调用:冲刷 extractThink 留下的截断残留,按当前所处模式归属输出
548
+ function flushThink(state) {
549
+ const buf = state.thinkBuf || "";
550
+ state.thinkBuf = "";
551
+ return state.inThink ? { thinking: buf, content: "" } : { thinking: "", content: buf };
552
+ }
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
+
609
+ // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
610
+ function handleChoices(choices, { logback, thinkback }, state) {
611
+ if (!Array.isArray(choices)) return;
612
+
613
+ for (let i = 0; i < choices.length; i++) {
614
+ const delta = choices[i].delta;
615
+
616
+ // 推理内容(reasoning / reasoning_content 字段)
617
+ let reasoning = delta.reasoning || delta.reasoning_content;
618
+ if (reasoning) {
619
+ const parsed = parseReasoning(reasoning, delta.content);
620
+ if (typeof parsed === "object") {
621
+ reasoning = parsed.reasoning;
622
+ delta.content = parsed.content;
623
+ }
624
+ if (thinkback) thinkback(reasoning);
625
+ }
626
+
627
+ // 正文内容:剥离混在 content 中的 <think>...</think> 思考片段
628
+ if (delta.content) {
629
+ const extracted = extractThink(delta.content, state);
630
+ if (extracted.thinking && thinkback) thinkback(extracted.thinking);
631
+ if (extracted.content) {
632
+ if (logback) logback(extracted.content);
633
+ state.content += extracted.content;
634
+ }
635
+ }
636
+
637
+ // 工具调用分片
638
+ if (Array.isArray(delta.tool_calls)) {
639
+ for (const toolCall of delta.tool_calls) {
640
+ mergeToolCall(state, toolCall);
641
+ }
642
+ }
643
+ }
644
+ }
645
+
646
+ // 流结束时调用:把 <think> 标签截断残留冲刷到对应回调
647
+ function flushThinkBuffer(state, { logback, thinkback }) {
648
+ const flushed = flushThink(state);
649
+ if (flushed.thinking && thinkback) thinkback(flushed.thinking);
650
+ if (flushed.content) {
651
+ if (logback) logback(flushed.content);
652
+ state.content += flushed.content;
653
+ }
654
+ }
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
+
686
+ function completions(params, logback, thinkback) {
687
+ return new Promise((resolve, reject) => {
688
+
689
+ // #doc:state
690
+ const state = { content: "", tool_calls: [] };
691
+ const callbacks = { logback, thinkback };
692
+
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
720
+
721
+ fetch$1({
722
+ url: `${this.baseURL.replace(/\/+$/, "")}/chat/completions`,
723
+ method: "POST",
724
+ headers: {
725
+ "Authorization": `Bearer ${this.apiKey}`,
726
+ "Content-Type": "application/json",
727
+ },
728
+ body: JSON.stringify(body),
729
+ timeout: params.timeout != null ? params.timeout : this.timeout,
730
+ signal: params.signal
731
+ // #end
732
+ }).then(res => {
733
+
734
+ // 非 2xx:非流式等错误体读完再判,流式直接中断
735
+ res.on("http-error", meta => {
736
+ httpError = meta;
737
+ if (params.stream) fail(errorFromHttp(meta));
738
+ });
739
+
740
+ // 数据流
741
+ // #doc:stream
742
+ res.on("data", chunk => {
743
+ if (settled) return;
744
+ if (!params.stream) {
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);
762
+ }
763
+ });
764
+
765
+ // 结束
766
+ res.on("end", () => {
767
+ if (!params.stream) {
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;
789
+ }
790
+
791
+ // 冲刷 <think> 标签截断残留
792
+ flushThinkBuffer(state, callbacks);
793
+ finish(resolve, { content: state.content, tool_calls: state.tool_calls });
794
+ });
795
+
796
+ res.on("error", err => fail(err));
797
+ }).catch(err => fail(err));
798
+
799
+ });
800
+ }
801
+
802
+ // #doc:ctor
803
+ function Model(fields) {
804
+ this.model = fields.model;
805
+ this.apiKey = fields.apiKey;
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
479
814
  }
480
815
 
481
- function Model(fields) {
482
- this.model = fields.model;
483
- this.apiKey = fields.apiKey;
484
- this.baseURL = fields.baseURL;
485
- }
486
-
487
816
  Model.prototype.completions = completions;
488
817
 
489
818
  exports.Model = Model;