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

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,9 @@
1
1
  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
@@ -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.1",
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.1",
29
34
  "oipage": "^2.1.0"
30
35
  }
31
36
  }
package/src/AuiPage.js CHANGED
@@ -1,14 +1,32 @@
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
 
@@ -16,56 +34,290 @@ function AuiPage(options) {
16
34
  this.currentMessages = [];
17
35
 
18
36
  // 请求对话列表
19
- this.adapter.ThreadList.list().then((threads) => {
37
+ this.adapter.ThreadList.list()?.then((threads) => {
20
38
 
21
39
  // 在页面中显示对话列表
22
40
  this.runtime.ThreadList.init(threads);
23
-
24
41
  });
25
42
 
26
43
  }
27
44
 
28
- AuiPage.prototype.adapter = {};
29
- AuiPage.prototype.runtime = {};
30
-
31
45
  AuiPage.prototype.sendMessage = function (message) {
32
- this.currentMessages.push(message);
46
+ let _this = this;
33
47
 
34
- let generator = this.adapter.ChatTransport.run({
35
- messages: this.currentMessages,
36
- context: {
37
- tools: []
38
- }
39
- });
48
+ return new Promise((resolve, reject) => {
40
49
 
41
- (function doit() {
42
- generator.next().then(res => {
43
- if (!res.done) {
44
-
45
- console.log(res.value);
50
+ if (this.isExecuting) return reject("当前正在执行中");
51
+ this.isExecuting = true;
46
52
 
47
- doit();
53
+ let generator = this.adapter.ChatTransport.run({
54
+ messages: [message],
55
+ context: {
56
+ history: this.currentMessages,
57
+ tools: this.tools_description
48
58
  }
49
- }, err => {
50
- console.error(err);
51
59
  });
52
- })();
53
60
 
61
+ if (!generator) {
62
+ this.isExecuting = false;
63
+ reject("ChatTransport.run() 返回空值");
64
+ return;
65
+ }
66
+
67
+ let cacheMessages = [message]; // 缓存消息,用于生成历史消息
68
+
69
+ let preType = "", preText = ""; // 上一个消息的类型和文本
70
+ let textTypes = ["loading", "thinking", "text"]; // 非特殊类型
71
+
72
+ let streamFun, tool_calls = {};
73
+
74
+ for (let i = 0; i < message.content.length; i++) {
75
+ this.runtime.ChatContent.append(message.role, message.content[i]);
76
+ }
77
+
78
+ (function doit() {
79
+ generator?.next().then(async function (res) {
80
+ if (!res.done) {
81
+
82
+ // 类型变了,或者是一种特殊类型
83
+ if (res.value.type != preType || !textTypes.includes(res.value.type)) {
84
+ streamFun = void 0;
85
+
86
+ if (preText) {
87
+ cacheMessages.push({
88
+ role: "assistant", content: [{
89
+ type: preType,
90
+ text: preText
91
+ }]
92
+ });
93
+ preText = "";
94
+ preType = "";
95
+ }
96
+
97
+ if (!textTypes.includes(res.value.type)) {
98
+
99
+ // 工具调用
100
+ if (res.value.type === "tool-call") {
101
+
102
+ // 工具开始调用(前端工具+后端工具)
103
+ if (res.value.status === "pending") {
104
+ tool_calls[res.value.id] = _this.runtime.ChatContent.append("assistant", res.value);
105
+
106
+ // 对于前端工具,需要自己执行工具调用
107
+ if (res.value.caller === "frontend") {
108
+ let result, status;
109
+
110
+ try {
111
+ result = await _this.tools_execute[res.value.name](res.value.args);
112
+ status = "success"; // 调用成功
113
+ } catch (error) {
114
+ result = error;
115
+ status = "error"; // 调用失败
116
+ }
117
+
118
+ let render = _this.tools_render[res.value.name];
119
+
120
+ // 需要视图交互获取结果
121
+ if (render) {
122
+ let result_ui, status_ui;
123
+
124
+ try {
125
+ result_ui = await tool_calls[res.value.id]({
126
+ ...res.value,
127
+ result,
128
+ status,
129
+ render
130
+ });
131
+ status_ui = "success";
132
+ } catch (error) {
133
+ result_ui = error;
134
+ status_ui = "error";
135
+ }
136
+
137
+ tool_calls[res.value.id]({
138
+ ...res.value,
139
+ result: result_ui,
140
+ status: status_ui
141
+ });
142
+ delete tool_calls[res.value.id];
143
+
144
+ cacheMessages.push({
145
+ role: "assistant", content: [{
146
+ type: "tool-call",
147
+ name: res.value.name,
148
+ args: res.value.args,
149
+ result,
150
+ status,
151
+ ui: {
152
+ status: status_ui,
153
+ result: result_ui
154
+ }
155
+ }]
156
+ });
157
+
158
+ _this.adapter.ChatTransport.response("tool-result", {
159
+ id: res.value.id,
160
+ status: status_ui,
161
+ result: result_ui
162
+ });
163
+ }
164
+
165
+ // 没有render,就相当于纯粹的工具调用
166
+ else {
167
+ tool_calls[res.value.id]({
168
+ ...res.value,
169
+ result,
170
+ status
171
+ });
172
+ delete tool_calls[res.value.id];
173
+
174
+ cacheMessages.push({
175
+ role: "assistant", content: [{
176
+ type: "tool-call",
177
+ name: res.value.name,
178
+ args: res.value.args,
179
+ result,
180
+ status
181
+ }]
182
+ });
183
+
184
+ _this.adapter.ChatTransport.response("tool-result", {
185
+ id: res.value.id,
186
+ result,
187
+ status
188
+ });
189
+ }
190
+
191
+ }
192
+
193
+ }
194
+
195
+ // 工具调用结束(后端工具)
196
+ else if (res.value.status === "success" || res.value.status === "error") {
197
+ if (tool_calls[res.value.id]) {
198
+ tool_calls[res.value.id](res.value);
199
+ delete tool_calls[res.value.id];
200
+
201
+ cacheMessages.push({
202
+ role: "assistant", content: [{
203
+ type: "tool-call",
204
+ name: res.value.name,
205
+ args: res.value.args,
206
+ result: res.value.result,
207
+ status: res.value.status
208
+ }]
209
+ });
210
+ }
211
+ }
212
+ } else {
213
+ // console.log("【其他消息】", res.value);
214
+ }
215
+
216
+ } else {
217
+ preText = res.value.text;
218
+ preType = res.value.type;
219
+ streamFun = _this.runtime.ChatContent.append("assistant", res.value);
220
+ }
221
+
222
+ } else {
223
+ preText += res.value.text;
224
+ if (streamFun) streamFun(res.value.text);
225
+ }
226
+
227
+ doit();
228
+ } 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
+ }
240
+
241
+ // 把准备入库的消息转换为历史消息
242
+ let historyMessages = toHistoryMessages({ messages: cacheMessages });
243
+
244
+ // 判断一下currentThreadId是否有值,如果没有,需要新建新的会话
245
+ if (_this.currentThreadId === void 0) {
246
+ let newThread = await _this.adapter.ThreadList.new(historyMessages);
247
+
248
+ if (!newThread) {
249
+ reject(new Error("新建会话失败"));
250
+ _this.isExecuting = false;
251
+ return;
252
+ }
253
+
254
+ await _this.runtime.ThreadList.append(newThread);
255
+ _this.activeThread(newThread.threadId, true);
256
+ }
257
+
258
+ _this.currentMessages.push(historyMessages);
259
+ _this.adapter.MessageHistory.append(_this.currentThreadId, historyMessages);
260
+
261
+ _this.isExecuting = false;
262
+ resolve();
263
+ }
264
+ }, err => {
265
+ _this.isExecuting = false;
266
+ reject(err);
267
+ });
268
+ })();
269
+
270
+ });
54
271
  };
55
272
 
56
- AuiPage.prototype.activeThread = function (threadId) {
273
+ AuiPage.prototype.activeThread = function (threadId, __noLoad__) {
57
274
  if (this.currentThreadId === threadId) return;
58
275
 
276
+ // 已经有执行的,不允许切换
277
+ if (this.isExecuting && !__noLoad__) return;
278
+
59
279
  this.currentThreadId = threadId;
60
280
  this.runtime.ThreadList.active(threadId);
281
+
282
+ if (threadId === void 0) {
283
+ this.currentMessages = [];
284
+ this.runtime.ChatContent.init([]);
285
+ } else if (!__noLoad__) {
286
+
287
+ // 加载历史消息
288
+ this.adapter.MessageHistory.load(threadId)?.then(messages => {
289
+ this.currentMessages = messages;
290
+
291
+ let plainMessages = [];
292
+ messages.forEach(item => {
293
+ plainMessages.push(...item.messages);
294
+ });
295
+ this.runtime.ChatContent.init(plainMessages);
296
+ });
297
+ }
61
298
  };
62
299
 
63
300
  AuiPage.prototype.deleteThread = function (threadId) {
64
- this.runtime.ThreadList.delete(threadId);
301
+ this.adapter.ThreadList.delete(threadId)?.then(() => {
302
+ this.runtime.ThreadList.delete(threadId);
303
+
304
+ if (threadId === this.currentThreadId) this.newThread();
305
+ });
306
+
65
307
  };
66
308
 
67
309
  AuiPage.prototype.archiveThread = function (threadId) {
68
- this.runtime.ThreadList.archive(threadId);
310
+ this.adapter.ThreadList.archive(threadId)?.then(() => {
311
+ this.runtime.ThreadList.archive(threadId);
312
+
313
+ if (threadId === this.currentThreadId) this.newThread();
314
+ });
315
+ };
316
+
317
+ AuiPage.prototype.unarchiveThread = function (threadId) {
318
+ this.adapter.ThreadList.unarchive(threadId).then(() => {
319
+ this.runtime.ThreadList.unarchive(threadId);
320
+ });
69
321
  };
70
322
 
71
323
  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;
@@ -0,0 +1,16 @@
1
+ export default function (value) {
2
+
3
+ let messages = [], index = -1;
4
+ for (let message of value.messages) {
5
+
6
+ if (index != -1 && messages[index].role === message.role) {
7
+ messages[index].content.push(...message.content);
8
+ } else {
9
+ messages.push(message);
10
+ index = messages.length - 1;
11
+ }
12
+ }
13
+
14
+ value.messages = messages;
15
+ return value;
16
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * ChatTransportAdapter:对接模型对话接口
3
+ */
4
+ import type { ToolDescription } from "@auipage/types";
5
+ import type {
6
+ ChatContentMessage,
7
+ ContentPart,
8
+ HistoryMessageGroup
9
+ } from "../message.js";
10
+ import type { AuiPage } from "../auipage.js";
11
+
12
+ /** run 的入参 */
13
+ export interface ChatTransportRunParams {
14
+ /** 本轮新发送的消息(当前实现中只有一条) */
15
+ messages: ChatContentMessage[];
16
+ context: {
17
+ /** 当前会话已入库的历史消息组 */
18
+ history: HistoryMessageGroup[];
19
+ /** AuiPage 构造时注册的工具描述 */
20
+ tools: Array<{ description: ToolDescription }>;
21
+ };
22
+ }
23
+
24
+ /**
25
+ * 发起一轮对话并返回异步生成器,逐个 yield 消息片段;
26
+ * 返回假值时 AuiPage 会直接终止本轮处理。
27
+ */
28
+ export type ChatTransportRun = (
29
+ params: ChatTransportRunParams
30
+ ) => AsyncGenerator<ContentPart, void, void> | void | null | undefined;
31
+
32
+ /**
33
+ * 页面 → 服务端的反向回传通道。
34
+ * 目前仅用于前端工具结果回传:response("tool-result", { id, status, result })。
35
+ */
36
+ export type ChatTransportResponse = (
37
+ name: string,
38
+ data: Record<string, unknown>
39
+ ) => unknown;
40
+
41
+ export interface ChatTransportAdapterOptions {
42
+ run?: ChatTransportRun;
43
+ response?: ChatTransportResponse;
44
+ }
45
+
46
+ export declare class ChatTransportAdapter {
47
+ constructor(options?: ChatTransportAdapterOptions);
48
+
49
+ /** 实例名,AuiPage 按它去掉 Adapter 后缀后挂载;子类可覆盖 */
50
+ name: string;
51
+
52
+ run: ChatTransportRun;
53
+ response: ChatTransportResponse;
54
+
55
+ /** 被 AuiPage 挂载后写入的反向引用 */
56
+ aui?: AuiPage;
57
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * 适配器(Adapter)类型入口:负责对接模型 / 存储等外部世界
3
+ */
4
+
5
+ export {
6
+ ChatTransportAdapter,
7
+ type ChatTransportAdapterOptions,
8
+ type ChatTransportRun,
9
+ type ChatTransportRunParams,
10
+ type ChatTransportResponse
11
+ } from "./chat-transport.js";
12
+
13
+ export {
14
+ MessageHistoryAdapter,
15
+ type MessageHistoryAdapterOptions,
16
+ type MessageHistoryLoad,
17
+ type MessageHistoryAppend
18
+ } from "./message-history.js";
19
+
20
+ export {
21
+ ThreadListAdapter,
22
+ type ThreadListAdapterOptions,
23
+ type ThreadListList,
24
+ type ThreadListNew,
25
+ type ThreadIdHandler
26
+ } from "./thread-list.js";
@@ -0,0 +1,35 @@
1
+ /**
2
+ * MessageHistoryAdapter:历史消息的加载与追加
3
+ */
4
+ import type { MaybePromise } from "@auipage/types";
5
+ import type { HistoryMessageGroup } from "../message.js";
6
+ import type { AuiPage } from "../auipage.js";
7
+
8
+ /** 加载指定会话的历史消息组;返回假值时 AuiPage 跳过历史加载 */
9
+ export type MessageHistoryLoad = (
10
+ threadId: string
11
+ ) => MaybePromise<HistoryMessageGroup[] | void | null | undefined>;
12
+
13
+ /** 把一轮消息组追加到指定会话 */
14
+ export type MessageHistoryAppend = (
15
+ threadId: string,
16
+ message: HistoryMessageGroup
17
+ ) => MaybePromise<void>;
18
+
19
+ export interface MessageHistoryAdapterOptions {
20
+ load?: MessageHistoryLoad;
21
+ append?: MessageHistoryAppend;
22
+ }
23
+
24
+ export declare class MessageHistoryAdapter {
25
+ constructor(options?: MessageHistoryAdapterOptions);
26
+
27
+ /** 实例名,AuiPage 按它去掉 Adapter 后缀后挂载;子类可覆盖 */
28
+ name: string;
29
+
30
+ load: MessageHistoryLoad;
31
+ append: MessageHistoryAppend;
32
+
33
+ /** 被 AuiPage 挂载后写入的反向引用 */
34
+ aui?: AuiPage;
35
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * ThreadListAdapter:会话列表的增删改查
3
+ */
4
+ import type { MaybePromise } from "@auipage/types";
5
+ import type { HistoryMessageGroup } from "../message.js";
6
+ import type { Thread } from "../thread.js";
7
+ import type { AuiPage } from "../auipage.js";
8
+
9
+ /** 获取会话列表 */
10
+ export type ThreadListList = () => MaybePromise<Thread[]>;
11
+
12
+ /**
13
+ * 创建新会话,入参为首轮消息组;
14
+ * 返回假值时 AuiPage 中止本轮后续处理(不渲染会话、不写历史)。
15
+ */
16
+ export type ThreadListNew = (
17
+ firstMessage: HistoryMessageGroup
18
+ ) => MaybePromise<Thread | void | null | undefined>;
19
+
20
+ /** 以会话 ID 为入参的操作:删除 / 归档 / 取消归档 */
21
+ export type ThreadIdHandler = (threadId: string) => MaybePromise<void>;
22
+
23
+ export interface ThreadListAdapterOptions {
24
+ list?: ThreadListList;
25
+ new?: ThreadListNew;
26
+ delete?: ThreadIdHandler;
27
+ archive?: ThreadIdHandler;
28
+ unarchive?: ThreadIdHandler;
29
+ }
30
+
31
+ export declare class ThreadListAdapter {
32
+ constructor(options?: ThreadListAdapterOptions);
33
+
34
+ /** 实例名,AuiPage 按它去掉 Adapter 后缀后挂载;子类可覆盖 */
35
+ name: string;
36
+
37
+ list: ThreadListList;
38
+ new: ThreadListNew;
39
+ delete: ThreadIdHandler;
40
+ archive: ThreadIdHandler;
41
+ unarchive: ThreadIdHandler;
42
+
43
+ /** 被 AuiPage 挂载后写入的反向引用 */
44
+ aui?: AuiPage;
45
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * AuiPage:框架核心,串联 Adapter(业务侧)与 Runtime(UI 侧),
3
+ * 维护会话、消息历史、流式对话与工具调用状态。
4
+ */
5
+ import type { ToolDescription, ToolExecutor } from "@auipage/types";
6
+ import type {
7
+ ChatContentMessage,
8
+ HistoryMessageGroup
9
+ } from "./message.js";
10
+ import type { Tool, ToolRender } from "./tool.js";
11
+ import type { ChatTransportAdapter } from "./adapters/chat-transport.js";
12
+ import type { MessageHistoryAdapter } from "./adapters/message-history.js";
13
+ import type { ThreadListAdapter } from "./adapters/thread-list.js";
14
+ import type { ThreadListRuntime } from "./runtimes/thread-list.js";
15
+ import type { ChatContentRuntime } from "./runtimes/chat-content.js";
16
+
17
+ /** 三个适配器的挂载集合(key 与实例 name 去掉 Adapter 后缀一致) */
18
+ export interface AuiPageAdapterSet {
19
+ ChatTransport: ChatTransportAdapter;
20
+ MessageHistory: MessageHistoryAdapter;
21
+ ThreadList: ThreadListAdapter;
22
+ }
23
+
24
+ /** 两个运行时的挂载集合(key 与实例 name 去掉 Runtime 后缀一致) */
25
+ export interface AuiPageRuntimeSet {
26
+ ThreadList: ThreadListRuntime;
27
+ ChatContent: ChatContentRuntime;
28
+ }
29
+
30
+ export interface AuiPageOptions {
31
+ adapter: AuiPageAdapterSet;
32
+ runtime: AuiPageRuntimeSet;
33
+ /** 页面侧工具列表;可选,不使用工具时省略 */
34
+ tools?: Tool[];
35
+ }
36
+
37
+ export declare class AuiPage {
38
+ constructor(options: AuiPageOptions);
39
+
40
+ /** 按 name 映射后的适配器集合 */
41
+ adapter: AuiPageAdapterSet;
42
+ /** 按 name 映射后的运行时集合 */
43
+ runtime: AuiPageRuntimeSet;
44
+
45
+ /** 工具名 → 页面执行函数 */
46
+ tools_execute: Record<string, ToolExecutor>;
47
+ /** 工具名 → UI 交互函数(可能为 undefined) */
48
+ tools_render: Record<string, ToolRender | undefined>;
49
+ /** 透传给 ChatTransport.run 的 context.tools */
50
+ tools_description: Array<{ description: ToolDescription }>;
51
+
52
+ /** 当前是否处于对话执行中;执行中拒绝重复发送、忽略会话切换 */
53
+ isExecuting: boolean;
54
+ /** 当前激活的会话 ID;undefined 表示“新建会话”状态 */
55
+ currentThreadId: string | undefined;
56
+ /** 当前会话已加载的历史消息组 */
57
+ currentMessages: HistoryMessageGroup[];
58
+
59
+ /**
60
+ * 发送一条消息并驱动完整的流式对话流程;
61
+ * 上一轮执行中时以 "当前正在执行中" reject,全部完成(含落库)后 resolve。
62
+ */
63
+ sendMessage(message: ChatContentMessage): Promise<void>;
64
+
65
+ /**
66
+ * 切换到指定会话;threadId 为 undefined 表示进入新建会话状态。
67
+ * 对话执行中调用会被忽略(noLoad 内部调用除外)。
68
+ * @param noLoad 内部参数:true 时跳过历史重载(新建会话后使用)
69
+ */
70
+ activeThread(threadId: string | undefined, noLoad?: boolean): void;
71
+
72
+ /** 删除会话;删除的是当前会话时自动进入新建会话状态 */
73
+ deleteThread(threadId: string): void;
74
+ /** 归档会话;归档的是当前会话时自动进入新建会话状态 */
75
+ archiveThread(threadId: string): void;
76
+ /** 取消归档(不自动切换会话) */
77
+ unarchiveThread(threadId: string): void;
78
+ /** 进入新建会话状态,等价于 activeThread(undefined) */
79
+ newThread(): void;
80
+ }
@@ -0,0 +1,18 @@
1
+ /**
2
+ * defineTool:工具工厂,把平铺参数组装为标准工具对象
3
+ */
4
+ import type { DefineToolOptions, Tool } from "./tool.js";
5
+
6
+ /**
7
+ * @example
8
+ * defineTool({
9
+ * name: "showPlain",
10
+ * description: "显示文本文件中的内容",
11
+ * parameters: { type: "object", properties: { ... }, required: ["content"] },
12
+ * execute: async (args) => args.content,
13
+ * render: async ({ result }) => { alert(result); return "显示成功"; }
14
+ * });
15
+ */
16
+ declare function defineTool(options: DefineToolOptions): Tool;
17
+
18
+ export default defineTool;
@@ -0,0 +1,27 @@
1
+ /**
2
+ * generator:把 next / done / error 回调式异步流程转换为 AsyncGenerator
3
+ */
4
+
5
+ /** 推送下一个值 */
6
+ export type StreamNext<T> = (value: T) => void;
7
+ /** 标记生产者结束 */
8
+ export type StreamDone = () => void;
9
+ /** 标记生产者异常 */
10
+ export type StreamError = (err: unknown) => void;
11
+
12
+ /** 生产者函数:立即执行,通过三个回调驱动数据流 */
13
+ export type StreamProducer<T> = (
14
+ next: StreamNext<T>,
15
+ done: StreamDone,
16
+ error: StreamError
17
+ ) => void;
18
+
19
+ /**
20
+ * @param rawFun 生产者函数,接收 next / done / error 三个回调
21
+ * @returns 按推送顺序产出值的异步生成器
22
+ */
23
+ declare function generator<T>(
24
+ rawFun: StreamProducer<T>
25
+ ): AsyncGenerator<T, void, void>;
26
+
27
+ export default generator;
package/types/index.d.ts CHANGED
@@ -0,0 +1,90 @@
1
+ /**
2
+ * @auipage/core 类型入口
3
+ *
4
+ * “适配器 + 运行时”机制的核心抽象层:
5
+ * 业务侧实现 Adapter 对接模型/存储,UI 侧实现 Runtime 负责渲染,
6
+ * AuiPage 串联两者,统一处理会话、历史、流式对话与前后端工具调用。
7
+ */
8
+
9
+ /* ---------- 核心类 ---------- */
10
+ export {
11
+ AuiPage,
12
+ type AuiPageOptions,
13
+ type AuiPageAdapterSet,
14
+ type AuiPageRuntimeSet
15
+ } from "./auipage.js";
16
+
17
+ /* ---------- 适配器 ---------- */
18
+ export {
19
+ ChatTransportAdapter,
20
+ type ChatTransportAdapterOptions,
21
+ type ChatTransportRun,
22
+ type ChatTransportRunParams,
23
+ type ChatTransportResponse
24
+ } from "./adapters/chat-transport.js";
25
+ export {
26
+ MessageHistoryAdapter,
27
+ type MessageHistoryAdapterOptions,
28
+ type MessageHistoryLoad,
29
+ type MessageHistoryAppend
30
+ } from "./adapters/message-history.js";
31
+ export {
32
+ ThreadListAdapter,
33
+ type ThreadListAdapterOptions,
34
+ type ThreadListList,
35
+ type ThreadListNew,
36
+ type ThreadIdHandler
37
+ } from "./adapters/thread-list.js";
38
+
39
+ /* ---------- 运行时 ---------- */
40
+ export {
41
+ ThreadListRuntime,
42
+ type ThreadListRuntimeOptions,
43
+ type ThreadInitHandler,
44
+ type ThreadActiveHandler,
45
+ type ThreadAppendHandler,
46
+ type ThreadIdUIHandler
47
+ } from "./runtimes/thread-list.js";
48
+ export {
49
+ ChatContentRuntime,
50
+ type ChatContentRuntimeOptions,
51
+ type ChatInitHandler,
52
+ type ChatAppendHandler,
53
+ type ChatAppendReturn,
54
+ type TextStreamUpdater,
55
+ type ToolEndCallback
56
+ } from "./runtimes/chat-content.js";
57
+
58
+ /* ---------- 工具 ---------- */
59
+ export type {
60
+ Tool,
61
+ ToolRender,
62
+ ToolRenderData,
63
+ DefineToolOptions
64
+ } from "./tool.js";
65
+ export { default as defineTool } from "./define-tool.js";
66
+
67
+ /* ---------- 消息与会话 ---------- */
68
+ export type {
69
+ TextContentType,
70
+ TextContentPart,
71
+ ToolCallContentPart,
72
+ ContentPart,
73
+ ChatContentMessage,
74
+ HistoryMessageGroup
75
+ } from "./message.js";
76
+ export type { Thread } from "./thread.js";
77
+
78
+ /* ---------- 流工具 ---------- */
79
+ export {
80
+ default as generator,
81
+ type StreamProducer,
82
+ type StreamNext,
83
+ type StreamDone,
84
+ type StreamError
85
+ } from "./generator.js";
86
+ export {
87
+ MessageStream,
88
+ type MessageSendHandler,
89
+ type MessageEndHandler
90
+ } from "./message-stream.js";
@@ -0,0 +1,22 @@
1
+ /**
2
+ * MessageStream:消息流的简单封装
3
+ *
4
+ * 常用于服务端(配合 @auipage/agent 的 CreateTool)向页面推送 SSE 事件。
5
+ */
6
+ import type { StreamEvent } from "@auipage/types";
7
+
8
+ /** 发送一条流式事件 */
9
+ export type MessageSendHandler = (data: StreamEvent) => void;
10
+ /** 结束本次消息流 */
11
+ export type MessageEndHandler = () => void;
12
+
13
+ export declare class MessageStream {
14
+ /**
15
+ * @param send 发送回调,缺省为空函数
16
+ * @param end 结束回调,缺省为空函数
17
+ */
18
+ constructor(send?: MessageSendHandler, end?: MessageEndHandler);
19
+
20
+ send: MessageSendHandler;
21
+ end: MessageEndHandler;
22
+ }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * 页面侧的消息 / 内容片段类型(UI 渲染与历史入库使用)
3
+ */
4
+ import type { ToolCallSide, ToolCallStatus } from "@auipage/types";
5
+ import type { ToolRender } from "./tool.js";
6
+
7
+ /** 文本类片段类型:正文 / 思维链 / 加载提示 */
8
+ export type TextContentType = "text" | "thinking" | "loading";
9
+
10
+ /** 文本类内容片段,同类型连续片段按增量拼接 */
11
+ export interface TextContentPart {
12
+ type: TextContentType;
13
+ /** 本次增量文本 */
14
+ text: string;
15
+ }
16
+
17
+ /**
18
+ * 工具调用内容片段。
19
+ *
20
+ * - 流中 pending 时携带 id / name / caller / args;
21
+ * - success / error 时补齐 result / status;
22
+ * - 带 render 的前端工具,运行时回调中还会带 render,落库时另存 ui 字段。
23
+ */
24
+ export interface ToolCallContentPart {
25
+ type: "tool-call";
26
+ /** 单次工具调用唯一标识(落库片段可能缺省) */
27
+ id?: string;
28
+ name: string;
29
+ caller?: ToolCallSide;
30
+ args?: Record<string, unknown>;
31
+ status?: ToolCallStatus;
32
+ result?: unknown;
33
+ /** 仅在带 render 的前端工具、通知运行时做 UI 交互时存在 */
34
+ render?: ToolRender;
35
+ /** 带 render 的前端工具落库时,记录 UI 交互环节的状态与结果 */
36
+ ui?: {
37
+ status: ToolCallStatus;
38
+ result: unknown;
39
+ };
40
+ }
41
+
42
+ /** 页面消费的全部内容片段;允许业务侧扩展自定义片段 */
43
+ export type ContentPart =
44
+ | TextContentPart
45
+ | ToolCallContentPart
46
+ | { type: string; [key: string]: unknown };
47
+
48
+ /** 一条页面消息(与发给模型的线上消息区分:content 是富片段数组) */
49
+ export interface ChatContentMessage {
50
+ role: string;
51
+ content: ContentPart[];
52
+ }
53
+
54
+ /**
55
+ * 历史消息组:一轮入站/出站消息的集合,
56
+ * MessageHistory.load 返回其数组,append 每次写入一组。
57
+ */
58
+ export interface HistoryMessageGroup {
59
+ messages: ChatContentMessage[];
60
+ }
@@ -0,0 +1,65 @@
1
+ /**
2
+ * ChatContentRuntime:对话内容的渲染钩子
3
+ */
4
+ import type {
5
+ ChatContentMessage,
6
+ ContentPart,
7
+ ToolCallContentPart
8
+ } from "../message.js";
9
+ import type { AuiPage } from "../auipage.js";
10
+
11
+ /** 初始化 / 重建整个对话区域 */
12
+ export type ChatInitHandler = (messages: ChatContentMessage[]) => void;
13
+
14
+ /**
15
+ * 文本分段的流式更新函数:
16
+ * append 创建文本节点时返回它,后续增量分片不再调用 append,而是调用它。
17
+ */
18
+ export type TextStreamUpdater = (deltaText: string) => void;
19
+
20
+ /**
21
+ * 工具节点的“结束回调”:
22
+ * tool-call 的 pending 片段调用 append 时返回它并按 id 缓存,
23
+ * 在工具 success / error(或前端工具 render 交互)时被调用。
24
+ *
25
+ * 带 render 的前端工具会调用两次:
26
+ * 1. 入参携带 render,其返回值(可 Promise)作为 UI 交互结果;
27
+ * 2. 入参携带 UI 交互结果,用于最终渲染。
28
+ */
29
+ export type ToolEndCallback = (data: ToolCallContentPart) => unknown;
30
+
31
+ /** append 的合法返回值:文本更新函数 / 工具结束回调 / 不返回 */
32
+ export type ChatAppendReturn =
33
+ | TextStreamUpdater
34
+ | ToolEndCallback
35
+ | void
36
+ | undefined;
37
+
38
+ /**
39
+ * 渲染一个消息片段:
40
+ * - 用户消息:每个片段调用一次,返回值被忽略;
41
+ * - 文本类流式片段:分段开始时调用,返回更新函数接收后续增量;
42
+ * - tool-call 的 pending:调用一次创建工具节点,返回结束回调。
43
+ */
44
+ export type ChatAppendHandler = (
45
+ role: string,
46
+ part: ContentPart
47
+ ) => ChatAppendReturn;
48
+
49
+ export interface ChatContentRuntimeOptions {
50
+ init?: ChatInitHandler;
51
+ append?: ChatAppendHandler;
52
+ }
53
+
54
+ export declare class ChatContentRuntime {
55
+ constructor(options?: ChatContentRuntimeOptions);
56
+
57
+ /** 实例名,AuiPage 按它去掉 Runtime 后缀后挂载;子类可覆盖 */
58
+ name: string;
59
+
60
+ init: ChatInitHandler;
61
+ append: ChatAppendHandler;
62
+
63
+ /** 被 AuiPage 挂载后写入的反向引用 */
64
+ aui?: AuiPage;
65
+ }
@@ -0,0 +1,22 @@
1
+ /**
2
+ * 运行时(Runtime)类型入口:负责把数据画到 UI 上
3
+ */
4
+
5
+ export {
6
+ ThreadListRuntime,
7
+ type ThreadListRuntimeOptions,
8
+ type ThreadInitHandler,
9
+ type ThreadActiveHandler,
10
+ type ThreadAppendHandler,
11
+ type ThreadIdUIHandler
12
+ } from "./thread-list.js";
13
+
14
+ export {
15
+ ChatContentRuntime,
16
+ type ChatContentRuntimeOptions,
17
+ type ChatInitHandler,
18
+ type ChatAppendHandler,
19
+ type ChatAppendReturn,
20
+ type TextStreamUpdater,
21
+ type ToolEndCallback
22
+ } from "./chat-content.js";
@@ -0,0 +1,40 @@
1
+ /**
2
+ * ThreadListRuntime:会话列表(侧边栏)的渲染钩子
3
+ */
4
+ import type { Thread } from "../thread.js";
5
+ import type { AuiPage } from "../auipage.js";
6
+
7
+ /** 首次渲染整个会话列表 */
8
+ export type ThreadInitHandler = (threads: Thread[]) => void;
9
+ /** 切换激活会话;threadId 为 undefined 表示“新建会话”状态 */
10
+ export type ThreadActiveHandler = (threadId: string | undefined) => void;
11
+ /** 追加一个新会话节点 */
12
+ export type ThreadAppendHandler = (thread: Thread) => void;
13
+ /** 以会话 ID 为入参的渲染操作:删除 / 归档 / 取消归档 */
14
+ export type ThreadIdUIHandler = (threadId: string) => void;
15
+
16
+ export interface ThreadListRuntimeOptions {
17
+ init?: ThreadInitHandler;
18
+ active?: ThreadActiveHandler;
19
+ append?: ThreadAppendHandler;
20
+ delete?: ThreadIdUIHandler;
21
+ archive?: ThreadIdUIHandler;
22
+ unarchive?: ThreadIdUIHandler;
23
+ }
24
+
25
+ export declare class ThreadListRuntime {
26
+ constructor(options?: ThreadListRuntimeOptions);
27
+
28
+ /** 实例名,AuiPage 按它去掉 Runtime 后缀后挂载;子类可覆盖 */
29
+ name: string;
30
+
31
+ init: ThreadInitHandler;
32
+ active: ThreadActiveHandler;
33
+ append: ThreadAppendHandler;
34
+ delete: ThreadIdUIHandler;
35
+ archive: ThreadIdUIHandler;
36
+ unarchive: ThreadIdUIHandler;
37
+
38
+ /** 被 AuiPage 挂载后写入的反向引用 */
39
+ aui?: AuiPage;
40
+ }
@@ -0,0 +1,14 @@
1
+ /**
2
+ * 会话(Thread)对象约定
3
+ */
4
+
5
+ export interface Thread {
6
+ /** 会话唯一 ID,AuiPage 内部依赖此字段 */
7
+ threadId: string;
8
+ /** 会话标题,通常取首轮用户消息的前缀 */
9
+ title?: string;
10
+ /** 是否归档 */
11
+ archived?: boolean;
12
+ /** 其它业务自定义字段 */
13
+ [key: string]: unknown;
14
+ }
@@ -0,0 +1,51 @@
1
+ /**
2
+ * 页面侧(前端)工具定义
3
+ */
4
+ import type {
5
+ MaybePromise,
6
+ ToolCallStatus,
7
+ ToolDescription,
8
+ ToolExecutor
9
+ } from "@auipage/types";
10
+
11
+ /** render 收到的数据:入参、execute 的执行结果与状态,以及工具事件上的其它字段 */
12
+ export interface ToolRenderData {
13
+ /** 模型解析出的入参 */
14
+ args: Record<string, unknown>;
15
+ /** execute 的执行结果(异常时为错误对象) */
16
+ result: unknown;
17
+ /** execute 的执行状态 */
18
+ status: ToolCallStatus;
19
+ [key: string]: unknown;
20
+ }
21
+
22
+ /**
23
+ * UI 交互函数:execute 完成后调用,可在页面上完成弹窗、表单补充等交互;
24
+ * 其返回值(可 Promise)才是最终回传给模型的结果。
25
+ */
26
+ export type ToolRender = (data: ToolRenderData) => MaybePromise<unknown>;
27
+
28
+ /**
29
+ * 注册到 AuiPage 的工具。
30
+ * execute / render 均可缺省,但缺省 execute 的工具只有在
31
+ * @auipage/agent 的 CreateTool 前后端桥接场景下才能正常工作。
32
+ */
33
+ export interface Tool {
34
+ description: ToolDescription;
35
+ execute?: ToolExecutor;
36
+ render?: ToolRender;
37
+ }
38
+
39
+ /** defineTool 的平铺入参 */
40
+ export interface DefineToolOptions {
41
+ /** 工具名,对应 description.function.name */
42
+ name: string;
43
+ /** 给模型看的功能描述 */
44
+ description: string;
45
+ /** 入参 JSON Schema */
46
+ parameters: Record<string, unknown>;
47
+ /** 页面侧执行函数 */
48
+ execute?: ToolExecutor;
49
+ /** UI 交互函数 */
50
+ render?: ToolRender;
51
+ }