@auipage/core 0.1.0-alpha.0 → 0.1.0-alpha.2

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
@@ -1,4 +1,4 @@
1
1
  v0.1.0:
2
2
  date:
3
3
  changes:
4
- - 初始化版本
4
+ - 初始化版本
package/README.md CHANGED
@@ -1,5 +1,6 @@
1
1
  # [@auipage/core](https://github.com/handless-ui/auipage/packages/core/README.md)
2
- 智能体快速开发框架,用于快速开发智能体网页应用。
2
+
3
+ auipage 的核心层:业务侧实现 Adapter 对接模型与存储,UI 侧实现 Runtime 负责渲染,`AuiPage` 把两者串起来,统一处理会话列表、消息历史、流式对话和历史入库。不耦合任何模型服务与 UI 框架。
3
4
 
4
5
  <p>
5
6
  <a href="https://zxl20070701.github.io/toolbox/#/npm-download?packages=@auipage/core&interval=7">
@@ -15,13 +16,36 @@
15
16
 
16
17
  <img src="https://nodei.co/npm/@auipage/core.png?downloads=true&amp;downloadRank=true&amp;stars=true" alt="NPM">
17
18
 
18
- ## 如何使用?
19
+ ## 安装
19
20
 
20
21
  ```
21
22
  npm install --save @auipage/core
22
23
  ```
23
24
 
24
- 安装后,即可在项目中使用。
25
+ 通常配合 `@auipage/agent`(对话循环)、`@auipage/model`(模型请求)一起使用。
26
+
27
+ ## 导出
28
+
29
+ | 导出名 | 类型 | 作用 |
30
+ | --- | --- | --- |
31
+ | `AuiPage` | 构造器 | 框架核心,管理 adapter / runtime、消息与会话状态 |
32
+ | `ChatTransportAdapter` | 适配器基类 | 对接模型对话接口,流式产出消息片段 |
33
+ | `MessageHistoryAdapter` | 适配器基类 | 历史消息的加载与追加 |
34
+ | `ThreadListAdapter` | 适配器基类 | 会话列表的增删改查 |
35
+ | `ThreadListRuntime` | 运行时基类 | 会话列表的 UI 渲染钩子 |
36
+ | `ChatContentRuntime` | 运行时基类 | 对话内容的 UI 渲染钩子 |
37
+ | `defineTool` | 函数 | 定义前端工具(`description` / `execute` / `render`) |
38
+ | `generator` | 函数 | 把回调式异步流转成 `AsyncGenerator` |
39
+ | `MessageStream` | 构造器 | 消息流封装(`send` / `end`),服务端配合 `CreateTool` 推送 SSE |
40
+
41
+ ## 文档
42
+
43
+ - [快速上手](./docs/quick-start.md):完整可运行示例与整体流程
44
+ - [AuiPage](./docs/auipage.md):构造参数、实例属性与方法、消息结构、任务生命周期事件
45
+ - [Adapter](./docs/adapters.md):三个适配器的接口与实现示例
46
+ - [Runtime](./docs/runtimes.md):两个运行时的渲染钩子约定
47
+ - [defineTool](./docs/define-tool.md):前端工具定义
48
+ - [generator](./docs/generator.md):回调式流到 `AsyncGenerator` 的转换
25
49
 
26
50
  ## 版权
27
51
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@auipage/core",
3
- "version": "0.1.0-alpha.0",
3
+ "version": "0.1.0-alpha.2",
4
4
  "description": "@auipage/core",
5
5
  "type": "module",
6
6
  "main": "./src/index.js",
@@ -15,6 +15,11 @@
15
15
  "url": "git+https://github.com/handless-ui/auipage.git",
16
16
  "directory": "packages/core"
17
17
  },
18
+ "keywords": [
19
+ "ui",
20
+ "page",
21
+ "agent"
22
+ ],
18
23
  "author": {
19
24
  "name": "zxl20070701",
20
25
  "url": "https://zxl20070701.github.io/notebook/home.html"
@@ -25,7 +30,7 @@
25
30
  },
26
31
  "homepage": "https://github.com/handless-ui/auipage#readme",
27
32
  "dependencies": {
28
- "@auipage/types": "^0.1.0-alpha.0",
33
+ "@auipage/types": "^0.1.0-alpha.2",
29
34
  "oipage": "^2.1.0"
30
35
  }
31
36
  }
