@ui-code-agent/capability-pack 0.1.69 → 0.1.71
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/AGENTS-static.md +42 -2
- package/AGENTS.md +12 -1
- package/SKILL.md +5 -2
- package/package.json +2 -1
- package/specs/auth-recovery.md +20 -1
- package/specs/code-style.md +1 -0
- package/specs/data-area-markers.md +87 -10
- package/specs/data-config-conversation.md +24 -0
- package/specs/data-config-conversion.md +252 -0
- package/specs/data-config-loading.md +63 -0
- package/specs/data-configuration-accepted.md +144 -0
- package/specs/data-configuration-editing.md +42 -0
- package/specs/data-configuration-empty.md +1 -1
- package/specs/data-configuration-revision.md +76 -0
- package/specs/data-configuration.md +35 -182
- package/specs/data-conversion-empty.md +1 -1
- package/specs/data-conversion-loading.md +81 -29
- package/specs/data-implementation/contact.md +3 -0
- package/specs/data-implementation/cowork.md +270 -0
- package/specs/data-implementation/document.md +116 -7
- package/specs/data-implementation/group.md +12 -5
- package/specs/data-implementation/list-pagination.md +99 -0
- package/specs/data-implementation/list.md +26 -0
- package/specs/data-implementation/mail-list.md +13 -7
- package/specs/data-implementation/meeting.md +5 -1
- package/specs/data-implementation/official-document.md +3 -0
- package/specs/data-implementation/placard.md +3 -0
- package/specs/data-implementation/stat.md +6 -2
- package/specs/data-implementation/workflow.md +216 -19
- package/specs/data-implementation.md +24 -43
- package/specs/data-integration.md +95 -270
- package/specs/data-plan.template.json +20 -11
- package/specs/data-review.md +236 -0
- package/specs/data-sources.md +12 -8
- package/specs/page-delivery.md +40 -22
- package/specs/page-revision.md +177 -0
- package/specs/portal-page.md +6 -6
- package/specs/portal-references/catalog.md +24 -31
- package/specs/xiaoe-html.md +407 -0
- package/static-html/xiaoe-assistant.js +244 -0
- package/specs/portal-references/full-captures/pc-portal-asset-management.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-ecode.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-info-security.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-jingqiaotong.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-jiuchuihui.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-job.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-knowledge.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-marketing.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-organization.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-party-government.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-project.png +0 -0
- package/specs/portal-references/full-captures/pc-portal-sales-report.png +0 -0
|
@@ -0,0 +1,407 @@
|
|
|
1
|
+
# 小 e HTML 接入
|
|
2
|
+
|
|
3
|
+
需求包含“小 e / AI 助手 / 智能助手”时,首次生成页面就接入;用户指定其他助手时服从用户。
|
|
4
|
+
使用完整 PC 单 JS SDK、同页 ShadowRoot,每页一个活动实例。它属于页面 SDK 集成,不登记为业务数据区域。
|
|
5
|
+
|
|
6
|
+
## 1. 准备固定模块
|
|
7
|
+
|
|
8
|
+
```sh
|
|
9
|
+
ui-code-agent xiaoe prepare --dir <工程>
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
命令安装或升级原版 `scripts/xiaoe-assistant.js`;同内容不写入,用户修改过的文件报冲突并保留。
|
|
13
|
+
页面负责布局、公开配置和业务插件,认证与加载统一交给模块。
|
|
14
|
+
|
|
15
|
+
模块通过当前 E10 登录态获取连接,再加载 `/app-chat/sdk/xiaoe-sdk.js` 并挂载:
|
|
16
|
+
|
|
17
|
+
| 相对路径(POST JSON) | 请求体 | 读取 |
|
|
18
|
+
| --- | --- | --- |
|
|
19
|
+
| `/api/ai/application/setting/getAiAuthConfig` | `{"modelType":99}` | `data.chatApi` |
|
|
20
|
+
| `/api/ai/application/chat/generateUserToken` | `{}` | `data` 非空字符串 |
|
|
21
|
+
|
|
22
|
+
SDK 使用 userToken 完成登录。凭证只在内存中使用,不写源码、存储或日志。
|
|
23
|
+
|
|
24
|
+
## 2. 完整挂载、loading、关闭与重试
|
|
25
|
+
|
|
26
|
+
以下片段放在 `index.html`;外部 JS 的 import 相对于其文件路径。
|
|
27
|
+
容器先显示并具有实际高度,再调用 `open()`。加载效果覆盖助手内容区,就绪后撤掉;仅失败或未登录时显示原因和重试。
|
|
28
|
+
|
|
29
|
+
```html
|
|
30
|
+
<aside id="assistant-panel">
|
|
31
|
+
<header>AI 助手 <button id="assistant-close">收起</button></header>
|
|
32
|
+
<div id="assistant-region" style="position:relative;flex:none;height:640px;min-width:0" aria-busy="false">
|
|
33
|
+
<div id="assistant-loading" role="status" aria-label="加载中" hidden>
|
|
34
|
+
<span class="assistant-spinner" aria-hidden="true"></span>
|
|
35
|
+
</div>
|
|
36
|
+
<div id="xiaoe" style="height:100%;min-width:0"></div>
|
|
37
|
+
</div>
|
|
38
|
+
<p id="assistant-error" role="alert" hidden></p>
|
|
39
|
+
<button id="assistant-retry" hidden>重试</button>
|
|
40
|
+
</aside>
|
|
41
|
+
<button id="assistant-open" hidden>打开 AI 助手</button>
|
|
42
|
+
<style>
|
|
43
|
+
#assistant-loading { position:absolute; inset:0; z-index:1; display:grid; place-items:center; background:#fff; }
|
|
44
|
+
#assistant-loading[hidden] { display:none; }
|
|
45
|
+
.assistant-spinner { width:32px; height:32px; border:3px solid #e6efff; border-top-color:#3370ff; border-radius:50%; animation:assistant-spin .75s linear infinite; }
|
|
46
|
+
@keyframes assistant-spin { to { transform:rotate(360deg); } }
|
|
47
|
+
@media (prefers-reduced-motion:reduce) { .assistant-spinner { animation-duration:1.5s; } }
|
|
48
|
+
</style>
|
|
49
|
+
<script type="module">
|
|
50
|
+
import {createXiaoeAssistant} from './scripts/xiaoe-assistant.js';
|
|
51
|
+
const panel = document.getElementById('assistant-panel');
|
|
52
|
+
const region = document.getElementById('assistant-region');
|
|
53
|
+
const container = document.getElementById('xiaoe');
|
|
54
|
+
const loading = document.getElementById('assistant-loading');
|
|
55
|
+
const errorMessage = document.getElementById('assistant-error');
|
|
56
|
+
const retryButton = document.getElementById('assistant-retry');
|
|
57
|
+
const openButton = document.getElementById('assistant-open');
|
|
58
|
+
const assistant = createXiaoeAssistant(container, {
|
|
59
|
+
pcSender: {channel: 'qaWork', showVoiceRecord: false},
|
|
60
|
+
onStatus(value) {
|
|
61
|
+
const busy = value === 'loading';
|
|
62
|
+
const failed = value === 'login-required' || value === 'error';
|
|
63
|
+
loading.hidden = !busy;
|
|
64
|
+
region.hidden = failed || value === 'closed';
|
|
65
|
+
region.setAttribute('aria-busy', String(busy));
|
|
66
|
+
container.inert = busy || value === 'closed';
|
|
67
|
+
errorMessage.hidden = !failed;
|
|
68
|
+
errorMessage.textContent = failed
|
|
69
|
+
? (value === 'login-required' ? '请先登录当前环境后重试' : '加载失败,请重试') : '';
|
|
70
|
+
retryButton.hidden = !failed;
|
|
71
|
+
},
|
|
72
|
+
});
|
|
73
|
+
document.getElementById('assistant-close').onclick = () => {
|
|
74
|
+
assistant.close();
|
|
75
|
+
panel.hidden = true;
|
|
76
|
+
openButton.hidden = false;
|
|
77
|
+
};
|
|
78
|
+
openButton.onclick = () => {
|
|
79
|
+
panel.hidden = false;
|
|
80
|
+
openButton.hidden = true;
|
|
81
|
+
void assistant.open();
|
|
82
|
+
};
|
|
83
|
+
retryButton.onclick = () => { void assistant.open(); };
|
|
84
|
+
void assistant.open();
|
|
85
|
+
</script>
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
正例:loading 覆盖内容区,SDK 容器保持可测量高度;收起先 close,重开先显示再 open。
|
|
89
|
+
反例:加载时隐藏 SDK 容器;flex 布局压成零高度;用“正在连接/已连接”状态条代替区域 loading;只隐藏不卸载。
|
|
90
|
+
|
|
91
|
+
`open()` 成功返回 true,失败或取消返回 false。模块处理重复打开、迟到结果、超时、单实例和 pagehide。
|
|
92
|
+
|
|
93
|
+
## 3. 输入、发送、附件与事件 API
|
|
94
|
+
|
|
95
|
+
以下操作在 `await assistant.open()` 返回 true 后或 `onReady(client)` 中执行。用当前 `assistant.client` 获取客户端;关闭重开后重新读取,避免保存旧实例。
|
|
96
|
+
|
|
97
|
+
### 输入框:setValue / insertTextAtCursor / getText
|
|
98
|
+
|
|
99
|
+
```js
|
|
100
|
+
if (await assistant.open()) {
|
|
101
|
+
assistant.input.setValue('请汇总本周待办');
|
|
102
|
+
assistant.input.insertTextAtCursor(',按优先级排序');
|
|
103
|
+
const draft = assistant.input.getText();
|
|
104
|
+
}
|
|
105
|
+
// 常见问题按钮:只填草稿,用户决定发送。
|
|
106
|
+
questionButton.onclick = () => {
|
|
107
|
+
if (assistant.client) assistant.input.setValue(questionButton.textContent);
|
|
108
|
+
};
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
正例:按钮每次通过 assistant 读取当前输入接口。反例:打开后不等就绪就写入;操作 SDK 内部编辑器 DOM。
|
|
112
|
+
|
|
113
|
+
### session.send / session.stop 与 client.send / client.stop
|
|
114
|
+
|
|
115
|
+
```js
|
|
116
|
+
// 发送当前输入区的文本与附件。
|
|
117
|
+
const result = await assistant.session.send();
|
|
118
|
+
if (!result.ok) showSendError();
|
|
119
|
+
await assistant.session.stop();
|
|
120
|
+
|
|
121
|
+
// 由业务按钮直接发送明确的文本与业务上下文。
|
|
122
|
+
const client = assistant.client;
|
|
123
|
+
if (client) {
|
|
124
|
+
const sent = await client.send({text: '汇总当前记录', context: currentBusinessContext});
|
|
125
|
+
if (!sent.ok) showSendError();
|
|
126
|
+
await client.stop();
|
|
127
|
+
}
|
|
128
|
+
```
|
|
129
|
+
|
|
130
|
+
正例:用户点击发送时调用;检查返回的 ok。反例:把 Promise 完成当成功;onReady 自动发送用户未要求的问题。
|
|
131
|
+
示例中的按钮、showSendError 和 currentBusinessContext 由页面实际需求实现。
|
|
132
|
+
|
|
133
|
+
### input.setFiles / input.getFiles 与 client.upload
|
|
134
|
+
|
|
135
|
+
```js
|
|
136
|
+
// 已上传附件来自实际服务返回,保留其完整记录。
|
|
137
|
+
assistant.input.setFiles(uploadedAttachments);
|
|
138
|
+
const selectedFiles = assistant.input.getFiles();
|
|
139
|
+
assistant.input.setFiles([]);
|
|
140
|
+
|
|
141
|
+
// 原始 File 交给 SDK 上传,不放入 setFiles。
|
|
142
|
+
const file = fileInput.files?.[0];
|
|
143
|
+
if (file && assistant.client) {
|
|
144
|
+
await assistant.client.upload(file, undefined, {showPending: true});
|
|
145
|
+
}
|
|
146
|
+
```
|
|
147
|
+
|
|
148
|
+
正例:setFiles 接收带 id/name 的已有附件记录;upload 接收用户选中的 File。
|
|
149
|
+
反例:编造附件 ID;将 File 数组传入 setFiles 当作上传。
|
|
150
|
+
|
|
151
|
+
### onReady / onError / onConversationChange
|
|
152
|
+
|
|
153
|
+
```js
|
|
154
|
+
const assistant = createXiaoeAssistant(container, {
|
|
155
|
+
onReady(client) {
|
|
156
|
+
// 只有需求要求预填时才执行;不自动发送。
|
|
157
|
+
client.setDraft('请总结当前待办');
|
|
158
|
+
},
|
|
159
|
+
onError(error) { showRetry(error.code === 'XIAOE_LOGIN_REQUIRED' ? '请先登录' : '加载失败'); },
|
|
160
|
+
onConversationChange(id) { currentConversationId = id; },
|
|
161
|
+
});
|
|
162
|
+
```
|
|
163
|
+
|
|
164
|
+
正例:ready 撤掉 loading;错误由用户显式重试;会话 ID 用于业务关联。
|
|
165
|
+
反例:在回调中再次 mount;把会话 ID 当完整回答;打印认证响应。
|
|
166
|
+
|
|
167
|
+
### on / client.on:订阅并取消
|
|
168
|
+
|
|
169
|
+
```js
|
|
170
|
+
if (await assistant.open()) {
|
|
171
|
+
const off = assistant.on('message.completed', ({conversationId, message}) => {
|
|
172
|
+
refreshRelatedRecord(conversationId, message);
|
|
173
|
+
});
|
|
174
|
+
// 业务不再需要该订阅时调用;close 也会清理 assistant.on 的订阅。
|
|
175
|
+
stopWatchingButton.onclick = off;
|
|
176
|
+
}
|
|
177
|
+
// 在 onReady(client) 中也可用 client.on;保存返回的取消函数,在页面清理时调用。
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
`assistant.on` 支持 session.changed、message.completed、error。正例:每轮就绪后注册;反例:每次按钮点击都追加订阅却不清理。
|
|
181
|
+
|
|
182
|
+
### getPlugins / invoke
|
|
183
|
+
|
|
184
|
+
```js
|
|
185
|
+
if (await assistant.open()) {
|
|
186
|
+
const pluginIds = assistant.getPlugins().map(plugin => plugin.id);
|
|
187
|
+
await assistant.invoke('input.setValue', '检查当前记录');
|
|
188
|
+
const draft = await assistant.invoke('input.getText');
|
|
189
|
+
const sent = await assistant.invoke('session.send');
|
|
190
|
+
if (!sent.ok) showSendError();
|
|
191
|
+
}
|
|
192
|
+
```
|
|
193
|
+
|
|
194
|
+
正例:getPlugins 用于核对实际注册;invoke 与直接 input/session 调用任选一种。
|
|
195
|
+
反例:调用未登记的命令;在关闭后继续使用旧 input/session 包装。
|
|
196
|
+
|
|
197
|
+
命令 case(均为 `await assistant.invoke(命令, 参数)`):
|
|
198
|
+
|
|
199
|
+
| 命令 | 参数示例 | 返回值 |
|
|
200
|
+
| --- | --- | --- |
|
|
201
|
+
| input.setValue / input.insertTextAtCursor | `'汇总待办'` | 无 |
|
|
202
|
+
| input.getText | 省略 | 字符串 |
|
|
203
|
+
| input.setFiles / input.getFiles | 前者为实际附件数组,后者省略 | 后者返回附件数组 |
|
|
204
|
+
| session.send / session.stop | 省略 | CommandResult,检查 ok |
|
|
205
|
+
| client.send | `{text: '汇总待办', context: currentBusinessContext}` | CommandResult |
|
|
206
|
+
| session.new / session.select | 前者省略,后者为实际会话 ID | 前者返回会话 ID |
|
|
207
|
+
| session.refresh / session.loadHistory | 前者省略,后者可传实际会话 ID | CommandResult |
|
|
208
|
+
| session.rename / session.delete | 前者 `{id: actualId, title: '本周待办'}`,后者实际 ID | CommandResult |
|
|
209
|
+
| state.get | 省略 | 会话状态快照 |
|
|
210
|
+
|
|
211
|
+
会话删除和重命名由明确的用户操作触发,不在挂载回调中执行。
|
|
212
|
+
|
|
213
|
+
## 4. 业务问数:skill 与选中数据集
|
|
214
|
+
|
|
215
|
+
在 `plugins[].beforeSend` 中合并业务参数。resolveSkill 和 getSelectedId 必须接到当前需求提供的真实配置与页面选择。
|
|
216
|
+
skill 为 `{scopeType:'skill', id, name}`;数据集 ID 与 clientInfo 平级放在 assist.expandQuestion。
|
|
217
|
+
|
|
218
|
+
```js
|
|
219
|
+
const assistant = createXiaoeAssistant(container, {
|
|
220
|
+
plugins: [{
|
|
221
|
+
id: 'host.business-query', apiVersion: 1,
|
|
222
|
+
async beforeSend(input) {
|
|
223
|
+
const selectedId = getSelectedId(); // 本次发送开始时读取选择。
|
|
224
|
+
const skill = await resolveSkill();
|
|
225
|
+
if (!skill || skill.scopeType !== 'skill' || !skill.id || !skill.name) {
|
|
226
|
+
return {cancel: true, reason: '请先配置问数技能'};
|
|
227
|
+
}
|
|
228
|
+
const assist = input.context?.assist || {};
|
|
229
|
+
const clientInfo = assist.clientInfo || {};
|
|
230
|
+
const scopes = Array.isArray(clientInfo.activeScope) ? clientInfo.activeScope : [];
|
|
231
|
+
return {
|
|
232
|
+
...input,
|
|
233
|
+
context: {
|
|
234
|
+
...input.context,
|
|
235
|
+
assist: {
|
|
236
|
+
...assist,
|
|
237
|
+
expandQuestion: selectedId || '',
|
|
238
|
+
clientInfo: {
|
|
239
|
+
...clientInfo,
|
|
240
|
+
activeScope: [
|
|
241
|
+
...scopes.filter(scope => scope.scopeType !== 'skill' || scope.id !== skill.id),
|
|
242
|
+
{scopeType: 'skill', id: skill.id, name: skill.name},
|
|
243
|
+
],
|
|
244
|
+
},
|
|
245
|
+
},
|
|
246
|
+
},
|
|
247
|
+
};
|
|
248
|
+
},
|
|
249
|
+
}],
|
|
250
|
+
});
|
|
251
|
+
```
|
|
252
|
+
|
|
253
|
+
正例:保留原 input/context,合并实际技能及数据集;无效配置取消本次发送。
|
|
254
|
+
反例:把技能 ID 写进问题文本当绑定;把 expandQuestion 放进 clientInfo;替换整个 context 丢掉已有配置。
|
|
255
|
+
其他业务也可用 beforeSend 追加已确认的上下文,或返回 `{cancel:true, reason:'原因'}` 进行业务校验。
|
|
256
|
+
|
|
257
|
+
## 5. 自定义渲染:configure 与插件
|
|
258
|
+
|
|
259
|
+
需要创建组件时使用 `configure({runtime,signal})`。模块先执行官方 `XiaoeSDK.load(baseUrl)`,再调用 configure,最后统一 mount。
|
|
260
|
+
configure 每次打开执行,可返回 Promise;只返回公开配置,返回值覆盖同名静态配置。异步业务准备使用传入 signal。
|
|
261
|
+
|
|
262
|
+
### 插槽按钮、消息卡片、样式与插件生命周期
|
|
263
|
+
|
|
264
|
+
```js
|
|
265
|
+
const assistant = createXiaoeAssistant(container, {
|
|
266
|
+
configure({runtime}) {
|
|
267
|
+
const h = runtime.createElement;
|
|
268
|
+
function QuickPrompt({client}) {
|
|
269
|
+
return h('button', {type: 'button', onClick: () => client.setDraft('总结当前记录')}, '快捷提问');
|
|
270
|
+
}
|
|
271
|
+
function BusinessCard({block}) {
|
|
272
|
+
const data = block.data || {};
|
|
273
|
+
return h('section', {className: 'host-card'},
|
|
274
|
+
h('strong', null, String(data.title || '业务记录')),
|
|
275
|
+
h('button', {type: 'button', onClick: () => openBusinessRecord(data.id)}, '查看详情'));
|
|
276
|
+
}
|
|
277
|
+
return {
|
|
278
|
+
plugins: [{
|
|
279
|
+
id: 'host.business-ui', apiVersion: 1,
|
|
280
|
+
slots: {'sender.actions': [{id: 'quick', component: QuickPrompt}]},
|
|
281
|
+
messageRenderers: {'host-card': BusinessCard},
|
|
282
|
+
styles: [{id: 'card', cssText: '.host-card{padding:16px;border:1px solid #e5e8ef;border-radius:8px}'}],
|
|
283
|
+
setup({on, onDispose}) {
|
|
284
|
+
onDispose(on('message.completed', refreshBusiness));
|
|
285
|
+
},
|
|
286
|
+
}],
|
|
287
|
+
};
|
|
288
|
+
},
|
|
289
|
+
});
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
正例:卡片匹配真实消息的 `type:'host-card'` block;styles 注入 ShadowRoot;setup 的资源用 onDispose 清理。
|
|
293
|
+
反例:只注册 renderer 就假定服务端会生成对应数据;直接返回 HTMLElement;用宿主全局 CSS 修改内部节点。
|
|
294
|
+
插件 id 唯一、apiVersion 为 1。替换已有渲染器时声明,例如 `messageRenderers:{markdown: AnswerCard}, overrideRenderers:['markdown']`。
|
|
295
|
+
|
|
296
|
+
### 替换发送按钮
|
|
297
|
+
|
|
298
|
+
```js
|
|
299
|
+
configure({runtime}) {
|
|
300
|
+
function SendButton({senderControls: c}) {
|
|
301
|
+
if (!c) return null;
|
|
302
|
+
return runtime.createElement('button', {
|
|
303
|
+
type: 'button',
|
|
304
|
+
disabled: !c.busy && (!c.canSend || c.pendingUploads > 0),
|
|
305
|
+
onClick: c.busy ? c.onStop : c.onSend,
|
|
306
|
+
}, c.busy ? '停止' : '发送');
|
|
307
|
+
}
|
|
308
|
+
return {plugins: [{
|
|
309
|
+
id: 'host.send', apiVersion: 1,
|
|
310
|
+
slots: {'sender.send': [{id: 'send', replaces: 'xiaoe.default-ui:send', component: SendButton}]},
|
|
311
|
+
}]};
|
|
312
|
+
}
|
|
313
|
+
```
|
|
314
|
+
|
|
315
|
+
正例:沿用 senderControls 的禁用、上传等待、发送和停止。反例:重复追加默认按钮;忽略上传状态就发送。
|
|
316
|
+
|
|
317
|
+
### 自定义欢迎区或页面布局
|
|
318
|
+
|
|
319
|
+
```js
|
|
320
|
+
configure({runtime}) {
|
|
321
|
+
const h = runtime.createElement;
|
|
322
|
+
function Welcome({client}) {
|
|
323
|
+
return h('section', null,
|
|
324
|
+
h('h2', null, '业务问数'),
|
|
325
|
+
h('button', {onClick: () => client.setDraft('本月销售情况如何?')}, '本月销售情况'));
|
|
326
|
+
}
|
|
327
|
+
return {components: {EmptyState: Welcome}};
|
|
328
|
+
}
|
|
329
|
+
```
|
|
330
|
+
|
|
331
|
+
需要重排整页时在同一 configure 中提供 Page:
|
|
332
|
+
|
|
333
|
+
```js
|
|
334
|
+
function Page({regions}) {
|
|
335
|
+
return h('main', {style: {height: '100%', display: 'flex', flexDirection: 'column'}},
|
|
336
|
+
regions.header, regions.sessionList,
|
|
337
|
+
h('div', {style: {flex: 1, minHeight: 0, overflow: 'auto'}}, regions.messages),
|
|
338
|
+
regions.sender, regions.overlay);
|
|
339
|
+
}
|
|
340
|
+
return {components: {Page, EmptyState: Welcome}};
|
|
341
|
+
```
|
|
342
|
+
|
|
343
|
+
正例:只替换需求涉及的组件;Page 保留输入和覆盖层。
|
|
344
|
+
反例:重写 Page 时漏掉 regions.overlay;为了改提示语替换整个 Sender。
|
|
345
|
+
使用插件内 `components` 覆写已有组件时同时声明 `overrideComponents:['Page']`;顶层 components 由 SDK 处理覆写。
|
|
346
|
+
|
|
347
|
+
### HTML 模板、原生事件与清理
|
|
348
|
+
|
|
349
|
+
静态模板:`runtime.createElement('div', {dangerouslySetInnerHTML:{__html: fixedTemplate}})`。
|
|
350
|
+
需要原生事件时,在自己的 ref 容器内管理 DOM:
|
|
351
|
+
|
|
352
|
+
```js
|
|
353
|
+
function NativeCard({client}) {
|
|
354
|
+
const ref = runtime.React.useRef(null);
|
|
355
|
+
runtime.React.useEffect(() => {
|
|
356
|
+
const root = ref.current;
|
|
357
|
+
root.innerHTML = '<button type="button">填入问题</button>';
|
|
358
|
+
const button = root.querySelector('button');
|
|
359
|
+
const click = () => client.setDraft('总结当前记录');
|
|
360
|
+
button.addEventListener('click', click);
|
|
361
|
+
return () => {
|
|
362
|
+
button.removeEventListener('click', click);
|
|
363
|
+
root.replaceChildren();
|
|
364
|
+
};
|
|
365
|
+
}, [client]);
|
|
366
|
+
return runtime.createElement('div', {ref});
|
|
367
|
+
}
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
正例:使用 configure 提供的 runtime;动态纯文本用 children/textContent;effect 清理监听及资源。
|
|
371
|
+
反例:把外部文本直接拼进 innerHTML;修改 ref 外的 SDK 节点;返回 HTML 字符串并期待它自动解析为组件。
|
|
372
|
+
|
|
373
|
+
## 6. 配置 case
|
|
374
|
+
|
|
375
|
+
这些字段放在 createXiaoeAssistant 的 options 或 configure 返回值中,按需求选择:
|
|
376
|
+
|
|
377
|
+
| 配置 | 使用 case | 反例 |
|
|
378
|
+
| --- | --- | --- |
|
|
379
|
+
| mode | 默认省略使用完整 PC;明确只要基础界面时 `mode:'basic'` | 所有页面都设置 basic |
|
|
380
|
+
| locale / messages | `locale:'zh-CN', messages:{placeholder:'查制度', send:'发送'}` | 把 messages 当聊天历史数组 |
|
|
381
|
+
| theme | `theme:'blue'` 或 `'red'`;自定义 tokens 使用实际主题契约 | 猜 token 名或穿透内部样式 |
|
|
382
|
+
| pcSender | `{channel:'qaWork', showVoiceRecord:false, showUpFile:false}` | 认为开关能绕过服务权限 |
|
|
383
|
+
| pcSender.onNavigate | `(path, options) => hostRouter.navigate(path, options)`,仅当宿主有对应管理路由 | 空回调吞掉默认跳转 |
|
|
384
|
+
| showHeader | `showHeader:true` 展示内部标题栏 | 已有宿主标题却无需求叠加一层 |
|
|
385
|
+
| userInfo | `userInfo: currentUserDisplay` 使用实际用户展示对象 | 将展示信息当登录身份 |
|
|
386
|
+
| defaultSenderPlugins | `defaultSenderPlugins:false` 关闭默认输入功能组合,配合需求实现替代控件 | 关闭后仍假定模型/上传等默认控件存在 |
|
|
387
|
+
| defaultSenderPluginOptions | `{beforeSend:{model: input => enrichModelContext(input)}}` 对应功能的发送参数使用其真实协议 | 插槽替换后假定旧功能映射仍自动生效 |
|
|
388
|
+
| isolation | `{stylesheetUrl: actualStylesheetUrl}` 使用实际部署的样式地址 | 填入不存在的资源 |
|
|
389
|
+
| className / style | `className:'business-chat', style:{height:'100%'}` | 只给子容器百分比高度而父容器没有高度 |
|
|
390
|
+
|
|
391
|
+
## 7. 独立连接与底层句柄
|
|
392
|
+
|
|
393
|
+
已有明确宿主连接方法时可替换来源;否则使用默认 E10 接口:
|
|
394
|
+
|
|
395
|
+
```js
|
|
396
|
+
const assistant = createXiaoeAssistant(container, {
|
|
397
|
+
getSession: ({signal}) => host.getXiaoeSession({signal}), // 返回 {baseUrl,userToken}
|
|
398
|
+
});
|
|
399
|
+
```
|
|
400
|
+
|
|
401
|
+
`getXiaoeSession({signal})` 也可独立导入。常规页面只用 open,避免重复获取和重复挂载。
|
|
402
|
+
官方方法对应关系:configure 之前由模块执行 load;open 内部 mount 后等待 chat.ready;close 调用 chat.unmount。
|
|
403
|
+
正例:统一沿用固定模块生命周期。反例:在同一容器另建 XiaoeSDK.mount;自建取凭证、脚本加载和超时逻辑。
|
|
404
|
+
|
|
405
|
+
## 验证
|
|
406
|
+
|
|
407
|
+
实际检查:区域 loading → 官方界面、关闭重开、加载中关闭、失败重试。需求涉及输入、插件、卡片时逐项操作;问数核对实际 skill/数据集参数和真实回复。
|
|
@@ -0,0 +1,244 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* ui-code-agent managed integration. Customize the page, not this file.
|
|
3
|
+
* @typedef {{baseUrl: string, userToken: string}} XiaoeSession
|
|
4
|
+
* @typedef {'loading'|'ready'|'login-required'|'error'|'closed'} XiaoeStatus
|
|
5
|
+
* @typedef {'session.changed'|'message.completed'|'error'} XiaoeEvent
|
|
6
|
+
* @typedef {{ok: boolean, error?: unknown}} CommandResult
|
|
7
|
+
* @typedef {{id: string, name: string, [key: string]: unknown}} Attachment
|
|
8
|
+
* @typedef {{setValue: (text: string) => void, insertTextAtCursor: (text: string) => void, getText: () => string, setFiles: (files: Attachment[]) => void, getFiles: () => Attachment[]}} XiaoeInput
|
|
9
|
+
* @typedef {{send: () => Promise<CommandResult>, stop: () => Promise<CommandResult>}} XiaoeSessionControls
|
|
10
|
+
* @typedef {Record<string, any>} XiaoeClient
|
|
11
|
+
* @typedef {{ready: Promise<void>, client?: XiaoeClient, input: XiaoeInput, session: XiaoeSessionControls, getPlugins: () => object[], invoke: (command: string, payload?: unknown) => Promise<unknown>, on: (event: XiaoeEvent, callback: (payload: any) => void) => () => void, unmount: () => void}} XiaoeHandle
|
|
12
|
+
* @typedef {{mode?: 'basic', locale?: 'zh-CN'|'en-US', messages?: Record<string, string>, theme?: string|object, pcSender?: object, plugins?: object[], components?: object, defaultSenderPlugins?: boolean, defaultSenderPluginOptions?: object, showHeader?: boolean, userInfo?: object, isolation?: object, className?: string, style?: object}} XiaoeOptions
|
|
13
|
+
* @typedef {XiaoeOptions & {onReady?: (client: XiaoeClient) => void, onError?: (error: Error) => void, onConversationChange?: (id: string) => void, onStatus?: (status: XiaoeStatus) => void, getSession?: (options: {signal: AbortSignal}) => Promise<XiaoeSession>, configure?: (context: {runtime: Record<string, any>, signal: AbortSignal}) => XiaoeOptions|Promise<XiaoeOptions>}} AssistantOptions
|
|
14
|
+
*/
|
|
15
|
+
|
|
16
|
+
/** @param {string} message @param {string} code */
|
|
17
|
+
function failure(message, code = 'XIAOE_CONNECTION_FAILED') {
|
|
18
|
+
return Object.assign(new Error(message), { code })
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param {XiaoeSession} session @returns {XiaoeSession} */
|
|
22
|
+
function validateSession(session) {
|
|
23
|
+
let url
|
|
24
|
+
try {
|
|
25
|
+
url = new URL(session?.baseUrl)
|
|
26
|
+
} catch {
|
|
27
|
+
throw failure('小 e 服务地址格式错误')
|
|
28
|
+
}
|
|
29
|
+
if (!['http:', 'https:'].includes(url.protocol) || url.search || url.hash || url.username || url.password) {
|
|
30
|
+
throw failure('小 e 服务地址格式错误')
|
|
31
|
+
}
|
|
32
|
+
const userToken = typeof session?.userToken === 'string' ? session.userToken.trim() : ''
|
|
33
|
+
if (!userToken) throw failure('当前账号未取得小 e 登录凭证')
|
|
34
|
+
return { baseUrl: url.href.replace(/\/+$/, ''), userToken }
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Get a fresh connection from the current E10 environment. Never persist credentials.
|
|
38
|
+
* @param {{signal?: AbortSignal}} options
|
|
39
|
+
* @returns {Promise<XiaoeSession>}
|
|
40
|
+
*/
|
|
41
|
+
export async function getXiaoeSession({ signal } = {}) {
|
|
42
|
+
/** @param {string} endpoint @param {object} body */
|
|
43
|
+
async function post(endpoint, body) {
|
|
44
|
+
let response
|
|
45
|
+
try {
|
|
46
|
+
response = await fetch(endpoint, {
|
|
47
|
+
method: 'POST', credentials: 'include', cache: 'no-store', signal,
|
|
48
|
+
headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body),
|
|
49
|
+
})
|
|
50
|
+
} catch {
|
|
51
|
+
if (signal?.aborted) throw signal.reason
|
|
52
|
+
throw failure('连接失败,请检查网络后重试')
|
|
53
|
+
}
|
|
54
|
+
if (response.status === 401) throw failure('请先登录当前 E10 环境后重试', 'XIAOE_LOGIN_REQUIRED')
|
|
55
|
+
if (!response.ok) throw failure('获取小 e 连接失败,请稍后重试')
|
|
56
|
+
let result
|
|
57
|
+
try { result = await response.json() } catch { throw failure('小 e 连接响应格式异常') }
|
|
58
|
+
if (result?.status !== true) throw failure('获取小 e 连接失败,请检查当前账号配置')
|
|
59
|
+
return result.data
|
|
60
|
+
}
|
|
61
|
+
const [config, userToken] = await Promise.all([
|
|
62
|
+
post('/api/ai/application/setting/getAiAuthConfig', { modelType: 99 }),
|
|
63
|
+
post('/api/ai/application/chat/generateUserToken', {}),
|
|
64
|
+
])
|
|
65
|
+
return validateSession({ baseUrl: config?.chatApi, userToken })
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** @typedef {{load: (baseUrl: string) => Promise<Record<string, any>>, mount: (target: HTMLElement, options: XiaoeOptions & XiaoeSession & {renderMode: string, onError: () => void, onConversationChange: (id: string) => void}) => XiaoeHandle}} HtmlSdk */
|
|
69
|
+
const sdkWindow = /** @type {Window & typeof globalThis & {XiaoeSDK?: HtmlSdk}} */ (window)
|
|
70
|
+
/** @type {Promise<HtmlSdk>|undefined} */
|
|
71
|
+
let sdkLoading
|
|
72
|
+
let loadedBaseUrl = ''
|
|
73
|
+
/** @type {{close: () => void}|undefined} */
|
|
74
|
+
let active
|
|
75
|
+
|
|
76
|
+
/** @param {string} baseUrl @returns {Promise<HtmlSdk>} */
|
|
77
|
+
function loadSdk(baseUrl) {
|
|
78
|
+
if (loadedBaseUrl && loadedBaseUrl !== baseUrl) {
|
|
79
|
+
return Promise.reject(failure('切换小 e 服务后请重新加载页面'))
|
|
80
|
+
}
|
|
81
|
+
if (!sdkLoading) {
|
|
82
|
+
if (sdkWindow.XiaoeSDK) return Promise.reject(failure('请移除重复加载的小 e SDK 脚本后刷新页面'))
|
|
83
|
+
loadedBaseUrl = baseUrl
|
|
84
|
+
sdkLoading = new Promise((resolve, reject) => {
|
|
85
|
+
const script = document.createElement('script')
|
|
86
|
+
const timer = setTimeout(() => finish(failure('小 e SDK 加载超时,请重试')), 30000)
|
|
87
|
+
/** @param {Error} [error] */
|
|
88
|
+
function finish(error) {
|
|
89
|
+
clearTimeout(timer)
|
|
90
|
+
script.onload = script.onerror = null
|
|
91
|
+
if (error) { script.remove(); reject(error) }
|
|
92
|
+
else if (sdkWindow.XiaoeSDK?.mount) resolve(sdkWindow.XiaoeSDK)
|
|
93
|
+
else { script.remove(); reject(failure('小 e SDK 入口不可用')) }
|
|
94
|
+
}
|
|
95
|
+
// Keep the external SDK URL out of the publisher's static resource rewriting.
|
|
96
|
+
script.src = [baseUrl, 'app-chat', 'sdk', 'xiaoe-sdk'].join('/') + '.js'
|
|
97
|
+
script.onload = () => finish()
|
|
98
|
+
script.onerror = () => finish(failure('小 e SDK 加载失败,请重试'))
|
|
99
|
+
document.head.appendChild(script)
|
|
100
|
+
}).catch(error => { sdkLoading = undefined; throw error })
|
|
101
|
+
}
|
|
102
|
+
return sdkLoading
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** @template T @param {Promise<T>} promise @param {AbortSignal} signal @returns {Promise<T>} */
|
|
106
|
+
function cancellable(promise, signal) {
|
|
107
|
+
return new Promise((resolve, reject) => {
|
|
108
|
+
const cancel = () => reject(signal.reason)
|
|
109
|
+
if (signal.aborted) { promise.catch(() => {}); reject(signal.reason); return }
|
|
110
|
+
signal.addEventListener('abort', cancel, { once: true })
|
|
111
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener('abort', cancel))
|
|
112
|
+
})
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** @param {HTMLElement} container @param {AssistantOptions} options */
|
|
116
|
+
export function createXiaoeAssistant(container, options = {}) {
|
|
117
|
+
if (!(container instanceof HTMLElement)) throw failure('请提供小 e 容器元素')
|
|
118
|
+
const sdkKeys = ['mode', 'locale', 'messages', 'theme', 'pcSender', 'plugins', 'components', 'defaultSenderPlugins', 'defaultSenderPluginOptions', 'showHeader', 'userInfo', 'isolation', 'className', 'style']
|
|
119
|
+
const allowed = new Set([...sdkKeys, 'onReady', 'onError', 'onConversationChange', 'onStatus', 'getSession', 'configure'])
|
|
120
|
+
if (Object.keys(options).some(key => !allowed.has(key))) throw failure('存在未支持的小 e HTML 配置,请查阅接入手册')
|
|
121
|
+
const { onStatus, getSession = getXiaoeSession, configure, onReady, onError, onConversationChange, ...sdkOptions } = options
|
|
122
|
+
/** @type {AbortController|undefined} */
|
|
123
|
+
let attempt
|
|
124
|
+
/** @type {XiaoeHandle|undefined} */
|
|
125
|
+
let handle
|
|
126
|
+
let ready = false
|
|
127
|
+
let closed = false
|
|
128
|
+
/** @type {Set<() => void>} */
|
|
129
|
+
const subscriptions = new Set()
|
|
130
|
+
/** @param {XiaoeStatus} status */
|
|
131
|
+
const status = status => onStatus?.(status)
|
|
132
|
+
function cleanup() {
|
|
133
|
+
ready = false
|
|
134
|
+
attempt?.abort(new DOMException('已关闭小 e', 'AbortError'))
|
|
135
|
+
attempt = undefined
|
|
136
|
+
for (const off of subscriptions) off()
|
|
137
|
+
subscriptions.clear()
|
|
138
|
+
handle?.unmount()
|
|
139
|
+
handle = undefined
|
|
140
|
+
if (active === assistant) active = undefined
|
|
141
|
+
}
|
|
142
|
+
function currentHandle() {
|
|
143
|
+
if (!ready || !handle) throw failure('请先打开小 e 并等待就绪', closed ? 'XIAOE_SDK_UNMOUNTED' : 'XIAOE_SDK_NOT_READY')
|
|
144
|
+
return handle
|
|
145
|
+
}
|
|
146
|
+
/** Bind operations to this mount so saved controls cannot operate a replacement instance. */
|
|
147
|
+
function controls() {
|
|
148
|
+
const expected = currentHandle()
|
|
149
|
+
return () => {
|
|
150
|
+
if (handle !== expected) throw failure('小 e 实例已关闭', 'XIAOE_SDK_UNMOUNTED')
|
|
151
|
+
return currentHandle()
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
const assistant = {
|
|
155
|
+
get client() { return ready ? handle?.client : undefined },
|
|
156
|
+
get input() {
|
|
157
|
+
const get = controls()
|
|
158
|
+
return {
|
|
159
|
+
/** @param {string} text */
|
|
160
|
+
setValue: text => get().input.setValue(text),
|
|
161
|
+
/** @param {string} text */
|
|
162
|
+
insertTextAtCursor: text => get().input.insertTextAtCursor(text),
|
|
163
|
+
getText: () => get().input.getText(),
|
|
164
|
+
/** @param {Attachment[]} files */
|
|
165
|
+
setFiles: files => get().input.setFiles(files),
|
|
166
|
+
getFiles: () => get().input.getFiles(),
|
|
167
|
+
}
|
|
168
|
+
},
|
|
169
|
+
get session() {
|
|
170
|
+
const get = controls()
|
|
171
|
+
return { send: async () => get().session.send(), stop: async () => get().session.stop() }
|
|
172
|
+
},
|
|
173
|
+
getPlugins() { return ready ? handle.getPlugins() : [] },
|
|
174
|
+
/** @param {string} command @param {unknown} [payload] */
|
|
175
|
+
async invoke(command, payload) { return currentHandle().invoke(command, payload) },
|
|
176
|
+
/** @param {XiaoeEvent} event @param {(payload: any) => void} callback */
|
|
177
|
+
on(event, callback) {
|
|
178
|
+
const expected = currentHandle()
|
|
179
|
+
const unsubscribe = expected.on(event, payload => {
|
|
180
|
+
if (handle === expected && ready) callback(payload)
|
|
181
|
+
})
|
|
182
|
+
const off = () => { unsubscribe(); subscriptions.delete(off) }
|
|
183
|
+
subscriptions.add(off)
|
|
184
|
+
return off
|
|
185
|
+
},
|
|
186
|
+
async open() {
|
|
187
|
+
if (active && active !== assistant) active.close()
|
|
188
|
+
cleanup()
|
|
189
|
+
closed = false
|
|
190
|
+
active = assistant
|
|
191
|
+
const current = new AbortController()
|
|
192
|
+
attempt = current
|
|
193
|
+
let failed = false
|
|
194
|
+
const timer = setTimeout(() => current.abort(failure('小 e 初始化超时,请重试')), 60000)
|
|
195
|
+
status('loading')
|
|
196
|
+
try {
|
|
197
|
+
if (!container.isConnected || !container.getClientRects().length || container.clientHeight <= 0) {
|
|
198
|
+
throw failure('请先显示小 e 容器并设置高度')
|
|
199
|
+
}
|
|
200
|
+
const session = validateSession(await cancellable(getSession({ signal: current.signal }), current.signal))
|
|
201
|
+
const sdk = await cancellable(loadSdk(session.baseUrl), current.signal)
|
|
202
|
+
let configured = {}
|
|
203
|
+
if (configure) {
|
|
204
|
+
const runtime = await cancellable(sdk.load(session.baseUrl), current.signal)
|
|
205
|
+
if (attempt !== current) return false
|
|
206
|
+
configured = await cancellable(Promise.resolve(configure({ runtime, signal: current.signal })), current.signal)
|
|
207
|
+
if (!configured || typeof configured !== 'object' || Array.isArray(configured) || Object.keys(configured).some(key => !sdkKeys.includes(key))) {
|
|
208
|
+
throw failure('configure 只能返回小 e 公开配置')
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (attempt !== current) return false
|
|
212
|
+
handle = sdk.mount(container, {
|
|
213
|
+
...sdkOptions, ...configured, ...session, renderMode: 'shadow-root',
|
|
214
|
+
onError() {
|
|
215
|
+
if (attempt !== current) return
|
|
216
|
+
failed = true
|
|
217
|
+
ready = false
|
|
218
|
+
status('error')
|
|
219
|
+
onError?.(failure('小 e 连接失败,请重试'))
|
|
220
|
+
},
|
|
221
|
+
onConversationChange(id) { if (attempt === current) onConversationChange?.(id) },
|
|
222
|
+
})
|
|
223
|
+
await cancellable(handle.ready, current.signal)
|
|
224
|
+
if (attempt !== current || failed) return false
|
|
225
|
+
ready = true
|
|
226
|
+
status('ready')
|
|
227
|
+
if (attempt !== current) return false
|
|
228
|
+
onReady?.(handle.client)
|
|
229
|
+
return attempt === current
|
|
230
|
+
} catch (error) {
|
|
231
|
+
if (attempt !== current) return false
|
|
232
|
+
cleanup()
|
|
233
|
+
const login = error?.code === 'XIAOE_LOGIN_REQUIRED'
|
|
234
|
+
status(login ? 'login-required' : 'error')
|
|
235
|
+
if (!failed) onError?.(failure(login ? '请先登录当前 E10 环境后重试' : '小 e 连接失败,请重试', login ? 'XIAOE_LOGIN_REQUIRED' : 'XIAOE_CONNECTION_FAILED'))
|
|
236
|
+
return false
|
|
237
|
+
} finally { clearTimeout(timer) }
|
|
238
|
+
},
|
|
239
|
+
close() { closed = true; cleanup(); status('closed') },
|
|
240
|
+
}
|
|
241
|
+
return assistant
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
window.addEventListener('pagehide', () => active?.close())
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|
|
Binary file
|