@auipage/core 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,449 +1,449 @@
1
- /*! @auipage/core v0.1.0-alpha.4 */
1
+ /*! @auipage/core 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_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;
23
- }
24
-
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
-
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;
74
23
  }
75
24
 
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);
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);
447
447
  };
448
448
 
449
449
  function initOption(setOption, defaultOption) {
@@ -456,166 +456,166 @@
456
456
 
457
457
  let EmptyFunction = () => void 0;
458
458
 
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
- }
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
+ }
471
471
  }
472
472
 
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
- }
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
+ }
485
485
  }
486
486
 
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
- }
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
+ }
502
502
  }
503
503
 
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
- }
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
+ }
520
520
  }
521
521
 
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
- }
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
+ }
534
534
  }
535
535
 
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
- };
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
+ };
549
549
  }
550
550
 
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
- }
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
+ }
614
614
  }
615
615
 
616
- function MessageStream(send, end) {
617
- this.send = send || EmptyFunction;
618
- this.end = end || EmptyFunction;
616
+ function MessageStream(send, end) {
617
+ this.send = send || EmptyFunction;
618
+ this.end = end || EmptyFunction;
619
619
  }
620
620
 
621
621
  exports.AuiPage = AuiPage;