@auipage/core 0.1.0-alpha.1 → 0.1.0-alpha.3

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/CHANGELOG CHANGED
@@ -2,8 +2,3 @@ v0.1.0:
2
2
  date:
3
3
  changes:
4
4
  - 初始化版本
5
- 1、@auipage/types 提供类型定义
6
- 2、@auipage/core 提供核心功能
7
- 3、@auipage/model 提供模型相关功能
8
- 4、@auipage/agent 提供智能体相关功能
9
- 5、@auipage/fetch 提供数据获取相关功能
package/README.md CHANGED
@@ -41,7 +41,7 @@ npm install --save @auipage/core
41
41
  ## 文档
42
42
 
43
43
  - [快速上手](./docs/quick-start.md):完整可运行示例与整体流程
44
- - [AuiPage](./docs/auipage.md):构造参数、实例属性与方法、消息结构
44
+ - [AuiPage](./docs/auipage.md):构造参数、实例属性与方法、消息结构、任务生命周期事件
45
45
  - [Adapter](./docs/adapters.md):三个适配器的接口与实现示例
46
46
  - [Runtime](./docs/runtimes.md):两个运行时的渲染钩子约定
47
47
  - [defineTool](./docs/define-tool.md):前端工具定义
@@ -0,0 +1 @@
1
+ export * from '../types/index.d.ts'
package/dist/index.js ADDED
@@ -0,0 +1,631 @@
1
+ /*! @auipage/core v0.1.0-alpha.3 */
2
+ (function (global, factory) {
3
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) :
4
+ typeof define === 'function' && define.amd ? define(['exports'], factory) :
5
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.auipage_core = {}));
6
+ })(this, (function (exports) { 'use strict';
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
+
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
+ };
448
+
449
+ function initOption(setOption, defaultOption) {
450
+ for (const key in setOption) {
451
+ defaultOption[key] = setOption[key];
452
+ }
453
+
454
+ return defaultOption;
455
+ }
456
+
457
+ let EmptyFunction = () => void 0;
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
+ }
471
+ }
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
+ }
485
+ }
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
+ }
502
+ }
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
+ }
520
+ }
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
+ }
534
+ }
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
+ };
549
+ }
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
+ }
614
+ }
615
+
616
+ function MessageStream(send, end) {
617
+ this.send = send || EmptyFunction;
618
+ this.end = end || EmptyFunction;
619
+ }
620
+
621
+ exports.AuiPage = AuiPage;
622
+ exports.ChatContentRuntime = ChatContentRuntime;
623
+ exports.ChatTransportAdapter = ChatTransportAdapter;
624
+ exports.MessageHistoryAdapter = MessageHistoryAdapter;
625
+ exports.MessageStream = MessageStream;
626
+ exports.ThreadListAdapter = ThreadListAdapter;
627
+ exports.ThreadListRuntime = ThreadListRuntime;
628
+ exports.defineTool = defineTool;
629
+ exports.generator = generator;
630
+
631
+ }));
@@ -0,0 +1,3 @@
1
+ {
2
+ "type": "commonjs"
3
+ }
package/package.json CHANGED
@@ -1,14 +1,14 @@
1
1
  {
2
2
  "name": "@auipage/core",
3
- "version": "0.1.0-alpha.1",
3
+ "version": "0.1.0-alpha.3",
4
4
  "description": "@auipage/core",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
7
7
  "typings": "types/index.d.ts",
8
8
  "sideEffects": false,
9
9
  "scripts": {
10
- "prepublishOnly": "node ../../swap-pkg.js --mode=publish",
11
- "postpublish": "node ../../swap-pkg.js --mode=restore"
10
+ "prepublishOnly": "node ../../scripts/swap-pkg.js --mode=publish",
11
+ "postpublish": "node ../../scripts/swap-pkg.js --mode=restore"
12
12
  },
13
13
  "repository": {
14
14
  "type": "git",
@@ -30,7 +30,7 @@
30
30
  },
31
31
  "homepage": "https://github.com/handless-ui/auipage#readme",
32
32
  "dependencies": {
33
- "@auipage/types": "^0.1.0-alpha.1",
33
+ "@auipage/types": "^0.1.0-alpha.3",
34
34
  "oipage": "^2.1.0"
35
35
  }
36
36
  }
package/src/AuiPage.js CHANGED
@@ -33,6 +33,15 @@ function AuiPage(options) {
33
33
  // 当前会话内容
34
34
  this.currentMessages = [];
35
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
+
36
45
  // 请求对话列表
37
46
  this.adapter.ThreadList.list()?.then((threads) => {
38
47
 
@@ -42,6 +51,32 @@ function AuiPage(options) {
42
51
 
43
52
  }
44
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
+
45
80
  AuiPage.prototype.sendMessage = function (message) {
46
81
  let _this = this;
47
82
 
@@ -64,17 +99,48 @@ AuiPage.prototype.sendMessage = function (message) {
64
99
  return;
65
100
  }
66
101
 
67
- let cacheMessages = [message]; // 缓存消息,用于生成历史消息
68
-
69
- let preType = "", preText = ""; // 上一个消息的类型和文本
70
- let textTypes = ["loading", "thinking", "text"]; // 非特殊类型
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
+ });
71
125
 
72
- let streamFun, tool_calls = {};
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;
73
132
 
74
133
  for (let i = 0; i < message.content.length; i++) {
75
134
  this.runtime.ChatContent.append(message.role, message.content[i]);
76
135
  }
77
136
 
137
+ // 同步写入 _currentTask 的小工具
138
+ let sync = function () {
139
+ _this._currentTask.preType = preType;
140
+ _this._currentTask.preText = preText;
141
+ _this._currentTask.streamFun = streamFun;
142
+ };
143
+
78
144
  (function doit() {
79
145
  generator?.next().then(async function (res) {
80
146
  if (!res.done) {
@@ -224,50 +290,86 @@ AuiPage.prototype.sendMessage = function (message) {
224
290
  if (streamFun) streamFun(res.value.text);
225
291
  }
226
292
 
293
+ sync();
227
294
  doit();
228
295
  } else {
229
- if (preText) {
230
- cacheMessages.push({
231
- role: "assistant",
232
- content: [{
233
- type: preType,
234
- text: preText
235
- }]
236
- });
237
- preText = "";
238
- preType = "";
239
- }
296
+ sync();
297
+ _this._finalize("complete", true);
298
+ }
299
+ }, err => {
300
+ _this._finalize("error", false, err);
301
+ });
302
+ })();
240
303
 
241
- // 把准备入库的消息转换为历史消息
242
- let historyMessages = toHistoryMessages({ messages: cacheMessages });
304
+ });
305
+ };
243
306
 