package/src/AuiPage.js CHANGED
@@ -1,71 +1,425 @@
1
+ import toHistoryMessages from "./tools/toHistoryMessages.js";
2
+
1
3
  function AuiPage(options) {
2
4
 
5
+ // 连接适配器和运行时视图
6
+ this.adapter = {};
7
+ this.runtime = {};
3
8
  for (let instance of Object.values(options.adapter)) {
4
9
  instance.aui = this;
5
- this.adapter[instance.constructor.name.replace("Adapter", "")] = instance;
10
+ this.adapter[instance.name.replace("Adapter", "")] = instance;
6
11
  }
7
12
  for (let instance of Object.values(options.runtime)) {
8
13
  instance.aui = this;
9
- this.runtime[instance.constructor.name.replace("Runtime", "")] = instance;
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 });
10
25
  }
11
26
 
27
+ // 当前是否在执行中
28
+ this.isExecuting = false;
29
+
12
30
  // 当前激活的会话ID
13
31
  this.currentThreadId = void 0;
14
32
 
15
33
  // 当前会话内容
16
34
  this.currentMessages = [];
17
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
+
18
45
  // 请求对话列表
19
- this.adapter.ThreadList.list().then((threads) => {
46
+ this.adapter.ThreadList.list()?.then((threads) => {
20
47
 
21
48
  // 在页面中显示对话列表
22
49
  this.runtime.ThreadList.init(threads);
23
-
24
50
  });
25
51
 
26
52
  }
27
53
 
28
- AuiPage.prototype.adapter = {};
29
- AuiPage.prototype.runtime = {};
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
+ };
30
79
 
31
80
  AuiPage.prototype.sendMessage = function (message) {
32
- this.currentMessages.push(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;
33
132
 
34
- let generator = this.adapter.ChatTransport.run({
35
- messages: this.currentMessages,
36
- context: {
37
- tools: []
133
+ for (let i = 0; i < message.content.length; i++) {
134
+ this.runtime.ChatContent.append(message.role, message.content[i]);
38
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
+
39
304
  });
305
+ };
40
306
 
41
- (function doit() {
42
- generator.next().then(res => {
43
- if (!res.done) {
44
-
45
- console.log(res.value);
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;
46
319
 
47
- doit();
48
- }
49
- }, err => {
50
- console.error(err);
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 }]
51
327
  });
52
- })();
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
+ }
53
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();
54
373
  };
55
374
 
56
- AuiPage.prototype.activeThread = function (threadId) {
375
+ AuiPage.prototype.activeThread = function (threadId, __noLoad__) {
57
376
  if (this.currentThreadId === threadId) return;
58
377
 
378
+ // 已经有执行的,不允许切换
379
+ if (this.isExecuting && !__noLoad__) return;
380
+
59
381
  this.currentThreadId = threadId;
60
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
+ }
61
400
  };
62
401
 
63
402
  AuiPage.prototype.deleteThread = function (threadId) {
64
- this.runtime.ThreadList.delete(threadId);
403
+ this.adapter.ThreadList.delete(threadId)?.then(() => {
404
+ this.runtime.ThreadList.delete(threadId);
405
+
406
+ if (threadId === this.currentThreadId) this.newThread();
407
+ });
408
+
65
409
  };
66
410
 
67
411
  AuiPage.prototype.archiveThread = function (threadId) {
68
- this.runtime.ThreadList.archive(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
+ });
69
423
  };
70
424
 
