@auipage/core 0.1.0-alpha.5 → 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,19 +1,21 @@
1
- /*! @auipage/core v0.1.0-alpha.5 */
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
+ // #doc:merge
8
9
  function toHistoryMessages (value) {
9
10
 
10
11
  let messages = [], index = -1;
11
- for (let message of value.messages) {
12
+ for (let message of value.messages || []) {
12
13
 
13
14
  if (index != -1 && messages[index].role === message.role) {
15
+ // 复制内容数组,避免改写入参消息对象
14
16
  messages[index].content.push(...message.content);
15
17
  } else {
16
- messages.push(message);
18
+ messages.push(Object.assign({}, message, { content: (message.content || []).slice() }));
17
19
  index = messages.length - 1;
18
20
  }
19
21
  }
@@ -21,20 +23,84 @@
21
23
  value.messages = messages;
22
24
  return value;
23
25
  }
26
+ // #end
27
+
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
+ }
24
96
 
97
+ // #doc:ctor
25
98
  function AuiPage(options) {
99
+ options = options || {};
26
100
 
27
101
  // 连接适配器和运行时视图
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
- }
102
+ this.adapter = mount(this, options.adapter, "Adapter");
103
+ this.runtime = mount(this, options.runtime, "Runtime");
38
104
 
39
105
  // 工具注册
40
106
  this.tools_execute = {};
@@ -64,16 +130,18 @@
64
130
  // 当前正在执行的任务句柄(sendMessage 进入执行期时写入)
65
131
  this._currentTask = null;
66
132
 
67
- // 请求对话列表
68
- this.adapter.ThreadList.list()?.then((threads) => {
133
+ // 取消时等待 next 落定的兜底时长
134
+ this._stopTimeout = options.stopTimeout > 0 ? options.stopTimeout : DEFAULT_STOP_TIMEOUT;
69
135
 
70
- // 在页面中显示对话列表
71
- this.runtime.ThreadList.init(threads);
136
+ // 请求对话列表
137
+ invoke(this.adapter.ThreadList, "list", (threads) => {
138
+ this.runtime.ThreadList?.init(threads);
72
139
  });
73
-
74
140
  }
141
+ // #end
75
142
 
76
143
  // 触发生命周期事件;handler 抛错被吞掉,避免影响 sendMessage 主流程
144
+ // #doc:events
77
145
  AuiPage.prototype._emit = function (event, payload) {
78
146
  let handlers = this._events[event];
79
147
  if (!handlers) return;
@@ -98,36 +166,74 @@
98
166
  if (idx >= 0) list.splice(idx, 1);
99
167
  return this;
100
168
  };
169
+ // #end
101
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
102
183
  AuiPage.prototype.sendMessage = function (message) {
103
184
  let _this = this;
104
185
 
105
186
  return new Promise((resolve, reject) => {
106
187
 
107
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
+
108
196
  this.isExecuting = true;
109
197
 
110
- let generator = this.adapter.ChatTransport.run({
111
- messages: [message],
112
- context: {
113
- history: this.currentMessages,
114
- tools: this.tools_description
115
- }
116
- });
198
+ // 取消通道:signal 交给适配器,由它透传到底层 HTTP / 模型请求
199
+ const controller = typeof AbortController === "function" ? new AbortController() : null;
117
200
 
118
- if (!generator) {
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") {
119
219
  this.isExecuting = false;
120
220
  reject("ChatTransport.run() 返回空值");
121
221
  return;
122
222
  }
123
223
 
224
+ // 结束信号:工具或界面里发起 stop / cancel 时唤醒等待中的流程
225
+ let signalEnd;
226
+ const endSignal = new Promise(function (resolve) { signalEnd = resolve; });
227
+
124
228
  // 写入任务上下文,供后续协同使用
125
229
  let taskId = String(++this._taskSeq);
126
- this._currentTask = {
230
+ const task = this._currentTask = {
127
231
  taskId,
128
- message,
232
+ message: input,
129
233
  generator,
130
- cacheMessages: [message],
234
+ controller,
235
+ cacheMessages: [input],
236
+ displayed: [],
131
237
  preType: "",
132
238
  preText: "",
133
239
  textTypes: ["loading", "thinking", "text"],
@@ -135,263 +241,463 @@
135
241
  tool_calls: {},
136
242
  resolve,
137
243
  reject,
138
- ended: false
244
+ ended: false,
245
+ endRequest: null,
246
+ endSignal: { promise: endSignal, resolve: signalEnd },
247
+ busy: false,
248
+ nextPending: false
139
249
  };
140
250
 
141
251
  // 任务开始生命周期
142
252
  this._emit("task:start", {
143
253
  taskId,
144
254
  threadId: this.currentThreadId,
145
- message
255
+ message: input
146
256
  });
147
257
 
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]);
258
+ // 回显用户消息
259
+ for (let i = 0; i < content.length; i++) {
260
+ this._render(task, input.role, content[i]);
157
261
  }
262
+ // #end
158
263
 
159
- // 同步写入 _currentTask 的小工具
160
- let sync = function () {
161
- _this._currentTask.preType = preType;
162
- _this._currentTask.preText = preText;
163
- _this._currentTask.streamFun = streamFun;
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);
164
269
  };
165
270
 
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();
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) {
317
293
  _this._finalize("complete", true);
294
+ return;
318
295
  }
319
- }, err => {
320
- _this._finalize("error", false, err);
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);
321
316
  });
