@glodon-aiot/bot-client-sdk 3.26.0-alpha.30 → 3.26.0-alpha.31
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/README.md +222 -242
- package/dist/es/package.json.mjs +2 -2
- package/dist/lib/index.js +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -1,60 +1,78 @@
|
|
|
1
1
|
# @glodon-aiot/bot-client-sdk
|
|
2
2
|
|
|
3
|
-
AIoT 应用客户端 SDK,支持 Agent
|
|
3
|
+
AIoT 应用客户端 SDK,支持 Agent 与对话型应用。会话、消息、产出物和客户端插件由本包执行,**界面由接入方实现**。
|
|
4
|
+
|
|
5
|
+
## 按角色阅读
|
|
6
|
+
|
|
7
|
+
| 你要做的事 | 读这些 |
|
|
8
|
+
| --- | --- |
|
|
9
|
+
| 只接对话 UI | [快速开始](#快速开始) → [对话界面](#对话界面) → [产出物](#产出物) |
|
|
10
|
+
| 浏览器里读本地文件夹 / 跑命令 | 上栏 + [Agent 插件](#agent-插件) → [本地工作文件夹](#本地工作文件夹) → [命令和脚本](#命令和脚本) |
|
|
11
|
+
| 端侧宿主(桌面内嵌页 + 沙箱) | [宿主通道](#宿主通道) + 沙箱包 [`workspace-sandbox` README](../workspace-sandbox/README.md) |
|
|
12
|
+
| 查工具参数 / 错误码 / 限额 | [内置工具参考](#内置工具参考) · [安全与限额](#安全与限额) · [错误码](#错误码) |
|
|
13
|
+
|
|
14
|
+
集成方总览:[`bot-client-ui/docs/agent-integration-handbook.md`](../bot-client-ui/docs/agent-integration-handbook.md)。Windows 宿主步骤:[`local-workspace-windows-host.md`](../bot-client-ui/docs/local-workspace-windows-host.md)。
|
|
4
15
|
|
|
5
16
|
| 能力 | 适用应用 | 运行环境 | 见 |
|
|
6
17
|
| --- | --- | --- | --- |
|
|
7
18
|
| 会话与流式对话 | Agent、对话型 | 浏览器、端侧宿主 | [对话界面](#对话界面) |
|
|
8
19
|
| 会话产出物 | Agent、对话型 | 浏览器、端侧宿主 | [产出物](#产出物) |
|
|
9
20
|
| 业务插件、本地文件 | Agent | 浏览器、端侧宿主 | [Agent 插件](#agent-插件) |
|
|
10
|
-
|
|
|
21
|
+
| 命令与脚本 | Agent | 浏览器运行时或端侧宿主沙箱 | [命令和脚本](#命令和脚本) |
|
|
11
22
|
|
|
12
|
-
|
|
23
|
+
**术语:** 浏览器 = 现代浏览器(命令另需能加载公司 OBS 上的 just-bash / Pyodide)。端侧宿主 = 内嵌此页、选定本地工程并管理 `@glodon-aiot/workspace-sandbox` 的桌面程序;文件和命令由页面**直连**沙箱,不经宿主转发。
|
|
13
24
|
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
## 安装
|
|
25
|
+
## 快速开始
|
|
17
26
|
|
|
18
27
|
```bash
|
|
19
28
|
yarn add @glodon-aiot/bot-client-sdk
|
|
20
|
-
# 或
|
|
21
|
-
npm install @glodon-aiot/bot-client-sdk
|
|
29
|
+
# 或 npm install @glodon-aiot/bot-client-sdk
|
|
22
30
|
```
|
|
23
31
|
|
|
24
32
|
```ts
|
|
25
33
|
import { BotClient } from '@glodon-aiot/bot-client-sdk';
|
|
34
|
+
|
|
35
|
+
const client = new BotClient(token, { env: 'dev', stream: true });
|
|
36
|
+
|
|
37
|
+
client.addEventListener('error', console.error);
|
|
38
|
+
client.addEventListener('ready', async () => {
|
|
39
|
+
const session = await client.loadSession(''); // 空字符串 = 新建
|
|
40
|
+
session.addEventListener('message:content', () => render(session.messages));
|
|
41
|
+
session.addEventListener('answer:finish', () => render(session.messages));
|
|
42
|
+
await session.send({ text: '你好' }, { stream: true });
|
|
43
|
+
});
|
|
26
44
|
```
|
|
27
45
|
|
|
28
|
-
|
|
46
|
+
`token` 为带应用 ID 的 AIoT 资源令牌。类型、工作区、工具 Schema、错误码均从包入口导出。需要本地文件时再开 `builtinPlugins.localFiles`,见下文。
|
|
29
47
|
|
|
30
48
|
## 创建客户端
|
|
31
49
|
|
|
32
50
|
```ts
|
|
33
51
|
const client = new BotClient(token, {
|
|
34
52
|
env: 'dev', // 'dev' | 'test' | 'prod' | 'local',决定默认 API 地址
|
|
35
|
-
// apiRoot: 'https://example.com/api/cvforce', // 传入后覆盖 env
|
|
36
|
-
stream: true, // 省略时 Agent
|
|
53
|
+
// apiRoot: 'https://example.com/api/cvforce', // 传入后覆盖 env
|
|
54
|
+
stream: true, // 省略时 Agent / 对话型默认流式
|
|
37
55
|
// plugins、builtinPlugins 见「Agent 插件」
|
|
38
56
|
});
|
|
39
57
|
|
|
40
58
|
client.addEventListener('error', (error) => {
|
|
41
|
-
//
|
|
59
|
+
// 配置问题:插件编码冲突、backend 写错等
|
|
42
60
|
console.error(error);
|
|
43
61
|
});
|
|
44
62
|
|
|
45
63
|
client.addEventListener('ready', () => {
|
|
46
|
-
//
|
|
64
|
+
// 应用信息已加载;loadSession / sessions / application 需等此事件
|
|
47
65
|
});
|
|
48
66
|
```
|
|
49
67
|
|
|
50
|
-
|
|
68
|
+
应用类型由平台应用决定,`loadSession` 按类型创建对应会话。
|
|
51
69
|
|
|
52
70
|
## 对话界面
|
|
53
71
|
|
|
54
|
-
|
|
72
|
+
界面自管渲染状态,数据以 `session.messages` 为准。事件都带当前消息或列表,收到后重绘即可。
|
|
55
73
|
|
|
56
74
|
```ts
|
|
57
|
-
const session = await client.loadSession(sessionId); //
|
|
75
|
+
const session = await client.loadSession(sessionId); // 空字符串 = 新建
|
|
58
76
|
|
|
59
77
|
session.addEventListener('history:loaded', () => render(session.messages));
|
|
60
78
|
session.addEventListener('message:new', () => render(session.messages));
|
|
@@ -62,20 +80,19 @@ session.addEventListener('message:updated', () => render(session.messages));
|
|
|
62
80
|
session.addEventListener('message:content', () => render(session.messages)); // 流式增量
|
|
63
81
|
session.addEventListener('answer:finish', () => render(session.messages));
|
|
64
82
|
session.addEventListener('message:error', (error) => showError(error));
|
|
65
|
-
session.addEventListener('message:action', () => render(session.messages)); //
|
|
83
|
+
session.addEventListener('message:action', () => render(session.messages)); // 工具步骤
|
|
66
84
|
|
|
67
|
-
await session.fetchMessages();
|
|
85
|
+
await session.fetchMessages();
|
|
68
86
|
await session.send({ text: '你好' }, { stream: true });
|
|
69
87
|
|
|
70
|
-
//
|
|
71
|
-
session.suspend();
|
|
88
|
+
session.suspend(); // 停止回答;进行中的客户端插件会取消,确认弹窗应关闭
|
|
72
89
|
```
|
|
73
90
|
|
|
74
91
|
会话列表:
|
|
75
92
|
|
|
76
93
|
```ts
|
|
77
94
|
const sessions = await client.getSessions();
|
|
78
|
-
const current = await client.loadSession(id); //
|
|
95
|
+
const current = await client.loadSession(id); // 同时设为活跃会话
|
|
79
96
|
await client.removeSession(id, true);
|
|
80
97
|
```
|
|
81
98
|
|
|
@@ -84,22 +101,21 @@ await client.removeSession(id, true);
|
|
|
84
101
|
| `history:loaded` | 用 `session.messages` 渲染历史 |
|
|
85
102
|
| `message:new` / `message:updated` | 重绘消息列表 |
|
|
86
103
|
| `message:content` | 流式更新当前回答 |
|
|
87
|
-
| `message:action` |
|
|
88
|
-
| `answer:finish` |
|
|
104
|
+
| `message:action` | 刷新工具步骤,见[展示工具步骤](#展示工具步骤) |
|
|
105
|
+
| `answer:finish` | 结束「正在回答」,允许再发送 |
|
|
89
106
|
| `message:error` / `error` | 展示错误 |
|
|
90
107
|
|
|
91
|
-
发送开始后 `session.frozen === true`,此时 `send`
|
|
108
|
+
发送开始后 `session.frozen === true`,此时 `send` 会失败;输入框保持禁用直到 `answer:finish`。
|
|
92
109
|
|
|
93
110
|
## 产出物
|
|
94
111
|
|
|
95
|
-
|
|
112
|
+
任务结束后可拉取本次会话留下的文件(会话级,不是单条消息附件)。无产出物返回空数组,不抛错。
|
|
96
113
|
|
|
97
114
|
```ts
|
|
98
115
|
import type { ISessionArtifact } from '@glodon-aiot/bot-client-sdk';
|
|
99
116
|
|
|
100
117
|
const artifacts: ISessionArtifact[] = await session.getArtifacts();
|
|
101
|
-
|
|
102
|
-
const same = await client.getArtifacts(session.id);
|
|
118
|
+
const same = await client.getArtifacts(session.id); // 省略 id 时用活跃会话
|
|
103
119
|
```
|
|
104
120
|
|
|
105
121
|
| 字段 | 含义 |
|
|
@@ -108,20 +124,20 @@ const same = await client.getArtifacts(session.id);
|
|
|
108
124
|
| `size` | 字节数 |
|
|
109
125
|
| `url` | 可访问地址 |
|
|
110
126
|
|
|
111
|
-
`Session.getArtifacts()
|
|
127
|
+
- `Session.getArtifacts()`:用该会话自己的应用 id / 会话 id,缺失则抛错
|
|
128
|
+
- `BotClient.getArtifacts(sessionId?)`:需等 `ready`;无 `sessionId` 且无活跃会话时抛错
|
|
129
|
+
- 已加载会话优先走 `Session.getArtifacts()`,否则直请求平台
|
|
112
130
|
|
|
113
|
-
一般在任务成功结束(`index === -1` 且 `code === 200
|
|
131
|
+
一般在任务成功结束(`index === -1` 且 `code === 200`)和用户中止(`index === -2`)后调用。
|
|
114
132
|
|
|
115
133
|
## Agent 插件
|
|
116
134
|
|
|
117
|
-
Agent
|
|
118
|
-
|
|
119
|
-
插件分两类,都在创建客户端时配置:
|
|
135
|
+
Agent 应用中,平台标记为**客户端执行**的插件函数由 SDK 在页面调用,结果回传平台。对话型应用不调用客户端插件。
|
|
120
136
|
|
|
121
137
|
| 配置 | 内容 | `pluginCode` |
|
|
122
138
|
| --- | --- | --- |
|
|
123
|
-
| `plugins` |
|
|
124
|
-
| `builtinPlugins` | SDK
|
|
139
|
+
| `plugins` | 接入方业务插件 | 平台分配,作为 key |
|
|
140
|
+
| `builtinPlugins` | SDK 内置工作区 / 命令 / 技能工具 | 固定 `builtin_tools`,不用传 |
|
|
125
141
|
|
|
126
142
|
```ts
|
|
127
143
|
const client = new BotClient(token, {
|
|
@@ -142,25 +158,25 @@ const client = new BotClient(token, {
|
|
|
142
158
|
|
|
143
159
|
### 业务插件
|
|
144
160
|
|
|
145
|
-
`plugins` 的 key
|
|
161
|
+
`plugins` 的 key 是平台 `pluginCode`,值是 `functionCode` → 函数。调用签名 `(params, callback, context)`:
|
|
146
162
|
|
|
147
163
|
| 参数 | 含义 |
|
|
148
164
|
| --- | --- |
|
|
149
|
-
| `params` |
|
|
150
|
-
| `callback` |
|
|
151
|
-
| `context` | `requestId`、`applicationId`、`sessionId`、`pluginCode`、`functionCode`、`signal
|
|
165
|
+
| `params` | 模型参数,已解析为对象 |
|
|
166
|
+
| `callback` | 回传 `{ code, message, data? }`;`message` 给模型;只认第一次调用 |
|
|
167
|
+
| `context` | `requestId`、`applicationId`、`sessionId`、`pluginCode`、`functionCode`、`signal`(`ToolContext`) |
|
|
152
168
|
|
|
153
|
-
停止回答或会话失活时 `signal`
|
|
169
|
+
停止回答或会话失活时 `signal` aborted,之后的 `callback` 不再回传。函数抛错 / Promise 拒绝 → 500;未注册插件或函数 → 404。
|
|
154
170
|
|
|
155
171
|
### 内置插件
|
|
156
172
|
|
|
157
|
-
`localFiles`
|
|
173
|
+
`localFiles` 启用后,工具注册到 `pluginCode` `builtin_tools`。`client.localWorkspace` 仅在 `localFiles.enabled === true` 时存在。
|
|
158
174
|
|
|
159
|
-
`shell` / `run_file` / `run_skill_script`
|
|
175
|
+
`shell` / `run_file` / `run_skill_script` 的执行器选择见[命令和脚本](#命令和脚本):注入的 `commandRunner` → 已就绪的协议 1 沙箱 → 无宿主时的 just-bash / Pyodide(默认开)→ 否则 501。**宿主工作区已授权但沙箱未就绪时直接失败,不降级浏览器运行时。**
|
|
160
176
|
|
|
161
|
-
业务 `plugins`
|
|
162
|
-
|
|
163
|
-
|
|
177
|
+
- 业务 `plugins` 已有 `builtin_tools` key → 内置工具不注册,`error` 事件带原因
|
|
178
|
+
- 同一页面只支持一个启用了内置插件的 `BotClient`(插件表全局)
|
|
179
|
+
- 平台注册时 `functionCode` 不可改名;参数定义见 `BUILTIN_TOOL_SCHEMAS`
|
|
164
180
|
|
|
165
181
|
| functionCode | 名称 | 运行环境 |
|
|
166
182
|
| --- | --- | --- |
|
|
@@ -168,19 +184,19 @@ const client = new BotClient(token, {
|
|
|
168
184
|
| `read_file` | 读取文件 | 浏览器、端侧宿主 |
|
|
169
185
|
| `write_file` | 写入文件 | 浏览器、端侧宿主 |
|
|
170
186
|
| `append_file` | 追加文件 | 浏览器、端侧宿主 |
|
|
171
|
-
| `run_file` | 执行文件 |
|
|
187
|
+
| `run_file` | 执行文件 | 浏览器(`.py` / `.sh` / `.bash`)或宿主(另含 `.js` / `.mjs` / `.cjs`) |
|
|
172
188
|
| `edit_file` | 修改文件 | 浏览器、端侧宿主 |
|
|
173
189
|
| `grep` | 搜索文件 | 浏览器、端侧宿主 |
|
|
174
190
|
| `find` | 查找文件 | 浏览器、端侧宿主 |
|
|
175
|
-
| `load_skill` | 加载技能 |
|
|
176
|
-
| `read_skill_resource` | 读取技能资源 |
|
|
191
|
+
| `load_skill` | 加载技能 | 浏览器、端侧宿主 |
|
|
192
|
+
| `read_skill_resource` | 读取技能资源 | 浏览器、端侧宿主 |
|
|
177
193
|
| `list_skill_files` | 列出技能文件 | 端侧宿主 |
|
|
178
194
|
| `grep_skill` | 搜索技能内容 | 端侧宿主 |
|
|
179
|
-
| `run_skill_script` | 运行技能脚本 | 同 `run_file
|
|
195
|
+
| `run_skill_script` | 运行技能脚本 | 同 `run_file`(无沙箱时 501,不降级) |
|
|
180
196
|
|
|
181
197
|
### 展示工具步骤
|
|
182
198
|
|
|
183
|
-
`message:action`
|
|
199
|
+
`message:action` 出现内置工具步骤时,用已注册插件编码和 `BUILTIN_TOOL_SCHEMAS` 换成中文名;只展示相对路径和参数,**不展示工程绝对路径**:
|
|
184
200
|
|
|
185
201
|
```ts
|
|
186
202
|
import {
|
|
@@ -191,23 +207,23 @@ import {
|
|
|
191
207
|
const schema = pluginCode === getRegisteredLocalFilesPluginCode()
|
|
192
208
|
? BUILTIN_TOOL_SCHEMAS[funcCode as keyof typeof BUILTIN_TOOL_SCHEMAS]
|
|
193
209
|
: undefined;
|
|
194
|
-
// schema
|
|
210
|
+
// schema 存在时展示 schema.name 与参数里的 path / destPath
|
|
195
211
|
```
|
|
196
212
|
|
|
197
|
-
|
|
213
|
+
业务插件步骤按接入方自己的规则展示。
|
|
198
214
|
|
|
199
215
|
## 本地工作文件夹
|
|
200
216
|
|
|
201
|
-
内置插件 `localFiles
|
|
217
|
+
内置插件 `localFiles`:助手只能访问一个文件夹——网页由用户选择,或由宿主指定。
|
|
202
218
|
|
|
203
|
-
|
|
219
|
+
### 路径约定
|
|
204
220
|
|
|
205
|
-
-
|
|
206
|
-
-
|
|
207
|
-
-
|
|
208
|
-
- `/dev`、`/usr`、`/bin`
|
|
221
|
+
- 工具参数:工作区内以 `/` 开头的绝对路径,或相对工作区根的相对路径(如 `/说明.md`、`notes/a.md`)
|
|
222
|
+
- **不要**约定 `input` / `output` / `uploads` / `tmp` 作为根目录
|
|
223
|
+
- 平台技能不在工程里;`load_skill` 等读端侧缓存;`read_file` / `shell` 等拒绝第一段为 `skills` 的路径
|
|
224
|
+
- `/dev`、`/usr`、`/bin` 仍是系统路径;脚本内请用相对路径
|
|
209
225
|
|
|
210
|
-
|
|
226
|
+
网页选文件夹依赖 File System Access API,仅 Chromium(Chrome / Edge / WebView2)的安全上下文(https 或 localhost)。宿主自管工程目录时不弹选择框,见[宿主通道](#宿主通道)。
|
|
211
227
|
|
|
212
228
|
### 开启
|
|
213
229
|
|
|
@@ -217,18 +233,14 @@ const client = new BotClient(token, {
|
|
|
217
233
|
builtinPlugins: {
|
|
218
234
|
localFiles: {
|
|
219
235
|
enabled: true,
|
|
220
|
-
// 'file-system-access'
|
|
221
|
-
// 'host-bridge'
|
|
236
|
+
// 'file-system-access'(默认):弹目录选择框
|
|
237
|
+
// 'host-bridge':目录由宿主推送
|
|
222
238
|
backend: 'file-system-access',
|
|
223
239
|
onApprovalRequired: async (request) => openApprovalDialog(request),
|
|
224
|
-
//
|
|
225
|
-
sensitiveRulesAppend: [],
|
|
240
|
+
sensitiveRulesAppend: [], // 只能追加,不能放宽基线
|
|
226
241
|
downloadUrlAllowlistAppend: [],
|
|
227
|
-
//
|
|
228
|
-
limits: { maxReadBytes: 512 * 1024 },
|
|
229
|
-
// 为 true 时 search_text 可以不指定子目录、搜整个工作区。默认 false
|
|
242
|
+
limits: { maxReadBytes: 512 * 1024 }, // 只能调小
|
|
230
243
|
allowWorkspaceWideTextSearch: false,
|
|
231
|
-
// 无宿主沙箱时,是否在页面里跑 shell / python(默认 true)
|
|
232
244
|
commandRuntime: {
|
|
233
245
|
browser: {
|
|
234
246
|
enabled: true,
|
|
@@ -242,69 +254,57 @@ const client = new BotClient(token, {
|
|
|
242
254
|
const workspace = client.localWorkspace;
|
|
243
255
|
```
|
|
244
256
|
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
### 十一个工具
|
|
248
|
-
|
|
249
|
-
路径见上文约定。`..`、反斜杠、越出工作区的路径返回 403。
|
|
250
|
-
|
|
251
|
-
**`read_file`** 读取 UTF-8 文本。`start_line` / `end_line` 从 1 计、含端点。不超过 81920 字节时按原文返回。超出后,JSON、XML、SVG、CSV、TSV 返回结构概览和短预览,`truncated` 为 true;指定了行范围则返回该片段。PDF 和图片只返回摘要,不返回正文。
|
|
252
|
-
|
|
253
|
-
**`write_file`** 覆盖写入。`content` 按 UTF-8 计不超过 81920 字节,超出返回 413。父目录会自动创建。需确认。
|
|
257
|
+
说明:
|
|
254
258
|
|
|
255
|
-
|
|
259
|
+
- `transfer` 仍可供旧上传下载实现;当前内置工具不走这套
|
|
260
|
+
- 宿主沙箱可用条件:`workspace.sandbox.state === "ready"` 且 `protocol === 1`(不在 `commandRuntime` 里配)
|
|
261
|
+
- `capabilities` 仅兼容旧 workspace 消息
|
|
256
262
|
|
|
257
|
-
|
|
263
|
+
### 内置工具参考
|
|
258
264
|
|
|
259
|
-
|
|
265
|
+
路径见上文。`..`、反斜杠、越出工作区 → 403。
|
|
260
266
|
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
267
|
+
| 工具 | 要点 |
|
|
268
|
+
| --- | --- |
|
|
269
|
+
| `read_file` | UTF-8;`start_line` / `end_line` 从 1 计。≤81920 字节原文;超出则结构化预览(`truncated`)。PDF / 图片只返回摘要 |
|
|
270
|
+
| `write_file` | 覆盖写;`content` ≤81920 字节(超则 413);自动建父目录;需确认 |
|
|
271
|
+
| `append_file` | 追加;文件不存在则创建;追加本身无字节上限 |
|
|
272
|
+
| `edit_file` | 替换第一处完全匹配的 `old_text`;找不到时 `message` 带最近片段行号 |
|
|
273
|
+
| `grep` | 递归搜索,基本正则;`data.matches` 含路径与行号 |
|
|
274
|
+
| `find` | 文件名通配(同 `find -name`);`data.files` 一行一个路径 |
|
|
275
|
+
| `shell` | 每次新 shell,只保留上次 cwd;≤20000 字;退出码在 `data.exitCode`;联网由宿主策略决定 |
|
|
276
|
+
| `run_file` | 浏览器:`.py` / `.sh` / `.bash`;`.js*` 不支持。宿主:另支持 `.js` / `.mjs` / `.cjs` |
|
|
277
|
+
| `load_skill` | 读已发布版 `SKILL.md` + 文件清单;技能在工程外缓存 |
|
|
278
|
+
| `read_skill_resource` | 技能包内相对路径;目录返回清单;`grep:正则` 搜全文 |
|
|
279
|
+
| `list_skill_files` | 列技能包或子目录 |
|
|
280
|
+
| `grep_skill` | 技能包内基本正则搜索 |
|
|
281
|
+
| `run_skill_script` | 仅宿主沙箱;`args` 为位置参数;无沙箱 → 501,不降级 |
|
|
274
282
|
|
|
275
283
|
### 浏览器里授权
|
|
276
284
|
|
|
277
|
-
`backend
|
|
285
|
+
`backend: 'file-system-access'` 时,构造会自己 `restore()`。订阅 `workspace:changed` 画按钮。**`pick()` / `requestPermission()` 必须在点击回调里同步调用**,中间不能有 `await`。
|
|
278
286
|
|
|
279
287
|
```ts
|
|
280
288
|
workspace.on('workspace:changed', ({ status, displayName }) => {
|
|
281
289
|
renderFolder(status, displayName);
|
|
282
290
|
});
|
|
283
291
|
|
|
284
|
-
selectButton.onclick = () => {
|
|
285
|
-
|
|
286
|
-
};
|
|
287
|
-
|
|
288
|
-
restoreButton.onclick = () => {
|
|
289
|
-
workspace.requestPermission().catch(console.error);
|
|
290
|
-
};
|
|
291
|
-
|
|
292
|
-
closeButton.onclick = () => {
|
|
293
|
-
workspace.clear().catch(console.error);
|
|
294
|
-
};
|
|
292
|
+
selectButton.onclick = () => { workspace.pick().catch(console.error); };
|
|
293
|
+
restoreButton.onclick = () => { workspace.requestPermission().catch(console.error); };
|
|
294
|
+
closeButton.onclick = () => { workspace.clear().catch(console.error); };
|
|
295
295
|
```
|
|
296
296
|
|
|
297
297
|
| status | 含义 | 按钮 |
|
|
298
298
|
| --- | --- | --- |
|
|
299
|
-
| `unsupported` |
|
|
300
|
-
| `none` |
|
|
301
|
-
| `prompt` |
|
|
302
|
-
| `granted` |
|
|
303
|
-
| `denied` |
|
|
299
|
+
| `unsupported` | 无目录选择能力 | 提示不可用 |
|
|
300
|
+
| `none` | 未选过 | 「选择工作文件夹」→ `pick()` |
|
|
301
|
+
| `prompt` | 有上次文件夹,需重新授权 | 「恢复访问」→ `requestPermission()` |
|
|
302
|
+
| `granted` | 可用;`displayName` 为文件夹名 | 「更换」→ `pick()`,「关闭」→ `clear()` |
|
|
303
|
+
| `denied` | 用户拒绝 | 「选择工作文件夹」→ `pick()` |
|
|
304
304
|
|
|
305
|
-
`pick()`
|
|
305
|
+
`pick()` 取消时返回 `false`,状态不变。`displayName` 只有文件夹名,无绝对路径。
|
|
306
306
|
|
|
307
|
-
|
|
307
|
+
首次选择前展示外发说明(助手会读该文件夹,内容可能发给模型;改 / 传 / 下前再确认)。SDK 只记「已看过」,文案由界面定:
|
|
308
308
|
|
|
309
309
|
```ts
|
|
310
310
|
selectButton.onclick = () => {
|
|
@@ -314,8 +314,7 @@ selectButton.onclick = () => {
|
|
|
314
314
|
}
|
|
315
315
|
openDisclosure({
|
|
316
316
|
onContinue: () => {
|
|
317
|
-
//
|
|
318
|
-
workspace.pick().catch(console.error);
|
|
317
|
+
workspace.pick().catch(console.error); // 仍须在本次点击里同步调用
|
|
319
318
|
disclosureAcked = true;
|
|
320
319
|
void workspace.acknowledgeDisclosure();
|
|
321
320
|
},
|
|
@@ -325,36 +324,27 @@ selectButton.onclick = () => {
|
|
|
325
324
|
const disclosureAcked = await workspace.isDisclosureAcknowledged();
|
|
326
325
|
```
|
|
327
326
|
|
|
328
|
-
|
|
327
|
+
不要先 `await acknowledgeDisclosure()` 再 `pick()`。`acknowledgeDisclosure` 按 `applicationId` 记忆。
|
|
329
328
|
|
|
330
329
|
### 读和写文件
|
|
331
330
|
|
|
332
|
-
`status === 'granted'`
|
|
331
|
+
`status === 'granted'` 后用 `workspace.files`。路径如 `notes/a.md` 或 `/notes/a.md`;根用 `''` 或省略。`..`、盘符、空字符会失败。
|
|
333
332
|
|
|
334
333
|
| 方法 | 作用 |
|
|
335
334
|
| --- | --- |
|
|
336
|
-
| `list(path?)` |
|
|
337
|
-
| `stat(path?)` |
|
|
338
|
-
| `read(path)` |
|
|
339
|
-
| `readText(path)` |
|
|
340
|
-
| `url(path)` | 给 `<img
|
|
341
|
-
| `releaseUrl(url)` |
|
|
342
|
-
| `write(path, source)` |
|
|
343
|
-
| `append(path, source)` |
|
|
344
|
-
| `mkdir(path)` |
|
|
345
|
-
| `remove(path, options?)` |
|
|
346
|
-
| `move(from, to)` |
|
|
347
|
-
|
|
348
|
-
`list`
|
|
349
|
-
|
|
350
|
-
| 字段 | 含义 |
|
|
351
|
-
| --- | --- |
|
|
352
|
-
| `name` | 这一层的名字 |
|
|
353
|
-
| `path` | 相对工作区根的路径。根目录本身是 `''` |
|
|
354
|
-
| `kind` | `file` 或 `directory` |
|
|
355
|
-
| `size` | 字节数。网页里选的文件夹,列目录时常常没有这一项 |
|
|
356
|
-
| `lastModified` | 修改时间。同样可能没有 |
|
|
357
|
-
| `sensitive` | 是否为敏感文件,例如 `.env`、密钥、证书。目录恒为 `false` |
|
|
335
|
+
| `list(path?)` | 只列一层 |
|
|
336
|
+
| `stat(path?)` | 文件或目录 |
|
|
337
|
+
| `read(path)` | 整个文件 → `Blob` |
|
|
338
|
+
| `readText(path)` | UTF-8 文本 |
|
|
339
|
+
| `url(path)` | 给 `<img>` / `<video>` / `<audio>`;浏览器自拉字节 |
|
|
340
|
+
| `releaseUrl(url)` | 不再显示时调用;引用归零后作废 |
|
|
341
|
+
| `write(path, source)` | 覆盖写(字符串 / `Uint8Array` / 字节流);自动建父目录 |
|
|
342
|
+
| `append(path, source)` | 追加;不存在则创建 |
|
|
343
|
+
| `mkdir(path)` | 逐级创建;已存在则 noop |
|
|
344
|
+
| `remove(path, options?)` | 删文件或目录;非空目录需 `{ recursive: true }` |
|
|
345
|
+
| `move(from, to)` | 移动 / 重命名;`to` 为完整新路径,父目录须已存在 |
|
|
346
|
+
|
|
347
|
+
`list` / `stat` 每项字段:`name`、`path`(相对根,根为 `''`)、`kind`、`size?`、`lastModified?`、`sensitive`。
|
|
358
348
|
|
|
359
349
|
```ts
|
|
360
350
|
const entries = await workspace.files.list('notes');
|
|
@@ -363,49 +353,41 @@ await workspace.files.write('notes/a.md', `${text}\n`);
|
|
|
363
353
|
await workspace.files.move('notes/a.md', 'notes/b.md');
|
|
364
354
|
```
|
|
365
355
|
|
|
366
|
-
|
|
356
|
+
失败抛 `ToolError`,用 `code` 与 `data.reason` 区分;文案无本机绝对路径。
|
|
367
357
|
|
|
368
|
-
| `data.reason` |
|
|
358
|
+
| `data.reason` | 何时 |
|
|
369
359
|
| --- | --- |
|
|
370
|
-
| `workspace_not_granted` |
|
|
371
|
-
| `path_outside_workspace` |
|
|
372
|
-
| `sensitive_file` |
|
|
360
|
+
| `workspace_not_granted` | 未授权(失效时 `status` 先离开 `granted`) |
|
|
361
|
+
| `path_outside_workspace` | 越界 |
|
|
362
|
+
| `sensitive_file` | 读改敏感文件或为其签发地址;`list`/`stat` 仍返回且 `sensitive: true` |
|
|
373
363
|
|
|
374
|
-
`
|
|
364
|
+
内存快照工作区(`attachFileSnapshot`)可读写列目录;`mkdir` / `remove` / `move` → 501,且不回写磁盘。
|
|
375
365
|
|
|
376
|
-
`write
|
|
366
|
+
`write` / `append` / `mkdir` / `remove` / `move` 成功后发 `files:changed`。
|
|
377
367
|
|
|
378
368
|
### 目录树
|
|
379
369
|
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
```ts
|
|
383
|
-
async function loadDirectory(dir = '') {
|
|
384
|
-
return workspace.files.list(dir);
|
|
385
|
-
}
|
|
386
|
-
```
|
|
387
|
-
|
|
388
|
-
记下用户已经展开的目录。文件有变化时,SDK 大约每 150 毫秒把要重读的目录合成一次 `files:changed`:
|
|
370
|
+
展开哪层就列哪层。文件变化时 SDK 约每 150ms 合并一次 `files:changed`:
|
|
389
371
|
|
|
390
372
|
| 来源 | `paths` |
|
|
391
373
|
| --- | --- |
|
|
392
|
-
|
|
|
393
|
-
|
|
|
394
|
-
| `shell
|
|
395
|
-
|
|
|
374
|
+
| 网页 `FileSystemObserver` | 变化目录;根为 `''` |
|
|
375
|
+
| 宿主 `fs-changed` | 宿主给出的相对目录 |
|
|
376
|
+
| `shell` / `run_file` / `run_skill_script` 结束 | `[]` = 重读根 + 已展开各层 |
|
|
377
|
+
| `files` 写入 / 建目录 / 删除 / 移动 | 被改项的父目录 |
|
|
396
378
|
|
|
397
379
|
```ts
|
|
398
380
|
const expanded = new Set<string>();
|
|
399
381
|
|
|
382
|
+
async function loadDirectory(dir = '') {
|
|
383
|
+
return workspace.files.list(dir);
|
|
384
|
+
}
|
|
385
|
+
|
|
400
386
|
workspace.on('files:changed', (event) => {
|
|
401
387
|
const dirs = event.paths.length ? event.paths : ['', ...expanded];
|
|
402
388
|
dirs.forEach((dir) => void loadDirectory(dir));
|
|
403
389
|
});
|
|
404
|
-
```
|
|
405
390
|
|
|
406
|
-
有的环境看不到资源管理器里的改动。窗口重新得到焦点时,重读根目录和已展开的目录。助手改完文件时还会发 `tool:finish`,用它刷新被改文件的父目录。
|
|
407
|
-
|
|
408
|
-
```ts
|
|
409
391
|
window.addEventListener('focus', () => {
|
|
410
392
|
if (document.visibilityState === 'hidden') return;
|
|
411
393
|
['', ...expanded].forEach((dir) => void loadDirectory(dir));
|
|
@@ -419,15 +401,19 @@ workspace.on('tool:finish', (event) => {
|
|
|
419
401
|
});
|
|
420
402
|
```
|
|
421
403
|
|
|
422
|
-
|
|
404
|
+
目录树只展示名字与层级。打开文本用 `read` / `readText`;媒体与 PDF 用 `url`,离开时 `releaseUrl`。**不要** `read` 再转地址(占内存)。地址只给界面,不要写进发给模型的内容。
|
|
423
405
|
|
|
424
406
|
```ts
|
|
425
407
|
const url = await workspace.files.url('shots/a.png');
|
|
426
|
-
// <img src={url} alt="" loading="lazy" />
|
|
427
408
|
workspace.files.releaseUrl(url);
|
|
428
409
|
```
|
|
429
410
|
|
|
430
|
-
|
|
411
|
+
| 后端 | 地址形态 |
|
|
412
|
+
| --- | --- |
|
|
413
|
+
| 沙箱 | `http://127.0.0.1:<端口>/file/<票据>`;每次读磁盘当前内容;30 分钟无读过期 |
|
|
414
|
+
| 网页文件夹 | `blob:`;内容停在取址那一刻,文件改了需再 `url` |
|
|
415
|
+
|
|
416
|
+
仅图片 / 音视频 / PDF;其他类型失败。
|
|
431
417
|
|
|
432
418
|
### 确认弹窗
|
|
433
419
|
|
|
@@ -438,10 +424,10 @@ workspace.files.releaseUrl(url);
|
|
|
438
424
|
| `functionCode` | `apply_patch` / `write_file` / `upload_file` / `download_file` |
|
|
439
425
|
| `path` | 工作区相对路径 |
|
|
440
426
|
| `workspaceName` | 文件夹名 |
|
|
441
|
-
| `preview` |
|
|
442
|
-
| `signal` |
|
|
427
|
+
| `preview` | 给用户看的内容 |
|
|
428
|
+
| `signal` | 停止回答、切会话、换/关文件夹、确认超时(默认 5 分钟)时 abort |
|
|
443
429
|
|
|
444
|
-
`
|
|
430
|
+
仅严格 `true` 继续;`false` / 抛错 / 超时均拒绝,原文件不变。`signal` abort 时关弹窗并 `resolve(false)`。
|
|
445
431
|
|
|
446
432
|
```ts
|
|
447
433
|
import type { ApprovalRequest } from '@glodon-aiot/bot-client-sdk';
|
|
@@ -461,52 +447,48 @@ function openApprovalDialog(request: ApprovalRequest): Promise<boolean> {
|
|
|
461
447
|
}
|
|
462
448
|
```
|
|
463
449
|
|
|
464
|
-
`preview.type` 决定弹窗内容:
|
|
465
|
-
|
|
466
450
|
| preview | 展示 |
|
|
467
451
|
| --- | --- |
|
|
468
|
-
| `{ type: 'text', created: true, after }` |
|
|
469
|
-
| `{ type: 'text', created: false, before, after }` |
|
|
470
|
-
| `{ type: 'upload', name, size, target: 'session' }` |
|
|
471
|
-
| `{ type: 'download', source, name?, size?, overwrite }` |
|
|
472
|
-
|
|
473
|
-
`tool:approval-required` 只有 `requestId`、`functionCode`、`path`、`approvalId`,不含文件内容。预览文本只出现在 `request.preview` 里。
|
|
452
|
+
| `{ type: 'text', created: true, after }` | 新建,展示 `after` |
|
|
453
|
+
| `{ type: 'text', created: false, before, after }` | 修改,按行对比 |
|
|
454
|
+
| `{ type: 'upload', name, size, target: 'session' }` | 文件名、大小、路径,目标为当前会话 |
|
|
455
|
+
| `{ type: 'download', source, name?, size?, overwrite }` | 来源标签、文件名、大小、保存路径、是否覆盖 |
|
|
474
456
|
|
|
475
|
-
|
|
457
|
+
`tool:approval-required` 只有 id / 函数码 / 路径 / `approvalId`,不含文件内容。界面若晚于 `BotClient` 挂载:挂载前回调直接 `false`,挂载后再 `setApprovalHandler`。
|
|
476
458
|
|
|
477
459
|
### 进度与未授权
|
|
478
460
|
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
工作区事件一览(载荷里没有文件内容):
|
|
461
|
+
- 上传下载:订 `tool:progress`(`stage`:`reading` \| `uploading` \| `downloading` \| `writing` \| `done`)
|
|
462
|
+
- `done` / `tool:finish` / `tool:error` / `tool:cancelled` 时清掉该条进度
|
|
463
|
+
- 未授权工具调用 → `tool:error`,`reason === 'workspace_not_granted'`;亮起选择/恢复按钮;`granted` 后关掉;**不要**自动重放失败调用
|
|
484
464
|
|
|
485
465
|
| 事件 | 载荷要点 |
|
|
486
466
|
| --- | --- |
|
|
487
467
|
| `workspace:changed` | `status`、`displayName` |
|
|
488
|
-
| `files:changed` | `paths
|
|
468
|
+
| `files:changed` | `paths`;空数组 = 根 + 已展开 |
|
|
489
469
|
| `tool:start` | `requestId`、`functionCode`、`path` |
|
|
490
|
-
| `tool:approval-required` |
|
|
491
|
-
| `tool:progress` |
|
|
492
|
-
| `tool:finish` |
|
|
493
|
-
| `tool:error` |
|
|
470
|
+
| `tool:approval-required` | 同上 + `approvalId` |
|
|
471
|
+
| `tool:progress` | 同上 + `stage`、`loaded`、`total` |
|
|
472
|
+
| `tool:finish` | 同上 + `code` |
|
|
473
|
+
| `tool:error` | 同上 + `code`、`message`、`reason` |
|
|
494
474
|
| `tool:cancelled` | `requestId`、`functionCode`、`path` |
|
|
495
475
|
|
|
496
|
-
`workspace.on`
|
|
476
|
+
`workspace.on` 返回取消订阅函数。载荷不含文件内容。
|
|
497
477
|
|
|
498
478
|
## 命令和脚本
|
|
499
479
|
|
|
500
|
-
`shell
|
|
480
|
+
`shell` / `run_file` 共用执行器选择(`runnerFor`)。`run_skill_script` 只用注入执行器或已就绪宿主沙箱,**无沙箱不降级浏览器**。
|
|
481
|
+
|
|
482
|
+
成功时 `data`:`{ exitCode, stdout, stderr, cwd? }`。`exitCode !== 0` 仍算工具成功(`code === 0`)。跨命令只保留 cwd。浏览器运行时同一工作区一次一条;连上沙箱后并发由 `exec.maxConcurrent` 决定,超限工具 `code` 429。
|
|
501
483
|
|
|
502
484
|
### 执行器选择顺序
|
|
503
485
|
|
|
504
|
-
1.
|
|
505
|
-
2.
|
|
506
|
-
3.
|
|
507
|
-
4.
|
|
486
|
+
1. 注入的 `LocalWorkspace.commandRunner`(测试 / 自定义)
|
|
487
|
+
2. 沙箱直连:宿主已授权且 `sandbox.state === 'ready'`、`protocol === 1` → 页面连 `ws://127.0.0.1`
|
|
488
|
+
3. 浏览器运行时:无宿主 WebView 且 `commandRuntime.browser.enabled`(默认 true)→ just-bash + Pyodide
|
|
489
|
+
4. 否则 → **501**
|
|
508
490
|
|
|
509
|
-
|
|
491
|
+
宿主已授权但沙箱未就绪时**不**降级。`starting` = 启动中;失败看 `sandbox.message`。协议非 1 另发 `error`。收到 `bye` / `exited` / `failed` 后在途调用以 `AbortError` 失败且不重放;等新的 `ready` 再用新地址与令牌。
|
|
510
492
|
|
|
511
493
|
参照宿主:`examples/qt-workspace-host`。
|
|
512
494
|
|
|
@@ -514,46 +496,43 @@ function openApprovalDialog(request: ApprovalRequest): Promise<boolean> {
|
|
|
514
496
|
|
|
515
497
|
| 能力 | 行为 |
|
|
516
498
|
| --- | --- |
|
|
517
|
-
| shell |
|
|
518
|
-
| Python |
|
|
519
|
-
| Node / `.js` |
|
|
499
|
+
| shell | 按需加载 just-bash,读写已授权工作区 |
|
|
500
|
+
| Python | Pyodide Worker;白名单:numpy、pandas、matplotlib、pillow、lxml |
|
|
501
|
+
| Node / `.js` | 明确报错 |
|
|
520
502
|
| pip / 任意第三方 | 不支持 |
|
|
521
503
|
|
|
522
|
-
默认 CDN(路径带版本,长缓存;可用配置覆盖):
|
|
523
|
-
|
|
524
504
|
| 配置项 | 默认 |
|
|
525
505
|
| --- | --- |
|
|
526
506
|
| `commandRuntime.browser.bashModuleURL` | `https://cv-cdn.obs.cn-north-4.myhuaweicloud.com/glodon/libs/just-bash/3.6.0/just-bash.mjs` |
|
|
527
507
|
| `commandRuntime.browser.pyodideIndexURL` | `https://cv-cdn.obs.cn-north-4.myhuaweicloud.com/glodon/libs/pyodide/314.0.7/` |
|
|
528
508
|
|
|
529
|
-
|
|
509
|
+
CSP:放行 OBS 的 `script-src` / `connect-src`;Pyodide 需 `worker-src blob:`。
|
|
530
510
|
|
|
531
|
-
浏览器运行时用于能力对齐与防误用,**不是**与宿主 MXC 同级的强隔离。
|
|
532
|
-
|
|
533
|
-
**打包注意:** just-bash / Pyodide **不打进** SDK npm 包。请使用包的 **ES 入口**(`import` / `exports.import`)。CJS 产物里动态 `import(url)` 的 `webpackIgnore` 注释可能被压缩去掉,webpack 从 CJS 入口打包时可能错误解析该导入。
|
|
511
|
+
浏览器运行时用于能力对齐与防误用,**不是**与宿主 MXC 同级的强隔离。just-bash / Pyodide **不打进** npm 包;请用 **ES 入口**。CJS + webpack 可能丢掉 `webpackIgnore` 导致错误解析动态 `import`。
|
|
534
512
|
|
|
535
513
|
### 宿主沙箱(摘要)
|
|
536
514
|
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
-
|
|
540
|
-
-
|
|
541
|
-
-
|
|
542
|
-
-
|
|
543
|
-
-
|
|
544
|
-
-
|
|
545
|
-
-
|
|
546
|
-
-
|
|
547
|
-
-
|
|
548
|
-
- 细节与 Windows 步骤见 [`local-workspace-windows-host.md`](../bot-client-ui/docs/local-workspace-windows-host.md)
|
|
515
|
+
完整协议、策略 JSON、平台隔离差异见 **[`@glodon-aiot/workspace-sandbox` README](../workspace-sandbox/README.md)**。此处只列页面侧要点:
|
|
516
|
+
|
|
517
|
+
- 启动:`workspace-sandbox --listen --root <工程> --origin <页面来源>`;联网 / pip / 并发由 `--policy` 定,页面不能改
|
|
518
|
+
- 宿主职责:启停、读 ready、可选 status / policy、shutdown(3 秒后杀进程组)、把退出告诉页面;**不中转**文件与命令
|
|
519
|
+
- 页面用 `sandbox.url` / `sandbox.token` 直连 `ws://127.0.0.1`(无 `wss://`);CSP `connect-src` 放行 `ws://127.0.0.1:*`
|
|
520
|
+
- `auth` 与后续 `policy` 推送含摘要:`exec.maxConcurrent`、`network.mode` / `allow`、`packages.python.enabled`(不含上游代理与镜像)
|
|
521
|
+
- 崩溃推送 `sandbox.state: "exited"`;同一次打开最多自动重启一次
|
|
522
|
+
- 默认断网;`allowlist` 拒绝项写在 `stderr`;允许时 `pip install` 直装工程 venv,不必先改 `open`
|
|
523
|
+
- 平台技能:进会话按编排核对版本;页面用 `client.token` 下载 ZIP,经已认证 WS 调 `installSkill`(沙箱收不到令牌)。缓存在用户目录,不在工程内
|
|
524
|
+
- 分发:`Resources/node/`(Node 24)+ `Resources/workspace-sandbox/`;可选 `python/`
|
|
525
|
+
- Windows 细节:[`local-workspace-windows-host.md`](../bot-client-ui/docs/local-workspace-windows-host.md)
|
|
549
526
|
|
|
550
527
|
## 宿主通道
|
|
551
528
|
|
|
552
|
-
|
|
529
|
+
端侧宿主 = 内嵌此页的桌面程序(内核不限)。
|
|
553
530
|
|
|
554
|
-
`localFiles.backend
|
|
531
|
+
`localFiles.backend === 'host-bridge'` 时,宿主在页面脚本前提供 `globalThis.__glodonHostBridge`(或 `registerHostBridge`):`postMessage` / `addEventListener('message')` / `removeEventListener('message')`。有一致的 `chrome.webview` 时可自动使用。
|
|
555
532
|
|
|
556
|
-
通道名固定 `glodon-workspace
|
|
533
|
+
- 通道名固定 `glodon-workspace`
|
|
534
|
+
- 消息只有相对路径与文件夹名;绝对路径留在宿主
|
|
535
|
+
- 页面不再出现「选择工作文件夹」;宿主未推送时 `status` 为 `unsupported`
|
|
557
536
|
|
|
558
537
|
页面加载后先发:
|
|
559
538
|
|
|
@@ -561,7 +540,7 @@ function openApprovalDialog(request: ApprovalRequest): Promise<boolean> {
|
|
|
561
540
|
{ "channel": "glodon-workspace", "type": "hello" }
|
|
562
541
|
```
|
|
563
542
|
|
|
564
|
-
|
|
543
|
+
宿主立刻回当前工程,之后每次打开 / 关闭再推:
|
|
565
544
|
|
|
566
545
|
```json
|
|
567
546
|
{
|
|
@@ -580,36 +559,37 @@ function openApprovalDialog(request: ApprovalRequest): Promise<boolean> {
|
|
|
580
559
|
}
|
|
581
560
|
```
|
|
582
561
|
|
|
583
|
-
`granted
|
|
562
|
+
- `granted: false` → 页面断开工作区
|
|
563
|
+
- `sandbox.state` 还可为 `starting` / `failed` / `exited`;`failed` 带固定 `message`,无令牌与绝对路径
|
|
564
|
+
- 是否直连只看 `sandbox.state`、`url`、`token`、`protocol`;`capabilities` / `sandboxVersion` 仅为兼容 / 诊断
|
|
565
|
+
- 页面**不**向宿主发文件或命令操作
|
|
584
566
|
|
|
585
|
-
|
|
567
|
+
目录增删时推送(`paths` 相对工程根;`""` = 根;空数组 = 重读已展开全部):
|
|
586
568
|
|
|
587
569
|
```json
|
|
588
570
|
{ "channel": "glodon-workspace", "type": "fs-changed", "paths": ["notes", ""] }
|
|
589
571
|
```
|
|
590
572
|
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
文件和命令不经过宿主。页面连上沙箱后发协议 1 的文本帧和二进制分片:`read` 按 `offset` / `maxBytes` 取窗口,`write` 按偏移写入临时文件再改名。占用时原文件不变。命令输出流式返回,SDK 每个流只保留最后 16000 字符;若有 `logPath`,截断说明里带上 `tmp/sandbox-exec/<id>.log`。
|
|
573
|
+
脚本跑完、用户在资源管理器改文件都应推送。Qt 示例默不监视 `.git` / `node_modules` / `__pycache__` 内部。
|
|
594
574
|
|
|
595
|
-
|
|
575
|
+
数据面:页面连沙箱后发协议 1 帧(见 sandbox README)。取消只发 `{ "op": "cancel", "id" }`,不关套接字。`bye` / `exited` / `failed` 后在途失败且不重放。
|
|
596
576
|
|
|
597
577
|
## 安全与限额
|
|
598
578
|
|
|
599
|
-
|
|
579
|
+
敏感文件不可读、不可写、不可上传、不可运行,也不出现在搜索结果里。`list` / `stat` 仍返回并标 `sensitive: true`;真正读写 → 403,`reason: sensitive_file`,`data.ruleId` 为规则 ID。
|
|
600
580
|
|
|
601
|
-
|
|
581
|
+
基线 `SDK_SENSITIVE_BASELINE` 始终生效;`sensitiveRulesAppend` 只能再加:
|
|
602
582
|
|
|
603
583
|
| 匹配 | 规则 |
|
|
604
584
|
| --- | --- |
|
|
605
585
|
| 文件名 | `.env*`、`*.pem`、`*.key`、`*.p12`、`*.pfx`、`id_rsa*`、`id_ed25519*`、`id_ecdsa*`、`.credentials`、`.npmrc`、`.pypirc` |
|
|
606
586
|
| 整段相对路径 | `**/.aws/credentials`、`**/.ssh/**` |
|
|
607
587
|
|
|
608
|
-
|
|
588
|
+
追加规则:`pattern` 为 `/` 分隔 glob;`match` 省略比文件名,`path` 比整段路径;`operations` 可限 `read` / `write` / `search`;`source` 为 `product` 或 `enterprise`。
|
|
609
589
|
|
|
610
|
-
下载 URL
|
|
590
|
+
下载 URL 仅 https,且域名在允许列表或其子域(默认仅 `glodon.com`)。`downloadUrlAllowlistAppend` 追加后缀。拒 IP / localhost / 带账号密码的地址;重定向同样校验;不带 Cookie。
|
|
611
591
|
|
|
612
|
-
`limits`
|
|
592
|
+
`limits` 只能调小(`DEFAULT_LIMITS`):
|
|
613
593
|
|
|
614
594
|
| 项 | 默认 |
|
|
615
595
|
| --- | --- |
|
|
@@ -618,33 +598,33 @@ function openApprovalDialog(request: ApprovalRequest): Promise<boolean> {
|
|
|
618
598
|
| `maxTransferBytes` | 50 MB |
|
|
619
599
|
| `maxSearchResults` | 200 |
|
|
620
600
|
| `maxConcurrentRequests` | 4 |
|
|
621
|
-
| `toolTimeoutMs` | 30
|
|
622
|
-
| `commandTimeoutMs` | 10
|
|
601
|
+
| `toolTimeoutMs` | 30 秒(读写改文件) |
|
|
602
|
+
| `commandTimeoutMs` | 10 分钟(`shell` / `run_file` / `run_skill_script`,同时传给沙箱) |
|
|
623
603
|
| `searchTimeoutMs` | 60 秒 |
|
|
624
604
|
| `transferTimeoutMs` | 10 分钟 |
|
|
625
|
-
| `approvalTimeoutMs` | 5
|
|
605
|
+
| `approvalTimeoutMs` | 5 分钟(不计入工具超时) |
|
|
626
606
|
|
|
627
|
-
|
|
607
|
+
停止回答、更换或关闭文件夹都会取消进行中的调用;确认框应关闭。
|
|
628
608
|
|
|
629
|
-
已知限制:File System Access API
|
|
609
|
+
已知限制:File System Access API 不暴露符号链接目标;`upload_file` 返回 `fileId` 即视为成功。
|
|
630
610
|
|
|
631
611
|
## 错误码
|
|
632
612
|
|
|
633
|
-
|
|
613
|
+
工具结果 `{ code, message, data? }`。界面主要看 `tool:error` 的 `code` 与 `reason`。
|
|
634
614
|
|
|
635
615
|
| code | 含义 |
|
|
636
616
|
| --- | --- |
|
|
637
617
|
| 0 | 成功 |
|
|
638
|
-
| 400 |
|
|
639
|
-
| 403 |
|
|
640
|
-
| 404 |
|
|
618
|
+
| 400 | 参数错误、二进制、非 UTF-8、`search_text` 范围为整个工作区 |
|
|
619
|
+
| 403 | 未授权 / 越界 / 敏感文件 / 用户拒绝 / 无确认回调 / 下载地址不允许 |
|
|
620
|
+
| 404 | 不存在 |
|
|
641
621
|
| 408 | 超时 |
|
|
642
|
-
| 409 | `expectedHash`
|
|
622
|
+
| 409 | `expectedHash` 不一致,或下载目标已存在 |
|
|
643
623
|
| 413 | 超过大小上限 |
|
|
644
|
-
| 429 |
|
|
645
|
-
| 499 |
|
|
646
|
-
| 500 |
|
|
647
|
-
| 501 |
|
|
624
|
+
| 429 | 并发过多,或已有脚本在运行 |
|
|
625
|
+
| 499 | 已取消 |
|
|
626
|
+
| 500 | 内部异常(消息无路径与调用栈) |
|
|
627
|
+
| 501 | 无可用命令执行器 |
|
|
648
628
|
|
|
649
629
|
## 开发
|
|
650
630
|
|
package/dist/es/package.json.mjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const e = "@glodon-aiot/bot-client-sdk", s = "3.26.0-alpha.
|
|
1
|
+
const e = "@glodon-aiot/bot-client-sdk", s = "3.26.0-alpha.31", t = "glodoncv", i = "aiot bot client js sdk", n = "module", g = !1, o = [
|
|
2
2
|
"aiot",
|
|
3
3
|
"bot",
|
|
4
4
|
"bot client",
|
|
@@ -68,7 +68,7 @@ const e = "@glodon-aiot/bot-client-sdk", s = "3.26.0-alpha.30", t = "glodoncv",
|
|
|
68
68
|
access: "public",
|
|
69
69
|
registry: "https://registry.npmjs.org/"
|
|
70
70
|
}, y = {
|
|
71
|
-
"@glodon-aiot/apis": "^3.26.0-alpha.
|
|
71
|
+
"@glodon-aiot/apis": "^3.26.0-alpha.31",
|
|
72
72
|
axios: "0.24.0",
|
|
73
73
|
buffer: "^6.0.3",
|
|
74
74
|
dayjs: "^1.11.13",
|
package/dist/lib/index.js
CHANGED
|
@@ -374,7 +374,7 @@ ${JSON.stringify(n.headers)}`}function Oo(n){const e=n.trim();if(!e)return{};if(
|
|
|
374
374
|
`):JSON.stringify(n)}function $o(n){return d(this,null,function*(){if(!(n.headers.get("content-type")||"").includes("text/event-stream")||!n.body)return n.text();const t=n.body.getReader(),i=new TextDecoder;let s="";try{for(;s.length<2e6;){const{done:r,value:o}=yield t.read();if(r)break;s+=i.decode(o,{stream:!0});const a=s.split(/\n\n/).filter(c=>/^\s*data:/m.test(c));if(a.length>0)return a[a.length-1]}return s}finally{yield t.cancel().catch(()=>{})}})}function rt(n,e,t,i,s){return d(this,null,function*(){const r=E(w({},n.headers),{"content-type":"application/json",accept:"application/json, text/event-stream"});t!=null&&t.id&&(r["mcp-session-id"]=t.id),t!=null&&t.protocol&&(r["mcp-protocol-version"]=t.protocol);const o=yield s(n.url,{method:"POST",headers:r,body:JSON.stringify(e),signal:Fo(i)}),a=yield $o(o);if(!o.ok)throw new Error(`MCP HTTP ${o.status}: ${a.slice(0,300)}`);const c=Oo(a),l=o.headers.get("mcp-session-id");return t&&l&&(t.id=l),c})}function ot(n){const e=n.error;if(!e||typeof e!="object")return;const t=e.message;return typeof t=="string"&&t?t:"MCP 调用失败"}function Po(n){const e=n instanceof Error?n.message:String(n);return/session/i.test(e)||e.includes("MCP HTTP 404")}function Je(n,e,t){return d(this,null,function*(){const i=Ji(n),s=st.get(i);if(s!=null&&s.id)return s;const r={protocol:"2024-11-05",nextId:1},o=yield rt(n,{jsonrpc:"2.0",id:r.nextId,method:"initialize",params:{protocolVersion:r.protocol,capabilities:{},clientInfo:{name:"bot-client-sdk",version:"1.0.0"}}},r,e,t);r.nextId+=1;const a=ot(o);if(a)throw new Error(a);const c=o.result;if(c&&typeof c=="object"){const l=c.protocolVersion;typeof l=="string"&&l&&(r.protocol=l)}return yield rt(n,{jsonrpc:"2.0",method:"notifications/initialized"},r,e,t),st.set(i,r),r})}function Do(t){return d(this,arguments,function*(n,e=fetch){var a;const i=yield Je(n,void 0,e),s=yield rt(n,{jsonrpc:"2.0",id:i.nextId,method:"tools/list",params:{}},i,void 0,e);i.nextId+=1;const r=ot(s);if(r)throw new Error(r);const o=s.result;return((a=o==null?void 0:o.tools)!=null?a:[]).filter(c=>c.name).map(c=>({name:c.name,description:c.description||"",inputSchema:c.inputSchema||{type:"object",properties:{}}}))})}function Bo(r,o,a,c){return d(this,arguments,function*(n,e,t,i,s=fetch){const l=Ji(n);let h=yield Je(n,i,s);const u=()=>rt(n,{jsonrpc:"2.0",id:h.nextId,method:"tools/call",params:{name:e,arguments:t&&typeof t=="object"?t:{}}},h,i,s);let f;try{f=yield u(),h.nextId+=1}catch(b){if(!Po(b))throw b;st.delete(l),h=yield Je(n,i,s),f=yield u(),h.nextId+=1}let g=ot(f);if(g&&/session/i.test(g)&&(st.delete(l),h=yield Je(n,i,s),f=yield u(),h.nextId+=1,g=ot(f)),g)throw new Error(g);return No(f.result)})}const we=new U("[LocalMcp] ",!0);function jo(n){const e=n==null?void 0:n.mcps;return Array.isArray(e)?e.filter(t=>t&&typeof t=="object"&&t.runtime==="local"&&t.id):[]}function Uo(n,e,t){return n==null||n.includes(e)?!0:!!t&&n.includes(t)}function qo(n){if(!n||typeof n!="object")return{};const e={};for(const[t,i]of Object.entries(n))typeof i=="string"&&(e[t]=i);return e}function Ho(n){var o,a;if(!n||typeof n!="object")return null;const e=n;if(typeof e.code=="number"&&e.code!==200)return null;const t=e.data&&typeof e.data=="object"?e.data:e,i=typeof t.code=="string"?t.code:"",s=i?(o=t.mcpServers)==null?void 0:o[i]:void 0,r=typeof(s==null?void 0:s.url)=="string"?s.url:void 0;return{code:i,deployType:typeof((a=t.deployConfig)==null?void 0:a.type)=="string"?t.deployConfig.type:void 0,url:r,headers:qo(s==null?void 0:s.headers)}}function zo(s,r,o){return d(this,arguments,function*(n,e,t,i=fetch){const a=n.replace(/\/$/,""),c=e.startsWith("Bearer ")?e:`Bearer ${e}`,l=yield i(`${a}/mcpmgr/v1/mcpserver/${encodeURIComponent(t)}`,{headers:{Authorization:c}}),h=yield l.json().catch(()=>null);if(!l.ok)throw new Error(`MCP 详情 HTTP ${l.status}`);const u=Ho(h);if(!u)throw new Error("MCP 详情不可用");return u})}function Wo(n,e){return(t,i,s)=>{const r=Xr(n);if(!r){i({code:500,message:"缺少 MCP 地址"});return}Bo(r,n,t,s==null?void 0:s.signal,e).then(o=>i({code:0,message:"ok",data:o})).catch(o=>{i({code:500,message:o instanceof Error?o.message:String(o)})})}}function Vo(n){return d(this,null,function*(){var a,c;const e=(a=n.fetchImpl)!=null?a:fetch,t=n.initMcp?Object.keys((c=n.initMcp.mcpServers)!=null?c:{}):null,i=jo(n.arrange);if(!i.length){we.log("编排里没有 runtime=local 的 MCP,不发送 register_client_mcp_tools"),Hn([]),De();return}const s=yield Promise.all(i.map(l=>d(this,null,function*(){const h=l.id;try{const u=yield zo(n.apiRoot,n.token,h,e);if(!Uo(t,h,u.code))return null;if(u.deployType!=="streamableHttp"||!u.url||!u.code)return we.log("skip local mcp",h),null;const f={code:u.code,url:u.url,headers:u.headers},g=yield Do(f,e);return g.length?{code:u.code,url:u.url,binding:f,tools:g}:null}catch(u){return we.error("local mcp failed",h,u instanceof Error?u.message:String(u)),null}})));if(n.isCurrent&&!n.isCurrent())return;const r={},o=[];for(const l of s)if(l){r[l.code]={type:"streamableHttp",url:l.url,tools:l.tools};for(const h of l.tools)o.push({name:h.name,binding:l.binding,handler:Wo(h.name,e)})}if(Hn(o),De(),!Object.keys(r).length||!n.socket){we.log("没有可注册的本地 MCP 工具,不发送 register_client_mcp_tools");return}we.log("发送 register_client_mcp_tools",Object.entries(r).map(([l,h])=>`${l}: ${h.tools.map(u=>u.name).join(", ")}`).join("; ")),n.socket.emit("register_client_mcp_tools",{mcpServers:r},l=>{const h=l&&typeof l=="object"?l.code:void 0;typeof h=="number"&&h!==200&&we.error("register_client_mcp_tools",h)})})}const H=new U("[AgentSession] ");function Jn(n){if(typeof n!="string")return n;const e=n.trim();if(e)try{return JSON.parse(e)}catch(t){return n}}function Qn(n){return n==null||n===""||typeof n=="object"&&!Array.isArray(n)&&Object.keys(n).length===0}function Go(n,e){const t=Jn(n==null?void 0:n.query);if(!Qn(t))return t;const i=Jn(e);return Qn(i)&&t!=null?t:i}class Xo extends pn{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"inflightCalls",new Set);y(this,"localMcpTicket",0)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this.socket&&t(!0);const i={version:"1.0",stream:JSON.stringify(exports.configuration.stream),appId:this._applicationId,sessionId:this.id,Authorization:`${this.token}`,userMode:exports.configuration.debug?be.Debug:be.Normal},s=new URL(exports.configuration.apiRoot),r=yield ds.io(s.origin,{path:s.pathname.replace("api","socketio")+"/copilot",query:i,transports:["websocket"]});r.on("connect",()=>{H.log("socket:connect"),this.event.emit("socket:connect"),r.emit("init")}),r.on("disconnect",()=>{H.log("socket:disconnect"),this.event.emit("socket:disconnect"),this._ready=!1}),r.on("ready",o=>{if(o.code===200){H.log("ready");const a=exports.configuration.debug?be.Debug:be.Normal;a===be.Debug&&o.userMode,this._ready||(this._ready=!0,this.event.emit("ready")),this.frozen=!1,this.registerMcpFromClientConfig(),this.registerLocalMcp(),t(!0)}else{this._ready&&(this._ready=!1);const a=new Error($e.SocketConnectionFailed);H.error("error",a),this.event.emit("error",a),t(!1)}}),r.on("action",(o,a)=>d(this,null,function*(){var v;if(this._stopAnswer||!this.id)return;const{type:c,data:{runnerIsClient:l,pluginCode:h,funcCode:u,parameters:f,requestBody:g}}=o,b=this.messages[this.messages.length-1];if(!b.messageId)b.actions||(b.actions=[]),b.actions[o.data.step-1]||(b.actions[o.data.step-1]=[]),b.actions[o.data.step-1].push(o),this.event.emit("message:action",{messageId:b.messageId,action:o}),this.event.emit("message:updated",b);else{const _={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[[o]],comment:{isAgree:0},isReplying:!0};this.pushMessage(_),this.event.emit("message:action",{messageId:_.messageId,action:o})}if(this.inactivating){const _=new Error($e.Inactive);H.warn("error",_),this.event.emit("error",_)}else if(c==="FUNCTION_CALL"&&l){H.log(`calling function ${u} of plugin ${h} with argument:
|
|
375
375
|
${JSON.stringify(f)}`);const _=(v=exports.configuration.plugins)==null?void 0:v[h];if(!_){a({code:404,message:"没有找到插件。"});return}const x=_[u];if(typeof x!="function"){a({code:404,message:"没有找到插件方法。"});return}const S=Go(f,g);this.invokeClientPlugin(x,S,a,{requestId:o.requestId,pluginCode:h,functionCode:u})}})),r.on("answer",o=>{if(!this._stopAnswer)if(o.data.code!==200&&(o.data.index=-1),o.data.stream||o.data.stream===void 0){let a=this.messages[this.messages.length-1];if(a&&a.role===I.ChatMessageRole.Robot)this.handleStreamAnswer(o.data,a),this.messages[this.messages.length-1]=a,this.event.emit("message:content",a),this.event.emit("message:updated",a),a.index===-1&&(a.isReplying=!1,this.event.emit("answer:finish",a));else{const c={content:"",role:I.ChatMessageRole.Robot,reference:[],searchReference:[],messageId:"",sessionId:this.id,messageTime:qt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""};this.handleStreamAnswer(o.data,c),this.pushMessage(c),this.event.emit("message:content",c),c.index===-1&&(c.isReplying=!1,this.event.emit("answer:finish",c))}}else if(o.data.updateSession&&this.data&&(this.data=w(w({},this.data),o.data.updateSession),this.event.emit("data:updated",this.data)),o.data.index===-1){let a=this.messages[this.messages.length-1];if(a&&!a.messageId)a=w(w({},a),o.data),this.event.emit("message:content",a),this.event.emit("message:updated",a),this.event.emit("answer:finish",a);else{const c=w({messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data);this.event.emit("message:content",c),this.pushMessage(c),this.event.emit("answer:finish",c)}}else{let a=this.messages[this.messages.length-1];a&&!a.messageId?(a=w(w({},a),o.data),this.messages[this.messages.length-1]=a,this.event.emit("message:content",a),this.event.emit("message:updated",a)):(this.pushMessage(w({messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!1,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0},o.data)),this.event.emit("message:content",o.data))}}),r.on("reference",o=>d(this,null,function*(){if(this._stopAnswer)return;if(!this.id){const f=new Error($e.IdUndefined);H.error(f),this.event.emit("error",f),this.frozen=!1;return}const{type:a,data:c,requestId:l}=o,h=this.messages.findIndex(f=>f.messageId===l&&f.role===I.ChatMessageRole.User);if(h<0)return;const u=h+1;if(u>=this.messages.length){const f={messageId:"",content:"",role:I.ChatMessageRole.Robot,sessionId:this.id,reference:[],searchReference:[],isLoading:!0,messageTime:"",actions:[],comment:{isAgree:0},isReplying:!0};this.pushMessage(f)}a==="KG"?(this.messages[u]=E(w({},this.messages[u]),{reference:c.knowledgeReference}),yield this.fillMessageReference(this.messages[u]),this.event.emit("message:reference",c.knowledgeReference),this.event.emit("message:updated",this.messages[u])):a==="WEB_SEARCH"&&(this.messages[u]=E(w({},this.messages[u]),{searchReference:c.knowledgeReference}),this.event.emit("message:searchreference",c.searchReference),this.event.emit("message:updated",this.messages[u]))})),this.socket=r,r.open()}))}registerMcpFromClientConfig(){return exports.configuration.mcp?new Promise((t,i)=>{if(!this.socket){i("socket is undefined");return}this.socket.emit("add_mcp_servers",exports.configuration.mcp,s=>{s.code===200?(Object.keys(s.data).forEach(r=>{s.data[r].code!==200&&console.error(r,"MCP Server 注册失败。",s.data[r])}),t(!0)):(console.error("MCP Server 注册失败。",s),i(s))})}):Promise.resolve(!0)}registerLocalMcp(){var s,r;const t=this.socket;if(!t)return;const i=++this.localMcpTicket;Vo({arrange:(r=(s=this.application)==null?void 0:s.arrange)==null?void 0:r[0],initMcp:exports.configuration.mcp,apiRoot:exports.configuration.apiRoot,token:this.token,socket:t,isCurrent:()=>i===this.localMcpTicket}).catch(o=>{H.error("local mcp",o instanceof Error?o.message:String(o))})}addMcpServers(t){return d(this,null,function*(){return this.ready?this.socket?new Promise((i,s)=>{this.socket&&this.socket.emit("add_mcp_servers",t,r=>{r.code===200?(Object.keys(r.data).forEach(o=>{r.data[o].code!==200&&console.error(o,"MCP Server 注册失败。",r.data[o])}),i(!0)):(console.error("MCP Server 注册失败。",r),s(r))})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}listMcpServers(){return d(this,null,function*(){return this.ready?this.socket?new Promise((t,i)=>{this.socket&&this.socket.emit("list_mcp_servers",s=>{s.code===200?t(s.data):i(s)})}):(console.error(" socket is undefined."),Promise.reject("socket is undefined")):(console.error("session is not avalible."),Promise.reject("session is not avalible"))})}sendQuestion(t,i){return d(this,null,function*(){var r,o,a;this.convertKnowledgesToChatFormat(this.knowledges);let s=E(w({},t),{promptVariables:this.promptVariables.filter(c=>c.type===I.PromptVariableType.User).reduce((c,l)=>E(w({},c),{[l.key]:l.value}),{}),systemPromptVariables:this.promptVariables.filter(c=>c.type===I.PromptVariableType.System).reduce((c,l)=>E(w({},c),{[l.key]:l.value}),{}),knowledges:(r=this.knowledges)==null?void 0:r.map(c=>c.id),enableTitleSummary:this.resolveEnableTitleSummary()});if(!this.active){if(yield this.activate(),!this.socket){const c=new Error($e.SocketConnectionFailed);return H.warn("error",c),this.event.emit("error",c),!1}(o=this.socket)==null||o.emit("question",s);return}(a=this.socket)==null||a.emit("question",s)})}invokeClientPlugin(t,i,s,r){const o=new AbortController;this.inflightCalls.add(o);let a=!1;const c=(...h)=>{a||(a=!0,this.inflightCalls.delete(o),!(this._stopAnswer||o.signal.aborted)&&s(...h))},l={requestId:r.requestId||ne.v4(),applicationId:this._applicationId,sessionId:this.id,pluginCode:r.pluginCode,functionCode:r.functionCode,signal:o.signal};try{const h=t(i,c,l);h&&typeof h.catch=="function"&&h.catch(u=>{H.error("client plugin failed",u),c({code:500,message:"客户端插件执行失败。"})})}catch(h){H.error("client plugin failed",h),c({code:500,message:"客户端插件执行失败。"})}}abortClientPluginCalls(){const t=Array.from(this.inflightCalls);this.inflightCalls.clear(),t.forEach(i=>i.abort())}stopAnswer(){var t;this.abortClientPluginCalls(),(t=this.socket)==null||t.emit("stop_answer")}inactivate(t=!1){return this.abortClientPluginCalls(),super.inactivate(t)}destroy(){return this.abortClientPluginCalls(),super.destroy()}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}function Yo(n,e){return d(this,null,function*(){const t=n.getReader();let i;for(;!(i=yield t.read()).done;)e(i.value)})}function Ko(n){let e,t,i,s=!1,r;return function(a){e===void 0?(e=a,t=0,i=-1,r=!1):e=Qo(e,a);const c=e.length;let l=0;for(;t<c;){s&&(e[t]===10&&(l=++t),s=!1);let h=-1;for(;t<c&&h===-1;++t)switch(e[t]){case 58:i===-1&&(i=t-l);break;case 13:s=!1,t+4<c&&e[t+1]===10&&e[t+2]!==13&&e[t-1]!==10&&e[t-2]!==13&&(r=!0);case 10:h=t;break}if(h===-1)break;n(e.subarray(l,h),i,r),l=t,i=-1,r=!1}l===c?e=void 0:l!==0&&(e=e.subarray(l),t-=l)}}function Jo(n,e,t){let i=Zn();const s=new TextDecoder;return function(o,a,c){if(o.length===0)t==null||t(i),i=Zn();else if(a>0){const l=s.decode(o.subarray(0,a)),h=a+(o[a+1]===32?2:1);let u=s.decode(o.subarray(h));switch(c&&(u+=`
|
|
376
376
|
`),l){case"data":i.data=i.data?i.data+`
|
|
377
|
-
`+u:u;break;case"event":i.event=u;break;case"id":n(i.id=u);break;case"retry":const f=parseInt(u,10);isNaN(f)||e(i.retry=f);break}}}}function Qo(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Zn(){return{data:"",event:"",id:"",retry:void 0}}const Ut="text/event-stream",Zo=1e3,ei="last-event-id";function ti(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=bn(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const b=w({},t);b.accept||(b.accept=Ut);let v;function _(){v.abort(),document.hidden||P()}a||document.addEventListener("visibilitychange",_);let x=Zo,S=0;function T(){document.removeEventListener("visibilitychange",_),window.clearTimeout(S),v.abort()}e==null||e.addEventListener("abort",()=>{T(),f()});const M=c!=null?c:window.fetch,ee=i!=null?i:ea;function P(){return d(this,null,function*(){var L;v=new AbortController;try{const A=yield M(n,E(w({},l),{headers:b,signal:v.signal}));yield ee(A),yield Yo(A.body,Ko(Jo(R=>{R?b[ei]=R:delete b[ei]},R=>{x=R},s))),r==null||r(),T(),f()}catch(A){if(!v.signal.aborted)try{const R=(L=o==null?void 0:o(A))!=null?L:x;window.clearTimeout(S),S=window.setTimeout(P,R)}catch(R){T(),g(R)}}})}P()})}function ea(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(Ut)))throw new Error(`Expected content-type to be ${Ut}, Actual: ${e}`)}const ni=new U("[DialogSession] ");class ta extends pn{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=E(w({},s),{stream:exports.configuration.stream});ti(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(h){if(!h.data.includes('{"code": ')){let f={};try{f=JSON.parse(h.data)}catch(b){}(f==null?void 0:f.mtype)==="search"?c.searchReference.push(f):c.content=c.content+h.data;const g={content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:qt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(o==null?void 0:o.onmessage)&&o.onmessage(g)}const u=JSON.parse(h.data);if(c.reference=u.data.reference,c.searchReference=u.data.searchReference,c.messageTime=u.data.messageTime,c.messageId=u.data.messageId,c.llmModel=u.data.llmModel,c.content=u.data.content,c.code=u.code,u.code===200){const f={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(c),a&&a({code:c.code,message:c.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const h={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(h)}})})}postChatV3EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c=this,l={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},h=E(w({},s),{stream:exports.configuration.stream});ti(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(u){return u.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(u){if(!u.data&&!u.event&&!u.id&&!u.retry)return;let f={};try{f=JSON.parse(u.data)}catch(g){console.error("parse eventData to JSON failed. ",u.data)}if(f.code!==200)return l.index=-1,l.code=f.code,l.message=f.message,o!=null&&o.onmessage&&o.onmessage(l),a&&a({code:f.code,message:f.message});c.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(w({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return d(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:a}=t,{stream:c,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const h=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:l,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===I.PromptVariableType.User).reduce((f,g)=>E(w({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===I.PromptVariableType.System).reduce((f,g)=>E(w({},f),{[g.key]:g.value}),{}),knowledges:h,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:a};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{ni.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===I.ChatMessageRole.Robot?(g=w(w({},g),f),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>d(this,null,function*(){this._stopAnswer||(ni.log(f,"onclose"),this.event.emit("answer:finish",f))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}const na="@glodon-aiot/bot-client-sdk",ia="3.26.0-alpha.30",sa="glodoncv",ra="aiot bot client js sdk",oa="module",aa=!1,ca=["aiot","bot","bot client","sdk"],la=["dist"],da="./dist/es/index.mjs",ha="./dist/lib/index.js",ua="./dist/src/index.d.ts",fa={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},pa="MIT",ma={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js","build:just-bash":"node scripts/build-just-bash.mjs","upload:just-bash":"node scripts/build-just-bash.mjs && node scripts/upload-cdn-libs.cjs just-bash","build:pyodide":"node scripts/build-pyodide.mjs","upload:pyodide":"node scripts/build-pyodide.mjs && node scripts/upload-cdn-libs.cjs pyodide",test:"vitest run","test:watch":"vitest"},ga={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","just-bash":"3.6.0","npm-run-all":"^4.1.5",prettier:"2.7.1",pyodide:"314.0.7","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4",vitest:"^0.34.6"},ya={access:"public",registry:"https://registry.npmjs.org/"},wa={"@glodon-aiot/apis":"^3.26.0-alpha.30",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},va={name:na,version:ia,author:sa,description:ra,type:oa,sideEffects:aa,keywords:ca,files:la,module:da,main:ha,typings:ua,exports:fa,license:pa,scripts:ma,devDependencies:ga,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ya,dependencies:wa},ii=new U("[BotClient] ");class ba{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new dn);y(this,"cvforceApi");y(this,"_applicationId");y(this,"_application",null);y(this,"_sessions",[]);y(this,"_activeSession");y(this,"_ready",!1);y(this,"_questionContextMaxLength",4e3);y(this,"_promptVariables",[]);y(this,"_localWorkspace");y(this,"_disconnectHost");if(this._token=e,this.lazyload=i,this.sdkConfigs=s,Dt(t,{refreshBuiltinPlugins:!1}),this._applicationId=it(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Dt(E(w({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===I.ApplicationTypes.Dialog||(r==null?void 0:r.type)===I.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}setupLocalWorkspace(){var s,r;const e=(s=exports.configuration.builtinPlugins)==null?void 0:s.localFiles;if(!(e!=null&&e.enabled)){zn(void 0),De();return}const t=[],i=(r=e.backend)!=null?r:"file-system-access";if(i!=="file-system-access"&&i!=="host-bridge")t.push(new Error(`[LocalFiles] 不支持的 backend:${e.backend}`));else{const o=no(exports.configuration.apiRoot,this.token,(a,c)=>ii.error(c));this._localWorkspace=new Ki({applicationId:this._applicationId,config:e,store:Xi(),picker:i==="host-bridge"?null:void 0,transfer:un(()=>this.cvforceApi,()=>o)}),zn(this._localWorkspace),this._localWorkspace.platformSkills=new oo({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var a,c,l,h;return(h=(l=(c=(a=this._application)==null?void 0:a.arrange)==null?void 0:c[0])==null?void 0:l.skills)!=null?h:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var c;const a=(c=this._localWorkspace)==null?void 0:c.adapter;return a instanceof Be?a.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=co(this._localWorkspace):this._localWorkspace.restore()}t.push(...De()),t.length&&Promise.resolve().then(()=>t.forEach(o=>this.event.emit("error",o)))}get localWorkspace(){return this._localWorkspace}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return d(this,null,function*(){var t,i,s,r,o;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(i=this.sdkConfigs.ui)==null?void 0:i.version,sdkVersion:va.version}).then(a=>(typeof a.arrange[0].thinkingModeOpen!="boolean"&&(a.arrange[0].thinkingModeOpen=!0),typeof a.arrange[0].thinkingTextOpen!="boolean"&&(a.arrange[0].thinkingTextOpen=!0),E(w({},a),{arrange:[E(w({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:I.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:I.PromptVariableType.System})]).then(([a,c])=>[...a,...c]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Ui(exports.configuration.apiRoot,this.token,(e,t)=>ii.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=it(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,i,s,r){return d(this,null,function*(){const o=this;return new Promise((a,c)=>{const l=h=>d(this,null,function*(){if(h===I.ApplicationTypes.Agent)a(new Xo(e,t,i,s,r,o));else if(h===I.ApplicationTypes.Dialog)a(new ta(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${h}`)});if(this.ready){if(!this._application)throw Error("client is not ready");l(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");l(this._application.type)},!0)})})}getArtifacts(e){return d(this,null,function*(){var r,o;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const i=this._sessions.find(a=>a.id===t);if(i)return i.getArtifacts();const s=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(o=s==null?void 0:s.artifacts)!=null?o:[]})}getSessions(e){return d(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>d(this,null,function*(){const o=[];for(const a of r){const c=this._sessions.find(l=>l.id===a.id);if(c)c.data=a,this._application?c.application=this._application:yield c.loadApplicationInfo(),o.push(c);else{const l=yield this.createSession(this.token,a.id,a,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const a=[...this._sessions,...o],c=new Map;for(const l of a)c.set(l.id,l);return this.sessions=Array.from(c.values()),this.sessions}else return this.sessions=o,o}));if(this.ready){if(!this._application)throw Error("_application is null");t(s())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(s())},!0)})})}loadSession(e="",t){return d(this,null,function*(){var s,r;this.checkReady(),(r=(s=this._localWorkspace)==null?void 0:s.platformSkills)==null||r.sync();let i=this.sessions.find(o=>o.id===e);if(i||(i=yield this.createSession(this.token,e,t),this._sessions.push(i)),this._activeSession){if(this._activeSession===i)return i;this._activeSession.inactivate()}return i.id?(this._activeSession=i,yield i.activate()):i.addEventListener("data:loaded",()=>{this._activeSession!==i&&(i==null||i.activate(),this._activeSession=i)},!0),i})}reload(){return this.loadApplication().then(()=>d(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return d(this,null,function*(){yield this.reload();let t=this._sessions.find(i=>i.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,i="top_time desc, sort_status desc, updated_at desc"){return d(this,null,function*(){let s=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!s){console.warn("setTop session failed.");return}return yield s.setTop(t),this.getSessions({order:i})})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return d(this,null,function*(){this.checkReady();let i=-1;if(typeof e=="string"?i=this._sessions.findIndex(s=>s.id===e):i=this._sessions.findIndex(s=>s.id===e.id),i>-1){const s=this._sessions[i];t&&(yield s.delete()),this._sessions.splice(i,1)}else console.warn("session delete failed, session is not exist.")})}clean(){var e;(e=this._disconnectHost)==null||e.call(this),this._disconnectHost=void 0,this._sessions.forEach(t=>t.destroy()),this.sessions=[]}}class _a{constructor(e,t={},i){y(this,"code");y(this,"description","");y(this,"loaded",!1);y(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}const X="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",Y={type:"string",enum:[Se],description:`工作区 ID。省略时按 ${Se} 处理,传其他值会被拒绝。`},K=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),At={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},Qi={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${X}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:Y,path:K('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${X}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要读取的文件。"),startLine:{type:"integer",minimum:1,description:"起始行(从 1 开始,含)。"},endLine:{type:"integer",minimum:1,description:"结束行(含)。"},maxBytes:{type:"integer",minimum:1,description:"返回内容的最大字节数,不超过 1 MiB。"},encoding:{type:"string",enum:["utf-8","gbk","gb18030"],description:"文本编码,默认 utf-8。"}}}},stat_file:{functionCode:"stat_file",name:"查看本地文件信息",description:`${X}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${X}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:Y,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:K("搜索起点目录,默认工作区根目录。"),maxDepth:{type:"integer",minimum:1,maximum:16,description:"最大目录深度,默认 8。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"}}}},search_text:{functionCode:"search_text",name:"搜索本地文本",description:`${X}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:Y,path:K("搜索范围,可以是文件或目录。"),query:{type:"string",minLength:1,description:"要查找的文本。"},caseSensitive:{type:"boolean",description:"是否区分大小写,默认否。"},isRegex:{type:"boolean",description:"暂不支持正则,传 true 会返回 501。"},glob:{type:"string",description:"只搜索匹配该 glob 的文件,如 *.md。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"},contextLines:{type:"integer",minimum:0,maximum:3,description:"附带的上下文行数,默认 0。"}}}},apply_patch:{functionCode:"apply_patch",name:"修改本地文件",description:`${X}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:Y,path:K("要修改的文件。"),expectedHash:At,edits:{type:"array",minItems:1,description:"按顺序应用的修改。",items:{type:"object",required:["oldText","newText"],properties:{oldText:{type:"string",minLength:1,description:"要替换的原文,需包含足够上下文以保证唯一。"},newText:{type:"string",description:"替换后的文本。"},replaceAll:{type:"boolean",description:"是否替换所有出现位置,默认否。"}}}}}}},write_file:{functionCode:"write_file",name:"写入本地文件",description:`${X}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:Y,path:K("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:At,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${X}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${X}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:Y,destPath:K("保存位置(文件路径)。"),source:{type:"object",required:["type"],description:"下载来源。type 为 url 时必填 url;type 为 sessionFile 或 platformFile 时必填 fileId。",properties:{type:{type:"string",enum:["sessionFile","platformFile","url"],description:"sessionFile:当前会话文件;platformFile:平台文件(upload_file 返回的 fileId);url:https 地址。"},fileId:{type:"string",description:"type 为 sessionFile 或 platformFile 时必填,不能只传 type。"},url:{type:"string",description:"type 为 url 时必填,填写完整 https 地址。不能只传 type。默认只允许 glodon.com 及其子域。"}}},overwrite:{type:"boolean",description:"目标已存在时是否覆盖,默认否。"},expectedHash:At}}}},ka=new TextEncoder;function ie(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const Ea=(n,e)=>d(exports,null,function*(){const t=Z(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new p(m.BadRequest,"目标是文件,不是目录。");const s=ie(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ie(n.limit,hi,1,ui),o=yield e.adapter.listEntries(t,e.signal);o.sort((c,l)=>c.kind!==l.kind?c.kind==="directory"?-1:1:c.name<l.name?-1:c.name>l.name?1:0);const a=o.slice(s,s+r).map(c=>{const l=Wi(t,c.name),h={name:c.name,path:l,kind:c.kind};return c.kind==="file"&&(h.size=c.size,h.lastModified=c.lastModified,e.sensitive.isSensitive(l)&&(h.sensitive=!0)),h});return{data:{path:t,entries:a,total:o.length,hasMore:s+a.length<o.length}}});function Sa(n,e,t){return pe(this,null,function*(){var a;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){F(t);const{done:c,value:l}=yield new se(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
|
|
377
|
+
`+u:u;break;case"event":i.event=u;break;case"id":n(i.id=u);break;case"retry":const f=parseInt(u,10);isNaN(f)||e(i.retry=f);break}}}}function Qo(n,e){const t=new Uint8Array(n.length+e.length);return t.set(n),t.set(e,n.length),t}function Zn(){return{data:"",event:"",id:"",retry:void 0}}const Ut="text/event-stream",Zo=1e3,ei="last-event-id";function ti(n,h){var u=h,{signal:e,headers:t,onopen:i,onmessage:s,onclose:r,onerror:o,openWhenHidden:a,fetch:c}=u,l=bn(u,["signal","headers","onopen","onmessage","onclose","onerror","openWhenHidden","fetch"]);return new Promise((f,g)=>{const b=w({},t);b.accept||(b.accept=Ut);let v;function _(){v.abort(),document.hidden||P()}a||document.addEventListener("visibilitychange",_);let x=Zo,S=0;function T(){document.removeEventListener("visibilitychange",_),window.clearTimeout(S),v.abort()}e==null||e.addEventListener("abort",()=>{T(),f()});const M=c!=null?c:window.fetch,ee=i!=null?i:ea;function P(){return d(this,null,function*(){var L;v=new AbortController;try{const A=yield M(n,E(w({},l),{headers:b,signal:v.signal}));yield ee(A),yield Yo(A.body,Ko(Jo(R=>{R?b[ei]=R:delete b[ei]},R=>{x=R},s))),r==null||r(),T(),f()}catch(A){if(!v.signal.aborted)try{const R=(L=o==null?void 0:o(A))!=null?L:x;window.clearTimeout(S),S=window.setTimeout(P,R)}catch(R){T(),g(R)}}})}P()})}function ea(n){const e=n.headers.get("content-type");if(!(e!=null&&e.startsWith(Ut)))throw new Error(`Expected content-type to be ${Ut}, Actual: ${e}`)}const ni=new U("[DialogSession] ");class ta extends pn{constructor(t,i="",s,r,o,a){super(t,i,s,r,o,a);y(this,"ctrl",new AbortController)}prepareConnection(){return new Promise(t=>d(this,null,function*(){this._ready=!0,this.event.emit("ready"),this.frozen=!1,t(!0)}))}postChatV2EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1},l=E(w({},s),{stream:exports.configuration.stream});ti(`${exports.configuration.apiRoot}/chat/v2/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(l),openWhenHidden:!0,signal:r,onopen(h){return h.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(h){if(!h.data.includes('{"code": ')){let f={};try{f=JSON.parse(h.data)}catch(b){}(f==null?void 0:f.mtype)==="search"?c.searchReference.push(f):c.content=c.content+h.data;const g={content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:qt(new Date).format("YYYY-MM-DD HH:mm:ss"),comment:{isAgree:0},isReplying:!0};return(o==null?void 0:o.onmessage)&&o.onmessage(g)}const u=JSON.parse(h.data);if(c.reference=u.data.reference,c.searchReference=u.data.searchReference,c.messageTime=u.data.messageTime,c.messageId=u.data.messageId,c.llmModel=u.data.llmModel,c.content=u.data.content,c.code=u.code,u.code===200){const f={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,isReplying:!0};o!=null&&o.onmessage&&o.onmessage(f)}else return o!=null&&o.onclose&&o.onclose(c),a&&a({code:c.code,message:c.message})},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const h={code:c.code,content:c.content,role:1,reference:c.reference,searchReference:c.searchReference,messageId:c.messageId,sessionId:i,messageTime:c.messageTime,comment:{isAgree:0},isReplying:!1,index:-1};o!=null&&o.onclose&&o.onclose(h)}})})}postChatV3EventSource(t,i,s,r,o,a){return d(this,null,function*(){const c=this,l={code:0,content:"",role:I.IHistoryRole.Robot,sessionId:i,reference:[],searchReference:[],messageTime:"",llmModel:"",comment:{isAgree:0},isReplying:!1,reasoningContent:"",thinkingSecs:"",thinkingStatus:"",searchingStatus:""},h=E(w({},s),{stream:exports.configuration.stream});ti(`${exports.configuration.apiRoot}/chat/v3/chat?applicationId=${t}&sessionId=${i}`,{method:"POST",headers:{Authorization:`Bearer ${this.token}`,"Content-Type":"application/json"},body:JSON.stringify(h),openWhenHidden:!0,signal:r,onopen(u){return u.ok&&o!=null&&o.onopen&&o.onopen(),Promise.resolve()},onmessage(u){if(!u.data&&!u.event&&!u.id&&!u.retry)return;let f={};try{f=JSON.parse(u.data)}catch(g){console.error("parse eventData to JSON failed. ",u.data)}if(f.code!==200)return l.index=-1,l.code=f.code,l.message=f.message,o!=null&&o.onmessage&&o.onmessage(l),a&&a({code:f.code,message:f.message});c.handleStreamAnswer(f,l),o!=null&&o.onmessage&&o.onmessage(l)},onerror(){o!=null&&o.onerror&&o.onerror()},onclose(){const u=E(w({},l),{isReplying:!1});o!=null&&o.onclose&&o.onclose(u)}})})}sendQuestion(t,i){return d(this,null,function*(){const{content:s,fileIds:r,oldMessageId:o,imageContent:a}=t,{stream:c,referenceFirst:l}=i;if(this.active||(yield this.activate()),this._id){const h=this.convertKnowledgesToChatFormat(this.knowledges);let u={content:s,fileIds:r,referenceFirst:l,oldMessageId:o,promptVariables:this.promptVariables.filter(f=>f.type===I.PromptVariableType.User).reduce((f,g)=>E(w({},f),{[g.key]:g.value}),{}),systemPromptVariables:this.promptVariables.filter(f=>f.type===I.PromptVariableType.System).reduce((f,g)=>E(w({},f),{[g.key]:g.value}),{}),knowledges:h,enableTitleSummary:this.resolveEnableTitleSummary(),imageContent:a};this.ctrl=new AbortController,this.postChatV3EventSource(this._applicationId,this._id,u,this.ctrl.signal,{onopen:()=>{ni.log("open",this.ctrl)},onmessage:f=>{if(this._stopAnswer)return;let g=this.messages[this.messages.length-1];g&&g.role===I.ChatMessageRole.Robot?(g=w(w({},g),f),this.messages[this.messages.length-1]=g,this.event.emit("message:content",g),this.event.emit("message:updated",g)):(this.pushMessage(f),this.event.emit("message:content",f))},onclose:f=>d(this,null,function*(){this._stopAnswer||(ni.log(f,"onclose"),this.event.emit("answer:finish",f))}),onerror:()=>{this._stopAnswer||(this.event.emit("message:error",""),this.frozen=!1)}})}})}stopAnswer(){this.ctrl.abort()}registerMcpFromClientConfig(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}addMcpServers(t){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}listMcpServers(){return d(this,null,function*(){throw new Error("MCP registration is not supported by DialogSession")})}convertKnowledgesToChatFormat(t){return t?t.map(i=>i!=null&&i.fileIds?{id:i.id,fileIds:i.fileIds}:i.id):[]}}const na="@glodon-aiot/bot-client-sdk",ia="3.26.0-alpha.31",sa="glodoncv",ra="aiot bot client js sdk",oa="module",aa=!1,ca=["aiot","bot","bot client","sdk"],la=["dist"],da="./dist/es/index.mjs",ha="./dist/lib/index.js",ua="./dist/src/index.d.ts",fa={".":{import:"./dist/es/index.mjs",require:"./dist/lib/index.js",types:"./dist/src/index.d.ts"}},pa="MIT",ma={watch:"yarn build --watch",example:"node ./example/server.js",dev:"npm-run-all -p watch example",start:"vite",build:"tsc && vite build --mode prod && yarn build:cdn","build:npm":"tsc && vite build --mode prod","build:cdn":"tsc && vite build --mode prod --config ./vite.config.cdn.ts",preview:"vite preview",check:"yarn prettier --check .",write:"yarn prettier --write .",lint:"eslint --ext .tsx,.ts --fix ./example -c .eslintrc.js","build:just-bash":"node scripts/build-just-bash.mjs","upload:just-bash":"node scripts/build-just-bash.mjs && node scripts/upload-cdn-libs.cjs just-bash","build:pyodide":"node scripts/build-pyodide.mjs","upload:pyodide":"node scripts/build-pyodide.mjs && node scripts/upload-cdn-libs.cjs pyodide",test:"vitest run","test:watch":"vitest"},ga={"@babel/core":"^7.20.12","@commitlint/cli":"^17.0.3","@commitlint/config-conventional":"^17.0.3","@rollup/plugin-babel":"^6.0.4","@rollup/plugin-typescript":"^11.1.6","@types/express":"^4","@types/identity-obj-proxy":"^3","@typescript-eslint/eslint-plugin":"^5.35.1","@typescript-eslint/parser":"^5.35.1","babel-loader":"^8.3.0",eslint:"^8.0.1","eslint-config-prettier":"^8.5.0","eslint-config-standard-with-typescript":"^22.0.0","eslint-plugin-import":"^2.25.2","eslint-plugin-n":"^15.0.0","eslint-plugin-promise":"^6.0.0","eslint-plugin-react":"^7.31.0","eslint-plugin-storybook":"^0.6.10",express:"4","http-proxy-middleware":"^3.0.0","identity-obj-proxy":"^3.0.0","just-bash":"3.6.0","npm-run-all":"^4.1.5",prettier:"2.7.1",pyodide:"314.0.7","rollup-plugin-visualizer":"^6.0.1","socket.io":"^4.7.5","ts-node":"^10.9.2",typescript:"*",vite:"^4.1.1","vite-plugin-dts":"^4.3.0","vite-plugin-externalize-deps":"^0.9.0","vite-tsconfig-paths":"^5.1.4",vitest:"^0.34.6"},ya={access:"public",registry:"https://registry.npmjs.org/"},wa={"@glodon-aiot/apis":"^3.26.0-alpha.31",axios:"0.24.0",buffer:"^6.0.3",dayjs:"^1.11.13","js-base64":"^3.7.7","socket.io-client":"^4.7.5",uuid:"^11.1.0"},va={name:na,version:ia,author:sa,description:ra,type:oa,sideEffects:aa,keywords:ca,files:la,module:da,main:ha,typings:ua,exports:fa,license:pa,scripts:ma,devDependencies:ga,"lint-staged":{"*.{js,css,md,jsx,less,ts,tsx,json}":"prettier --write"},publishConfig:ya,dependencies:wa},ii=new U("[BotClient] ");class ba{constructor(e,t,i=!0,s={analytics:{enabled:!1}}){y(this,"event",new dn);y(this,"cvforceApi");y(this,"_applicationId");y(this,"_application",null);y(this,"_sessions",[]);y(this,"_activeSession");y(this,"_ready",!1);y(this,"_questionContextMaxLength",4e3);y(this,"_promptVariables",[]);y(this,"_localWorkspace");y(this,"_disconnectHost");if(this._token=e,this.lazyload=i,this.sdkConfigs=s,Dt(t,{refreshBuiltinPlugins:!1}),this._applicationId=it(e).rid||exports.configuration.applicationId,!this._applicationId)throw"token is not vaild";this.cvforceApi=this.getService(),this.setupLocalWorkspace(),this.loadApplication().then(r=>{Dt(E(w({},t),{stream:t.stream===void 0?(r==null?void 0:r.type)===I.ApplicationTypes.Dialog||(r==null?void 0:r.type)===I.ApplicationTypes.Agent:t.stream})),this.event.emit("ready")})}setupLocalWorkspace(){var s,r;const e=(s=exports.configuration.builtinPlugins)==null?void 0:s.localFiles;if(!(e!=null&&e.enabled)){zn(void 0),De();return}const t=[],i=(r=e.backend)!=null?r:"file-system-access";if(i!=="file-system-access"&&i!=="host-bridge")t.push(new Error(`[LocalFiles] 不支持的 backend:${e.backend}`));else{const o=no(exports.configuration.apiRoot,this.token,(a,c)=>ii.error(c));this._localWorkspace=new Ki({applicationId:this._applicationId,config:e,store:Xi(),picker:i==="host-bridge"?null:void 0,transfer:un(()=>this.cvforceApi,()=>o)}),zn(this._localWorkspace),this._localWorkspace.platformSkills=new oo({applicationId:()=>this._applicationId,getToken:()=>this.token,getSkills:()=>{var a,c,l,h;return(h=(l=(c=(a=this._application)==null?void 0:a.arrange)==null?void 0:c[0])==null?void 0:l.skills)!=null?h:[]},apiRoot:()=>exports.configuration.apiRoot,getSandbox:()=>{var c;const a=(c=this._localWorkspace)==null?void 0:c.adapter;return a instanceof Be?a.sandbox:void 0}}),i==="host-bridge"?this._disconnectHost=co(this._localWorkspace):this._localWorkspace.restore()}t.push(...De()),t.length&&Promise.resolve().then(()=>t.forEach(o=>this.event.emit("error",o)))}get localWorkspace(){return this._localWorkspace}checkReady(){if(!this.ready)throw Error("client is not ready.")}get ready(){return this._ready}set ready(e){this._ready=e}get questionContextMaxLength(){return this.checkReady(),this._questionContextMaxLength}get promptVariables(){return this.checkReady(),this._promptVariables}get knowledges(){var e;return this.checkReady(),(e=this._application)==null?void 0:e.arrange[0].knowledges}get sessions(){return this.checkReady(),this._sessions}set sessions(e){this.checkReady(),this._sessions=e,this.event.emit("sessions:updated",e)}loadApplication(){return d(this,null,function*(){var t,i,s,r,o;this._application=yield this.cvforceApi.getApplicationId(this._applicationId,{ui:(t=this.sdkConfigs.ui)==null?void 0:t.name,uiVersion:(i=this.sdkConfigs.ui)==null?void 0:i.version,sdkVersion:va.version}).then(a=>(typeof a.arrange[0].thinkingModeOpen!="boolean"&&(a.arrange[0].thinkingModeOpen=!0),typeof a.arrange[0].thinkingTextOpen!="boolean"&&(a.arrange[0].thinkingTextOpen=!0),E(w({},a),{arrange:[E(w({},a.arrange[0]),{recommendQuestionOpen:exports.configuration.loadRelatedQuesions&&a.arrange[0].recommendQuestionOpen})]})));const e=(o=(r=(s=this._application)==null?void 0:s.arrange)==null?void 0:r[0])==null?void 0:o.llmModel;return e&&(this._questionContextMaxLength=yield this.cvforceApi.getBaseModel(e).then(a=>a.maxModelLength)),this._promptVariables=yield Promise.all([this.cvforceApi.getPrompts(this._applicationId,{type:I.PromptVariableType.User}),this.cvforceApi.getPrompts(this._applicationId,{type:I.PromptVariableType.System})]).then(([a,c])=>[...a,...c]),this._ready=!0,this.event.emit("application:loaded"),this._application})}getService(){return this.cvforceApi?this.cvforceApi:Ui(exports.configuration.apiRoot,this.token,(e,t)=>ii.error(t))}get token(){return this._token}set token(e){this.checkReady(),this._token=e,this.ready=!1;const t=it(e).rid;this._applicationId!==t&&(this._applicationId=t,this._application=null,this.loadApplication().then(()=>{this.event.emit("ready")}),this.clean())}get applicationId(){return this._applicationId}get application(){return this.checkReady(),this._application}get activeSession(){var e;return this.checkReady(),((e=this._activeSession)==null?void 0:e.id)||""}set activeSession(e){this.checkReady(),this.loadSession(e).then(t=>{this._activeSession&&this._activeSession.id!==e&&this._activeSession.inactivate(),this._activeSession=t})}createSession(e,t,i,s,r){return d(this,null,function*(){const o=this;return new Promise((a,c)=>{const l=h=>d(this,null,function*(){if(h===I.ApplicationTypes.Agent)a(new Xo(e,t,i,s,r,o));else if(h===I.ApplicationTypes.Dialog)a(new ta(e,t,i,s,r,o));else throw Error(`不支持的应用类型:${h}`)});if(this.ready){if(!this._application)throw Error("client is not ready");l(this._application.type)}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");l(this._application.type)},!0)})})}getArtifacts(e){return d(this,null,function*(){var r,o;this.checkReady();const t=e||((r=this._activeSession)==null?void 0:r.id);if(!t)throw new Error("session id is not defined");const i=this._sessions.find(a=>a.id===t);if(i)return i.getArtifacts();const s=yield this.cvforceApi.getSessionArtifacts(this._applicationId,t);return(o=s==null?void 0:s.artifacts)!=null?o:[]})}getSessions(e){return d(this,null,function*(){return new Promise((t,i)=>{const s=()=>this.cvforceApi.listSessions(this._applicationId,e).then(r=>d(this,null,function*(){const o=[];for(const a of r){const c=this._sessions.find(l=>l.id===a.id);if(c)c.data=a,this._application?c.application=this._application:yield c.loadApplicationInfo(),o.push(c);else{const l=yield this.createSession(this.token,a.id,a,this.lazyload,this._application||void 0);o.push(l)}}if(e!=null&&e.pageSize){const a=[...this._sessions,...o],c=new Map;for(const l of a)c.set(l.id,l);return this.sessions=Array.from(c.values()),this.sessions}else return this.sessions=o,o}));if(this.ready){if(!this._application)throw Error("_application is null");t(s())}else this.event.on("ready",()=>{if(!this._application)throw Error("_application is null");t(s())},!0)})})}loadSession(e="",t){return d(this,null,function*(){var s,r;this.checkReady(),(r=(s=this._localWorkspace)==null?void 0:s.platformSkills)==null||r.sync();let i=this.sessions.find(o=>o.id===e);if(i||(i=yield this.createSession(this.token,e,t),this._sessions.push(i)),this._activeSession){if(this._activeSession===i)return i;this._activeSession.inactivate()}return i.id?(this._activeSession=i,yield i.activate()):i.addEventListener("data:loaded",()=>{this._activeSession!==i&&(i==null||i.activate(),this._activeSession=i)},!0),i})}reload(){return this.loadApplication().then(()=>d(this,null,function*(){return yield this.getSessions(),this.event.emit("ready"),this}))}reloadSession(e){return d(this,null,function*(){yield this.reload();let t=this._sessions.find(i=>i.id===e)||this._activeSession;if(!t){console.warn("reloadSession session failed.");return}return yield t.reload(),t})}setTop(e,t,i="top_time desc, sort_status desc, updated_at desc"){return d(this,null,function*(){let s=e?this._sessions.find(r=>r.id===e):this._activeSession;if(!s){console.warn("setTop session failed.");return}return yield s.setTop(t),this.getSessions({order:i})})}addEventListener(e,t,i=!1){if(typeof t!="function")throw Error("event listener is not a function");if(i){this.event.once(e,t);return}this.event.on(e,t)}removeEventListener(e,t){this.event.off(e,t)}removeSession(e,t){return d(this,null,function*(){this.checkReady();let i=-1;if(typeof e=="string"?i=this._sessions.findIndex(s=>s.id===e):i=this._sessions.findIndex(s=>s.id===e.id),i>-1){const s=this._sessions[i];t&&(yield s.delete()),this._sessions.splice(i,1)}else console.warn("session delete failed, session is not exist.")})}clean(){var e;(e=this._disconnectHost)==null||e.call(this),this._disconnectHost=void 0,this._sessions.forEach(t=>t.destroy()),this.sessions=[]}}class _a{constructor(e,t={},i){y(this,"code");y(this,"description","");y(this,"loaded",!1);y(this,"functions",{});this.code=e,t&&(this.functions=t)}fetchData(){this.description="描述",this.loaded=!0}checkFunctions(){}}const X="只操作用户在当前浏览器里选择的本地文件夹,路径相对该文件夹。云端工作区的文件不要用本工具。",Y={type:"string",enum:[Se],description:`工作区 ID。省略时按 ${Se} 处理,传其他值会被拒绝。`},K=n=>({type:"string",description:`${n}使用相对工作区根目录的路径,以 / 分隔,不能包含 .. 或绝对路径。`}),At={type:"string",description:"文件当前内容的 hash(sha256:<hex>),来自 read_file 或 stat_file 的返回值。"},Qi={list_directory:{functionCode:"list_directory",name:"列出本地目录",description:`${X}列出某个目录的直接子项(目录在前),支持分页。`,parameters:{type:"object",required:["grantId"],properties:{grantId:Y,path:K('要列出的目录,省略或传 "." 表示工作区根目录。'),offset:{type:"integer",minimum:0,description:"分页起始位置,默认 0。"},limit:{type:"integer",minimum:1,maximum:1e3,description:"每页条数,默认 200。"}}}},read_file:{functionCode:"read_file",name:"读取本地文件",description:`${X}按行读取文本文件,单次最多返回 1 MiB,超出部分会被截断(truncated: true)。返回内容的 hash 可用于后续修改。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要读取的文件。"),startLine:{type:"integer",minimum:1,description:"起始行(从 1 开始,含)。"},endLine:{type:"integer",minimum:1,description:"结束行(含)。"},maxBytes:{type:"integer",minimum:1,description:"返回内容的最大字节数,不超过 1 MiB。"},encoding:{type:"string",enum:["utf-8","gbk","gb18030"],description:"文本编码,默认 utf-8。"}}}},stat_file:{functionCode:"stat_file",name:"查看本地文件信息",description:`${X}返回文件或目录的类型、大小、修改时间,可选返回 hash。不返回文件内容。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要查看的文件或目录。"),includeHash:{type:"boolean",description:"是否计算文件 hash。"}}}},search_files:{functionCode:"search_files",name:"查找本地文件",description:`${X}按文件名或 glob(支持 *、?、**)查找文件。不含 / 的模式匹配文件名,含 / 的模式匹配相对 path 的路径。`,parameters:{type:"object",required:["grantId","pattern"],properties:{grantId:Y,pattern:{type:"string",minLength:1,description:"如 *.xlsx 或 reports/**/*.docx。"},path:K("搜索起点目录,默认工作区根目录。"),maxDepth:{type:"integer",minimum:1,maximum:16,description:"最大目录深度,默认 8。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"}}}},search_text:{functionCode:"search_text",name:"搜索本地文本",description:`${X}在指定文件或目录(递归)中搜索普通文本(不支持正则),返回所在文件、行号与该行内容。必须指定 path,不能搜索整个文件夹。`,parameters:{type:"object",required:["grantId","path","query"],properties:{grantId:Y,path:K("搜索范围,可以是文件或目录。"),query:{type:"string",minLength:1,description:"要查找的文本。"},caseSensitive:{type:"boolean",description:"是否区分大小写,默认否。"},isRegex:{type:"boolean",description:"暂不支持正则,传 true 会返回 501。"},glob:{type:"string",description:"只搜索匹配该 glob 的文件,如 *.md。"},maxResults:{type:"integer",minimum:1,maximum:200,description:"最多返回条数,默认 200。"},contextLines:{type:"integer",minimum:0,maximum:3,description:"附带的上下文行数,默认 0。"}}}},apply_patch:{functionCode:"apply_patch",name:"修改本地文件",description:`${X}以查找替换的方式修改 UTF-8 文本文件。每条修改的 oldText 必须在文件中唯一出现(或设置 replaceAll)。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","expectedHash","edits"],properties:{grantId:Y,path:K("要修改的文件。"),expectedHash:At,edits:{type:"array",minItems:1,description:"按顺序应用的修改。",items:{type:"object",required:["oldText","newText"],properties:{oldText:{type:"string",minLength:1,description:"要替换的原文,需包含足够上下文以保证唯一。"},newText:{type:"string",description:"替换后的文本。"},replaceAll:{type:"boolean",description:"是否替换所有出现位置,默认否。"}}}}}}},write_file:{functionCode:"write_file",name:"写入本地文件",description:`${X}新建文件,或整体覆盖已有文件(覆盖时必须提供 expectedHash)。修改已有文件优先使用 apply_patch。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path","content"],properties:{grantId:Y,path:K("要写入的文件。"),content:{type:"string",description:"完整的文件内容(UTF-8)。"},expectedHash:At,createDirectories:{type:"boolean",description:"父目录不存在时是否自动创建,默认否。"}}}},upload_file:{functionCode:"upload_file",name:"上传本地文件",description:`${X}把本地文件夹中的文件上传到平台文件服务,返回 fileId、name、size 和 url。url 是文件访问地址,可直接用于后续推理或对话。下载回本地文件夹时使用 download_file,source.type 为 platformFile。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","path"],properties:{grantId:Y,path:K("要上传的文件。"),target:{type:"string",description:"上传目标,目前只支持 session(默认),其他值返回 501。"},mimeHint:{type:"string",description:"可选的 MIME 类型。"}}}},download_file:{functionCode:"download_file",name:"下载到本地文件夹",description:`${X}把会话文件、平台文件或 https 地址保存到本地文件夹。source.type 为 url 时必须同时填写 source.url(完整地址),为 sessionFile 或 platformFile 时必须同时填写 source.fileId。不要只传 type。单文件不超过 50 MB。执行前需要用户确认。`,parameters:{type:"object",required:["grantId","destPath","source"],properties:{grantId:Y,destPath:K("保存位置(文件路径)。"),source:{type:"object",required:["type"],description:"下载来源。type 为 url 时必填 url;type 为 sessionFile 或 platformFile 时必填 fileId。",properties:{type:{type:"string",enum:["sessionFile","platformFile","url"],description:"sessionFile:当前会话文件;platformFile:平台文件(upload_file 返回的 fileId);url:https 地址。"},fileId:{type:"string",description:"type 为 sessionFile 或 platformFile 时必填,不能只传 type。"},url:{type:"string",description:"type 为 url 时必填,填写完整 https 地址。不能只传 type。默认只允许 glodon.com 及其子域。"}}},overwrite:{type:"boolean",description:"目标已存在时是否覆盖,默认否。"},expectedHash:At}}}},ka=new TextEncoder;function ie(n,e,t,i){return n===void 0?e:Math.min(Math.max(Math.trunc(n),t),i)}const Ea=(n,e)=>d(exports,null,function*(){const t=Z(n.path,{allowRoot:!0});if((yield e.adapter.stat(t)).kind!=="directory")throw new p(m.BadRequest,"目标是文件,不是目录。");const s=ie(n.offset,0,0,Number.MAX_SAFE_INTEGER),r=ie(n.limit,hi,1,ui),o=yield e.adapter.listEntries(t,e.signal);o.sort((c,l)=>c.kind!==l.kind?c.kind==="directory"?-1:1:c.name<l.name?-1:c.name>l.name?1:0);const a=o.slice(s,s+r).map(c=>{const l=Wi(t,c.name),h={name:c.name,path:l,kind:c.kind};return c.kind==="file"&&(h.size=c.size,h.lastModified=c.lastModified,e.sensitive.isSensitive(l)&&(h.sensitive=!0)),h});return{data:{path:t,entries:a,total:o.length,hasMore:s+a.length<o.length}}});function Sa(n,e,t){return pe(this,null,function*(){var a;const i=new TextDecoder(e),s=n.stream().getReader();let r="",o=!1;try{for(;;){F(t);const{done:c,value:l}=yield new se(s.read());r+=c?i.decode():i.decode(l,{stream:!0});const h=r.split(`
|
|
378
378
|
`);r=(a=h.pop())!=null?a:"";for(const u of h)o=!0,yield u;if(c)break}}finally{s.releaseLock()}(r||!o)&&(yield r)})}const Ia=(n,e)=>d(exports,null,function*(){var T,M;const t=Z(n.path);Te(e,t,"read");const i=yield Zt(e.adapter,t),s=yield e.adapter.readFile(t),r=(T=i.size)!=null?T:s.size;if(yield Ds(s))throw new p(m.BadRequest,"这是二进制文件,不能按文本读取。可以使用 stat_file 查看信息,或使用 upload_file 上传到会话。");const o=yield G(s.slice(0,3)),a=Ri(o)?"utf-8":(M=n.encoding)!=null?M:"utf-8",c=ie(n.startLine,1,1,Number.MAX_SAFE_INTEGER),l=n.endLine===void 0?Number.MAX_SAFE_INTEGER:Math.max(Math.trunc(n.endLine),c),h=ie(n.maxBytes,e.limits.maxReadBytes,1,e.limits.maxReadBytes),u=r<=e.limits.maxTransferBytes,f=[];let g=0,b=0,v=c-1,_=!1,x=!1;try{for(var ee=V(Sa(s,a,e.signal)),P,L,A;P=!(L=yield ee.next()).done;P=!1){const R=L.value;b++;const q=R.endsWith("\r")?R.slice(0,-1):R;if(q!==R&&(x=!0),b<c||b>l||_){if(!u&&(_||b>l))break;continue}const j=en(q)+(f.length?1:0);if(g+j>h){if(_=!0,f.length||(f.push(xa(q,h)),v=b),!u)break;continue}f.push(q),g+=j,v=b}}catch(L){A=[L]}finally{try{P&&(L=ee.return)&&(yield L.call(ee))}finally{if(A)throw A[0]}}const S={path:t,content:f.join(`
|
|
379
379
|
`),startLine:c,endLine:Math.max(v,c-1),size:r,encoding:a,lineEnding:x?"crlf":"lf"};return u&&(S.totalLines=b),r<=e.limits.maxWriteBytes&&(S.hash=yield xe(yield G(s))),{data:S,truncated:_||void 0}});function xa(n,e){const t=ka.encode(n);return t.byteLength<=e?n:new TextDecoder().decode(t.slice(0,e)).replace(/\uFFFD$/,"")}const Aa=(n,e)=>d(exports,null,function*(){var r;const t=Z(n.path),i=yield e.adapter.stat(t),s={path:t,kind:i.kind,sensitive:i.kind==="file"&&e.sensitive.isSensitive(t)};return i.kind==="file"&&(s.size=i.size,s.lastModified=i.lastModified,n.includeHash&&((r=i.size)!=null?r:0)<=e.limits.maxTransferBytes&&(s.hash=yield xe(yield G(yield e.adapter.readFile(t))))),{data:s}});function Ta(n){return vi.some(e=>tt(e,n))}function Zi(n,e,t){return pe(this,null,function*(){const i=[{path:e,depth:0}];let s=0;for(;i.length;){const r=i.shift();F(n.signal),++s%20===0&&(yield new se(Mi()));const o=yield new se(n.adapter.listEntries(r.path,n.signal));o.sort((a,c)=>a.name<c.name?-1:a.name>c.name?1:0);for(const a of o){const c=Wi(r.path,a.name);if(a.kind==="directory"){r.depth+1<t&&!wi.includes(a.name)&&i.push({path:c,depth:r.depth+1});continue}Ta(a.name)||n.sensitive.match(c,"search")||(yield{path:c,relativePath:e?c.slice(e.length+1):c,name:a.name,size:a.size,lastModified:a.lastModified})}}})}function es(n,e){return n.includes("/")?tt(n,e.relativePath):tt(n,e.name)}const La=(n,e)=>d(exports,null,function*(){const t=Z(n.path,{allowRoot:!0});if(!n.pattern.trim())throw new p(m.BadRequest,"参数 pattern 不能为空。");const i=n.pattern.replace(/\\/g,"/").replace(/^\.\//,"");if((yield e.adapter.stat(t)).kind!=="directory")throw new p(m.BadRequest,"参数 path 必须是目录。");const r=ie(n.maxDepth,fi,1,zt),o=ie(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=[];let c=!1;try{for(var l=V(Zi(e,t,r)),h,u,f;h=!(u=yield l.next()).done;h=!1){const g=u.value;if(es(i,g)){if(a.length>=o){c=!0;break}a.push({path:g.path,size:g.size,lastModified:g.lastModified})}}}catch(u){f=[u]}finally{try{h&&(u=l.return)&&(yield u.call(l))}finally{if(f)throw f[0]}}return{data:{matches:a},truncated:c||void 0}});function Tt(n,e){if(n.length<=Xe)return n;const t=Math.max(0,Math.min(e-100,n.length-Xe));return n.slice(t,t+Xe)}const Ra=(n,e)=>d(exports,null,function*(){var f;const t=Z(n.path,{allowRoot:!0});if(!t&&!e.allowWorkspaceWideTextSearch)throw new p(m.BadRequest,"不支持在整个工作区内搜索文本,请把 path 缩小到具体的子目录或文件。");if(n.isRegex)throw new p(m.NotImplemented,"暂不支持正则搜索,请使用普通文本搜索。");if(!n.query)throw new p(m.BadRequest,"参数 query 不能为空。");const i=n.caseSensitive===!0,s=i?n.query:n.query.toLowerCase(),r=ie(n.contextLines,0,0,gi),o=ie(n.maxResults,e.limits.maxSearchResults,1,e.limits.maxSearchResults),a=yield e.adapter.stat(t);let c;a.kind==="file"?(Te(e,t,"search"),c=function(){return pe(this,null,function*(){yield{path:t,relativePath:t,name:a.name,size:a.size}})}()):c=Zi(e,t,zt);const l=[];let h=0,u=!1;e:try{for(var g=V(c),b,v,_;b=!(v=yield g.next()).done;b=!1){const x=v.value;if(n.glob&&!es(n.glob,x)||((f=x.size)!=null?f:0)>mi)continue;if(h>=pi){u=!0;break}h++,h%20===0&&(yield Mi()),F(e.signal);const S=yield G(yield e.adapter.readFile(x.path));if(he(S))continue;const T=new TextDecoder("utf-8").decode(S).split(/\r?\n/);for(let M=0;M<T.length;M++){const P=(i?T[M]:T[M].toLowerCase()).indexOf(s);if(P<0)continue;if(l.length>=o){u=!0;break e}const L={path:x.path,line:M+1,column:P+1,text:Tt(T[M],P)};r&&(L.before=T.slice(Math.max(0,M-r),M).map(A=>Tt(A,0)),L.after=T.slice(M+1,M+1+r).map(A=>Tt(A,0))),l.push(L)}}}catch(v){_=[v]}finally{try{b&&(v=g.return)&&(yield v.call(g))}finally{if(_)throw _[0]}}return{data:{matches:l,filesScanned:h},truncated:u||void 0}});function si(){return new p(m.Forbidden,"下载地址不在允许范围内:只允许 https 协议且域名在白名单中的地址。",{reason:"url_not_allowed"})}const Ma=(n,e)=>d(exports,null,function*(){var u,f;const t=Z(n.path);if(((u=n.target)!=null?u:"session")!=="session")throw new p(m.NotImplemented,"目前只支持上传到当前会话(target: session)。");Te(e,t,"read");const s=yield Zt(e.adapter,t),r=(f=s.size)!=null?f:0;if(r>e.limits.maxTransferBytes)throw de(e.limits.maxTransferBytes);const o=Jt(t);yield e.requestApproval(t,{type:"upload",name:o,size:r,target:"session"}),e.progress({stage:"reading",loaded:0,total:r,path:t});const a=yield e.adapter.readFile(t);F(e.signal);const c=new File([a],o,{type:n.mimeHint||a.type||"application/octet-stream",lastModified:s.lastModified}),{fileId:l,url:h}=yield e.transfer.upload(c,e.context,({loaded:g,total:b})=>e.progress({stage:"uploading",loaded:g,total:b,path:t}));return F(e.signal),e.progress({stage:"done",loaded:r,total:r,path:t}),{data:{fileId:l,name:o,size:r,url:h}}});function Ca(n){const e=n;if(!e||typeof e!="object")throw new p(m.BadRequest,"缺少参数 source。");if(e.type==="sessionFile"||e.type==="platformFile"){if(typeof e.fileId!="string"||!e.fileId)throw new p(m.BadRequest,"source.fileId 必须是非空字符串。");return{type:e.type,fileId:e.fileId}}if(e.type==="url"){if(typeof e.url!="string"||!e.url)throw new p(m.BadRequest,"source.url 必须是非空字符串。");return{type:"url",url:e.url}}throw new p(m.BadRequest,"source.type 必须是 sessionFile、platformFile 或 url 之一。")}function Fa(n){return n.type==="sessionFile"?"会话文件":n.type==="platformFile"?"平台文件":new URL(n.url).hostname}function Oa(n,e,t,i,s){return pe(this,null,function*(){const r=n.getReader();let o=0;try{for(;;){F(e.signal);const{done:a,value:c}=yield new se(r.read());if(a)break;if(o+=c.byteLength,o>e.limits.maxTransferBytes)throw de(e.limits.maxTransferBytes,"下载内容");s.push(c),e.progress({stage:"downloading",loaded:o,total:i,path:t}),yield c}}finally{r.cancel().catch(()=>{})}})}const Na=(n,e)=>d(exports,null,function*(){var v,_,x;const t=Z(n.destPath,{field:"destPath"}),i=Ca(n.source);if(i.type==="url"&&!jt(i.url,e.downloadUrlAllowlist))throw si();Te(e,t,"write");const s=yield Ke(e.adapter,t);if((s==null?void 0:s.kind)==="directory")throw new p(m.BadRequest,"目标是目录,不能写入文件。");if(s&&!n.overwrite)throw new p(m.Conflict,"目标文件已存在。如需覆盖,请设置 overwrite: true。");const r=()=>d(exports,null,function*(){if(!s||!n.expectedHash)return;const S=yield xe(yield G(yield e.adapter.readFile(t)));if(S!==n.expectedHash)throw new p(m.Conflict,"expectedHash 与目标文件当前内容不一致。",{currentHash:S})});yield r();const o=i.type==="url"?{url:i.url}:yield e.transfer.resolveDownload(i,e.context);if(o.size!==void 0&&o.size>e.limits.maxTransferBytes)throw de(e.limits.maxTransferBytes);const a={type:"download",source:{type:i.type,label:Fa(i)},name:(v=o.name)!=null?v:Jt(t),size:o.size,overwrite:!!s};yield e.requestApproval(t,a),yield r();let c;try{c=yield e.fetch(o.url,{headers:o.headers,credentials:"omit",redirect:"follow",signal:e.signal})}catch(S){throw F(e.signal),new p(m.Internal,"下载失败,无法连接到文件地址。")}if(i.type==="url"&&c.url&&!jt(c.url,e.downloadUrlAllowlist))throw(_=c.body)==null||_.cancel().catch(()=>{}),si();if(!c.ok||!c.body)throw(x=c.body)==null||x.cancel().catch(()=>{}),new p(c.status===404?m.NotFound:m.Internal,`下载失败(HTTP ${c.status})。`);const l=Number(c.headers.get("content-length")),h=Number.isFinite(l)&&l>0?l:void 0;if(h!==void 0&&h>e.limits.maxTransferBytes)throw c.body.cancel().catch(()=>{}),de(e.limits.maxTransferBytes);const u=[];yield e.adapter.writeFile(t,Oa(c.body,e,t,h,u),{signal:e.signal});const f=u.reduce((S,T)=>S+T.byteLength,0),g=new Uint8Array(f);let b=0;return u.forEach(S=>{g.set(S,b),b+=S.byteLength}),e.progress({stage:"done",loaded:f,total:f,path:t}),{data:{path:t,size:f,hash:yield xe(g)}}}),Lt=new Uint8Array([239,187,191]);function at(n,e){return new p(m.Conflict,e,{currentHash:n})}function mn(n,e){return d(this,null,function*(){var s;if(((s=(yield Zt(n.adapter,e)).size)!=null?s:0)>n.limits.maxWriteBytes)throw de(n.limits.maxWriteBytes,"目标文件");const i=yield G(yield n.adapter.readFile(e));return{bytes:i,hash:yield xe(i)}})}function ts(n,e,t){return d(this,null,function*(){const{hash:i}=yield mn(n,e);if(i!==t)throw at(i,"文件在确认期间已被修改,本次写入已取消。请重新读取后再修改。")})}function $a(n,e){const t=new TextEncoder().encode(n);if(!e)return t;const i=new Uint8Array(Lt.byteLength+t.byteLength);return i.set(Lt,0),i.set(t,Lt.byteLength),i}function Pa(n,e){let t=0,i=n.indexOf(e);for(;i>=0;)t++,i=n.indexOf(e,i+e.length);return t}function ri(n,e){return!e||n.includes(`\r
|
|
380
380
|
`)?n:n.replace(/\n/g,`\r
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@glodon-aiot/bot-client-sdk",
|
|
3
|
-
"version": "3.26.0-alpha.
|
|
3
|
+
"version": "3.26.0-alpha.31",
|
|
4
4
|
"author": "glodoncv",
|
|
5
5
|
"description": "aiot bot client js sdk",
|
|
6
6
|
"type": "module",
|
|
@@ -88,7 +88,7 @@
|
|
|
88
88
|
"registry": "https://registry.npmjs.org/"
|
|
89
89
|
},
|
|
90
90
|
"dependencies": {
|
|
91
|
-
"@glodon-aiot/apis": "^3.26.0-alpha.
|
|
91
|
+
"@glodon-aiot/apis": "^3.26.0-alpha.31",
|
|
92
92
|
"axios": "0.24.0",
|
|
93
93
|
"buffer": "^6.0.3",
|
|
94
94
|
"dayjs": "^1.11.13",
|