@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/src/AuiPage.js CHANGED
@@ -1,429 +1,736 @@
1
- import toHistoryMessages from "./tools/toHistoryMessages.js";
2
-
3
- function AuiPage(options) {
4
-
5
- // 连接适配器和运行时视图
6
- this.adapter = {};
7
- this.runtime = {};
8
- for (let instance of Object.values(options.adapter)) {
9
- instance.aui = this;
10
- this.adapter[instance.name.replace("Adapter", "")] = instance;
11
- }
12
- for (let instance of Object.values(options.runtime)) {
13
- instance.aui = this;
14
- this.runtime[instance.name.replace("Runtime", "")] = instance;
15
- }
16
-
17
- // 工具注册
18
- this.tools_execute = {};
19
- this.tools_render = {};
20
- this.tools_description = [];
21
- for (let tool of options.tools || []) {
22
- this.tools_execute[tool.description.function.name] = tool.execute;
23
- this.tools_render[tool.description.function.name] = tool.render;
24
- this.tools_description.push({ description: tool.description });
25
- }
26
-
27
- // 当前是否在执行中
28
- this.isExecuting = false;
29
-
30
- // 当前激活的会话ID
31
- this.currentThreadId = void 0;
32
-
33
- // 当前会话内容
34
- this.currentMessages = [];
35
-
36
- // 任务生命周期事件:task:start / task:end
37
- this._events = { "task:start": [], "task:end": [] };
38
-
39
- // 任务自增序号,用于生成 taskId
40
- this._taskSeq = 0;
41
-
42
- // 当前正在执行的任务句柄(sendMessage 进入执行期时写入)
43
- this._currentTask = null;
44
-
45
- // 请求对话列表
46
- this.adapter.ThreadList.list()?.then((threads) => {
47
-
48
- // 在页面中显示对话列表
49
- this.runtime.ThreadList.init(threads);
50
- });
51
-
52
- }
53
-
54
- // 触发生命周期事件;handler 抛错被吞掉,避免影响 sendMessage 主流程
55
- AuiPage.prototype._emit = function (event, payload) {
56
- let handlers = this._events[event];
57
- if (!handlers) return;
58
- // 复制一份,防止 off() 在回调中修改原数组
59
- handlers.slice().forEach(function (fn) {
60
- try { fn(payload); } catch (e) { /* 吞掉 handler 异常 */ }
61
- });
62
- };
63
-
64
- // 订阅生命周期事件
65
- AuiPage.prototype.on = function (event, handler) {
66
- if (!this._events[event]) this._events[event] = [];
67
- this._events[event].push(handler);
68
- return this;
69
- };
70
-
71
- // 取消订阅
72
- AuiPage.prototype.off = function (event, handler) {
73
- let list = this._events[event];
74
- if (!list) return this;
75
- let idx = list.indexOf(handler);
76
- if (idx >= 0) list.splice(idx, 1);
77
- return this;
78
- };
79
-
80
- AuiPage.prototype.sendMessage = function (message) {
81
- let _this = this;
82
-
83
- return new Promise((resolve, reject) => {
84
-
85
- if (this.isExecuting) return reject("当前正在执行中");
86
- this.isExecuting = true;
87
-
88
- let generator = this.adapter.ChatTransport.run({
89
- messages: [message],
90
- context: {
91
- history: this.currentMessages,
92
- tools: this.tools_description
93
- }
94
- });
95
-
96
- if (!generator) {
97
- this.isExecuting = false;
98
- reject("ChatTransport.run() 返回空值");
99
- return;
100
- }
101
-
102
- // 写入任务上下文,供后续协同使用
103
- let taskId = String(++this._taskSeq);
104
- this._currentTask = {
105
- taskId,
106
- message,
107
- generator,
108
- cacheMessages: [message],
109
- preType: "",
110
- preText: "",
111
- textTypes: ["loading", "thinking", "text"],
112
- streamFun: void 0,
113
- tool_calls: {},
114
- resolve,
115
- reject,
116
- ended: false
117
- };
118
-
119
- // 任务开始生命周期
120
- this._emit("task:start", {
121
- taskId,
122
- threadId: this.currentThreadId,
123
- message
124
- });
125
-
126
- let cacheMessages = this._currentTask.cacheMessages;
127
- let preType = this._currentTask.preType;
128
- let preText = this._currentTask.preText;
129
- let textTypes = this._currentTask.textTypes;
130
- let streamFun = this._currentTask.streamFun;
131
- let tool_calls = this._currentTask.tool_calls;
132
-
133
- for (let i = 0; i < message.content.length; i++) {
134
- this.runtime.ChatContent.append(message.role, message.content[i]);
135
- }
136
-
137
- // 同步写入 _currentTask 的小工具
138
- let sync = function () {
139
- _this._currentTask.preType = preType;
140
- _this._currentTask.preText = preText;
141
- _this._currentTask.streamFun = streamFun;
142
- };
143
-
144
- (function doit() {
145
- generator?.next().then(async function (res) {
146
- if (!res.done) {
147
-
148
- // 类型变了,或者是一种特殊类型
149
- if (res.value.type != preType || !textTypes.includes(res.value.type)) {
150
- streamFun = void 0;
151
-
152
- if (preText) {
153
- cacheMessages.push({
154
- role: "assistant", content: [{
155
- type: preType,
156
- text: preText
157
- }]
158
- });
159
- preText = "";
160
- preType = "";
161
- }
162
-
163
- if (!textTypes.includes(res.value.type)) {
164
-
165
- // 工具调用
166
- if (res.value.type === "tool-call") {
167
-
168
- // 工具开始调用(前端工具+后端工具)
169
- if (res.value.status === "pending") {
170
- tool_calls[res.value.id] = _this.runtime.ChatContent.append("assistant", res.value);
171
-
172
- // 对于前端工具,需要自己执行工具调用
173
- if (res.value.caller === "frontend") {
174
- let result, status;
175
-
176
- try {
177
- result = await _this.tools_execute[res.value.name](res.value.args);
178
- status = "success"; // 调用成功
179
- } catch (error) {
180
- result = error;
181
- status = "error"; // 调用失败
182
- }
183
-
184
- let render = _this.tools_render[res.value.name];
185
-
186
- // 需要视图交互获取结果
187
- if (render) {
188
- let result_ui, status_ui;
189
-
190
- try {
191
- result_ui = await tool_calls[res.value.id]({
192
- ...res.value,
193
- result,
194
- status,
195
- render
196
- });
197
- status_ui = "success";
198
- } catch (error) {
199
- result_ui = error;
200
- status_ui = "error";
201
- }
202
-
203
- tool_calls[res.value.id]({
204
- ...res.value,
205
- result: result_ui,
206
- status: status_ui
207
- });
208
- delete tool_calls[res.value.id];
209
-
210
- cacheMessages.push({
211
- role: "assistant", content: [{
212
- type: "tool-call",
213
- name: res.value.name,
214
- args: res.value.args,
215
- result,
216
- status,
217
- ui: {
218
- status: status_ui,
219
- result: result_ui
220
- }
221
- }]
222
- });
223
-
224
- _this.adapter.ChatTransport.response("tool-result", {
225
- id: res.value.id,
226
- status: status_ui,
227
- result: result_ui
228
- });
229
- }
230
-
231
- // 没有render,就相当于纯粹的工具调用
232
- else {
233
- tool_calls[res.value.id]({
234
- ...res.value,
235
- result,
236
- status
237
- });
238
- delete tool_calls[res.value.id];
239
-
240
- cacheMessages.push({
241
- role: "assistant", content: [{
242
- type: "tool-call",
243
- name: res.value.name,
244
- args: res.value.args,
245
- result,
246
- status
247
- }]
248
- });
249
-
250
- _this.adapter.ChatTransport.response("tool-result", {
251
- id: res.value.id,
252
- result,
253
- status
254
- });
255
- }
256
-
257
- }
258
-
259
- }
260
-
261
- // 工具调用结束(后端工具)
262
- else if (res.value.status === "success" || res.value.status === "error") {
263
- if (tool_calls[res.value.id]) {
264
- tool_calls[res.value.id](res.value);
265
- delete tool_calls[res.value.id];
266
-
267
- cacheMessages.push({
268
- role: "assistant", content: [{
269
- type: "tool-call",
270
- name: res.value.name,
271
- args: res.value.args,
272
- result: res.value.result,
273
- status: res.value.status
274
- }]
275
- });
276
- }
277
- }
278
- } else {
279
- // console.log("【其他消息】", res.value);
280
- }
281
-
282
- } else {
283
- preText = res.value.text;
284
- preType = res.value.type;
285
- streamFun = _this.runtime.ChatContent.append("assistant", res.value);
286
- }
287
-
288
- } else {
289
- preText += res.value.text;
290
- if (streamFun) streamFun(res.value.text);
291
- }
292
-
293
- sync();
294
- doit();
295
- } else {
296
- sync();
297
- _this._finalize("complete", true);
298
- }
299
- }, err => {
300
- _this._finalize("error", false, err);
301
- });
302
- })();
303
-
304
- });
305
- };
306
-
307
- /**
308
- * 收尾当前 sendMessage 任务。统一处理:残留文本归并、是否入库、isExecuting 复位、
309
- * 发出 task:end 事件、释放 Promise。
310
- *
311
- * @param {"complete"|"error"} status 任务结束原因
312
- * @param {boolean} isHistory 是否走入库分支(complete 始终 true;error 始终 false)
313
- * @param {Error|string} [err] status === "error" 时附带的错误对象
314
- */
315
- AuiPage.prototype._finalize = async function (status, isHistory, err) {
316
- let task = this._currentTask;
317
- if (!task || task.ended) return;
318
- task.ended = true;
319
-
320
- let { taskId, message, cacheMessages, preType, preText, resolve, reject } = task;
321
-
322
- // 1. 残留文本归并到 cacheMessages
323
- if (preText) {
324
- cacheMessages.push({
325
- role: "assistant",
326
- content: [{ type: preType, text: preText }]
327
- });
328
- task.preText = "";
329
- task.preType = "";
330
- }
331
-
332
- // 2. 入库分支
333
- if (isHistory) {
334
- try {
335
- let historyMessages = toHistoryMessages({ messages: cacheMessages });
336
-
337
- if (this.currentThreadId === void 0) {
338
- let newThread = await this.adapter.ThreadList.new(historyMessages);
339
-
340
- if (!newThread) {
341
- // 新建会话失败 → 退化为 error,不入库、不 resolve
342
- this.isExecuting = false;
343
- this._currentTask = null;
344
- this._emit("task:end", { taskId, threadId: this.currentThreadId, message, status: "error" });
345
- reject(new Error("新建会话失败"));
346
- return;
347
- }
348
-
349
- await this.runtime.ThreadList.append(newThread);
350
- this.activeThread(newThread.threadId, true);
351
- }
352
-
353
- this.currentMessages.push(historyMessages);
354
- this.adapter.MessageHistory.append(this.currentThreadId, historyMessages);
355
- } catch (e) {
356
- // 入库链路本身抛错 → 退化为 error
357
- this.isExecuting = false;
358
- this._currentTask = null;
359
- this._emit("task:end", { taskId, threadId: this.currentThreadId, message, status: "error" });
360
- reject(e);
361
- return;
362
- }
363
- }
364
-
365
- // 4. 复位、emit task:end、释放 Promise
366
- this.isExecuting = false;
367
- this._currentTask = null;
368
-
369
- this._emit("task:end", { taskId, threadId: this.currentThreadId, message, status });
370
-
371
- if (status === "error") reject(err);
372
- else resolve();
373
- };
374
-
375
- AuiPage.prototype.activeThread = function (threadId, __noLoad__) {
376
- if (this.currentThreadId === threadId) return;
377
-
378
- // 已经有执行的,不允许切换
379
- if (this.isExecuting && !__noLoad__) return;
380
-
381
- this.currentThreadId = threadId;
382
- this.runtime.ThreadList.active(threadId);
383
-
384
- if (threadId === void 0) {
385
- this.currentMessages = [];
386
- this.runtime.ChatContent.init([]);
387
- } else if (!__noLoad__) {
388
-
389
- // 加载历史消息
390
- this.adapter.MessageHistory.load(threadId)?.then(messages => {
391
- this.currentMessages = messages;
392
-
393
- let plainMessages = [];
394
- messages.forEach(item => {
395
- plainMessages.push(...item.messages);
396
- });
397
- this.runtime.ChatContent.init(plainMessages);
398
- });
399
- }
400
- };
401
-
402
- AuiPage.prototype.deleteThread = function (threadId) {
403
- this.adapter.ThreadList.delete(threadId)?.then(() => {
404
- this.runtime.ThreadList.delete(threadId);
405
-
406
- if (threadId === this.currentThreadId) this.newThread();
407
- });
408
-
409
- };
410
-
411
- AuiPage.prototype.archiveThread = function (threadId) {
412
- this.adapter.ThreadList.archive(threadId)?.then(() => {
413
- this.runtime.ThreadList.archive(threadId);
414
-
415
- if (threadId === this.currentThreadId) this.newThread();
416
- });
417
- };
418
-
419
- AuiPage.prototype.unarchiveThread = function (threadId) {
420
- this.adapter.ThreadList.unarchive(threadId).then(() => {
421
- this.runtime.ThreadList.unarchive(threadId);
422
- });
423
- };
424
-
425
- AuiPage.prototype.newThread = function () {
426
- this.activeThread(void 0);
427
- };
428
-
429
- export default AuiPage;
1
+ import toHistoryMessages from "./tools/toHistoryMessages.js";
2
+
3
+ // 挂载适配器/运行时:name 缺失时回退到配置对象的 key,避免直接崩
4
+ // #doc:mount
5
+ function mount(aui, list, suffix) {
6
+ const result = {};
7
+ for (const [key, instance] of Object.entries(list || {})) {
8
+ if (!instance) continue;
9
+ instance.aui = aui;
10
+ const name = typeof instance.name === "string" ? instance.name : "";
11
+ result[name.replace(suffix, "") || key.replace(suffix, "")] = instance;
12
+ }
13
+ return result;
14
+ }
15
+ // #end
16
+
17
+ // 适配器调用:Promise 就等完成,同步值直接处理,同步返回 undefined 视为未实现
18
+ // #doc:invoke
19
+ function invoke(target, method, apply, args) {
20
+ if (!target || typeof target[method] !== "function") return;
21
+ let ret;
22
+ try {
23
+ ret = target[method].apply(target, args || []);
24
+ } catch (e) {
25
+ return;
26
+ }
27
+ if (ret === void 0 || ret === null) return;
28
+ if (typeof ret.then === "function") {
29
+ ret.then(apply, function () { });
30
+ return;
31
+ }
32
+ if (typeof apply === "function") apply(ret);
33
+ }
34
+ // #end
35
+
36
+ // 安全调用:返回值可能为 void / Promise,异常与拒绝都不外泄
37
+ // #doc:safe
38
+ function callSafely(fn, arg) {
39
+ if (typeof fn !== "function") return;
40
+ try {
41
+ const ret = fn(arg);
42
+ if (ret && typeof ret.then === "function") ret.then(null, function () { });
43
+ } catch (e) { /* 忽略视图与上报通道异常 */ }
44
+ }
45
+
46
+ // 视图更新函数:runtime 的 append 允许返回 void(类型契约如此),这里统一兜底
47
+ function asUpdater(ret) {
48
+ return typeof ret === "function" ? ret : null;
49
+ }
50
+ // #end
51
+
52
+ // content 规范化为片段数组:字符串按整段处理,避免逐字符渲染
53
+ // #doc:content
54
+ function normalizeContent(content) {
55
+ if (Array.isArray(content)) return content;
56
+ if (content === void 0 || content === null) return [];
57
+ if (typeof content === "string") return content === "" ? [] : [{ type: "text", text: content }];
58
+ return [content];
59
+ }
60
+ // #end
61
+
62
+ // 取消时等待 next() 落定的兜底上限(毫秒),防止适配器忽略 signal 时页面停在执行中
63
+ // #doc:cancelchk
64
+ const DEFAULT_STOP_TIMEOUT = 5000;
65
+
66
+ // 被取消的任务:后续分片与工具结果一律丢弃;被 stop 则继续把结果落地
67
+ function isCancelled(task) {
68
+ return !!(task.endRequest && task.endRequest.status === "cancelled");
69
+ // #end
70
+ }
71
+
72
+ // #doc:ctor
73
+ function AuiPage(options) {
74
+ options = options || {};
75
+
76
+ // 连接适配器和运行时视图
77
+ this.adapter = mount(this, options.adapter, "Adapter");
78
+ this.runtime = mount(this, options.runtime, "Runtime");
79
+
80
+ // 工具注册
81
+ this.tools_execute = {};
82
+ this.tools_render = {};
83
+ this.tools_description = [];
84
+ for (let tool of options.tools || []) {
85
+ this.tools_execute[tool.description.function.name] = tool.execute;
86
+ this.tools_render[tool.description.function.name] = tool.render;
87
+ this.tools_description.push({ description: tool.description });
88
+ }
89
+
90
+ // 当前是否在执行中
91
+ this.isExecuting = false;
92
+
93
+ // 当前激活的会话ID
94
+ this.currentThreadId = void 0;
95
+
96
+ // 当前会话内容
97
+ this.currentMessages = [];
98
+
99
+ // 任务生命周期事件:task:start / task:end
100
+ this._events = { "task:start": [], "task:end": [] };
101
+
102
+ // 任务自增序号,用于生成 taskId
103
+ this._taskSeq = 0;
104
+
105
+ // 当前正在执行的任务句柄(sendMessage 进入执行期时写入)
106
+ this._currentTask = null;
107
+
108
+ // 取消时等待 next 落定的兜底时长
109
+ this._stopTimeout = options.stopTimeout > 0 ? options.stopTimeout : DEFAULT_STOP_TIMEOUT;
110
+
111
+ // 请求对话列表
112
+ invoke(this.adapter.ThreadList, "list", (threads) => {
113
+ this.runtime.ThreadList?.init(threads);
114
+ });
115
+ }
116
+ // #end
117
+
118
+ // 触发生命周期事件;handler 抛错被吞掉,避免影响 sendMessage 主流程
119
+ // #doc:events
120
+ AuiPage.prototype._emit = function (event, payload) {
121
+ let handlers = this._events[event];
122
+ if (!handlers) return;
123
+ // 复制一份,防止 off() 在回调中修改原数组
124
+ handlers.slice().forEach(function (fn) {
125
+ try { fn(payload); } catch (e) { /* 吞掉 handler 异常 */ }
126
+ });
127
+ };
128
+
129
+ // 订阅生命周期事件
130
+ AuiPage.prototype.on = function (event, handler) {
131
+ if (!this._events[event]) this._events[event] = [];
132
+ this._events[event].push(handler);
133
+ return this;
134
+ };
135
+
136
+ // 取消订阅
137
+ AuiPage.prototype.off = function (event, handler) {
138
+ let list = this._events[event];
139
+ if (!list) return this;
140
+ let idx = list.indexOf(handler);
141
+ if (idx >= 0) list.splice(idx, 1);
142
+ return this;
143
+ };
144
+ // #end
145
+
146
+ // 交给界面渲染,同时登记显示条目:取消时据此告诉界面涉及哪几条
147
+ // #doc:render
148
+ AuiPage.prototype._render = function (task, role, part) {
149
+ const content = this.runtime.ChatContent;
150
+ if (!content || typeof content.append !== "function") return;
151
+
152
+ task.displayed.push({ index: task.displayed.length, role: role, part: part });
153
+ return content.append(role, part);
154
+ };
155
+ // #end
156
+
157
+ // #doc:send
158
+ AuiPage.prototype.sendMessage = function (message) {
159
+ let _this = this;
160
+
161
+ return new Promise((resolve, reject) => {
162
+
163
+ if (this.isExecuting) return reject("当前正在执行中");
164
+
165
+ if (!message || typeof message !== "object") return reject("消息格式不正确");
166
+
167
+ // content 规范化:字符串包成单个 text 片段,避免逐字符渲染
168
+ const content = normalizeContent(message.content);
169
+ const input = Array.isArray(message.content) ? message : Object.assign({}, message, { content });
170
+
171
+ this.isExecuting = true;
172
+
173
+ // 取消通道:signal 交给适配器,由它透传到底层 HTTP / 模型请求
174
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
175
+
176
+ let generator;
177
+ try {
178
+ generator = this.adapter.ChatTransport.run({
179
+ messages: [input],
180
+ context: {
181
+ history: this.currentMessages,
182
+ tools: this.tools_description,
183
+ signal: controller ? controller.signal : void 0
184
+ }
185
+ });
186
+ } catch (error) {
187
+ // run() 同步抛错:复位状态,否则页面永久卡在“执行中”
188
+ this.isExecuting = false;
189
+ reject(error);
190
+ return;
191
+ }
192
+
193
+ if (!generator || typeof generator.next !== "function") {
194
+ this.isExecuting = false;
195
+ reject("ChatTransport.run() 返回空值");
196
+ return;
197
+ }
198
+
199
+ // 结束信号:工具或界面里发起 stop / cancel 时唤醒等待中的流程
200
+ let signalEnd;
201
+ const endSignal = new Promise(function (resolve) { signalEnd = resolve; });
202
+
203
+ // 写入任务上下文,供后续协同使用
204
+ let taskId = String(++this._taskSeq);
205
+ const task = this._currentTask = {
206
+ taskId,
207
+ message: input,
208
+ generator,
209
+ controller,
210
+ cacheMessages: [input],
211
+ displayed: [],
212
+ preType: "",
213
+ preText: "",
214
+ textTypes: ["loading", "thinking", "text"],
215
+ streamFun: void 0,
216
+ tool_calls: {},
217
+ resolve,
218
+ reject,
219
+ ended: false,
220
+ endRequest: null,
221
+ endSignal: { promise: endSignal, resolve: signalEnd },
222
+ busy: false,
223
+ nextPending: false
224
+ };
225
+
226
+ // 任务开始生命周期
227
+ this._emit("task:start", {
228
+ taskId,
229
+ threadId: this.currentThreadId,
230
+ message: input
231
+ });
232
+
233
+ // 回显用户消息
234
+ for (let i = 0; i < content.length; i++) {
235
+ this._render(task, input.role, content[i]);
236
+ }
237
+ // #end
238
+
239
+ // #doc:pump
240
+ const finishEnd = () => {
241
+ const request = task.endRequest;
242
+ if (task.ended || !request) return;
243
+ this._finalize(request.status, true, null, request.by, task);
244
+ };
245
+
246
+ const pump = () => {
247
+ if (task.ended) return;
248
+ if (task.endRequest) return finishEnd();
249
+
250
+ let step;
251
+ try {
252
+ step = generator.next();
253
+ } catch (error) {
254
+ this._finalize("error", false, error);
255
+ return;
256
+ }
257
+
258
+ task.nextPending = true;
259
+
260
+ Promise.resolve(step).then(function (res) {
261
+ task.nextPending = false;
262
+
263
+ // next 未决期间发起过结束请求:此刻已落定,可以安全收尾
264
+ if (task.endRequest) return finishEnd();
265
+ if (task.ended) return;
266
+
267
+ if (res && res.done) {
268
+ _this._finalize("complete", true);
269
+ return;
270
+ }
271
+
272
+ task.busy = true;
273
+ _this._handleChunk(task, res).then(function () {
274
+ task.busy = false;
275
+
276
+ if (task.endRequest) return finishEnd();
277
+ if (task.ended) return;
278
+ pump();
279
+ // #end
280
+ }, function (error) {
281
+ task.busy = false;
282
+
283
+ if (task.endRequest) return finishEnd();
284
+ _this._finalize("error", false, error);
285
+ });
286
+ }, function (error) {
287
+ task.nextPending = false;
288
+
289
+ if (task.endRequest) return finishEnd();
290
+ _this._finalize("error", false, error);
291
+ });
292
+ };
293
+
294
+ pump();
295
+
296
+ });
297
+ };
298
+
299
+ /**
300
+ * 统一结束请求:stopped 当成功收尾,cancelled 当取消。
301
+ * 有分片或工具正在处理时不立即收尾,等它把手上的结果落完再结束,
302
+ * 否则这次工具调用会从消息里丢掉。
303
+ *
304
+ * @param {"stopped"|"cancelled"} status 结束状态
305
+ * @param {"user"|"tool"} by 发起方
306
+ * @param {object} [task] 指定任务;工具侧传入自己所属的任务,避免打到下一轮
307
+ * @returns {boolean} 当时是否有可结束的任务
308
+ */
309
+ // #doc:end
310
+ AuiPage.prototype._requestEnd = function (status, by, task) {
311
+ task = task || this._currentTask;
312
+ if (!task || task.ended) return false;
313
+ if (task.endRequest) return true;
314
+
315
+ task.endRequest = { status: status, by: by };
316
+
317
+ // 中断底层请求;适配器把 context.signal 透传下去即可立即停止
318
+ callSafely(function () {
319
+ if (task.controller) task.controller.abort();
320
+ });
321
+
322
+ // 唤醒可能卡在界面交互里的流程
323
+ callSafely(task.endSignal.resolve);
324
+
325
+ if (task.busy || task.nextPending) {
326
+ // 等着当前分片落定;兜底超时防止适配器忽略 signal 时页面停在执行中
327
+ const _this = this;
328
+ task.stopTimer = setTimeout(function () {
329
+ _this._finalize(status, true, null, by, task);
330
+ }, this._stopTimeout);
331
+ if (task.stopTimer && typeof task.stopTimer.unref === "function") task.stopTimer.unref();
332
+
333
+ return true;
334
+ }
335
+
336
+ this._finalize(status, true, null, by, task);
337
+ return true;
338
+ };
339
+ // #end
340
+
341
+ /**
342
+ * 主动结束当前任务:当作成功收尾——内容保留、入库标记 stopped、sendMessage 正常 resolve。
343
+ * 与 cancel 的区别只在这份“怎么收下这一轮”的口径,不在谁点的。
344
+ *
345
+ * @returns {boolean} 当时是否有正在执行的任务
346
+ */
347
+ // #doc:stopcancel
348
+ AuiPage.prototype.stop = function () {
349
+ return this._requestEnd("stopped", "user");
350
+ };
351
+
352
+ /**
353
+ * 取消当前任务:中断底层请求,已产出的部分照常入库并标记 cancelled,
354
+ * task:end 附带 displayed,界面可自行撤销。
355
+ *
356
+ * @returns {boolean} 当时是否有正在执行的任务
357
+ */
358
+ AuiPage.prototype.cancel = function () {
359
+ return this._requestEnd("cancelled", "user");
360
+ };
361
+
362
+ /**
363
+ * 交给工具的任务控制句柄:execute / render 里直接调用 stop() 或 cancel()。
364
+ *
365
+ * @param {object} task 任务句柄
366
+ * @param {object} call 工具调用分片
367
+ */
368
+ AuiPage.prototype._toolControl = function (task, call) {
369
+ const _this = this;
370
+ return {
371
+ taskId: task.taskId,
372
+ toolCallId: call.id,
373
+ stop: function () { return _this._requestEnd("stopped", "tool", task); },
374
+ cancel: function () { return _this._requestEnd("cancelled", "tool", task); }
375
+ };
376
+ };
377
+ // #end
378
+
379
+ /**
380
+ * 处理单个生成器分片。文本类分片按类型累积并通过 streamFun 流式追加,
381
+ * 工具调用分片交给 _handleToolCall。
382
+ *
383
+ * @param {object} task 当前任务句柄
384
+ * @param {{value: object, done: boolean}} chunk 生成器返回项
385
+ */
386
+ // #doc:chunk
387
+ AuiPage.prototype._handleChunk = async function (task, chunk) {
388
+ if (!task || task.ended || task.endRequest) return;
389
+
390
+ const value = (chunk && chunk.value) || {};
391
+ const text = typeof value.text === "string" ? value.text : "";
392
+
393
+ // 类型变了,或者是一种特殊类型
394
+ if (value.type != task.preType || !task.textTypes.includes(value.type)) {
395
+ task.streamFun = void 0;
396
+
397
+ if (task.preText) {
398
+ task.cacheMessages.push({
399
+ role: "assistant",
400
+ content: [{ type: task.preType, text: task.preText }]
401
+ });
402
+ task.preText = "";
403
+ task.preType = "";
404
+ }
405
+
406
+ if (!task.textTypes.includes(value.type)) {
407
+ if (value.type === "tool-call") await this._handleToolCall(task, value);
408
+ } else {
409
+ task.preText = text;
410
+ task.preType = value.type;
411
+ task.streamFun = this._render(task, "assistant", value);
412
+ }
413
+
414
+ } else {
415
+ task.preText += text;
416
+ if (task.streamFun) callSafely(task.streamFun, value.text);
417
+ }
418
+ };
419
+ // #end
420
+
421
+ /**
422
+ * 工具调用分片:pending 时挂上视图并执行前端工具,success/error 时回填后端工具结果。
423
+ *
424
+ * @param {object} task 当前任务句柄
425
+ * @param {object} call 工具调用分片
426
+ */
427
+ // #doc:toolpending
428
+ AuiPage.prototype._handleToolCall = async function (task, call) {
429
+
430
+ // 工具开始调用(前端工具 + 后端工具)
431
+ if (call.status === "pending") {
432
+ const updater = asUpdater(this._render(task, "assistant", call));
433
+ if (updater) task.tool_calls[call.id] = updater;
434
+
435
+ // 后端工具由 ChatTransport 自己执行,这里只挂视图
436
+ if (call.caller !== "frontend") return;
437
+
438
+ // 前端工具需要自己执行;第二个参数是任务控制句柄,工具里可直接 stop / cancel
439
+ const execute = this.tools_execute[call.name];
440
+ const control = this._toolControl(task, call);
441
+ let result, status;
442
+
443
+ if (typeof execute === "function") {
444
+ try {
445
+ result = await execute(call.args, control);
446
+ status = "success";
447
+ } catch (error) {
448
+ result = error;
449
+ status = "error";
450
+ }
451
+ } else {
452
+ result = new Error("未注册的工具:" + call.name);
453
+ status = "error";
454
+ }
455
+
456
+ // 工具执行期间被取消:结果丢弃;被 stop 则继续把这次调用的结果落地
457
+ if (task.ended || isCancelled(task)) return;
458
+
459
+ const render = this.tools_render[call.name];
460
+ // #end
461
+
462
+ // 需要视图交互获取结果
463
+ // #doc:toolrender
464
+ if (typeof render === "function" && updater) {
465
+ const pending = Promise.resolve(updater(Object.assign({}, call, {
466
+ result: result,
467
+ status: status,
468
+ render: render,
469
+ taskId: control.taskId,
470
+ stop: control.stop,
471
+ cancel: control.cancel
472
+ })));
473
+
474
+ // 界面还挂着等交互时被结束:放弃等待,按 execute 的结果收尾
475
+ const outcome = await Promise.race([
476
+ pending.then(function (value) {
477
+ return { value: value };
478
+ }, function (error) {
479
+ return { error: error };
480
+ }),
481
+ task.endRequest
482
+ ? Promise.resolve({ ended: true })
483
+ : task.endSignal.promise.then(function () { return { ended: true }; })
484
+ ]);
485
+
486
+ if (task.ended || isCancelled(task)) return;
487
+
488
+ if (outcome.ended) {
489
+ callSafely(updater, Object.assign({}, call, { result: result, status: status }));
490
+ delete task.tool_calls[call.id];
491
+
492
+ task.cacheMessages.push({
493
+ role: "assistant",
494
+ content: [{
495
+ type: "tool-call",
496
+ name: call.name,
497
+ args: call.args,
498
+ result,
499
+ status
500
+ }]
501
+ });
502
+
503
+ return;
504
+ }
505
+
506
+ let result_ui = outcome.error !== void 0 ? outcome.error : outcome.value;
507
+ let status_ui = outcome.error !== void 0 ? "error" : "success";
508
+
509
+ callSafely(updater, Object.assign({}, call, { result: result_ui, status: status_ui }));
510
+ delete task.tool_calls[call.id];
511
+
512
+ task.cacheMessages.push({
513
+ role: "assistant",
514
+ content: [{
515
+ type: "tool-call",
516
+ name: call.name,
517
+ args: call.args,
518
+ result,
519
+ status,
520
+ ui: { status: status_ui, result: result_ui }
521
+ }]
522
+ });
523
+
524
+ invoke(this.adapter.ChatTransport, "response", null, ["tool-result", {
525
+ id: call.id,
526
+ status: status_ui,
527
+ result: result_ui
528
+ }]);
529
+ }
530
+
531
+ // #end
532
+ // #doc:toolplain
533
+ // 没有可用的视图入口,就当作纯工具调用
534
+ else {
535
+ if (updater) {
536
+ callSafely(updater, Object.assign({}, call, { result, status }));
537
+ delete task.tool_calls[call.id];
538
+ }
539
+
540
+ task.cacheMessages.push({
541
+ role: "assistant",
542
+ content: [{
543
+ type: "tool-call",
544
+ name: call.name,
545
+ args: call.args,
546
+ result,
547
+ status
548
+ }]
549
+ });
550
+
551
+ invoke(this.adapter.ChatTransport, "response", null, ["tool-result", {
552
+ id: call.id,
553
+ result,
554
+ status
555
+ }]);
556
+ }
557
+
558
+ return;
559
+ // #end
560
+ }
561
+
562
+ // 工具调用结束(后端工具)
563
+ // #doc:toolbackend
564
+ if (call.status === "success" || call.status === "error") {
565
+ if (task.tool_calls[call.id]) {
566
+ callSafely(task.tool_calls[call.id], call);
567
+ delete task.tool_calls[call.id];
568
+
569
+ task.cacheMessages.push({
570
+ role: "assistant",
571
+ content: [{
572
+ type: "tool-call",
573
+ name: call.name,
574
+ args: call.args,
575
+ result: call.result,
576
+ status: call.status
577
+ }]
578
+ });
579
+ }
580
+ }
581
+ // #end
582
+ };
583
+
584
+ /**
585
+ * 收尾 sendMessage 任务。统一处理:残留文本归并、入库、isExecuting 复位、
586
+ * 发出 task:end 事件、释放 Promise。
587
+ *
588
+ * @param {"complete"|"stopped"|"error"|"cancelled"} status 任务结束原因
589
+ * @param {boolean} isHistory 是否走入库分支(complete / stopped / cancelled 为 true,error 为 false)
590
+ * @param {Error|string} [err] status === "error" 时附带的错误对象
591
+ * @param {"user"|"tool"} [by] stopped / cancelled 时的发起方
592
+ * @param {object} [taskArg] 指定任务;兜底计时器传入,避免落到下一轮
593
+ */
594
+ // #doc:finishA
595
+ AuiPage.prototype._finalize = async function (status, isHistory, err, by, taskArg) {
596
+ let task = taskArg || this._currentTask;
597
+ if (!task || task.ended) return;
598
+ task.ended = true;
599
+
600
+ // 清理兜底计时器,并释放还在等结束信号的流程
601
+ if (task.stopTimer && typeof clearTimeout === "function") clearTimeout(task.stopTimer);
602
+ task.stopTimer = null;
603
+ callSafely(task.endSignal.resolve);
604
+
605
+ // 1. 残留文本归并到 cacheMessages
606
+ if (task.preText) {
607
+ task.cacheMessages.push({
608
+ role: "assistant",
609
+ content: [{ type: task.preType, text: task.preText }]
610
+ });
611
+ task.preText = "";
612
+ task.preType = "";
613
+ }
614
+
615
+ // 2. 让生成器停止继续产出(此时 next() 已 settle,可安全调用)
616
+ if (typeof task.generator.return === "function") {
617
+ callSafely(function () { return task.generator.return(); });
618
+ }
619
+
620
+ // #end
621
+ // #doc:finishB
622
+ // 3. 入库;失败降级为 error,避免前端误以为消息已保存
623
+ let failure = status === "error" ? err : null;
624
+
625
+ if (isHistory && !failure) {
626
+ try {
627
+ let historyMessages = toHistoryMessages({ messages: task.cacheMessages });
628
+
629
+ // 主动结束与取消也入库,只打标记;存或丢由 MessageHistory.append 自己决定
630
+ if (status === "stopped" || status === "cancelled") historyMessages.status = status;
631
+
632
+ if (this.currentThreadId === void 0) {
633
+ let newThread = await this.adapter.ThreadList?.new?.(historyMessages);
634
+
635
+ if (!newThread) throw new Error("新建会话失败");
636
+
637
+ await Promise.resolve(this.runtime.ThreadList?.append(newThread));
638
+ this.activeThread(newThread.threadId, true);
639
+ }
640
+
641
+ this.currentMessages.push(historyMessages);
642
+ await this.adapter.MessageHistory?.append?.(this.currentThreadId, historyMessages);
643
+ } catch (e) {
644
+ failure = e;
645
+ }
646
+ }
647
+
648
+ // 4. 复位、emit task:end、释放 Promise
649
+ if (this._currentTask === task) {
650
+ this.isExecuting = false;
651
+ this._currentTask = null;
652
+ }
653
+
654
+ const finalStatus = failure ? "error" : status;
655
+
656
+ const payload = {
657
+ taskId: task.taskId,
658
+ threadId: this.currentThreadId,
659
+ message: task.message,
660
+ status: finalStatus
661
+ };
662
+
663
+ // 主动结束 / 取消时说明是谁发起的;取消另附已显示条目,界面据此决定是否撤销
664
+ if (finalStatus === "stopped" || finalStatus === "cancelled") payload.by = by || "user";
665
+ if (finalStatus === "cancelled") payload.displayed = task.displayed;
666
+
667
+ this._emit("task:end", payload);
668
+
669
+ if (finalStatus === "error") task.reject(failure || new Error("任务执行失败"));
670
+ else if (finalStatus === "cancelled") task.reject("已取消");
671
+ else task.resolve();
672
+ };
673
+ // #end
674
+
675
+ // #doc:active
676
+ AuiPage.prototype.activeThread = function (threadId, __noLoad__) {
677
+ if (this.currentThreadId === threadId) return;
678
+
679
+ // 已经有执行的,不允许切换
680
+ if (this.isExecuting && !__noLoad__) return;
681
+
682
+ this.currentThreadId = threadId;
683
+ this.runtime.ThreadList?.active(threadId);
684
+
685
+ if (threadId === void 0) {
686
+ this.currentMessages = [];
687
+ this.runtime.ChatContent?.init([]);
688
+ return;
689
+ }
690
+
691
+ if (__noLoad__) return;
692
+
693
+ // 加载历史消息
694
+ invoke(this.adapter.MessageHistory, "load", (messages) => {
695
+ this.currentMessages = messages;
696
+
697
+ let plainMessages = [];
698
+ messages.forEach(item => {
699
+ plainMessages.push(...item.messages);
700
+ });
701
+ this.runtime.ChatContent?.init(plainMessages);
702
+ }, [threadId]);
703
+ };
704
+ // #end
705
+
706
+ // #doc:threads
707
+ AuiPage.prototype.deleteThread = function (threadId) {
708
+ invoke(this.adapter.ThreadList, "delete", () => {
709
+ this.runtime.ThreadList?.delete(threadId);
710
+
711
+ if (threadId === this.currentThreadId) this.newThread();
712
+ }, [threadId]);
713
+ };
714
+
715
+ AuiPage.prototype.archiveThread = function (threadId) {
716
+ invoke(this.adapter.ThreadList, "archive", () => {
717
+ this.runtime.ThreadList?.archive(threadId);
718
+
719
+ if (threadId === this.currentThreadId) this.newThread();
720
+ }, [threadId]);
721
+ };
722
+
723
+ AuiPage.prototype.unarchiveThread = function (threadId) {
724
+ invoke(this.adapter.ThreadList, "unarchive", () => {
725
+ this.runtime.ThreadList?.unarchive(threadId);
726
+ }, [threadId]);
727
+ };
728
+
729
+ // #end
730
+ // #doc:newthread
731
+ AuiPage.prototype.newThread = function () {
732
+ this.activeThread(void 0);
733
+ };
734
+ // #end
735
+
736
+ export default AuiPage;