322
- })();
317
+ };
318
+
319
+ pump();
323
320
 
324
321
  });
325
322
  };
326
323
 
327
324
  /**
328
- * 收尾当前 sendMessage 任务。统一处理:残留文本归并、是否入库、isExecuting 复位、
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 复位、
329
611
  * 发出 task:end 事件、释放 Promise。
330
612
  *
331
- * @param {"complete"|"error"} status 任务结束原因
332
- * @param {boolean} isHistory 是否走入库分支(complete 始终 true;error 始终 false)
613
+ * @param {"complete"|"stopped"|"error"|"cancelled"} status 任务结束原因
614
+ * @param {boolean} isHistory 是否走入库分支(complete / stopped / cancelled 为 true,error 为 false)
333
615
  * @param {Error|string} [err] status === "error" 时附带的错误对象
616
+ * @param {"user"|"tool"} [by] stopped / cancelled 时的发起方
617
+ * @param {object} [taskArg] 指定任务;兜底计时器传入,避免落到下一轮
334
618
  */
335
- AuiPage.prototype._finalize = async function (status, isHistory, err) {
336
- let task = this._currentTask;
619
+ // #doc:finishA
620
+ AuiPage.prototype._finalize = async function (status, isHistory, err, by, taskArg) {
621
+ let task = taskArg || this._currentTask;
337
622
  if (!task || task.ended) return;
338
623
  task.ended = true;
339
624
 
340
- let { taskId, message, cacheMessages, preType, preText, resolve, reject } = task;
625
+ // 清理兜底计时器,并释放还在等结束信号的流程
626
+ if (task.stopTimer && typeof clearTimeout === "function") clearTimeout(task.stopTimer);
627
+ task.stopTimer = null;
628
+ callSafely(task.endSignal.resolve);
341
629
 
342
630
  // 1. 残留文本归并到 cacheMessages
343
- if (preText) {
344
- cacheMessages.push({
631
+ if (task.preText) {
632
+ task.cacheMessages.push({
345
633
  role: "assistant",
346
- content: [{ type: preType, text: preText }]
634
+ content: [{ type: task.preType, text: task.preText }]
347
635
  });
348
636
  task.preText = "";
349
637
  task.preType = "";
350
638
  }
351
639
 
352
- // 2. 入库分支
353
- if (isHistory) {
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) {
354
651
  try {
355
- let historyMessages = toHistoryMessages({ messages: cacheMessages });
652
+ let historyMessages = toHistoryMessages({ messages: task.cacheMessages });
653
+
654
+ // 主动结束与取消也入库,只打标记;存或丢由 MessageHistory.append 自己决定
655
+ if (status === "stopped" || status === "cancelled") historyMessages.status = status;
356
656
 
357
657
  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
- }
658
+ let newThread = await this.adapter.ThreadList?.new?.(historyMessages);
368
659
 
369
- await this.runtime.ThreadList.append(newThread);
660
+ if (!newThread) throw new Error("新建会话失败");
661
+
662
+ await Promise.resolve(this.runtime.ThreadList?.append(newThread));
370
663
  this.activeThread(newThread.threadId, true);
371
664
  }
372
665
 
373
666
  this.currentMessages.push(historyMessages);
374
- this.adapter.MessageHistory.append(this.currentThreadId, historyMessages);
667
+ await this.adapter.MessageHistory?.append?.(this.currentThreadId, historyMessages);
375
668
  } 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;
669
+ failure = e;
382
670
  }
383
671
  }
384
672
 
385
673
  // 4. 复位、emit task:end、释放 Promise
386
- this.isExecuting = false;
387
- this._currentTask = null;
674
+ if (this._currentTask === task) {
675
+ this.isExecuting = false;
676
+ this._currentTask = null;
677
+ }
388
678
 
389
- this._emit("task:end", { taskId, threadId: this.currentThreadId, message, status });
679
+ const finalStatus = failure ? "error" : status;
390
680
 
391
- if (status === "error") reject(err);
392
- else resolve();
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();
393
697
  };
698
+ // #end
394
699
 
700
+ // #doc:active
395
701
  AuiPage.prototype.activeThread = function (threadId, __noLoad__) {
396
702
  if (this.currentThreadId === threadId) return;
397
703
 
@@ -399,49 +705,54 @@
399
705
  if (this.isExecuting && !__noLoad__) return;
400
706
 
401
707
  this.currentThreadId = threadId;
402
- this.runtime.ThreadList.active(threadId);
708
+ this.runtime.ThreadList?.active(threadId);
403
709
 
404
710
  if (threadId === void 0) {
405
711
  this.currentMessages = [];
406
- this.runtime.ChatContent.init([]);
407
- } else if (!__noLoad__) {
712
+ this.runtime.ChatContent?.init([]);
713
+ return;
714
+ }
408
715
 
409
- // 加载历史消息
410
- this.adapter.MessageHistory.load(threadId)?.then(messages => {
411
- this.currentMessages = messages;
716
+ if (__noLoad__) return;
412
717
 
413
- let plainMessages = [];
414
- messages.forEach(item => {
415
- plainMessages.push(...item.messages);
416
- });
417
- this.runtime.ChatContent.init(plainMessages);
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);
418
725
  });
419
- }
726
+ this.runtime.ChatContent?.init(plainMessages);
727
+ }, [threadId]);
420
728
  };
