@auipage/core 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,449 +1,760 @@
1
- /*! @auipage/core v0.1.0 */
1
+ /*! @auipage/core 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_core = {}));
6
6
  })(this, (function (exports) { 'use strict';
7
7
 
8
- function toHistoryMessages (value) {
9
-
10
- let messages = [], index = -1;
11
- for (let message of value.messages) {
12
-
13
- if (index != -1 && messages[index].role === message.role) {
14
- messages[index].content.push(...message.content);
15
- } else {
16
- messages.push(message);
17
- index = messages.length - 1;
18
- }
19
- }
20
-
21
- value.messages = messages;
22
- return value;
8
+ // #doc:merge
9
+ function toHistoryMessages (value) {
10
+
11
+ let messages = [], index = -1;
12
+ for (let message of value.messages || []) {
13
+
14
+ if (index != -1 && messages[index].role === message.role) {
15
+ // 复制内容数组,避免改写入参消息对象
16
+ messages[index].content.push(...message.content);
17
+ } else {
18
+ messages.push(Object.assign({}, message, { content: (message.content || []).slice() }));
19
+ index = messages.length - 1;
20
+ }
21
+ }
22
+
23
+ value.messages = messages;
24
+ return value;
23
25
  }
26
+ // #end
24
27
 
25
- function AuiPage(options) {
26
-
27
- // 连接适配器和运行时视图
28
- this.adapter = {};
29
- this.runtime = {};
30
- for (let instance of Object.values(options.adapter)) {
31
- instance.aui = this;
32
- this.adapter[instance.name.replace("Adapter", "")] = instance;
33
- }
34
- for (let instance of Object.values(options.runtime)) {
35
- instance.aui = this;
36
- this.runtime[instance.name.replace("Runtime", "")] = instance;
37
- }
38
-
39
- // 工具注册
40
- this.tools_execute = {};
41
- this.tools_render = {};
42
- this.tools_description = [];
43
- for (let tool of options.tools || []) {
44
- this.tools_execute[tool.description.function.name] = tool.execute;
45
- this.tools_render[tool.description.function.name] = tool.render;
46
- this.tools_description.push({ description: tool.description });
47
- }
48
-
49
- // 当前是否在执行中
50
- this.isExecuting = false;
51
-
52
- // 当前激活的会话ID
53
- this.currentThreadId = void 0;
54
-
55
- // 当前会话内容
56
- this.currentMessages = [];
57
-
58
- // 任务生命周期事件:task:start / task:end
59
- this._events = { "task:start": [], "task:end": [] };
60
-
61
- // 任务自增序号,用于生成 taskId
62
- this._taskSeq = 0;
63
-
64
- // 当前正在执行的任务句柄(sendMessage 进入执行期时写入)
65
- this._currentTask = null;
66
-
67
- // 请求对话列表
68
- this.adapter.ThreadList.list()?.then((threads) => {
69
-
70
- // 在页面中显示对话列表
71
- this.runtime.ThreadList.init(threads);
72
- });
73
-
74
- }
75
-
76
- // 触发生命周期事件;handler 抛错被吞掉,避免影响 sendMessage 主流程
77
- AuiPage.prototype._emit = function (event, payload) {
78
- let handlers = this._events[event];
79
- if (!handlers) return;
80
- // 复制一份,防止 off() 在回调中修改原数组
81
- handlers.slice().forEach(function (fn) {
82
- try { fn(payload); } catch (e) { /* 吞掉 handler 异常 */ }
83
- });
84
- };
85
-
86
- // 订阅生命周期事件
87
- AuiPage.prototype.on = function (event, handler) {
88
- if (!this._events[event]) this._events[event] = [];
89
- this._events[event].push(handler);
90
- return this;
91
- };
92
-
93
- // 取消订阅
94
- AuiPage.prototype.off = function (event, handler) {
95
- let list = this._events[event];
96
- if (!list) return this;
97
- let idx = list.indexOf(handler);
98
- if (idx >= 0) list.splice(idx, 1);
99
- return this;
100
- };
101
-
102
- AuiPage.prototype.sendMessage = function (message) {
103
- let _this = this;
104
-
105
- return new Promise((resolve, reject) => {
106
-
107
- if (this.isExecuting) return reject("当前正在执行中");
108
- this.isExecuting = true;
109
-
110
- let generator = this.adapter.ChatTransport.run({
111
- messages: [message],
112
- context: {
113
- history: this.currentMessages,
114
- tools: this.tools_description
115
- }
116
- });
117
-
118
- if (!generator) {
119
- this.isExecuting = false;
120
- reject("ChatTransport.run() 返回空值");
121
- return;
122
- }
123
-
124
- // 写入任务上下文,供后续协同使用
125
- let taskId = String(++this._taskSeq);
126
- this._currentTask = {
127
- taskId,
128
- message,
129
- generator,
130
- cacheMessages: [message],
131
- preType: "",
132
- preText: "",
133
- textTypes: ["loading", "thinking", "text"],
134
- streamFun: void 0,
135
- tool_calls: {},
136
- resolve,
137
- reject,
138
- ended: false
139
- };
140
-
141
- // 任务开始生命周期
142
- this._emit("task:start", {
143
- taskId,
144
- threadId: this.currentThreadId,
145
- message
146
- });
147
-
148
- let cacheMessages = this._currentTask.cacheMessages;
149
- let preType = this._currentTask.preType;
150
- let preText = this._currentTask.preText;
151
- let textTypes = this._currentTask.textTypes;
152
- let streamFun = this._currentTask.streamFun;
153
- let tool_calls = this._currentTask.tool_calls;
154
-
155
- for (let i = 0; i < message.content.length; i++) {
156
- this.runtime.ChatContent.append(message.role, message.content[i]);
157
- }
158
-
159
- // 同步写入 _currentTask 的小工具
160
- let sync = function () {
161
- _this._currentTask.preType = preType;
162
- _this._currentTask.preText = preText;
163
- _this._currentTask.streamFun = streamFun;
164
- };
165
-
166
- (function doit() {
167
- generator?.next().then(async function (res) {
168
- if (!res.done) {
169
-
170
- // 类型变了,或者是一种特殊类型
171
- if (res.value.type != preType || !textTypes.includes(res.value.type)) {
172
- streamFun = void 0;
173
-
174
- if (preText) {
175
- cacheMessages.push({
176
- role: "assistant", content: [{
177
- type: preType,
178
- text: preText
179
- }]
180
- });
181
- preText = "";
182
- preType = "";
183
- }
184
-
185
- if (!textTypes.includes(res.value.type)) {
186
-
187
- // 工具调用
188
- if (res.value.type === "tool-call") {
189
-
190
- // 工具开始调用(前端工具+后端工具)
191
- if (res.value.status === "pending") {
192
- tool_calls[res.value.id] = _this.runtime.ChatContent.append("assistant", res.value);
193
-
194
- // 对于前端工具,需要自己执行工具调用
195
- if (res.value.caller === "frontend") {
196
- let result, status;
197
-
198
- try {
199
- result = await _this.tools_execute[res.value.name](res.value.args);
200
- status = "success"; // 调用成功
201
- } catch (error) {
202
- result = error;
203
- status = "error"; // 调用失败
204
- }
205
-
206
- let render = _this.tools_render[res.value.name];
207
-
208
- // 需要视图交互获取结果
209
- if (render) {
210
- let result_ui, status_ui;
211
-
212
- try {
213
- result_ui = await tool_calls[res.value.id]({
214
- ...res.value,
215
- result,
216
- status,
217
- render
218
- });
219
- status_ui = "success";
220
- } catch (error) {
221
- result_ui = error;
222
- status_ui = "error";
223
- }
224
-
225
- tool_calls[res.value.id]({
226
- ...res.value,
227
- result: result_ui,
228
- status: status_ui
229
- });
230
- delete tool_calls[res.value.id];
231
-
232
- cacheMessages.push({
233
- role: "assistant", content: [{
234
- type: "tool-call",
235
- name: res.value.name,
236
- args: res.value.args,
237
- result,
238
- status,
239
- ui: {
240
- status: status_ui,
241
- result: result_ui
242
- }
243
- }]
244
- });
245
-
246
- _this.adapter.ChatTransport.response("tool-result", {
247
- id: res.value.id,
248
- status: status_ui,
249
- result: result_ui
250
- });
251
- }
252
-
253
- // 没有render,就相当于纯粹的工具调用
254
- else {
255
- tool_calls[res.value.id]({
256
- ...res.value,
257
- result,
258
- status
259
- });
260
- delete tool_calls[res.value.id];
261
-
262
- cacheMessages.push({
263
- role: "assistant", content: [{
264
- type: "tool-call",
265
- name: res.value.name,
266
- args: res.value.args,
267
- result,
268
- status
269
- }]
270
- });
271
-
272
- _this.adapter.ChatTransport.response("tool-result", {
273
- id: res.value.id,
274
- result,
275
- status
276
- });
277
- }
278
-
279
- }
280
-
281
- }
282
-
283
- // 工具调用结束(后端工具)
284
- else if (res.value.status === "success" || res.value.status === "error") {
285
- if (tool_calls[res.value.id]) {
286
- tool_calls[res.value.id](res.value);
287
- delete tool_calls[res.value.id];
288
-
289
- cacheMessages.push({
290
- role: "assistant", content: [{
291
- type: "tool-call",
292
- name: res.value.name,
293
- args: res.value.args,
294
- result: res.value.result,
295
- status: res.value.status
296
- }]
297
- });
298
- }
299
- }
300
- }
301
-
302
- } else {
303
- preText = res.value.text;
304
- preType = res.value.type;
305
- streamFun = _this.runtime.ChatContent.append("assistant", res.value);
306
- }
307
-
308
- } else {
309
- preText += res.value.text;
310
- if (streamFun) streamFun(res.value.text);
311
- }
312
-
313
- sync();
314
- doit();
315
- } else {
316
- sync();
317
- _this._finalize("complete", true);
318
- }
319
- }, err => {
320
- _this._finalize("error", false, err);
321
- });
322
- })();
323
-
324
- });
325
- };
326
-
327
- /**
328
- * 收尾当前 sendMessage 任务。统一处理:残留文本归并、是否入库、isExecuting 复位、
329
- * 发出 task:end 事件、释放 Promise。
330
- *
331
- * @param {"complete"|"error"} status 任务结束原因
332
- * @param {boolean} isHistory 是否走入库分支(complete 始终 true;error 始终 false)
333
- * @param {Error|string} [err] status === "error" 时附带的错误对象
334
- */
335
- AuiPage.prototype._finalize = async function (status, isHistory, err) {
336
- let task = this._currentTask;
337
- if (!task || task.ended) return;
338
- task.ended = true;
339
-
340
- let { taskId, message, cacheMessages, preType, preText, resolve, reject } = task;
341
-
342
- // 1. 残留文本归并到 cacheMessages
343
- if (preText) {
344
- cacheMessages.push({
345
- role: "assistant",
346
- content: [{ type: preType, text: preText }]
347
- });
348
- task.preText = "";
349
- task.preType = "";
350
- }
351
-
352
- // 2. 入库分支
353
- if (isHistory) {
354
- try {
355
- let historyMessages = toHistoryMessages({ messages: cacheMessages });
356
-
357
- if (this.currentThreadId === void 0) {
358
- let newThread = await this.adapter.ThreadList.new(historyMessages);
359
-
360
- if (!newThread) {
361
- // 新建会话失败 → 退化为 error,不入库、不 resolve
362
- this.isExecuting = false;
363
- this._currentTask = null;
364
- this._emit("task:end", { taskId, threadId: this.currentThreadId, message, status: "error" });
365
- reject(new Error("新建会话失败"));
366
- return;
367
- }
368
-
369
- await this.runtime.ThreadList.append(newThread);
370
- this.activeThread(newThread.threadId, true);
371
- }
372
-
373
- this.currentMessages.push(historyMessages);
374
- this.adapter.MessageHistory.append(this.currentThreadId, historyMessages);
375
- } catch (e) {
376
- // 入库链路本身抛错 → 退化为 error
377
- this.isExecuting = false;
378
- this._currentTask = null;
379
- this._emit("task:end", { taskId, threadId: this.currentThreadId, message, status: "error" });
380
- reject(e);
381
- return;
382
- }
383
- }
384
-
385
- // 4. 复位、emit task:end、释放 Promise
386
- this.isExecuting = false;
387
- this._currentTask = null;
388
-
389
- this._emit("task:end", { taskId, threadId: this.currentThreadId, message, status });
390
-
391
- if (status === "error") reject(err);
392
- else resolve();
393
- };
394
-
395
- AuiPage.prototype.activeThread = function (threadId, __noLoad__) {
396
- if (this.currentThreadId === threadId) return;
397
-
398
- // 已经有执行的,不允许切换
399
- if (this.isExecuting && !__noLoad__) return;
400
-
401
- this.currentThreadId = threadId;
402
- this.runtime.ThreadList.active(threadId);
403
-
404
- if (threadId === void 0) {
405
- this.currentMessages = [];
406
- this.runtime.ChatContent.init([]);
407
- } else if (!__noLoad__) {
408
-
409
- // 加载历史消息
410
- this.adapter.MessageHistory.load(threadId)?.then(messages => {
411
- this.currentMessages = messages;
412
-
413
- let plainMessages = [];
414
- messages.forEach(item => {
415
- plainMessages.push(...item.messages);
416
- });
417
- this.runtime.ChatContent.init(plainMessages);
418
- });
419
- }
420
- };
421
-
422
- AuiPage.prototype.deleteThread = function (threadId) {
423
- this.adapter.ThreadList.delete(threadId)?.then(() => {
424
- this.runtime.ThreadList.delete(threadId);
425
-
426
- if (threadId === this.currentThreadId) this.newThread();
427
- });
428
-
429
- };
430
-
431
- AuiPage.prototype.archiveThread = function (threadId) {
432
- this.adapter.ThreadList.archive(threadId)?.then(() => {
433
- this.runtime.ThreadList.archive(threadId);
434
-
435
- if (threadId === this.currentThreadId) this.newThread();
436
- });
437
- };
438
-
439
- AuiPage.prototype.unarchiveThread = function (threadId) {
440
- this.adapter.ThreadList.unarchive(threadId).then(() => {
441
- this.runtime.ThreadList.unarchive(threadId);
442
- });
443
- };
444
-
445
- AuiPage.prototype.newThread = function () {
446
- this.activeThread(void 0);
28
+ // 挂载适配器/运行时:name 缺失时回退到配置对象的 key,避免直接崩
29
+ // #doc:mount
30
+ function mount(aui, list, suffix) {
31
+ const result = {};
32
+ for (const [key, instance] of Object.entries(list || {})) {
33
+ if (!instance) continue;
34
+ instance.aui = aui;
35
+ const name = typeof instance.name === "string" ? instance.name : "";
36
+ result[name.replace(suffix, "") || key.replace(suffix, "")] = instance;
37
+ }
38
+ return result;
39
+ }
40
+ // #end
41
+
42
+ // 适配器调用:Promise 就等完成,同步值直接处理,同步返回 undefined 视为未实现
43
+ // #doc:invoke
44
+ function invoke(target, method, apply, args) {
45
+ if (!target || typeof target[method] !== "function") return;
46
+ let ret;
47
+ try {
48
+ ret = target[method].apply(target, args || []);
49
+ } catch (e) {
50
+ return;
51
+ }
52
+ if (ret === void 0 || ret === null) return;
53
+ if (typeof ret.then === "function") {
54
+ ret.then(apply, function () { });
55
+ return;
56
+ }
57
+ if (typeof apply === "function") apply(ret);
58
+ }
59
+ // #end
60
+
61
+ // 安全调用:返回值可能为 void / Promise,异常与拒绝都不外泄
62
+ // #doc:safe
63
+ function callSafely(fn, arg) {
64
+ if (typeof fn !== "function") return;
65
+ try {
66
+ const ret = fn(arg);
67
+ if (ret && typeof ret.then === "function") ret.then(null, function () { });
68
+ } catch (e) { /* 忽略视图与上报通道异常 */ }
69
+ }
70
+
71
+ // 视图更新函数:runtime 的 append 允许返回 void(类型契约如此),这里统一兜底
72
+ function asUpdater(ret) {
73
+ return typeof ret === "function" ? ret : null;
74
+ }
75
+ // #end
76
+
77
+ // content 规范化为片段数组:字符串按整段处理,避免逐字符渲染
78
+ // #doc:content
79
+ function normalizeContent(content) {
80
+ if (Array.isArray(content)) return content;
81
+ if (content === void 0 || content === null) return [];
82
+ if (typeof content === "string") return content === "" ? [] : [{ type: "text", text: content }];
83
+ return [content];
84
+ }
85
+ // #end
86
+
87
+ // 取消时等待 next() 落定的兜底上限(毫秒),防止适配器忽略 signal 时页面停在执行中
88
+ // #doc:cancelchk
89
+ const DEFAULT_STOP_TIMEOUT = 5000;
90
+
91
+ // 被取消的任务:后续分片与工具结果一律丢弃;被 stop 则继续把结果落地
92
+ function isCancelled(task) {
93
+ return !!(task.endRequest && task.endRequest.status === "cancelled");
94
+ // #end
95
+ }
96
+
97
+ // #doc:ctor
98
+ function AuiPage(options) {
99
+ options = options || {};
100
+
101
+ // 连接适配器和运行时视图
102
+ this.adapter = mount(this, options.adapter, "Adapter");
103
+ this.runtime = mount(this, options.runtime, "Runtime");
104
+
105
+ // 工具注册
106
+ this.tools_execute = {};
107
+ this.tools_render = {};
108
+ this.tools_description = [];
109
+ for (let tool of options.tools || []) {
110
+ this.tools_execute[tool.description.function.name] = tool.execute;
111
+ this.tools_render[tool.description.function.name] = tool.render;
112
+ this.tools_description.push({ description: tool.description });
113
+ }
114
+
115
+ // 当前是否在执行中
116
+ this.isExecuting = false;
117
+
118
+ // 当前激活的会话ID
119
+ this.currentThreadId = void 0;
120
+
121
+ // 当前会话内容
122
+ this.currentMessages = [];
123
+
124
+ // 任务生命周期事件:task:start / task:end
125
+ this._events = { "task:start": [], "task:end": [] };
126
+
127
+ // 任务自增序号,用于生成 taskId
128
+ this._taskSeq = 0;
129
+
130
+ // 当前正在执行的任务句柄(sendMessage 进入执行期时写入)
131
+ this._currentTask = null;
132
+
133
+ // 取消时等待 next 落定的兜底时长
134
+ this._stopTimeout = options.stopTimeout > 0 ? options.stopTimeout : DEFAULT_STOP_TIMEOUT;
135
+
136
+ // 请求对话列表
137
+ invoke(this.adapter.ThreadList, "list", (threads) => {
138
+ this.runtime.ThreadList?.init(threads);
139
+ });
140
+ }
141
+ // #end
142
+
143
+ // 触发生命周期事件;handler 抛错被吞掉,避免影响 sendMessage 主流程
144
+ // #doc:events
145
+ AuiPage.prototype._emit = function (event, payload) {
146
+ let handlers = this._events[event];
147
+ if (!handlers) return;
148
+ // 复制一份,防止 off() 在回调中修改原数组
149
+ handlers.slice().forEach(function (fn) {
150
+ try { fn(payload); } catch (e) { /* 吞掉 handler 异常 */ }
151
+ });
152
+ };
153
+
154
+ // 订阅生命周期事件
155
+ AuiPage.prototype.on = function (event, handler) {
156
+ if (!this._events[event]) this._events[event] = [];
157
+ this._events[event].push(handler);
158
+ return this;
159
+ };
160
+
161
+ // 取消订阅
162
+ AuiPage.prototype.off = function (event, handler) {
163
+ let list = this._events[event];
164
+ if (!list) return this;
165
+ let idx = list.indexOf(handler);
166
+ if (idx >= 0) list.splice(idx, 1);
167
+ return this;
168
+ };
169
+ // #end
170
+
171
+ // 交给界面渲染,同时登记显示条目:取消时据此告诉界面涉及哪几条
172
+ // #doc:render
173
+ AuiPage.prototype._render = function (task, role, part) {
174
+ const content = this.runtime.ChatContent;
175
+ if (!content || typeof content.append !== "function") return;
176
+
177
+ task.displayed.push({ index: task.displayed.length, role: role, part: part });
178
+ return content.append(role, part);
179
+ };
180
+ // #end
181
+
182
+ // #doc:send
183
+ AuiPage.prototype.sendMessage = function (message) {
184
+ let _this = this;
185
+
186
+ return new Promise((resolve, reject) => {
187
+
188
+ if (this.isExecuting) return reject("当前正在执行中");
189
+
190
+ if (!message || typeof message !== "object") return reject("消息格式不正确");
191
+
192
+ // content 规范化:字符串包成单个 text 片段,避免逐字符渲染
193
+ const content = normalizeContent(message.content);
194
+ const input = Array.isArray(message.content) ? message : Object.assign({}, message, { content });
195
+
196
+ this.isExecuting = true;
197
+
198
+ // 取消通道:signal 交给适配器,由它透传到底层 HTTP / 模型请求
199
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
200
+
201
+ let generator;
202
+ try {
203
+ generator = this.adapter.ChatTransport.run({
204
+ messages: [input],
205
+ context: {
206
+ history: this.currentMessages,
207
+ tools: this.tools_description,
208
+ signal: controller ? controller.signal : void 0
209
+ }
210
+ });
211
+ } catch (error) {
212
+ // run() 同步抛错:复位状态,否则页面永久卡在“执行中”
213
+ this.isExecuting = false;
214
+ reject(error);
215
+ return;
216
+ }
217
+
218
+ if (!generator || typeof generator.next !== "function") {
219
+ this.isExecuting = false;
220
+ reject("ChatTransport.run() 返回空值");
221
+ return;
222
+ }
223
+
224
+ // 结束信号:工具或界面里发起 stop / cancel 时唤醒等待中的流程
225
+ let signalEnd;
226
+ const endSignal = new Promise(function (resolve) { signalEnd = resolve; });
227
+
228
+ // 写入任务上下文,供后续协同使用
229
+ let taskId = String(++this._taskSeq);
230
+ const task = this._currentTask = {
231
+ taskId,
232
+ message: input,
233
+ generator,
234
+ controller,
235
+ cacheMessages: [input],
236
+ displayed: [],
237
+ preType: "",
238
+ preText: "",
239
+ textTypes: ["loading", "thinking", "text"],
240
+ streamFun: void 0,
241
+ tool_calls: {},
242
+ resolve,
243
+ reject,
244
+ ended: false,
245
+ endRequest: null,
246
+ endSignal: { promise: endSignal, resolve: signalEnd },
247
+ busy: false,
248
+ nextPending: false
249
+ };
250
+
251
+ // 任务开始生命周期
252
+ this._emit("task:start", {
253
+ taskId,
254
+ threadId: this.currentThreadId,
255
+ message: input
256
+ });
257
+
258
+ // 回显用户消息
259
+ for (let i = 0; i < content.length; i++) {
260
+ this._render(task, input.role, content[i]);
261
+ }
262
+ // #end
263
+
264
+ // #doc:pump
265
+ const finishEnd = () => {
266
+ const request = task.endRequest;
267
+ if (task.ended || !request) return;
268
+ this._finalize(request.status, true, null, request.by, task);
269
+ };
270
+
271
+ const pump = () => {
272
+ if (task.ended) return;
273
+ if (task.endRequest) return finishEnd();
274
+
275
+ let step;
276
+ try {
277
+ step = generator.next();
278
+ } catch (error) {
279
+ this._finalize("error", false, error);
280
+ return;
281
+ }
282
+
283
+ task.nextPending = true;
284
+
285
+ Promise.resolve(step).then(function (res) {
286
+ task.nextPending = false;
287
+
288
+ // next 未决期间发起过结束请求:此刻已落定,可以安全收尾
289
+ if (task.endRequest) return finishEnd();
290
+ if (task.ended) return;
291
+
292
+ if (res && res.done) {
293
+ _this._finalize("complete", true);
294
+ return;
295
+ }
296
+
297
+ task.busy = true;
298
+ _this._handleChunk(task, res).then(function () {
299
+ task.busy = false;
300
+
301
+ if (task.endRequest) return finishEnd();
302
+ if (task.ended) return;
303
+ pump();
304
+ // #end
305
+ }, function (error) {
306
+ task.busy = false;
307
+
308
+ if (task.endRequest) return finishEnd();
309
+ _this._finalize("error", false, error);
310
+ });
311
+ }, function (error) {
312
+ task.nextPending = false;
313
+
314
+ if (task.endRequest) return finishEnd();
315
+ _this._finalize("error", false, error);
316
+ });
317
+ };
318
+
319
+ pump();
320
+
321
+ });
322
+ };
323
+
324
+ /**
325
+ * 统一结束请求:stopped 当成功收尾,cancelled 当取消。
326
+ * 有分片或工具正在处理时不立即收尾,等它把手上的结果落完再结束,
327
+ * 否则这次工具调用会从消息里丢掉。
328
+ *
329
+ * @param {"stopped"|"cancelled"} status 结束状态
330
+ * @param {"user"|"tool"} by 发起方
331
+ * @param {object} [task] 指定任务;工具侧传入自己所属的任务,避免打到下一轮
332
+ * @returns {boolean} 当时是否有可结束的任务
333
+ */
334
+ // #doc:end
335
+ AuiPage.prototype._requestEnd = function (status, by, task) {
336
+ task = task || this._currentTask;
337
+ if (!task || task.ended) return false;
338
+ if (task.endRequest) return true;
339
+
340
+ task.endRequest = { status: status, by: by };
341
+
342
+ // 中断底层请求;适配器把 context.signal 透传下去即可立即停止
343
+ callSafely(function () {
344
+ if (task.controller) task.controller.abort();
345
+ });
346
+
347
+ // 唤醒可能卡在界面交互里的流程
348
+ callSafely(task.endSignal.resolve);
349
+
350
+ if (task.busy || task.nextPending) {
351
+ // 等着当前分片落定;兜底超时防止适配器忽略 signal 时页面停在执行中
352
+ const _this = this;
353
+ task.stopTimer = setTimeout(function () {
354
+ _this._finalize(status, true, null, by, task);
355
+ }, this._stopTimeout);
356
+ if (task.stopTimer && typeof task.stopTimer.unref === "function") task.stopTimer.unref();
357
+
358
+ return true;
359
+ }
360
+
361
+ this._finalize(status, true, null, by, task);
362
+ return true;
363
+ };
364
+ // #end
365
+
366
+ /**
367
+ * 主动结束当前任务:当作成功收尾——内容保留、入库标记 stopped、sendMessage 正常 resolve。
368
+ * 与 cancel 的区别只在这份“怎么收下这一轮”的口径,不在谁点的。
369
+ *
370
+ * @returns {boolean} 当时是否有正在执行的任务
371
+ */
372
+ // #doc:stopcancel
373
+ AuiPage.prototype.stop = function () {
374
+ return this._requestEnd("stopped", "user");
375
+ };
376
+
377
+ /**
378
+ * 取消当前任务:中断底层请求,已产出的部分照常入库并标记 cancelled,
379
+ * task:end 附带 displayed,界面可自行撤销。
380
+ *
381
+ * @returns {boolean} 当时是否有正在执行的任务
382
+ */
383
+ AuiPage.prototype.cancel = function () {
384
+ return this._requestEnd("cancelled", "user");
385
+ };
386
+
387
+ /**
388
+ * 交给工具的任务控制句柄:execute / render 里直接调用 stop() 或 cancel()。
389
+ *
390
+ * @param {object} task 任务句柄
391
+ * @param {object} call 工具调用分片
392
+ */
393
+ AuiPage.prototype._toolControl = function (task, call) {
394
+ const _this = this;
395
+ return {
396
+ taskId: task.taskId,
397
+ toolCallId: call.id,
398
+ stop: function () { return _this._requestEnd("stopped", "tool", task); },
399
+ cancel: function () { return _this._requestEnd("cancelled", "tool", task); }
400
+ };
401
+ };
402
+ // #end
403
+
404
+ /**
405
+ * 处理单个生成器分片。文本类分片按类型累积并通过 streamFun 流式追加,
406
+ * 工具调用分片交给 _handleToolCall。
407
+ *
408
+ * @param {object} task 当前任务句柄
409
+ * @param {{value: object, done: boolean}} chunk 生成器返回项
410
+ */
411
+ // #doc:chunk
412
+ AuiPage.prototype._handleChunk = async function (task, chunk) {
413
+ if (!task || task.ended || task.endRequest) return;
414
+
415
+ const value = (chunk && chunk.value) || {};
416
+ const text = typeof value.text === "string" ? value.text : "";
417
+
418
+ // 类型变了,或者是一种特殊类型
419
+ if (value.type != task.preType || !task.textTypes.includes(value.type)) {
420
+ task.streamFun = void 0;
421
+
422
+ if (task.preText) {
423
+ task.cacheMessages.push({
424
+ role: "assistant",
425
+ content: [{ type: task.preType, text: task.preText }]
426
+ });
427
+ task.preText = "";
428
+ task.preType = "";
429
+ }
430
+
431
+ if (!task.textTypes.includes(value.type)) {
432
+ if (value.type === "tool-call") await this._handleToolCall(task, value);
433
+ } else {
434
+ task.preText = text;
435
+ task.preType = value.type;
436
+ task.streamFun = this._render(task, "assistant", value);
437
+ }
438
+
439
+ } else {
440
+ task.preText += text;
441
+ if (task.streamFun) callSafely(task.streamFun, value.text);
442
+ }
443
+ };
444
+ // #end
445
+
446
+ /**
447
+ * 工具调用分片:pending 时挂上视图并执行前端工具,success/error 时回填后端工具结果。
448
+ *
449
+ * @param {object} task 当前任务句柄
450
+ * @param {object} call 工具调用分片
451
+ */
452
+ // #doc:toolpending
453
+ AuiPage.prototype._handleToolCall = async function (task, call) {
454
+
455
+ // 工具开始调用(前端工具 + 后端工具)
456
+ if (call.status === "pending") {
457
+ const updater = asUpdater(this._render(task, "assistant", call));
458
+ if (updater) task.tool_calls[call.id] = updater;
459
+
460
+ // 后端工具由 ChatTransport 自己执行,这里只挂视图
461
+ if (call.caller !== "frontend") return;
462
+
463
+ // 前端工具需要自己执行;第二个参数是任务控制句柄,工具里可直接 stop / cancel
464
+ const execute = this.tools_execute[call.name];
465
+ const control = this._toolControl(task, call);
466
+ let result, status;
467
+
468
+ if (typeof execute === "function") {
469
+ try {
470
+ result = await execute(call.args, control);
471
+ status = "success";
472
+ } catch (error) {
473
+ result = error;
474
+ status = "error";
475
+ }
476
+ } else {
477
+ result = new Error("未注册的工具:" + call.name);
478
+ status = "error";
479
+ }
480
+
481
+ // 工具执行期间被取消:结果丢弃;被 stop 则继续把这次调用的结果落地
482
+ if (task.ended || isCancelled(task)) return;
483
+
484
+ const render = this.tools_render[call.name];
485
+ // #end
486
+
487
+ // 需要视图交互获取结果
488
+ // #doc:toolrender
489
+ if (typeof render === "function" && updater) {
490
+ const pending = Promise.resolve(updater(Object.assign({}, call, {
491
+ result: result,
492
+ status: status,
493
+ render: render,
494
+ taskId: control.taskId,
495
+ stop: control.stop,
496
+ cancel: control.cancel
497
+ })));
498
+
499
+ // 界面还挂着等交互时被结束:放弃等待,按 execute 的结果收尾
500
+ const outcome = await Promise.race([
501
+ pending.then(function (value) {
502
+ return { value: value };
503
+ }, function (error) {
504
+ return { error: error };
505
+ }),
506
+ task.endRequest
507
+ ? Promise.resolve({ ended: true })
508
+ : task.endSignal.promise.then(function () { return { ended: true }; })
509
+ ]);
510
+
511
+ if (task.ended || isCancelled(task)) return;
512
+
513
+ if (outcome.ended) {
514
+ callSafely(updater, Object.assign({}, call, { result: result, status: status }));
515
+ delete task.tool_calls[call.id];
516
+
517
+ task.cacheMessages.push({
518
+ role: "assistant",
519
+ content: [{
520
+ type: "tool-call",
521
+ name: call.name,
522
+ args: call.args,
523
+ result,
524
+ status
525
+ }]
526
+ });
527
+
528
+ return;
529
+ }
530
+
531
+ let result_ui = outcome.error !== void 0 ? outcome.error : outcome.value;
532
+ let status_ui = outcome.error !== void 0 ? "error" : "success";
533
+
534
+ callSafely(updater, Object.assign({}, call, { result: result_ui, status: status_ui }));
535
+ delete task.tool_calls[call.id];
536
+
537
+ task.cacheMessages.push({
538
+ role: "assistant",
539
+ content: [{
540
+ type: "tool-call",
541
+ name: call.name,
542
+ args: call.args,
543
+ result,
544
+ status,
545
+ ui: { status: status_ui, result: result_ui }
546
+ }]
547
+ });
548
+
549
+ invoke(this.adapter.ChatTransport, "response", null, ["tool-result", {
550
+ id: call.id,
551
+ status: status_ui,
552
+ result: result_ui
553
+ }]);
554
+ }
555
+
556
+ // #end
557
+ // #doc:toolplain
558
+ // 没有可用的视图入口,就当作纯工具调用
559
+ else {
560
+ if (updater) {
561
+ callSafely(updater, Object.assign({}, call, { result, status }));
562
+ delete task.tool_calls[call.id];
563
+ }
564
+
565
+ task.cacheMessages.push({
566
+ role: "assistant",
567
+ content: [{
568
+ type: "tool-call",
569
+ name: call.name,
570
+ args: call.args,
571
+ result,
572
+ status
573
+ }]
574
+ });
575
+
576
+ invoke(this.adapter.ChatTransport, "response", null, ["tool-result", {
577
+ id: call.id,
578
+ result,
579
+ status
580
+ }]);
581
+ }
582
+
583
+ return;
584
+ // #end
585
+ }
586
+
587
+ // 工具调用结束(后端工具)
588
+ // #doc:toolbackend
589
+ if (call.status === "success" || call.status === "error") {
590
+ if (task.tool_calls[call.id]) {
591
+ callSafely(task.tool_calls[call.id], call);
592
+ delete task.tool_calls[call.id];
593
+
594
+ task.cacheMessages.push({
595
+ role: "assistant",
596
+ content: [{
597
+ type: "tool-call",
598
+ name: call.name,
599
+ args: call.args,
600
+ result: call.result,
601
+ status: call.status
602
+ }]
603
+ });
604
+ }
605
+ }
606
+ // #end
607
+ };
608
+
609
+ /**
610
+ * 收尾 sendMessage 任务。统一处理:残留文本归并、入库、isExecuting 复位、
611
+ * 发出 task:end 事件、释放 Promise。
612
+ *
613
+ * @param {"complete"|"stopped"|"error"|"cancelled"} status 任务结束原因
614
+ * @param {boolean} isHistory 是否走入库分支(complete / stopped / cancelled 为 true,error 为 false)
615
+ * @param {Error|string} [err] status === "error" 时附带的错误对象
616
+ * @param {"user"|"tool"} [by] stopped / cancelled 时的发起方
617
+ * @param {object} [taskArg] 指定任务;兜底计时器传入,避免落到下一轮
618
+ */
619
+ // #doc:finishA
620
+ AuiPage.prototype._finalize = async function (status, isHistory, err, by, taskArg) {
621
+ let task = taskArg || this._currentTask;
622
+ if (!task || task.ended) return;
623
+ task.ended = true;
624
+
625
+ // 清理兜底计时器,并释放还在等结束信号的流程
626
+ if (task.stopTimer && typeof clearTimeout === "function") clearTimeout(task.stopTimer);
627
+ task.stopTimer = null;
628
+ callSafely(task.endSignal.resolve);
629
+
630
+ // 1. 残留文本归并到 cacheMessages
631
+ if (task.preText) {
632
+ task.cacheMessages.push({
633
+ role: "assistant",
634
+ content: [{ type: task.preType, text: task.preText }]
635
+ });
636
+ task.preText = "";
637
+ task.preType = "";
638
+ }
639
+
640
+ // 2. 让生成器停止继续产出(此时 next() 已 settle,可安全调用)
641
+ if (typeof task.generator.return === "function") {
642
+ callSafely(function () { return task.generator.return(); });
643
+ }
644
+
645
+ // #end
646
+ // #doc:finishB
647
+ // 3. 入库;失败降级为 error,避免前端误以为消息已保存
648
+ let failure = status === "error" ? err : null;
649
+
650
+ if (isHistory && !failure) {
651
+ try {
652
+ let historyMessages = toHistoryMessages({ messages: task.cacheMessages });
653
+
654
+ // 主动结束与取消也入库,只打标记;存或丢由 MessageHistory.append 自己决定
655
+ if (status === "stopped" || status === "cancelled") historyMessages.status = status;
656
+
657
+ if (this.currentThreadId === void 0) {
658
+ let newThread = await this.adapter.ThreadList?.new?.(historyMessages);
659
+
660
+ if (!newThread) throw new Error("新建会话失败");
661
+
662
+ await Promise.resolve(this.runtime.ThreadList?.append(newThread));
663
+ this.activeThread(newThread.threadId, true);
664
+ }
665
+
666
+ this.currentMessages.push(historyMessages);
667
+ await this.adapter.MessageHistory?.append?.(this.currentThreadId, historyMessages);
668
+ } catch (e) {
669
+ failure = e;
670
+ }
671
+ }
672
+
673
+ // 4. 复位、emit task:end、释放 Promise
674
+ if (this._currentTask === task) {
675
+ this.isExecuting = false;
676
+ this._currentTask = null;
677
+ }
678
+
679
+ const finalStatus = failure ? "error" : status;
680
+
681
+ const payload = {
682
+ taskId: task.taskId,
683
+ threadId: this.currentThreadId,
684
+ message: task.message,
685
+ status: finalStatus
686
+ };
687
+
688
+ // 主动结束 / 取消时说明是谁发起的;取消另附已显示条目,界面据此决定是否撤销
689
+ if (finalStatus === "stopped" || finalStatus === "cancelled") payload.by = by || "user";
690
+ if (finalStatus === "cancelled") payload.displayed = task.displayed;
691
+
692
+ this._emit("task:end", payload);
693
+
694
+ if (finalStatus === "error") task.reject(failure || new Error("任务执行失败"));
695
+ else if (finalStatus === "cancelled") task.reject("已取消");
696
+ else task.resolve();
697
+ };
698
+ // #end
699
+
700
+ // #doc:active
701
+ AuiPage.prototype.activeThread = function (threadId, __noLoad__) {
702
+ if (this.currentThreadId === threadId) return;
703
+
704
+ // 已经有执行的,不允许切换
705
+ if (this.isExecuting && !__noLoad__) return;
706
+
707
+ this.currentThreadId = threadId;
708
+ this.runtime.ThreadList?.active(threadId);
709
+
710
+ if (threadId === void 0) {
711
+ this.currentMessages = [];
712
+ this.runtime.ChatContent?.init([]);
713
+ return;
714
+ }
715
+
716
+ if (__noLoad__) return;
717
+
718
+ // 加载历史消息
719
+ invoke(this.adapter.MessageHistory, "load", (messages) => {
720
+ this.currentMessages = messages;
721
+
722
+ let plainMessages = [];
723
+ messages.forEach(item => {
724
+ plainMessages.push(...item.messages);
725
+ });
726
+ this.runtime.ChatContent?.init(plainMessages);
727
+ }, [threadId]);
728
+ };
729
+ // #end
730
+
731
+ // #doc:threads
732
+ AuiPage.prototype.deleteThread = function (threadId) {
733
+ invoke(this.adapter.ThreadList, "delete", () => {
734
+ this.runtime.ThreadList?.delete(threadId);
735
+
736
+ if (threadId === this.currentThreadId) this.newThread();
737
+ }, [threadId]);
738
+ };
739
+
740
+ AuiPage.prototype.archiveThread = function (threadId) {
741
+ invoke(this.adapter.ThreadList, "archive", () => {
742
+ this.runtime.ThreadList?.archive(threadId);
743
+
744
+ if (threadId === this.currentThreadId) this.newThread();
745
+ }, [threadId]);
746
+ };
747
+
748
+ AuiPage.prototype.unarchiveThread = function (threadId) {
749
+ invoke(this.adapter.ThreadList, "unarchive", () => {
750
+ this.runtime.ThreadList?.unarchive(threadId);
751
+ }, [threadId]);
752
+ };
753
+
754
+ // #end
755
+ // #doc:newthread
756
+ AuiPage.prototype.newThread = function () {
757
+ this.activeThread(void 0);
447
758
  };
448
759
 
449
760
  function initOption(setOption, defaultOption) {
@@ -456,166 +767,283 @@
456
767
 
457
768
  let EmptyFunction = () => void 0;
458
769
 
459
- const DEFAUTL_OPTIONS$4 = {
460
- run: EmptyFunction,
461
- response: EmptyFunction,
462
- };
463
-
464
- function ChatTransportAdapter(options) {
465
- this.name="ChatTransportAdapter";
466
-
467
- let value = initOption(options, { ...DEFAUTL_OPTIONS$4 });
468
- for (let key in DEFAUTL_OPTIONS$4) {
469
- this[key] = value[key];
470
- }
770
+ // #doc:ctor
771
+ const DEFAUTL_OPTIONS$4 = {
772
+ run: EmptyFunction,
773
+ response: EmptyFunction,
774
+ };
775
+
776
+ // #end
777
+
778
+ function ChatTransportAdapter(options) {
779
+ this.name="ChatTransportAdapter";
780
+
781
+ // #doc:merge
782
+ let value = initOption(options, { ...DEFAUTL_OPTIONS$4 });
783
+ for (let key in DEFAUTL_OPTIONS$4) {
784
+ this[key] = value[key];
785
+ }
786
+ // #end
471
787
  }
472
788
 
473
- const DEFAUTL_OPTIONS$3 = {
474
- load: EmptyFunction,
475
- append: EmptyFunction
476
- };
477
-
478
- function MessageHistoryAdapter(options) {
479
- this.name="MessageHistoryAdapter";
480
-
481
- let value = initOption(options, { ...DEFAUTL_OPTIONS$3 });
482
- for (let key in DEFAUTL_OPTIONS$3) {
483
- this[key] = value[key];
484
- }
789
+ const DEFAUTL_OPTIONS$3 = {
790
+ load: EmptyFunction,
791
+ append: EmptyFunction
792
+ };
793
+
794
+ function MessageHistoryAdapter(options) {
795
+ this.name="MessageHistoryAdapter";
796
+
797
+ let value = initOption(options, { ...DEFAUTL_OPTIONS$3 });
798
+ for (let key in DEFAUTL_OPTIONS$3) {
799
+ this[key] = value[key];
800
+ }
485
801
  }
486
802
 
487
- const DEFAUTL_OPTIONS$2 = {
488
- list: EmptyFunction,
489
- new: EmptyFunction,
490
- archive: EmptyFunction,
491
- unarchive: EmptyFunction,
492
- delete: EmptyFunction
493
- };
494
-
495
- function ThreadListAdapter(options) {
496
- this.name="ThreadListAdapter";
497
-
498
- let value = initOption(options, { ...DEFAUTL_OPTIONS$2 });
499
- for (let key in DEFAUTL_OPTIONS$2) {
500
- this[key] = value[key];
501
- }
803
+ // #doc:methods
804
+ const DEFAUTL_OPTIONS$2 = {
805
+ list: EmptyFunction,
806
+ new: EmptyFunction,
807
+ archive: EmptyFunction,
808
+ unarchive: EmptyFunction,
809
+ delete: EmptyFunction
810
+ };
811
+ // #end
812
+
813
+ function ThreadListAdapter(options) {
814
+ this.name="ThreadListAdapter";
815
+
816
+ let value = initOption(options, { ...DEFAUTL_OPTIONS$2 });
817
+ for (let key in DEFAUTL_OPTIONS$2) {
818
+ this[key] = value[key];
819
+ }
502
820
  }
503
821
 
504
- const DEFAUTL_OPTIONS$1 = {
505
- init: EmptyFunction,
506
- active: EmptyFunction,
507
- delete: EmptyFunction,
508
- archive: EmptyFunction,
509
- unarchive: EmptyFunction,
510
- append: EmptyFunction,
511
- };
512
-
513
- function ThreadListRuntime(options) {
514
- this.name="ThreadListRuntime";
515
-
516
- let value = initOption(options, { ...DEFAUTL_OPTIONS$1 });
517
- for (let key in DEFAUTL_OPTIONS$1) {
518
- this[key] = value[key];
519
- }
822
+ const DEFAUTL_OPTIONS$1 = {
823
+ init: EmptyFunction,
824
+ active: EmptyFunction,
825
+ delete: EmptyFunction,
826
+ archive: EmptyFunction,
827
+ unarchive: EmptyFunction,
828
+ append: EmptyFunction,
829
+ };
830
+
831
+ function ThreadListRuntime(options) {
832
+ this.name="ThreadListRuntime";
833
+
834
+ let value = initOption(options, { ...DEFAUTL_OPTIONS$1 });
835
+ for (let key in DEFAUTL_OPTIONS$1) {
836
+ this[key] = value[key];
837
+ }
520
838
  }
521
839
 
522
- const DEFAUTL_OPTIONS = {
523
- init: EmptyFunction,
524
- append: EmptyFunction,
525
- };
526
-
527
- function ChatContentRuntime(options) {
528
- this.name="ChatContentRuntime";
529
-
530
- let value = initOption(options, { ...DEFAUTL_OPTIONS });
531
- for (let key in DEFAUTL_OPTIONS) {
532
- this[key] = value[key];
533
- }
840
+ // #doc:ctor
841
+ const DEFAUTL_OPTIONS = {
842
+ init: EmptyFunction,
843
+ append: EmptyFunction,
844
+ };
845
+
846
+ // #end
847
+
848
+ function ChatContentRuntime(options) {
849
+ this.name="ChatContentRuntime";
850
+
851
+ let value = initOption(options, { ...DEFAUTL_OPTIONS });
852
+ for (let key in DEFAUTL_OPTIONS) {
853
+ this[key] = value[key];
854
+ }
534
855
  }
535
856
 
536
- function defineTool (options) {
537
- return {
538
- description: {
539
- type: "function",
540
- function: {
541
- name: options.name,
542
- description: options.description,
543
- parameters: options.parameters
544
- }
545
- },
546
- execute: options.execute,
547
- render: options.render
548
- };
857
+ // #doc:shape
858
+ function defineTool (options) {
859
+ return {
860
+ description: {
861
+ type: "function",
862
+ function: {
863
+ name: options.name,
864
+ description: options.description,
865
+ parameters: options.parameters
866
+ }
867
+ },
868
+ execute: options.execute,
869
+ render: options.render
870
+ };
871
+ // #end
549
872
  }
550
873
 
551
- async function* generator (rawFun) {
552
-
553
- // 已产出但尚未被消费的值缓冲
554
- const queue = [];
555
- // 当前等待消费者请求的 Promise 控制器;同时最多一个
556
- let pending = null;
557
- // 生产者是否已结束
558
- let ended = false;
559
- // 生产者是否已报错;一旦设置,后续 next/done 调用被忽略
560
- let errored = null;
561
-
562
- // 启动生产者,三个回调驱动数据流
563
- rawFun(
564
- // next:推送下一个值
565
- (value) => {
566
- if (errored) return;
567
- if (pending) {
568
- // 有等待中的消费者,立刻交值
569
- pending.resolve({ value, done: false });
570
- pending = null;
571
- } else {
572
- // 否则入队缓存
573
- queue.push(value);
574
- }
575
- },
576
- // done:结束
577
- () => {
578
- if (errored) return;
579
- ended = true;
580
- if (pending) {
581
- pending.resolve({ value: void 0, done: true });
582
- pending = null;
583
- }
584
- },
585
- // error:异常
586
- (err) => {
587
- errored = err;
588
- if (pending) {
589
- pending.reject(err);
590
- pending = null;
591
- }
592
- }
593
- );
594
-
595
- // 消费者主循环
596
- while (true) {
597
- if (errored) throw errored;
598
- // 优先消费缓冲
599
- if (queue.length) {
600
- yield queue.shift();
601
- continue;
602
- }
603
- // 缓冲空且生产者已结束 → 终止迭代
604
- if (ended) return;
605
- // 缓冲空且未结束 → 挂起等待生产者回调唤醒
606
- const result = await new Promise((resolve, reject) => {
607
- pending = { resolve, reject };
608
- });
609
- // 被唤醒后再判一次 error,防止回调已设 errored 但未分发
610
- if (errored) throw errored;
611
- if (result.done) return;
612
- yield result.value;
613
- }
874
+ async function* generator (rawFun) {
875
+
876
+ // 已产出但尚未被消费的值缓冲
877
+ const queue = [];
878
+ // 当前等待消费者请求的 Promise 控制器;同时最多一个
879
+ let pending = null;
880
+ // 生产者是否已结束
881
+ let ended = false;
882
+ // 生产者是否已报错;一旦设置,后续 next/done 调用被忽略
883
+ let errored = null;
884
+ // 消费者是否已退出(return / throw),退出后不再接收生产者推送
885
+ let cancelled = false;
886
+
887
+ const resolvePending = (payload) => {
888
+ if (!pending) return;
889
+ const p = pending;
890
+ pending = null;
891
+ p.resolve(payload);
892
+ };
893
+
894
+ // 启动生产者,三个回调驱动数据流
895
+ rawFun(
896
+ // next:推送下一个值
897
+ (value) => {
898
+ if (errored || cancelled) return;
899
+ if (pending) {
900
+ // 有等待中的消费者,立刻交值
901
+ resolvePending({ value, done: false });
902
+ } else {
903
+ // 否则入队缓存
904
+ queue.push(value);
905
+ }
906
+ },
907
+ // done:结束
908
+ () => {
909
+ if (errored || cancelled) return;
910
+ ended = true;
911
+ resolvePending({ value: void 0, done: true });
912
+ },
913
+ // error:异常
914
+ (err) => {
915
+ if (cancelled) return;
916
+ errored = err;
917
+ if (pending) {
918
+ const p = pending;
919
+ pending = null;
920
+ p.reject(err);
921
+ }
922
+ }
923
+ );
924
+
925
+ try {
926
+ // 消费者主循环
927
+ while (true) {
928
+ if (errored) throw errored;
929
+ // 优先消费缓冲
930
+ if (queue.length) {
931
+ yield queue.shift();
932
+ continue;
933
+ }
934
+ // 缓冲空且生产者已结束 → 终止迭代
935
+ if (ended) return;
936
+ // 缓冲空且未结束 → 挂起等待生产者回调唤醒
937
+ const result = await new Promise((resolve, reject) => {
938
+ pending = { resolve, reject };
939
+ });
940
+ // 被唤醒后再判一次 error,防止回调已设 errored 但未分发
941
+ if (errored) throw errored;
942
+ if (result.done) return;
943
+ yield result.value;
944
+ }
945
+ } finally {
946
+ // 消费者提前退出:停止接收,释放缓冲与挂起的控制器
947
+ cancelled = true;
948
+ queue.length = 0;
949
+ resolvePending({ value: void 0, done: true });
950
+ }
951
+ }
952
+
953
+ // #doc:ctor
954
+ function MessageStream(send, end) {
955
+ this.send = send || EmptyFunction;
956
+ this.end = end || EmptyFunction;
614
957
  }
615
958
 
616
- function MessageStream(send, end) {
617
- this.send = send || EmptyFunction;
618
- this.end = end || EmptyFunction;
959
+ // 页面消息(富片段)→ 模型线上消息(纯文本 + tool_calls / tool 结果)
960
+
961
+ // 入参既可以是历史消息组数组,也可以是纯消息数组
962
+ // #doc:flat
963
+ function flatten(input) {
964
+ const list = [];
965
+ for (const item of input || []) {
966
+ if (!item) continue;
967
+ if (Array.isArray(item.messages)) list.push(...item.messages);
968
+ else list.push(item);
969
+ }
970
+ return list;
971
+ }
972
+ // #end
973
+
974
+ // 只拼接 text 片段;thinking / loading 与自定义片段不进模型上下文
975
+ function textOf(parts) {
976
+ let text = "";
977
+ for (const part of parts) {
978
+ if (!part || part.type !== "text" || typeof part.text !== "string") continue;
979
+ text += part.text;
980
+ }
981
+ return text;
982
+ }
983
+
984
+ function contentOf(value) {
985
+ if (typeof value === "string") return value;
986
+ if (value instanceof Error) return String(value);
987
+ try {
988
+ const text = JSON.stringify(value);
989
+ return typeof text === "string" ? text : "";
990
+ } catch (e) {
991
+ return String(value);
992
+ }
993
+ }
994
+
995
+ /**
996
+ * 把页面侧的历史消息转换为模型可用的 ChatMessage 数组。
997
+ *
998
+ * @param {Array} input 历史消息组数组(HistoryMessageGroup[])或消息数组(ChatContentMessage[])
999
+ * @returns {Array} 可直接作为 completions.messages 的数组
1000
+ */
1001
+ function toModelMessages(input) {
1002
+ const messages = flatten(input);
1003
+ const result = [];
1004
+ let seq = 0;
1005
+
1006
+ for (const message of messages) {
1007
+ const parts = Array.isArray(message.content) ? message.content : [];
1008
+ const text = typeof message.content === "string" ? message.content : textOf(parts);
1009
+
1010
+ // #doc:calls
1011
+ // 只保留已结束的工具调用,避免模型收到没有结果的 tool_call
1012
+ const calls = parts.filter(part => part
1013
+ && part.type === "tool-call"
1014
+ && typeof part.name === "string"
1015
+ && (part.status === "success" || part.status === "error"));
1016
+
1017
+ if (calls.length === 0) {
1018
+ if (text) result.push({ role: message.role, content: text });
1019
+ continue;
1020
+ }
1021
+
1022
+ // 历史片段可能没有 id,这里补一个稳定 id,让 tool 消息能对应上
1023
+ const tool_calls = calls.map(call => ({
1024
+ id: call.id || ("call_" + (++seq)),
1025
+ type: "function",
1026
+ function: {
1027
+ name: call.name,
1028
+ arguments: JSON.stringify(call.args || {})
1029
+ }
1030
+ }));
1031
+
1032
+ result.push({ role: "assistant", content: text || void 0, tool_calls });
1033
+
1034
+ calls.forEach((call, i) => {
1035
+ const payload = call.ui && call.ui.status ? call.ui.result : call.result;
1036
+ result.push({
1037
+ role: "tool",
1038
+ tool_call_id: tool_calls[i].id,
1039
+ tool_name: call.name,
1040
+ content: contentOf(payload)
1041
+ });
1042
+ });
1043
+ // #end
1044
+ }
1045
+
1046
+ return result;
619
1047
  }
620
1048
 
621
1049
  exports.AuiPage = AuiPage;
@@ -627,5 +1055,6 @@
627
1055
  exports.ThreadListRuntime = ThreadListRuntime;
628
1056
  exports.defineTool = defineTool;
629
1057
  exports.generator = generator;
1058
+ exports.toModelMessages = toModelMessages;
630
1059
 
631
1060
  }));