@auipage/agent 0.1.0-alpha.4 → 0.1.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,498 +1,580 @@
1
- /*! @auipage/agent v0.1.0-alpha.4 */
1
+ /*! @auipage/agent v0.1.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_agent = {}));
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
+ 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
+ }
45
45
  }
46
46
 
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
- }
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
+ }
108
108
  }
109
109
 
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
- };
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
+ };
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
+ // 浏览器环境适配器:基于原生 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));
210
210
  }
211
211
 
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();
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();
265
265
  }
266
266
 
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
-
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
+
274
274
  const fetch$1 = createFetch(adapter);
275
275
 
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;
291
- }
292
-
293
- // 解析 LLM 返回的推理内容(reasoning / reasoning_content)
294
- // 将 <think>...</think> 形式的内容从 delta.content 中剥离出来
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: thinkPart[1] + (content || "")
303
- };
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;
304
291
  }
305
292
 
306
- // 处理单批 choices 数据:累加 content、拼装 tool_calls、回调 thinkback / logback
307
- // 返回累积的 { content, tool_calls }
308
- function handleChoices(choices, { logback, thinkback }, state) {
309
- for (let i = 0; i < choices.length; i++) {
310
- const delta = choices[i].delta;
311
-
312
- // 推理内容
313
- let reasoning = delta.reasoning || delta.reasoning_content;
314
- if (reasoning) {
315
- const parsed = parseReasoning(reasoning, delta.content);
316
- if (typeof parsed === "object") {
317
- reasoning = parsed.reasoning;
318
- delta.content = parsed.content;
319
- }
320
- if (thinkback) thinkback(reasoning);
321
- }
322
-
323
- // 正文内容
324
- if (delta.content) {
325
- if (logback) logback(delta.content);
326
- state.content += delta.content;
327
- }
328
-
329
- // 工具调用
330
- if (delta.tool_calls) {
331
- for (const toolCall of delta.tool_calls) {
332
- if (toolCall.id) {
333
- state.tool_calls.push(toolCall);
334
- } else {
335
- state.tool_calls[state.tool_calls.length - 1].function.arguments += toolCall.function.arguments;
336
- }
337
- }
338
- }
339
- }
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 };
340
370
  }
341
371
 
342
- function completions(params, logback, thinkback) {
343
- return new Promise((resolve, reject) => {
344
-
345
- const state = { content: "", tool_calls: [] };
346
- const callbacks = { logback, thinkback };
347
-
348
- let buffer = "";
349
-
350
- fetch$1({
351
- url: `${this.baseURL}/chat/completions`,
352
- method: "POST",
353
- headers: {
354
- "Authorization": `Bearer ${this.apiKey}`,
355
- "Content-Type": "application/json",
356
- },
357
- body: JSON.stringify({
358
- model: this.model,
359
- messages: params.messages,
360
- tools: params.tools ? params.tools.map(tool => tool.description) : [],
361
- stream: params.stream,
362
- })
363
- }).then(res => {
364
-
365
- // 数据流
366
- res.on("data", chunk => {
367
- if (params.stream) {
368
- const parsed = parseString(chunk.toString());
369
- if (Array.isArray(parsed)) {
370
- for (const item of parsed) {
371
- handleChoices(item.choices, callbacks, state);
372
- }
373
- } else {
374
- handleChoices(parsed.choices, callbacks, state);
375
- }
376
- } else {
377
- buffer += chunk;
378
- }
379
- });
380
-
381
- // 结束
382
- res.on("end", () => {
383
- if (!params.stream) {
384
- handleChoices(
385
- [{ delta: parseString(buffer).choices[0].message }],
386
- callbacks,
387
- state
388
- );
389
- }
390
- resolve({ content: state.content, tool_calls: state.tool_calls });
391
- });
392
-
393
- res.on("error", err => reject(err));
394
- }).catch(err => reject(err));
395
-
396
- });
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
+ }
397
420
  }
398
421
 
399
- function Model(fields) {
400
- this.model = fields.model;
401
- this.apiKey = fields.apiKey;
402
- this.baseURL = fields.baseURL;
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
+ });
403
479
  }
404
480
 
481
+ function Model(fields) {
482
+ this.model = fields.model;
483
+ this.apiKey = fields.apiKey;
484
+ this.baseURL = fields.baseURL;
485
+ }
486
+
405
487
  Model.prototype.completions = completions;
406
488
 
407
- /**
408
- * 根据模型返回的 tool_calls,依次在 _this.tools 中查找匹配的工具并执行,
409
- * 返回与 tool_calls 等长的结果数组(同步值/异步值都会被规范化)。
410
- *
411
- * @param {Object} _this Agent 实例
412
- * @param {Array} tool_calls 模型返回的工具调用列表
413
- * @returns {Promise<Array>} 每个工具的执行结果,未匹配到的槽位会被填入错误说明字符串
414
- */
415
- function callFuns(_this, tool_calls) {
416
-
417
- const tasks = tool_calls.map(call => {
418
- const tool = _this.tools.find(
419
- t => t.description.function.name === call.function.name
420
- );
421
-
422
- if (!tool) {
423
- return Promise.resolve("工具" + call.function.name + "不存在");
424
- }
425
-
426
- let result;
427
- try {
428
- result = tool.execute(JSON.parse(call.function.arguments));
429
- } catch (e) {
430
- return Promise.resolve("参数解析失败:" + e);
431
- }
432
-
433
- if (result instanceof Promise) {
434
- // 工具内部报错也不要阻断对话,转成字符串继续往下走
435
- return result.catch(e => "运行出错:" + e);
436
- }
437
- return Promise.resolve(result);
438
- });
439
-
440
- return Promise.all(tasks);
441
- }
442
-
443
- /**
444
- * 把一次工具调用的执行结果转成 tool 消息。
445
- */
446
- function toToolMessage(call, value) {
447
- return {
448
- role: "tool",
449
- tool_call_id: call.id,
450
- tool_name: call.function.name,
451
- content: typeof value === "string" ? value : (JSON.stringify(value) + "")
452
- };
453
- }
454
-
455
- /**
456
- * 把模型响应按 role 追加到 messages,返回是否还有工具调用需要下一轮处理。
457
- */
458
- function appendAssistantMessage(messages, result) {
459
- if (result.content) {
460
- messages.push({ role: "assistant", content: result.content });
461
- }
462
- if (result.tool_calls && result.tool_calls.length > 0) {
463
- messages.push({ role: "assistant", tool_calls: result.tool_calls });
464
- return true;
465
- }
466
- return false;
489
+ /**
490
+ * 根据模型返回的 tool_calls,依次在 _this.tools 中查找匹配的工具并执行,
491
+ * 返回与 tool_calls 等长的结果数组(同步值/异步值都会被规范化)。
492
+ *
493
+ * @param {Object} _this Agent 实例
494
+ * @param {Array} tool_calls 模型返回的工具调用列表
495
+ * @returns {Promise<Array>} 每个工具的执行结果,未匹配到的槽位会被填入错误说明字符串
496
+ */
497
+ function callFuns(_this, tool_calls) {
498
+
499
+ const tasks = tool_calls.map(call => {
500
+ const tool = _this.tools.find(
501
+ t => t.description.function.name === call.function.name
502
+ );
503
+
504
+ if (!tool) {
505
+ return Promise.resolve("工具" + call.function.name + "不存在");
506
+ }
507
+
508
+ let result;
509
+ try {
510
+ result = tool.execute(JSON.parse(call.function.arguments));
511
+ } catch (e) {
512
+ return Promise.resolve("参数解析失败:" + e);
513
+ }
514
+
515
+ if (result instanceof Promise) {
516
+ // 工具内部报错也不要阻断对话,转成字符串继续往下走
517
+ return result.catch(e => "运行出错:" + e);
518
+ }
519
+ return Promise.resolve(result);
520
+ });
521
+
522
+ return Promise.all(tasks);
467
523
  }
468
524
 
469
- /**
470
- * 执行模型对话循环:
471
- * 1. 调用模型获取响应
472
- * 2. 若返回工具调用,依次执行工具并将结果追加到 messages,继续循环
473
- * 3. 否则将最终内容 resolve 给调用方
474
- */
475
- async function runConversation(_this, messages, logback, thinkback) {
476
-
477
- while (true) {
478
- const result = await _this.model.completions({
479
- messages,
480
- tools: _this.tools,
481
- stream: _this.stream,
482
- }, logback, thinkback);
483
-
484
- const hasToolCalls = appendAssistantMessage(messages, result);
485
-
486
- if (!hasToolCalls) {
487
- return result.content;
488
- }
489
-
490
- const toolResults = await callFuns(_this, result.tool_calls);
491
-
492
- result.tool_calls.forEach((call, i) => {
493
- messages.push(toToolMessage(call, toolResults[i]));
494
- });
495
- }
525
+ /**
526
+ * 把一次工具调用的执行结果转成 tool 消息。
527
+ */
528
+ function toToolMessage(call, value) {
529
+ return {
530
+ role: "tool",
531
+ tool_call_id: call.id,
532
+ tool_name: call.function.name,
533
+ content: typeof value === "string" ? value : (JSON.stringify(value) + "")
534
+ };
535
+ }
536
+
537
+ /**
538
+ * 把模型响应按 role 追加到 messages,返回是否还有工具调用需要下一轮处理。
539
+ */
540
+ function appendAssistantMessage(messages, result) {
541
+ if (result.content) {
542
+ messages.push({ role: "assistant", content: result.content });
543
+ }
544
+ if (result.tool_calls && result.tool_calls.length > 0) {
545
+ messages.push({ role: "assistant", tool_calls: result.tool_calls });
546
+ return true;
547
+ }
548
+ return false;
549
+ }
550
+
551
+ /**
552
+ * 执行模型对话循环:
553
+ * 1. 调用模型获取响应
554
+ * 2. 若返回工具调用,依次执行工具并将结果追加到 messages,继续循环
555
+ * 3. 否则将最终内容 resolve 给调用方
556
+ */
557
+ async function runConversation(_this, messages, logback, thinkback) {
558
+
559
+ while (true) {
560
+ const result = await _this.model.completions({
561
+ messages,
562
+ tools: _this.tools,
563
+ stream: _this.stream,
564
+ }, logback, thinkback);
565
+
566
+ const hasToolCalls = appendAssistantMessage(messages, result);
567
+
568
+ if (!hasToolCalls) {
569
+ return result.content;
570
+ }
571
+
572
+ const toolResults = await callFuns(_this, result.tool_calls);
573
+
574
+ result.tool_calls.forEach((call, i) => {
575
+ messages.push(toToolMessage(call, toolResults[i]));
576
+ });
577
+ }
496
578
  }
497
579
 
498
580
  function initOption(setOption, defaultOption) {
@@ -503,77 +585,77 @@
503
585
  return defaultOption;
504
586
  }
505
587
 
506
- function CreateTool(ms) {
507
- this.ms = ms;
508
- }
509
-
510
- CreateTool.prototype.create = function ({ description, execute }) {
511
- let _this = this;
512
- return {
513
- description,
514
- execute: async function (args) {
515
- let toolInfo = {
516
- type: "tool-call",
517
- status: "pending",
518
- id: Date.now().toString()+"_"+Math.random().toString(36).substring(2).toUpperCase(),
519
- name: description.function.name,
520
- caller: execute ? "backend" : "frontend",
521
- args
522
- };
523
-
524
- // 后端工具调用
525
- if (execute) {
526
- _this.ms.send(toolInfo); // 开始调用工具
527
-
528
- let result, status;
529
- try {
530
- result = await execute(args);
531
- status = "success"; // 调用成功
532
- } catch (error) {
533
- result = error;
534
- status = "error"; // 调用失败
535
- }
536
-
537
- _this.ms.send(initOption({ // 结束调用工具
538
- status,
539
- result
540
- }, toolInfo));
541
-
542
- return result;
543
- }
544
-
545
- // 前端工具调用
546
- else {
547
- let _resolve = null;
548
- globalThis[toolInfo.id] = function (result) {
549
- _resolve(result);
550
- delete globalThis[toolInfo.id];
551
- };
552
-
553
- _this.ms.send(toolInfo); // 开始调用工具
554
-
555
- return new Promise((resolve, reject) => {
556
- _resolve = resolve;
557
- });
558
- }
559
- }
560
- };
588
+ function CreateTool(ms) {
589
+ this.ms = ms;
590
+ }
591
+
592
+ CreateTool.prototype.create = function ({ description, execute }) {
593
+ let _this = this;
594
+ return {
595
+ description,
596
+ execute: async function (args) {
597
+ let toolInfo = {
598
+ type: "tool-call",
599
+ status: "pending",
600
+ id: Date.now().toString()+"_"+Math.random().toString(36).substring(2).toUpperCase(),
601
+ name: description.function.name,
602
+ caller: execute ? "backend" : "frontend",
603
+ args
604
+ };
605
+
606
+ // 后端工具调用
607
+ if (execute) {
608
+ _this.ms.send(toolInfo); // 开始调用工具
609
+
610
+ let result, status;
611
+ try {
612
+ result = await execute(args);
613
+ status = "success"; // 调用成功
614
+ } catch (error) {
615
+ result = error;
616
+ status = "error"; // 调用失败
617
+ }
618
+
619
+ _this.ms.send(initOption({ // 结束调用工具
620
+ status,
621
+ result
622
+ }, toolInfo));
623
+
624
+ return result;
625
+ }
626
+
627
+ // 前端工具调用
628
+ else {
629
+ let _resolve = null;
630
+ globalThis[toolInfo.id] = function (result) {
631
+ _resolve(result);
632
+ delete globalThis[toolInfo.id];
633
+ };
634
+
635
+ _this.ms.send(toolInfo); // 开始调用工具
636
+
637
+ return new Promise((resolve, reject) => {
638
+ _resolve = resolve;
639
+ });
640
+ }
641
+ }
642
+ };
561
643
  };
562
644
 
563
- function Agent(option) {
564
- this.model = new Model(option.model);
565
- this.tools = option.tools || [];
566
- this.systemPrompt = option.systemPrompt || "";
567
- this.stream = option.stream || false;
568
- }
569
-
570
- Agent.prototype.generate = function (messages, logback, thinkback) {
571
- if (this.systemPrompt) messages.unshift({
572
- role: "system",
573
- content: this.systemPrompt
574
- });
575
-
576
- return runConversation(this, messages, logback, thinkback);
645
+ function Agent(option) {
646
+ this.model = new Model(option.model);
647
+ this.tools = option.tools || [];
648
+ this.systemPrompt = option.systemPrompt || "";
649
+ this.stream = option.stream || false;
650
+ }
651
+
652
+ Agent.prototype.generate = function (messages, logback, thinkback) {
653
+ if (this.systemPrompt) messages.unshift({
654
+ role: "system",
655
+ content: this.systemPrompt
656
+ });
657
+
658
+ return runConversation(this, messages, logback, thinkback);
577
659
  };
578
660
 
579
661
  exports.Agent = Agent;