729
+ // #end
421
730
 
731
+ // #doc:threads
422
732
  AuiPage.prototype.deleteThread = function (threadId) {
423
- this.adapter.ThreadList.delete(threadId)?.then(() => {
424
- this.runtime.ThreadList.delete(threadId);
733
+ invoke(this.adapter.ThreadList, "delete", () => {
734
+ this.runtime.ThreadList?.delete(threadId);
425
735
 
426
736
  if (threadId === this.currentThreadId) this.newThread();
427
- });
428
-
737
+ }, [threadId]);
429
738
  };
430
739
 
431
740
  AuiPage.prototype.archiveThread = function (threadId) {
432
- this.adapter.ThreadList.archive(threadId)?.then(() => {
433
- this.runtime.ThreadList.archive(threadId);
741
+ invoke(this.adapter.ThreadList, "archive", () => {
742
+ this.runtime.ThreadList?.archive(threadId);
434
743
 
435
744
  if (threadId === this.currentThreadId) this.newThread();
436
- });
745
+ }, [threadId]);
437
746
  };
438
747
 
439
748
  AuiPage.prototype.unarchiveThread = function (threadId) {
440
- this.adapter.ThreadList.unarchive(threadId).then(() => {
441
- this.runtime.ThreadList.unarchive(threadId);
442
- });
749
+ invoke(this.adapter.ThreadList, "unarchive", () => {
750
+ this.runtime.ThreadList?.unarchive(threadId);
751
+ }, [threadId]);
443
752
  };
444
753
 
754
+ // #end
755
+ // #doc:newthread
445
756
  AuiPage.prototype.newThread = function () {
446
757
  this.activeThread(void 0);
447
758
  };
@@ -456,18 +767,23 @@
456
767
 
457
768
  let EmptyFunction = () => void 0;
458
769
 
770
+ // #doc:ctor
459
771
  const DEFAUTL_OPTIONS$4 = {
460
772
  run: EmptyFunction,
461
773
  response: EmptyFunction,
462
774
  };
463
775
 