71
425
  AuiPage.prototype.newThread = function () {
@@ -1,10 +1,14 @@
1
1
  import { initOption } from "oipage/web/option/index.js";
2
+ import { EmptyFunction } from "./tools/enum.js";
2
3
 
3
4
  const DEFAUTL_OPTIONS = {
4
- init: void 0,
5
+ init: EmptyFunction,
6
+ append: EmptyFunction,
5
7
  };
6
8
 
7
9
  function ChatContentRuntime(options) {
10
+ this.name="ChatContentRuntime";
11
+
8
12
  let value = initOption(options, { ...DEFAUTL_OPTIONS });
9
13
  for (let key in DEFAUTL_OPTIONS) {
10
14
  this[key] = value[key];
@@ -1,10 +1,14 @@
1
1
  import { initOption } from "oipage/web/option/index.js";
2
+ import { EmptyFunction } from "./tools/enum.js";
2
3
 
3
4
  const DEFAUTL_OPTIONS = {
4
- run: void 0
5
+ run: EmptyFunction,
6
+ response: EmptyFunction,
5
7
  };
6
8
 
7
9
  function ChatTransportAdapter(options) {
10
+ this.name="ChatTransportAdapter";
11
+
8
12
  let value = initOption(options, { ...DEFAUTL_OPTIONS });
9
13
  for (let key in DEFAUTL_OPTIONS) {
10
14
  this[key] = value[key];
@@ -1,11 +1,14 @@
1
1
  import { initOption } from "oipage/web/option/index.js";
2
+ import { EmptyFunction } from "./tools/enum.js";
2
3
 
3
4
  const DEFAUTL_OPTIONS = {
4
- load: void 0,
5
- append: void 0
5
+ load: EmptyFunction,
6
+ append: EmptyFunction
6
7
  };
7
8
 
8
9
  function MessageHistoryAdapter(options) {
10
+ this.name="MessageHistoryAdapter";
11
+
9
12
  let value = initOption(options, { ...DEFAUTL_OPTIONS });
10
13
  for (let key in DEFAUTL_OPTIONS) {
11
14
  this[key] = value[key];
@@ -0,0 +1,8 @@
1
+ import { EmptyFunction } from "./tools/enum.js";
2
+
3
+ function MessageStream(send, end) {
4
+ this.send = send || EmptyFunction;
5
+ this.end = end || EmptyFunction;
6
+ }
7
+
8
+ export default MessageStream;
@@ -1,15 +1,17 @@
1
1
  import { initOption } from "oipage/web/option/index.js";
2
+ import { EmptyFunction } from "./tools/enum.js";
2
3
 
3
4
  const DEFAUTL_OPTIONS = {
4
- list: void 0,
5
- new: void 0,
6
- rename: void 0,
7
- archive: void 0,
8
- unarchive: void 0,
9
- delete: void 0
5
+ list: EmptyFunction,
6
+ new: EmptyFunction,
7
+ archive: EmptyFunction,
8
+ unarchive: EmptyFunction,
9
+ delete: EmptyFunction
10
10
  };
11
11
 
12
12
  function ThreadListAdapter(options) {
13
+ this.name="ThreadListAdapter";
14
+
13
15
  let value = initOption(options, { ...DEFAUTL_OPTIONS });
14
16
  for (let key in DEFAUTL_OPTIONS) {
15
17
  this[key] = value[key];
@@ -1,15 +1,18 @@
1
1
  import { initOption } from "oipage/web/option/index.js";
2
+ import { EmptyFunction } from "./tools/enum.js";
2
3
 
3
4
  const DEFAUTL_OPTIONS = {
4
- init: void 0,
5
- active: void 0,
6
- delete: void 0,
7
- archive: void 0,
8
- append: void 0,
9
- retitle: void 0,
5
+ init: EmptyFunction,
6
+ active: EmptyFunction,
7
+ delete: EmptyFunction,
8
+ archive: EmptyFunction,
9
+ unarchive: EmptyFunction,
10
+ append: EmptyFunction,
10
11
  };
11
12
 
12
13
  function ThreadListRuntime(options) {
14
+ this.name="ThreadListRuntime";
15
+
13
16
  let value = initOption(options, { ...DEFAUTL_OPTIONS });
14
17
  for (let key in DEFAUTL_OPTIONS) {
15
18
  this[key] = value[key];
package/src/defineTool.js CHANGED
@@ -1,5 +1,14 @@
1
- function defineTool() {
2
-
3
- }
4
-
5
- export default defineTool;
1
+ export default function (options) {
2
+ return {
3
+ description: {
4
+ type: "function",
5
+ function: {
6
+ name: options.name,
7
+ description: options.description,
8
+ parameters: options.parameters
9
+ }
10
+ },
11
+ execute: options.execute,
12
+ render: options.render
13
+ };
14
+ };
package/src/index.js CHANGED
@@ -8,4 +8,5 @@ export { default as ThreadListRuntime } from "./ThreadListRuntime.js";
8
8
  export { default as ChatContentRuntime } from "./ChatContentRuntime.js";
9
9
 
10
10
  export { default as defineTool } from "./defineTool.js";
11
- export { default as generator } from "./generator.js";
11
+ export { default as generator } from "./generator.js";
12
+ export { default as MessageStream } from "./MessageStream.js";
@@ -0,0 +1 @@
1
+ export let EmptyFunction = () => void 0;