244
- // 判断一下currentThreadId是否有值,如果没有,需要新建新的会话
245
- if (_this.currentThreadId === void 0) {
246
- let newThread = await _this.adapter.ThreadList.new(historyMessages);
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
+ }
247
331
 
248
- if (!newThread) {
249
- reject(new Error("新建会话失败"));
250
- _this.isExecuting = false;
251
- return;
252
- }
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
+ }
253
348
 
254
- await _this.runtime.ThreadList.append(newThread);
255
- _this.activeThread(newThread.threadId, true);
256
- }
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
+ }
257
364
 
258
- _this.currentMessages.push(historyMessages);
259
- _this.adapter.MessageHistory.append(_this.currentThreadId, historyMessages);
365
+ // 4. 复位、emit task:end、释放 Promise
366
+ this.isExecuting = false;
367
+ this._currentTask = null;
260
368
 
261
- _this.isExecuting = false;
262
- resolve();
263
- }
264
- }, err => {
265
- _this.isExecuting = false;
266
- reject(err);
267
- });
268
- })();
369
+ this._emit("task:end", { taskId, threadId: this.currentThreadId, message, status });
269
370
 
270
- });
371
+ if (status === "error") reject(err);
372
+ else resolve();
271
373
  };
272
374
 
273
375
  AuiPage.prototype.activeThread = function (threadId, __noLoad__) {
@@ -34,6 +34,31 @@ export interface AuiPageOptions {
34
34
  tools?: Tool[];
35
35
  }
36
36
 
37
+ /** 任务生命周期事件名 */
38
+ export type AuiLifecycleEvent = "task:start" | "task:end";
39
+
40
+ /** 任务结束状态 */
41
+ export type AuiTaskStatus = "complete" | "error";
42
+
43
+ /** task:start 回调载荷 */
44
+ export interface TaskLifecyclePayload {
45
+ /** 本次 sendMessage 自增生成的唯一任务 id */
46
+ taskId: string;
47
+ /** 任务发起时所处的会话 ID;新建会话场景下为 undefined */
48
+ threadId: string | undefined;
49
+ /** 本次发送的原始页面消息 */
50
+ message: ChatContentMessage;
51
+ }
52
+
53
+ /** task:end 回调载荷;在 TaskLifecyclePayload 基础上附带 status */
54
+ export interface TaskEndPayload extends TaskLifecyclePayload {
55
+ status: AuiTaskStatus;
56
+ }
57
+
58
+ /** 生命周期事件 handler 签名 */
59
+ export type TaskStartHandler = (payload: TaskLifecyclePayload) => void;
60
+ export type TaskEndHandler = (payload: TaskEndPayload) => void;
61
+
37
62
  export declare class AuiPage {
38
63
  constructor(options: AuiPageOptions);
39
64
 
@@ -58,10 +83,21 @@ export declare class AuiPage {
58
83
 
59
84
  /**
60
85
  * 发送一条消息并驱动完整的流式对话流程;
61
- * 上一轮执行中时以 "当前正在执行中" reject,全部完成(含落库)后 resolve。
86
+ * 上一轮执行中时以 "当前正在执行中" reject,全部完成(含落库)后 resolve;
87
+ * 流式过程出错时以原始 error reject(同时触发 task:end { status: "error" })。
62
88
  */
63
89
  sendMessage(message: ChatContentMessage): Promise<void>;
64
90
 
91
+ /**
92
+ * 订阅任务生命周期事件。同名事件可注册多个 handler,触发时按注册顺序串行调用,
93
+ * handler 内部抛错被吞掉,不会影响 sendMessage 主流程。链式返回 AuiPage。
94
+ */
95
+ on(event: "task:start", handler: TaskStartHandler): this;
96
+ on(event: "task:end", handler: TaskEndHandler): this;
97
+
98
+ /** 取消事件订阅;handler 未注册过则 no-op。链式返回 AuiPage */
99
+ off(event: AuiLifecycleEvent, handler: Function): this;
100
+
65
101
  /**
66
102
  * 切换到指定会话;threadId 为 undefined 表示进入新建会话状态。
67
103
  * 对话执行中调用会被忽略(noLoad 内部调用除外)。
package/types/index.d.ts CHANGED
@@ -11,7 +11,13 @@ export {
11
11
  AuiPage,
12
12
  type AuiPageOptions,
13
13
  type AuiPageAdapterSet,
14
- type AuiPageRuntimeSet
14
+ type AuiPageRuntimeSet,
15
+ type AuiLifecycleEvent,
16
+ type AuiTaskStatus,
17
+ type TaskLifecyclePayload,
18
+ type TaskEndPayload,
19
+ type TaskStartHandler,
20
+ type TaskEndHandler
15
21
  } from "./auipage.js";
16
22
 
17
23
  /* ---------- 适配器 ---------- */