776
+ // #end
777
+
464
778
  function ChatTransportAdapter(options) {
465
779
  this.name="ChatTransportAdapter";
466
780
 
781
+ // #doc:merge
467
782
  let value = initOption(options, { ...DEFAUTL_OPTIONS$4 });
468
783
  for (let key in DEFAUTL_OPTIONS$4) {
469
784
  this[key] = value[key];
470
785
  }
786
+ // #end
471
787
  }
472
788
 
473
789
  const DEFAUTL_OPTIONS$3 = {
@@ -484,6 +800,7 @@
484
800
  }
485
801
  }
486
802
 
803
+ // #doc:methods
487
804
  const DEFAUTL_OPTIONS$2 = {
488
805
  list: EmptyFunction,
489
806
  new: EmptyFunction,
@@ -491,6 +808,7 @@
491
808
  unarchive: EmptyFunction,
492
809
  delete: EmptyFunction
493
810
  };
811
+ // #end
494
812
 
495
813
  function ThreadListAdapter(options) {
496
814
  this.name="ThreadListAdapter";
@@ -519,11 +837,14 @@
519
837
  }
520
838
  }
521
839
 
840
+ // #doc:ctor
522
841
  const DEFAUTL_OPTIONS = {
523
842
  init: EmptyFunction,
524
843
  append: EmptyFunction,
525
844
  };
526
845
 
846
+ // #end
847
+
527
848
  function ChatContentRuntime(options) {
528
849
  this.name="ChatContentRuntime";
529
850
 
@@ -533,6 +854,7 @@
533
854
  }
534
855
  }
535
856
 
857
+ // #doc:shape
536
858
  function defineTool (options) {
537
859
  return {
538
860
  description: {
@@ -546,6 +868,7 @@
546
868
  execute: options.execute,
547
869
  render: options.render
548
870
  };
871
+ // #end
549
872
  }
550
873
 
551
874
  async function* generator (rawFun) {
@@ -558,16 +881,24 @@
558
881
  let ended = false;
559
882
  // 生产者是否已报错;一旦设置,后续 next/done 调用被忽略
560
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
+ };
561
893
 
562
894
  // 启动生产者,三个回调驱动数据流
563
895
  rawFun(
564
896
  // next:推送下一个值
565
897
  (value) => {
566
- if (errored) return;
898
+ if (errored || cancelled) return;
567
899
  if (pending) {
568
900
  // 有等待中的消费者,立刻交值
569
- pending.resolve({ value, done: false });
570
- pending = null;
901
+ resolvePending({ value, done: false });
571
902
  } else {
572
903
  // 否则入队缓存
573
904
  queue.push(value);
@@ -575,49 +906,146 @@
575
906
  },
576
907
  // done:结束
577
908
  () => {
578
- if (errored) return;
909
+ if (errored || cancelled) return;
579
910
  ended = true;
580
- if (pending) {
581
- pending.resolve({ value: void 0, done: true });
582
- pending = null;
583
- }
911
+ resolvePending({ value: void 0, done: true });
584
912
  },
585
913
  // error:异常
586
914
  (err) => {
915
+ if (cancelled) return;
587
916
  errored = err;
588
917
  if (pending) {
589
- pending.reject(err);
918
+ const p = pending;
590
919
  pending = null;
920
+ p.reject(err);
591
921
  }
592
922
  }
593
923
  );
594
924
 
595
- // 消费者主循环
596
- while (true) {
597
- if (errored) throw errored;
598
- // 优先消费缓冲
599
- if (queue.length) {
600
- yield queue.shift();
601
- continue;
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;
602
944
  }
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;
945
+ } finally {
946
+ // 消费者提前退出:停止接收,释放缓冲与挂起的控制器
947
+ cancelled = true;
948
+ queue.length = 0;
949
+ resolvePending({ value: void 0, done: true });
613
950
  }
614
951
  }
615
952
 
953
+ // #doc:ctor
616
954
  function MessageStream(send, end) {
617
955
  this.send = send || EmptyFunction;
618
956
  this.end = end || EmptyFunction;
619
957
  }
620
958
 
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;
1047
+ }
1048
+
621
1049
  exports.AuiPage = AuiPage;
622
1050
  exports.ChatContentRuntime = ChatContentRuntime;
623
1051
  exports.ChatTransportAdapter = ChatTransportAdapter;
@@ -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
  }));