@baiducloud/qianfan-mutil-agent 0.1.0-beta.0
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 +196 -0
- package/dist/esm/index.d.ts +751 -0
- package/dist/esm/index.js +2 -0
- package/dist/esm/index.js.LICENSE.txt +6 -0
- package/package.json +45 -0
package/README.md
ADDED
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
# @baiducloud/qianfan-mutil-agent
|
|
2
|
+
|
|
3
|
+
千帆 SSE 消息协议 SDK,用于解析和处理 AI 流式响应。
|
|
4
|
+
|
|
5
|
+
## 安装
|
|
6
|
+
|
|
7
|
+
```bash
|
|
8
|
+
npm install @baiducloud/qianfan-mutil-agent
|
|
9
|
+
```
|
|
10
|
+
|
|
11
|
+
## 快速开始
|
|
12
|
+
|
|
13
|
+
### 基础用法
|
|
14
|
+
|
|
15
|
+
```typescript
|
|
16
|
+
import {
|
|
17
|
+
Executor,
|
|
18
|
+
FetchSSETransport,
|
|
19
|
+
TreeView,
|
|
20
|
+
ChatEvent,
|
|
21
|
+
ThoughtEvent,
|
|
22
|
+
ToolCallEvent
|
|
23
|
+
} from '@baiducloud/qianfan-mutil-agent';
|
|
24
|
+
|
|
25
|
+
// 创建传输层
|
|
26
|
+
const transport = new FetchSSETransport({
|
|
27
|
+
endpoint: new URL('https://api.example.com/chat'),
|
|
28
|
+
header: {
|
|
29
|
+
'Authorization': 'Bearer your-token'
|
|
30
|
+
},
|
|
31
|
+
timeout: 60000
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
// 创建执行器
|
|
35
|
+
const executor = new Executor({
|
|
36
|
+
transport,
|
|
37
|
+
views: [TreeView],
|
|
38
|
+
events: [ChatEvent, ThoughtEvent, ToolCallEvent]
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
// 执行请求
|
|
42
|
+
const response = executor.invoke({
|
|
43
|
+
query: 'Hello, AI!'
|
|
44
|
+
});
|
|
45
|
+
|
|
46
|
+
// 获取视图并迭代结果
|
|
47
|
+
const treeView = response.getView(TreeView);
|
|
48
|
+
|
|
49
|
+
for await (const node of treeView) {
|
|
50
|
+
console.log(node);
|
|
51
|
+
}
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
### 使用 XHR 传输层
|
|
55
|
+
|
|
56
|
+
```typescript
|
|
57
|
+
import {
|
|
58
|
+
Executor,
|
|
59
|
+
XHRSSETransport,
|
|
60
|
+
TreeView
|
|
61
|
+
} from '@baiducloud/qianfan-mutil-agent';
|
|
62
|
+
|
|
63
|
+
const transport = new XHRSSETransport({
|
|
64
|
+
endpoint: new URL('https://api.example.com/chat')
|
|
65
|
+
});
|
|
66
|
+
|
|
67
|
+
const executor = new Executor({
|
|
68
|
+
transport,
|
|
69
|
+
views: [TreeView]
|
|
70
|
+
});
|
|
71
|
+
|
|
72
|
+
const response = executor.invoke({ query: 'Hello' });
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### 处理事件
|
|
76
|
+
|
|
77
|
+
```typescript
|
|
78
|
+
import {
|
|
79
|
+
Executor,
|
|
80
|
+
FetchSSETransport,
|
|
81
|
+
TreeView,
|
|
82
|
+
ChatEvent,
|
|
83
|
+
ToolCallEvent,
|
|
84
|
+
RAGEvent
|
|
85
|
+
} from '@baiducloud/qianfan-mutil-agent';
|
|
86
|
+
|
|
87
|
+
const executor = new Executor({
|
|
88
|
+
transport: new FetchSSETransport({
|
|
89
|
+
endpoint: new URL('https://api.example.com/chat')
|
|
90
|
+
}),
|
|
91
|
+
views: [TreeView],
|
|
92
|
+
events: [ChatEvent, ToolCallEvent, RAGEvent]
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
const response = executor.invoke({ query: 'Search something' });
|
|
96
|
+
|
|
97
|
+
// 监听消息
|
|
98
|
+
response.eventTarget.addEventListener('message', () => {
|
|
99
|
+
for (const event of response.events) {
|
|
100
|
+
if (event instanceof ChatEvent) {
|
|
101
|
+
console.log('Chat:', event.content);
|
|
102
|
+
} else if (event instanceof ToolCallEvent) {
|
|
103
|
+
console.log('Tool:', event);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
```
|
|
108
|
+
|
|
109
|
+
### 取消请求
|
|
110
|
+
|
|
111
|
+
```typescript
|
|
112
|
+
const abortController = new AbortController();
|
|
113
|
+
|
|
114
|
+
const response = executor.invoke(
|
|
115
|
+
{ query: 'Hello' },
|
|
116
|
+
{ abortController }
|
|
117
|
+
);
|
|
118
|
+
|
|
119
|
+
// 取消请求
|
|
120
|
+
setTimeout(() => {
|
|
121
|
+
abortController.abort();
|
|
122
|
+
}, 5000);
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
## API
|
|
126
|
+
|
|
127
|
+
### 核心类
|
|
128
|
+
|
|
129
|
+
| 导出 | 说明 |
|
|
130
|
+
|------|------|
|
|
131
|
+
| `Executor` | 执行器,管理请求和响应 |
|
|
132
|
+
| `ExecutionResponse` | 执行响应,包含事件和视图 |
|
|
133
|
+
| `ExecutionEvent` | 执行事件基类 |
|
|
134
|
+
| `EventMessage` | SSE 消息封装 |
|
|
135
|
+
| `ExecutionError` | 错误类型 |
|
|
136
|
+
|
|
137
|
+
### 传输层
|
|
138
|
+
|
|
139
|
+
| 导出 | 说明 |
|
|
140
|
+
|------|------|
|
|
141
|
+
| `FetchSSETransport` | 基于 Fetch API 的 SSE 传输层 |
|
|
142
|
+
| `XHRSSETransport` | 基于 XMLHttpRequest 的 SSE 传输层 |
|
|
143
|
+
| `ITransport` | 传输层接口 (类型) |
|
|
144
|
+
|
|
145
|
+
### 事件插件
|
|
146
|
+
|
|
147
|
+
| 插件 | action | resource | 说明 |
|
|
148
|
+
|------|--------|----------|------|
|
|
149
|
+
| `ChatEvent` | chat | - | 聊天对话事件 |
|
|
150
|
+
| `ThoughtEvent` | thought | - | 思考过程事件 |
|
|
151
|
+
| `ToolCallEvent` | toolcall | - | 工具调用事件 |
|
|
152
|
+
| `RAGEvent` | tools | knowledge | 知识库检索事件 |
|
|
153
|
+
| `DatabaseEvent` | tools | database | 数据库查询事件 |
|
|
154
|
+
| `DataSheetEvent` | tools | database_sheet | 数据表事件 |
|
|
155
|
+
| `FileParserEvent` | tools | file_parser | 文件解析事件 |
|
|
156
|
+
| `DeepSearchStepEvent` | deep_search | - | 深度搜索步骤事件 |
|
|
157
|
+
|
|
158
|
+
### 视图层
|
|
159
|
+
|
|
160
|
+
| 导出 | 说明 |
|
|
161
|
+
|------|------|
|
|
162
|
+
| `BaseView` | 视图基类 |
|
|
163
|
+
| `TreeView` | 树形结构视图 |
|
|
164
|
+
| `ToolUseView` | 工具使用视图 |
|
|
165
|
+
| `IView` | 视图接口 (类型) |
|
|
166
|
+
|
|
167
|
+
### 聚合规则
|
|
168
|
+
|
|
169
|
+
| 导出 | 说明 |
|
|
170
|
+
|------|------|
|
|
171
|
+
| `AggregateRule` | 聚合规则基类 |
|
|
172
|
+
| `defaultAggregatePresets` | 默认聚合规则预设 |
|
|
173
|
+
| `multiAgentAggregatePresets` | 多 Agent 聚合规则预设 |
|
|
174
|
+
| `assistantAgentAggregatePresets` | Assistant Agent 聚合规则预设 |
|
|
175
|
+
| `IAggregateRule` | 聚合规则接口 (类型) |
|
|
176
|
+
|
|
177
|
+
### 内容聚合策略
|
|
178
|
+
|
|
179
|
+
| contentType | 聚合策略 |
|
|
180
|
+
|-------------|---------|
|
|
181
|
+
| `text` | 字符串拼接 |
|
|
182
|
+
| `code` | 字符串拼接 |
|
|
183
|
+
| `json` | 对象替换 |
|
|
184
|
+
| `audio` | 对象替换 |
|
|
185
|
+
| `chart` | 对象替换 |
|
|
186
|
+
| `files` | 数组合并 |
|
|
187
|
+
| `image` | 数组合并 |
|
|
188
|
+
| `references` | 数组合并 |
|
|
189
|
+
| `urls` | 数组合并 |
|
|
190
|
+
|
|
191
|
+
## 依赖
|
|
192
|
+
|
|
193
|
+
该包依赖以下库(会自动安装):
|
|
194
|
+
|
|
195
|
+
- `ky` - HTTP 客户端
|
|
196
|
+
- `@baidu/ky-sse-hook` - SSE 响应处理钩子
|
|
@@ -0,0 +1,751 @@
|
|
|
1
|
+
/** 聚合规则注册类 */
|
|
2
|
+
export declare class AggregateRule {
|
|
3
|
+
/** 规则对应的content type */
|
|
4
|
+
static contentType: string;
|
|
5
|
+
/** 聚合规则 */
|
|
6
|
+
execute: IAggregateRule<any, any>;
|
|
7
|
+
}
|
|
8
|
+
|
|
9
|
+
/** assistant content type聚合预设集,目前和default一样 */
|
|
10
|
+
export declare const assistantAgentAggregatePresets: Array<typeof AggregateRule>;
|
|
11
|
+
|
|
12
|
+
export declare class BaseView<TNext = any> implements IView<TNext> {
|
|
13
|
+
readonly response: ExecutionResponse;
|
|
14
|
+
static viewName: string;
|
|
15
|
+
/** 当次执行是否已经完成 */
|
|
16
|
+
completed: boolean;
|
|
17
|
+
constructor(response: ExecutionResponse);
|
|
18
|
+
/** 通知视图, 信息传输已结束传输 */
|
|
19
|
+
complete(): void;
|
|
20
|
+
/** 通知视图层, 当前接受到一条新事件 */
|
|
21
|
+
[receiveNewEvent](_event: ExecutionEvent): void;
|
|
22
|
+
/** 通知视图层, 当前接受到一条新SSE消息 */
|
|
23
|
+
[receiveNewMessage](_message: EventMessage): void;
|
|
24
|
+
/** 数据恢复完成 */
|
|
25
|
+
restoreCompleted(_executionResponse: ExecutionResponse, _aborted: boolean): void;
|
|
26
|
+
/** 中断对话 */
|
|
27
|
+
abortAction(_executionResponse: ExecutionResponse, _aborted: boolean): void;
|
|
28
|
+
/**
|
|
29
|
+
* 完整执行结果视图的迭代器
|
|
30
|
+
*
|
|
31
|
+
* 如果执行未结束则会阻塞, 可以在任意时间段调用, 均会返回组件的完整执行结果
|
|
32
|
+
*/
|
|
33
|
+
[Symbol.asyncIterator](): AsyncIterator<TNext, undefined, void>;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export declare class ChatEvent extends ExecutionEvent implements IExecutionEvent {
|
|
37
|
+
static action: string;
|
|
38
|
+
static resource: string;
|
|
39
|
+
/** 闲聊中的实际Markdown文本内容 */
|
|
40
|
+
get content(): string;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export declare class DatabaseEvent extends ExecutionEvent implements IExecutionEvent {
|
|
44
|
+
static action: string;
|
|
45
|
+
static resource: string;
|
|
46
|
+
/** 执行数据库查询的语句 */
|
|
47
|
+
get sqlCode(): string | null;
|
|
48
|
+
get chartContent(): EventOutputContent<IChartEventMessagePayload> | null;
|
|
49
|
+
get dataset(): any[] | null;
|
|
50
|
+
/** 数据库reference */
|
|
51
|
+
get references(): Array<IReferenceContent<any>>;
|
|
52
|
+
/** 组件详情, 后端返回的数据 */
|
|
53
|
+
get componentDetail(): Record<string, any>;
|
|
54
|
+
/** 工具的入参 */
|
|
55
|
+
get inputs(): Record<string, any>;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export declare class DataSheetEvent extends ExecutionEvent implements IExecutionEvent {
|
|
59
|
+
static action: string;
|
|
60
|
+
static resource: string;
|
|
61
|
+
/** 数据库reference */
|
|
62
|
+
get references(): Array<IReferenceContent<any>>;
|
|
63
|
+
/** TODO: 是否还需要?database_sheet输出json化组装 */
|
|
64
|
+
get componentOutputs(): Record<string, any>;
|
|
65
|
+
/** 组件详情, 后端返回的数据 */
|
|
66
|
+
get componentDetail(): Record<string, any>;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export declare class DeepSearchStepEvent extends ExecutionEvent implements IExecutionEvent {
|
|
70
|
+
static action: string;
|
|
71
|
+
static resource: string;
|
|
72
|
+
/** 思考内容 */
|
|
73
|
+
get thought(): string;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** 默认content type聚合预设集 */
|
|
77
|
+
export declare const defaultAggregatePresets: Array<typeof AggregateRule>;
|
|
78
|
+
|
|
79
|
+
/** event输出消息 */
|
|
80
|
+
export declare class EventMessage<Payload = any> {
|
|
81
|
+
/** 解析后的原始sse消息生成EventMessage对象 */
|
|
82
|
+
static fromRawMessage(message: any): EventMessage[];
|
|
83
|
+
/** 判断消息是否报错 */
|
|
84
|
+
static isErrorMessage(message: EventMessage): boolean;
|
|
85
|
+
event: {
|
|
86
|
+
/** event id */
|
|
87
|
+
id: EventType;
|
|
88
|
+
/** 事件名称 */
|
|
89
|
+
name: string;
|
|
90
|
+
status: ExecutionEvent["status"];
|
|
91
|
+
is_stop: boolean;
|
|
92
|
+
error_code: string;
|
|
93
|
+
error_message: string;
|
|
94
|
+
/**
|
|
95
|
+
* 用于前端渲染的额外数据字段
|
|
96
|
+
*
|
|
97
|
+
* app builder console和分享应用对于渲染有部分定制化要求, 这类参数统一放在render字段中,
|
|
98
|
+
* openapi中不会有这个字段
|
|
99
|
+
*/
|
|
100
|
+
render: (Record<string, any> | undefined);
|
|
101
|
+
task_id: (string | undefined);
|
|
102
|
+
parent_task_id: (string | undefined);
|
|
103
|
+
task_name: (string | undefined);
|
|
104
|
+
};
|
|
105
|
+
/** 模型资源消耗 */
|
|
106
|
+
usage: {
|
|
107
|
+
prompt_tokens: number;
|
|
108
|
+
completion_tokens: number;
|
|
109
|
+
total_tokens: number;
|
|
110
|
+
};
|
|
111
|
+
/** 消息有效荷载内容 */
|
|
112
|
+
payload: Payload;
|
|
113
|
+
/** 荷载content的类型 */
|
|
114
|
+
contentType: string;
|
|
115
|
+
/** 荷载content的name */
|
|
116
|
+
contentName: string;
|
|
117
|
+
/**
|
|
118
|
+
* 消息有效范围
|
|
119
|
+
*
|
|
120
|
+
* @see {@link EventOutputContent.visibleScope} 了解类型定义
|
|
121
|
+
*/
|
|
122
|
+
visibleScope: EventOutputContent['visibleScope'];
|
|
123
|
+
/** 本条event 输出消息所属的对话id */
|
|
124
|
+
conversationId: string;
|
|
125
|
+
/** 本次执行的traceId, 用于追踪本次执行全链路日志 */
|
|
126
|
+
traceId: string;
|
|
127
|
+
/**
|
|
128
|
+
* 当前事件的父事件的id
|
|
129
|
+
*
|
|
130
|
+
* 图结构, 一个节点可能会有多个parent
|
|
131
|
+
*/
|
|
132
|
+
parentEventId: string[];
|
|
133
|
+
/** 错误码 */
|
|
134
|
+
error_code: string;
|
|
135
|
+
/** 错误细节 */
|
|
136
|
+
error_message: string;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
/**
|
|
140
|
+
* event输出内容类
|
|
141
|
+
*
|
|
142
|
+
* Event:EventOutputContent 1:N
|
|
143
|
+
*/
|
|
144
|
+
export declare class EventOutputContent<Payload = any> implements IEventOutputContentJson<Payload> {
|
|
145
|
+
private readonly aggregateRuleRegistration;
|
|
146
|
+
/**
|
|
147
|
+
* EventMessage转为EventOutputConte类的工厂
|
|
148
|
+
*
|
|
149
|
+
* 一个Event收到一个新的路径的content后, 需要创建content实例, 此方法用于创建首次接受到的content的实例
|
|
150
|
+
*/
|
|
151
|
+
static listFromRawMessage(eventMessage: EventMessage, aggregateRuleRegistration: Map<string, AggregateRule>): EventOutputContent;
|
|
152
|
+
/**
|
|
153
|
+
* 内容的名称
|
|
154
|
+
*
|
|
155
|
+
* 在一个event内唯一
|
|
156
|
+
*/
|
|
157
|
+
name: string;
|
|
158
|
+
/** 输出内容的类型 */
|
|
159
|
+
contentType: string;
|
|
160
|
+
/** 荷载内容 */
|
|
161
|
+
payload: Payload | null;
|
|
162
|
+
/**
|
|
163
|
+
* 输出有效范围
|
|
164
|
+
*
|
|
165
|
+
* all - 对于用户和思考模型均有意义
|
|
166
|
+
* llm - 仅对思考模型有意义
|
|
167
|
+
* user - 仅对用户有意义
|
|
168
|
+
*/
|
|
169
|
+
visibleScope: 'all' | 'llm' | 'user' | undefined;
|
|
170
|
+
constructor(aggregateRuleRegistration: Map<string, AggregateRule>);
|
|
171
|
+
/**
|
|
172
|
+
* 内容聚合
|
|
173
|
+
*
|
|
174
|
+
* @param incomingMessage - 事件消息
|
|
175
|
+
*
|
|
176
|
+
* EventOutputContent:EventMessage 1:N, event message聚合形成输出内容
|
|
177
|
+
*/
|
|
178
|
+
aggregate(incomingMessage: EventMessage<Payload>): void;
|
|
179
|
+
/** message数据更新 content */
|
|
180
|
+
fromMessage(eventMessage: EventMessage): void;
|
|
181
|
+
/** 转为供plain json */
|
|
182
|
+
toJSON(): IEventOutputContentJson<Payload>;
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* app builder风格树视图
|
|
187
|
+
*
|
|
188
|
+
* DTE原始数据为DAG结构, app builder对话渲染的是定制化的树状结构
|
|
189
|
+
* 与DTE原始数据差距较大, 因此需要重整树结构, 本类用户组织app builder渲染所需的
|
|
190
|
+
* 树结构
|
|
191
|
+
*/
|
|
192
|
+
declare class EventTreeNode {
|
|
193
|
+
/** 关联的实际的Event */
|
|
194
|
+
event: ExecutionEvent;
|
|
195
|
+
/** 兄弟节点 */
|
|
196
|
+
siblings: EventTreeNode[];
|
|
197
|
+
/** 孩子节点 */
|
|
198
|
+
children: EventTreeNode[];
|
|
199
|
+
/** 父节点 */
|
|
200
|
+
parent: EventTreeNode | null;
|
|
201
|
+
constructor(
|
|
202
|
+
/** 关联的实际的Event */
|
|
203
|
+
event: ExecutionEvent);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export declare type EventType = string | typeof unscheduledEventId;
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* @file 错误类定义集合
|
|
210
|
+
* @author FranckChen(chenfan02@baidu.com)
|
|
211
|
+
*/
|
|
212
|
+
export declare class ExecutionError extends Error {
|
|
213
|
+
/** 创建执行引擎错误 */
|
|
214
|
+
static createEngineError(code: string, message: string): ExecutionError;
|
|
215
|
+
/** 错误码 */
|
|
216
|
+
code: string | number;
|
|
217
|
+
/**
|
|
218
|
+
* 错误来源
|
|
219
|
+
*
|
|
220
|
+
* biz - 百度云业务层错误
|
|
221
|
+
* engine - agent调度执行引擎(DTE)错误
|
|
222
|
+
*/
|
|
223
|
+
origin: 'biz' | 'engine';
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
/** 执行事件 */
|
|
227
|
+
export declare abstract class ExecutionEvent implements IExecutionEvent {
|
|
228
|
+
private readonly aggregateRuleRegistration;
|
|
229
|
+
static action: string;
|
|
230
|
+
static resource: string;
|
|
231
|
+
/** 根据sse消息初始化Event, 用于接受到首条消息时生成数据 */
|
|
232
|
+
static liftFromEventMessage(eventMessage: EventMessage, aggregateRuleRegistration: Map<string, AggregateRule>, options?: {
|
|
233
|
+
contentConstructor?: typeof EventOutputContent;
|
|
234
|
+
}): ExecutionEvent;
|
|
235
|
+
/** 解析event name */
|
|
236
|
+
static parseEventName(name: string): [action: string, resource: string, subRender: string];
|
|
237
|
+
/** 事件id */
|
|
238
|
+
id: EventType;
|
|
239
|
+
/**
|
|
240
|
+
* event所述的task
|
|
241
|
+
*
|
|
242
|
+
* 多agent架构下, plan agent会规划,生成若干个task, 然后将task分发给执行agent
|
|
243
|
+
* 如果包含task字段, 则标识该event是多agent架构下agent规划出的任务(即子agent)执行
|
|
244
|
+
* 产出的event, 根据task字段可以追踪到plan规划出的任务, 定位event属于哪个task
|
|
245
|
+
*/
|
|
246
|
+
task_id?: string;
|
|
247
|
+
/**
|
|
248
|
+
* event所述的task的父task
|
|
249
|
+
*/
|
|
250
|
+
parent_task_id?: string;
|
|
251
|
+
/** event所属任务名称 */
|
|
252
|
+
task_name?: string;
|
|
253
|
+
/**
|
|
254
|
+
* event状态
|
|
255
|
+
*
|
|
256
|
+
* 强调调度器视角的状态, 如调度任务启动失败, 调度任务执行中等等
|
|
257
|
+
*/
|
|
258
|
+
status: IExecutionEvent['status'];
|
|
259
|
+
/**
|
|
260
|
+
* 原始名称
|
|
261
|
+
*
|
|
262
|
+
* 服务端返回的event的name字段, 其规则是 /:action/:resource/[:sub_resource], 3部分组成
|
|
263
|
+
* 其中sub_resource是可选的, 工作流组件有此段落, 官方及其他没有
|
|
264
|
+
*/
|
|
265
|
+
name: string;
|
|
266
|
+
/**
|
|
267
|
+
* 中文名称
|
|
268
|
+
*/
|
|
269
|
+
name_cn?: string;
|
|
270
|
+
/**
|
|
271
|
+
* 节点执行状态
|
|
272
|
+
*
|
|
273
|
+
* 如果code不为空代码执行有误, 错误代表执行引擎调度的工具执行有误, 这个错误对于Agent来讲
|
|
274
|
+
* 可能是有意义的输入信息, Agent会根据错误信息做出合理判断继续完成工作, 因此这个报错不代表
|
|
275
|
+
* Agent执行有误
|
|
276
|
+
*/
|
|
277
|
+
error_code: string | null;
|
|
278
|
+
/**
|
|
279
|
+
* 错误信息, 当存在错误时, 错误信息不为空
|
|
280
|
+
*/
|
|
281
|
+
error_message: string;
|
|
282
|
+
/**
|
|
283
|
+
* 本次事件所产出的content
|
|
284
|
+
*
|
|
285
|
+
* event:content 1:N
|
|
286
|
+
*/
|
|
287
|
+
contents: EventOutputContent[];
|
|
288
|
+
/** content name -> Content 映射Map */
|
|
289
|
+
nameToContentMap: Map<string, EventOutputContent<any>>;
|
|
290
|
+
/** 事件id */
|
|
291
|
+
parentEventId: string[];
|
|
292
|
+
/** 是否因为命中终止回复条件而终止 */
|
|
293
|
+
isStop: boolean;
|
|
294
|
+
/** event中供前端渲染使用的属性 */
|
|
295
|
+
render: Record<string, any> | undefined;
|
|
296
|
+
/**
|
|
297
|
+
* content构造函数
|
|
298
|
+
*
|
|
299
|
+
* 由外界注入, 优先使用这个构造函数创建生成content
|
|
300
|
+
*/
|
|
301
|
+
contentConstructor: typeof EventOutputContent | null;
|
|
302
|
+
/** event name中的resource部分 */
|
|
303
|
+
get resource(): string;
|
|
304
|
+
/** event name中的action部分 */
|
|
305
|
+
get action(): string;
|
|
306
|
+
constructor(aggregateRuleRegistration: Map<string, AggregateRule>);
|
|
307
|
+
/** 接受content消息 */
|
|
308
|
+
receiveContentMessageMessage(eventMessage: EventMessage): void;
|
|
309
|
+
/** 接受到新的content */
|
|
310
|
+
onReceiveNewContent(content: EventOutputContent): void;
|
|
311
|
+
/** 聚合content */
|
|
312
|
+
onAggregateContent(content: EventOutputContent): void;
|
|
313
|
+
/** 根据type获取内容类型 */
|
|
314
|
+
getContentByType(type: string): EventOutputContent[];
|
|
315
|
+
/** 输出内容中适合用户查看的内容 */
|
|
316
|
+
get userOutputContents(): EventOutputContent[];
|
|
317
|
+
/** 转为json */
|
|
318
|
+
toJSON(): IExecutionData;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
/** app builder 执行响应类 */
|
|
322
|
+
export declare class ExecutionResponse {
|
|
323
|
+
private readonly options?;
|
|
324
|
+
/**
|
|
325
|
+
* 执行响应中包含的events
|
|
326
|
+
*
|
|
327
|
+
* response:events 1:N event:content 1:N
|
|
328
|
+
*/
|
|
329
|
+
events: ExecutionEvent[];
|
|
330
|
+
/** 本次执行返回所属的conversationId */
|
|
331
|
+
conversationId: string;
|
|
332
|
+
/** 本次执行的traceId, 用于追踪本次执行全链路日志 */
|
|
333
|
+
traceId: string;
|
|
334
|
+
/** 视图访问器 */
|
|
335
|
+
views: Record<string, BaseView>;
|
|
336
|
+
/** 本次执行是否已经结束 */
|
|
337
|
+
completed: boolean;
|
|
338
|
+
/** 本次response的message_id */
|
|
339
|
+
message_id: string;
|
|
340
|
+
/**
|
|
341
|
+
* response错误
|
|
342
|
+
*
|
|
343
|
+
* response执行过程中遇到任何错误时, 此字段会被赋值, 记录错误
|
|
344
|
+
*/
|
|
345
|
+
error: Error | null;
|
|
346
|
+
/** 事件通知器 */
|
|
347
|
+
eventTarget: EventTarget;
|
|
348
|
+
/**
|
|
349
|
+
* response是否执行完成
|
|
350
|
+
*
|
|
351
|
+
* 不论成功失败均会resolve, 过程中遇到错会reject
|
|
352
|
+
*/
|
|
353
|
+
get finished(): Promise<void>;
|
|
354
|
+
/** view视图name */
|
|
355
|
+
get viewNames(): string[];
|
|
356
|
+
/** event id -> event的map */
|
|
357
|
+
private readonly idToEventMap;
|
|
358
|
+
/** content type -> 聚合规则的map */
|
|
359
|
+
private readonly aggregateRuleRegistration;
|
|
360
|
+
/** 注册生效的视图规则插件集合 */
|
|
361
|
+
private readonly activeViews;
|
|
362
|
+
/** 视图名称 -> 视图实例 */
|
|
363
|
+
private readonly nameToViewMap;
|
|
364
|
+
/** 通知response是否执行完成的 promise resolver */
|
|
365
|
+
private readonly finishedResolver;
|
|
366
|
+
/** 仅包含action的Event plugin */
|
|
367
|
+
private readonly actionBaseEventPluginsMap;
|
|
368
|
+
/** 同时注册了action 和 resource的更具体的,优先级更高的Event Plugin */
|
|
369
|
+
private readonly actionResourceBaseEventPluginsMap;
|
|
370
|
+
constructor(options?: ExecutionResponse.IOptions | undefined);
|
|
371
|
+
/** 标记传输已结束 */
|
|
372
|
+
complete(error?: Error): void;
|
|
373
|
+
/** 接受处理事件消息 */
|
|
374
|
+
receiveEventMessage: (rawMessage: Record<string, any>) => void;
|
|
375
|
+
/** 处理error message */
|
|
376
|
+
receiveErrorMessage: (errorMessage: EventMessage) => void;
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
export declare namespace ExecutionResponse {
|
|
380
|
+
/** 构造函数配置 */
|
|
381
|
+
export interface IOptions {
|
|
382
|
+
/** 视图插件 */
|
|
383
|
+
views: Array<typeof BaseView<any>>;
|
|
384
|
+
/** event插件 */
|
|
385
|
+
eventPlugins?: {
|
|
386
|
+
actionBaseEventPluginsMap: Map<string, typeof ExecutionEvent>;
|
|
387
|
+
actionResourceBaseEventPluginsMap: Map<string, typeof ExecutionEvent>;
|
|
388
|
+
};
|
|
389
|
+
/** 聚合规则插件 */
|
|
390
|
+
aggregateRules?: Array<typeof AggregateRule>;
|
|
391
|
+
/** SDK执行器options */
|
|
392
|
+
executorOptions: Executor.IOptions;
|
|
393
|
+
}
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** 执行器 */
|
|
397
|
+
export declare class Executor {
|
|
398
|
+
private readonly options;
|
|
399
|
+
/** transport插件 */
|
|
400
|
+
readonly transport: ITransport;
|
|
401
|
+
/** 聚合规则插件 */
|
|
402
|
+
private readonly aggregateRules;
|
|
403
|
+
/** 仅包含action的Event plugin */
|
|
404
|
+
private readonly actionBaseEventPluginsMap;
|
|
405
|
+
/** 同时注册了action 和 resource的更具体的,优先级更高的Event Plugin */
|
|
406
|
+
private readonly actionResourceBaseEventPluginsMap;
|
|
407
|
+
constructor(options: Executor.IOptions);
|
|
408
|
+
/** 生成response初始化参数 */
|
|
409
|
+
genResponseOptions: () => ExecutionResponse.IOptions;
|
|
410
|
+
/** 执行调用 */
|
|
411
|
+
invoke: <Param = unknown, Options = unknown>(param: Param, options?: Options & {
|
|
412
|
+
headers?: HeadersInit;
|
|
413
|
+
abortController?: AbortController;
|
|
414
|
+
}) => ExecutionResponse;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
export declare namespace Executor {
|
|
418
|
+
/** 执行器类的options */
|
|
419
|
+
export interface IOptions {
|
|
420
|
+
/** 视图插件 */
|
|
421
|
+
views: Array<typeof BaseView<any>>;
|
|
422
|
+
/** 传输通路 */
|
|
423
|
+
transport: ITransport;
|
|
424
|
+
/** 聚合规则插件 */
|
|
425
|
+
aggregateRules?: Array<typeof AggregateRule>;
|
|
426
|
+
/** event 插件 */
|
|
427
|
+
events?: Array<typeof ExecutionEvent>;
|
|
428
|
+
/** 类行覆盖配置 */
|
|
429
|
+
factory?: {
|
|
430
|
+
/** event 输出内容覆盖类 */
|
|
431
|
+
EventOutputContent?: typeof EventOutputContent;
|
|
432
|
+
};
|
|
433
|
+
/** 接受到消息后的回调 */
|
|
434
|
+
onMessage?(response: ExecutionResponse): void;
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/** 基于fetch的transport */
|
|
439
|
+
export declare class FetchSSETransport implements ITransport<IFetchSSETransportOptions, IFetchSSETransportSendOptions> {
|
|
440
|
+
options: IFetchSSETransportOptions;
|
|
441
|
+
constructor(options: IFetchSSETransportOptions);
|
|
442
|
+
/** 修改agent服务终端地址 */
|
|
443
|
+
changeEndPoint: (endpoint: URL) => void;
|
|
444
|
+
/** @see ITransport.send */
|
|
445
|
+
send: ITransport['send'];
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
export declare class FileParserEvent extends ExecutionEvent implements IExecutionEvent {
|
|
449
|
+
static action: string;
|
|
450
|
+
/** 文件解析信息 */
|
|
451
|
+
get fileParserInfo(): FileParserEvent.IFileParserInfo;
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
export declare namespace FileParserEvent {
|
|
455
|
+
export interface IFileParserInfo {
|
|
456
|
+
/** 文件信息 */
|
|
457
|
+
files: IFileInfo[];
|
|
458
|
+
}
|
|
459
|
+
/** 解析的文件信息 */
|
|
460
|
+
export interface IFileInfo {
|
|
461
|
+
/** 文件名 */
|
|
462
|
+
file_name: string;
|
|
463
|
+
/** 文件id */
|
|
464
|
+
file_id: string;
|
|
465
|
+
/** 文件解析状态 */
|
|
466
|
+
status: 'error' | 'done';
|
|
467
|
+
}
|
|
468
|
+
}
|
|
469
|
+
|
|
470
|
+
/**
|
|
471
|
+
* @file sse消息聚合规则
|
|
472
|
+
* @author FranckChen(chenfan02@baidu.com)
|
|
473
|
+
*/
|
|
474
|
+
/**
|
|
475
|
+
* 消息集合规则定义
|
|
476
|
+
*
|
|
477
|
+
* 一个event由若干sse消息组成, sse消息聚合, 最终形成event完整输出
|
|
478
|
+
*
|
|
479
|
+
* @param accumulation 当前已积累的数据
|
|
480
|
+
* @param incoming 当前新到的数据荷载
|
|
481
|
+
*
|
|
482
|
+
* @returns 累积消息
|
|
483
|
+
*/
|
|
484
|
+
export declare type IAggregateRule<Incoming, IAccumulation> = (incoming: Incoming, accumulation: IAccumulation | null) => IAccumulation;
|
|
485
|
+
|
|
486
|
+
/** chart消息实际荷载类型 */
|
|
487
|
+
declare interface IChartEventMessagePayload<T = any> {
|
|
488
|
+
/** chart表示直连数据库问答,chart_sheet表示本地数据库问答, chart_code_agent表示代码解释器图表生成 */
|
|
489
|
+
type: 'chart' | 'chart_sheet' | 'chart_code_agent';
|
|
490
|
+
/** @deprecated 图表绘制数据, 当前已废弃, 绘制echarts的数据会以序列化的json的形式存在于data字段内 */
|
|
491
|
+
chart_data: T;
|
|
492
|
+
/** 图表数据 */
|
|
493
|
+
data: string;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/** 解析,聚合后的内容输出结果 */
|
|
497
|
+
declare interface IEventOutputContentJson<Payload = any> {
|
|
498
|
+
contentType: string;
|
|
499
|
+
name: string;
|
|
500
|
+
visibleScope: EventOutputContent['visibleScope'];
|
|
501
|
+
payload: Payload | null;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
/** Event 数据 */
|
|
505
|
+
declare interface IExecutionData {
|
|
506
|
+
task_id?: string;
|
|
507
|
+
id: EventType;
|
|
508
|
+
status: 'preparing' | 'done' | 'running' | 'error';
|
|
509
|
+
contents: IEventOutputContentJson[];
|
|
510
|
+
nameToContentMap: Map<string, EventOutputContent>;
|
|
511
|
+
name: string;
|
|
512
|
+
action: string;
|
|
513
|
+
resource: string;
|
|
514
|
+
isStop: boolean;
|
|
515
|
+
userOutputContents: IEventOutputContentJson[];
|
|
516
|
+
}
|
|
517
|
+
|
|
518
|
+
/** 执行事件 interface */
|
|
519
|
+
declare interface IExecutionEvent extends IExecutionData {
|
|
520
|
+
receiveContentMessageMessage(eventMessage: EventMessage): void;
|
|
521
|
+
/** 聚合content */
|
|
522
|
+
aggregateContent?(accumulation: EventOutputContent, incomingMessage: EventMessage): void;
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
declare interface IFetchSSETransportOptions {
|
|
526
|
+
/** agent服务终端地址 */
|
|
527
|
+
endpoint: URL;
|
|
528
|
+
/** 发送query请求时的http header */
|
|
529
|
+
header?: HeadersInit;
|
|
530
|
+
/**
|
|
531
|
+
* 请求超时时间
|
|
532
|
+
*
|
|
533
|
+
* 默认60s
|
|
534
|
+
*/
|
|
535
|
+
timeout?: number;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
declare interface IFetchSSETransportSendOptions {
|
|
539
|
+
/** 发送query请求时的http header */
|
|
540
|
+
headers?: HeadersInit;
|
|
541
|
+
/**
|
|
542
|
+
* 请求超时时间
|
|
543
|
+
*
|
|
544
|
+
* 默认60s
|
|
545
|
+
*/
|
|
546
|
+
timeout?: number;
|
|
547
|
+
}
|
|
548
|
+
|
|
549
|
+
/**
|
|
550
|
+
* @file 消息协议reference类
|
|
551
|
+
* @author FranckChen(chenfan02@baidu.com)
|
|
552
|
+
*/
|
|
553
|
+
/** 应用内容基础reference */
|
|
554
|
+
declare interface IReferenceContent<Payload> {
|
|
555
|
+
/**
|
|
556
|
+
* 搜索执行器类型
|
|
557
|
+
*
|
|
558
|
+
* engine - app builder自建的文档搜索引擎
|
|
559
|
+
* web - 搜索引擎
|
|
560
|
+
* rule_intervention - 规则干预
|
|
561
|
+
*/
|
|
562
|
+
type: 'engine' | 'web' | 'rule_intervention';
|
|
563
|
+
/**
|
|
564
|
+
* 来源
|
|
565
|
+
*
|
|
566
|
+
* search_db_sheet - 用户上传表, 问表,问数
|
|
567
|
+
* database - 直连数据库问答
|
|
568
|
+
* search_db - 知识库检索
|
|
569
|
+
* search_baidu - 百度搜索
|
|
570
|
+
*/
|
|
571
|
+
source: 'search_db_sheet' | 'search_db' | 'search_baidu' | 'search_bing' | 'database' | 'ai_search' | 'aiapi';
|
|
572
|
+
/**
|
|
573
|
+
* 核心内容
|
|
574
|
+
*
|
|
575
|
+
* 文档检索, 百度search, 数据库检索均为
|
|
576
|
+
* reference但其核心荷载(payload)不同
|
|
577
|
+
*/
|
|
578
|
+
payload: Payload;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* @file 传输链路通道插件接口定义
|
|
583
|
+
* @author FranckChen(chenfan02@baidu.com)
|
|
584
|
+
*/
|
|
585
|
+
export declare interface ITransport<Options = any, SendOptions = any> {
|
|
586
|
+
/** Transport插件配置 */
|
|
587
|
+
options: Options;
|
|
588
|
+
/** 修改服务终端地址 */
|
|
589
|
+
changeEndPoint: (endpoint: URL) => void;
|
|
590
|
+
/** 发送query */
|
|
591
|
+
send(param: any, callbacks: {
|
|
592
|
+
/** 接受到消息的回调 */
|
|
593
|
+
onMessage: (message: string) => void;
|
|
594
|
+
/** 任务执行完成的回调 */
|
|
595
|
+
onCompleted: () => void;
|
|
596
|
+
/** 任务执行错误的回调 */
|
|
597
|
+
onError: (error: Error) => void;
|
|
598
|
+
}, options?: SendOptions & {
|
|
599
|
+
abortController?: AbortController;
|
|
600
|
+
headers?: HeadersInit;
|
|
601
|
+
}): void;
|
|
602
|
+
}
|
|
603
|
+
|
|
604
|
+
export declare interface IView<TNext = any> extends AsyncIterable<TNext, undefined, void> {
|
|
605
|
+
[receiveNewMessage](message: EventMessage): void;
|
|
606
|
+
[receiveNewEvent](event: ExecutionEvent): void;
|
|
607
|
+
/** 数据恢复完成 */
|
|
608
|
+
restoreCompleted(executionResponse: ExecutionResponse, aborted: boolean): void;
|
|
609
|
+
/** 中断对话 */
|
|
610
|
+
abortAction(executionResponse: ExecutionResponse, aborted: boolean): void;
|
|
611
|
+
}
|
|
612
|
+
|
|
613
|
+
declare interface IXHRSSETransportOptions {
|
|
614
|
+
/** agent服务终端地址 */
|
|
615
|
+
endpoint: URL;
|
|
616
|
+
/** 发送query请求时的http header */
|
|
617
|
+
headers?: HeadersInit;
|
|
618
|
+
/**
|
|
619
|
+
* 超时时间
|
|
620
|
+
*
|
|
621
|
+
* 默认60s
|
|
622
|
+
*/
|
|
623
|
+
timeout?: number;
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
declare interface IXHRSSETransportSendOptions {
|
|
627
|
+
/** 发送query请求时的http header */
|
|
628
|
+
headers?: HeadersInit;
|
|
629
|
+
/**
|
|
630
|
+
* 请求超时时间
|
|
631
|
+
*
|
|
632
|
+
* 默认60s
|
|
633
|
+
*/
|
|
634
|
+
timeout?: number;
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/** 多agent架构 content type聚合预设集 */
|
|
638
|
+
export declare const multiAgentAggregatePresets: Array<typeof AggregateRule>;
|
|
639
|
+
|
|
640
|
+
export declare class RAGEvent extends ExecutionEvent implements IExecutionEvent {
|
|
641
|
+
static action: string;
|
|
642
|
+
static resource: string;
|
|
643
|
+
/** rag的所有引用 */
|
|
644
|
+
get references(): Array<IReferenceContent<any>>;
|
|
645
|
+
/**
|
|
646
|
+
* RAG最终答案
|
|
647
|
+
*
|
|
648
|
+
* 命中RAG Event 即命中Rag Agent后触发的event, 整体对话(一个response)仅包含一个event
|
|
649
|
+
* event中包含了ref和最终答案. 不同于其他agent行为, 命中了Rag agent后,
|
|
650
|
+
* 最终答案是在rag event中的
|
|
651
|
+
*/
|
|
652
|
+
get finalAnswer(): string;
|
|
653
|
+
/** TODO: 是否还需要?rag输出json化组装 */
|
|
654
|
+
get componentOutputs(): Record<string, any>;
|
|
655
|
+
/** 组件详情, 后端返回的数据 */
|
|
656
|
+
get componentDetail(): Record<string, any>;
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
/** 接收事件成员方法symbol */
|
|
660
|
+
export declare const receiveNewEvent: unique symbol;
|
|
661
|
+
|
|
662
|
+
/** 接收新消息的symbol */
|
|
663
|
+
export declare const receiveNewMessage: unique symbol;
|
|
664
|
+
|
|
665
|
+
export declare class ThoughtEvent extends ExecutionEvent implements IExecutionEvent {
|
|
666
|
+
static action: string;
|
|
667
|
+
static resource: string;
|
|
668
|
+
/** 思考文案 */
|
|
669
|
+
get thoughtText(): string;
|
|
670
|
+
}
|
|
671
|
+
|
|
672
|
+
export declare class ToolCallEvent extends ExecutionEvent implements IExecutionEvent {
|
|
673
|
+
static action: string;
|
|
674
|
+
static resource: string;
|
|
675
|
+
/** 组件详情, 后端返回的数据 */
|
|
676
|
+
get componentDetail(): Record<string, any>;
|
|
677
|
+
/** 调用的是否是官方组件 */
|
|
678
|
+
get isOfficialComponent(): boolean;
|
|
679
|
+
/** 工具的入参 */
|
|
680
|
+
get inputs(): Record<string, any>;
|
|
681
|
+
/** 工具调用的的思考内容 */
|
|
682
|
+
get thought(): string;
|
|
683
|
+
/** 组件name */
|
|
684
|
+
get componentName(): string;
|
|
685
|
+
/** 组件输出json化组装 */
|
|
686
|
+
get componentOutputs(): Record<string, any>;
|
|
687
|
+
}
|
|
688
|
+
|
|
689
|
+
/** 工具调用视图 */
|
|
690
|
+
export declare class ToolUseView extends BaseView {
|
|
691
|
+
static viewName: string;
|
|
692
|
+
/** 工具调用事件的event id */
|
|
693
|
+
event: ExecutionEvent | null;
|
|
694
|
+
/**
|
|
695
|
+
* @see BaseView.completed
|
|
696
|
+
*/
|
|
697
|
+
completed: boolean;
|
|
698
|
+
/** 当前生效中的异步迭代器 */
|
|
699
|
+
private readonly asyncIterators;
|
|
700
|
+
[receiveNewMessage](): void;
|
|
701
|
+
complete(): void;
|
|
702
|
+
[receiveNewEvent](event: ExecutionEvent): void;
|
|
703
|
+
/** 组件调用全过程异步迭代器 */
|
|
704
|
+
[Symbol.asyncIterator](): AsyncIterator<IEventOutputContentJson[], undefined, void>;
|
|
705
|
+
get contents(): EventOutputContent[];
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
/** app builder风格树视图
|
|
709
|
+
* 目前服务于消息树组装分析器,因为顶层消息会不断新增维护,TreeView也需要持续新增顶层事件
|
|
710
|
+
* */
|
|
711
|
+
export declare class TreeView extends BaseView implements IView<EventTreeNode[]> {
|
|
712
|
+
/** 插件名称 */
|
|
713
|
+
static viewName: string;
|
|
714
|
+
/**
|
|
715
|
+
* 需要重组树状结构的action names
|
|
716
|
+
*/
|
|
717
|
+
static splitActionNames: string[];
|
|
718
|
+
/**
|
|
719
|
+
* 需要在最顶层展示的会见名称
|
|
720
|
+
*/
|
|
721
|
+
static topLevelResourceNames: string[];
|
|
722
|
+
/** 底层事件 */
|
|
723
|
+
topLevelEvents: EventTreeNode[];
|
|
724
|
+
/** event id -> event的hash map,
|
|
725
|
+
*
|
|
726
|
+
* 降低循环,保持O(1)时间复杂度
|
|
727
|
+
*/
|
|
728
|
+
private readonly idToEventTreeNodeMap;
|
|
729
|
+
/** 当前生效中的异步迭代器 */
|
|
730
|
+
private readonly asyncIterators;
|
|
731
|
+
complete(): void;
|
|
732
|
+
[receiveNewMessage](): void;
|
|
733
|
+
/** 接收新的event, 实时生成树结构 */
|
|
734
|
+
[receiveNewEvent](event: ExecutionEvent): void;
|
|
735
|
+
[Symbol.asyncIterator](): AsyncIterator<EventTreeNode[], undefined, void>;
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
/** 未经过调度器的event的id */
|
|
739
|
+
declare const unscheduledEventId: unique symbol;
|
|
740
|
+
|
|
741
|
+
/** 基于xhr + sse 的transport */
|
|
742
|
+
export declare class XHRSSETransport implements ITransport<IXHRSSETransportOptions, IXHRSSETransportSendOptions> {
|
|
743
|
+
options: IXHRSSETransportOptions;
|
|
744
|
+
constructor(options: IXHRSSETransportOptions);
|
|
745
|
+
/** 修改agent服务终端地址 */
|
|
746
|
+
changeEndPoint: (endpoint: URL) => void;
|
|
747
|
+
/** @see ITransport.send */
|
|
748
|
+
send: ITransport<IXHRSSETransportOptions, IXHRSSETransportSendOptions>['send'];
|
|
749
|
+
}
|
|
750
|
+
|
|
751
|
+
export { }
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
/*! For license information please see index.js.LICENSE.txt */
|
|
2
|
+
let e;import t,{HTTPError as s}from"ky";import{createHook as i}from"@baidu/ky-sse-hook";class a{static contentType="";execute=(e,t)=>{throw Error("Rule not implemented")}}let o=[class extends a{static contentType="text";execute=(e,t)=>t?{info:`${t.info}${e.info||""}`}:e},class extends a{static contentType="function_call";execute=e=>e},class extends a{static contentType="audio";execute=e=>({...e,audio:e.url})},class extends a{static contentType="chart";execute=e=>e},class extends a{static contentType="code";execute=(e,t)=>t?{code:`${t.code}${e.code||""}`}:e},class extends a{static contentType="files";execute=(e,t)=>t?[...t,e]:[e]},class extends a{static contentType="image";execute=(e,t)=>t?[...t,e]:[e]},class extends a{static contentType="json";execute=e=>e},class extends a{static contentType="oral_text";execute=(e,t)=>t?{info:`${t.info}${e.info||""}`}:e},class extends a{static contentType="references";execute=(e,t)=>t?[...t,e]:[e]},class extends a{static contentType="urls";execute=(e,t)=>t?[...t,e]:[e]}],n=[...o,class extends a{static contentType="plan";execute=e=>e},class extends a{static contentType="browser";execute=e=>e}],r=[...o],l=e=>"string"==typeof e,c=()=>{let e,t,s=new Promise((s,i)=>{e=s,t=i});return s.resolve=e,s.reject=t,s},h=e=>null==e?"":""+e,d=(e,t,s)=>{e.forEach(e=>{t[e]&&(s[e]=t[e])})},p=/###/g,u=e=>e&&e.indexOf("###")>-1?e.replace(p,"."):e,g=e=>!e||l(e),f=(e,t,s)=>{let i=l(t)?t.split("."):t,a=0;for(;a<i.length-1;){if(g(e))return{};let t=u(i[a]);!e[t]&&s&&(e[t]=new s),e=Object.prototype.hasOwnProperty.call(e,t)?e[t]:{},++a}return g(e)?{}:{obj:e,k:u(i[a])}},m=(e,t,s)=>{let{obj:i,k:a}=f(e,t,Object);if(void 0!==i||1===t.length){i[a]=s;return}let o=t[t.length-1],n=t.slice(0,t.length-1),r=f(e,n,Object);for(;void 0===r.obj&&n.length;)o=`${n[n.length-1]}.${o}`,r=f(e,n=n.slice(0,n.length-1),Object),r?.obj&&void 0!==r.obj[`${r.k}.${o}`]&&(r.obj=void 0);r.obj[`${r.k}.${o}`]=s},y=(e,t,s,i)=>{let{obj:a,k:o}=f(e,t,Object);a[o]=a[o]||[],a[o].push(s)},v=(e,t)=>{let{obj:s,k:i}=f(e,t);if(s&&Object.prototype.hasOwnProperty.call(s,i))return s[i]},x=(e,t,s)=>{let i=v(e,s);return void 0!==i?i:v(t,s)},b=(e,t,s)=>{for(let i in t)"__proto__"!==i&&"constructor"!==i&&(i in e?l(e[i])||e[i]instanceof String||l(t[i])||t[i]instanceof String?s&&(e[i]=t[i]):b(e[i],t[i],s):e[i]=t[i]);return e},_=e=>e.replace(/[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,"\\$&");var w,k,S,E,O={"&":"&","<":"<",">":">",'"':""","'":"'","/":"/"};let R=e=>l(e)?e.replace(/[&<>"'\/]/g,e=>O[e]):e,C=[" ",",","?","!",";"],L=new class{constructor(e){this.capacity=e,this.regExpMap=new Map,this.regExpQueue=[]}getRegExp(e){let t=this.regExpMap.get(e);if(void 0!==t)return t;let s=new RegExp(e);return this.regExpQueue.length===this.capacity&&this.regExpMap.delete(this.regExpQueue.shift()),this.regExpMap.set(e,s),this.regExpQueue.push(e),s}}(20),P=(e,t,s)=>{t=t||"",s=s||"";let i=C.filter(e=>0>t.indexOf(e)&&0>s.indexOf(e));if(0===i.length)return!0;let a=L.getRegExp(`(${i.map(e=>"?"===e?"\\?":e).join("|")})`),o=!a.test(e);if(!o){let t=e.indexOf(s);t>0&&!a.test(e.substring(0,t))&&(o=!0)}return o},M=(e,t,s=".")=>{if(!e)return;if(e[t]){if(!Object.prototype.hasOwnProperty.call(e,t))return;return e[t]}let i=t.split(s),a=e;for(let e=0;e<i.length;){let t;if(!a||"object"!=typeof a)return;let o="";for(let n=e;n<i.length;++n)if(n!==e&&(o+=s),o+=i[n],void 0!==(t=a[o])){if(["string","number","boolean"].indexOf(typeof t)>-1&&n<i.length-1)continue;e+=n-e+1;break}a=t}return a},T=e=>e?.replace("_","-"),N={type:"logger",log(e){this.output("log",e)},warn(e){this.output("warn",e)},error(e){this.output("error",e)},output(e,t){console?.[e]?.apply?.(console,t)}};class ${constructor(e,t={}){this.init(e,t)}init(e,t={}){this.prefix=t.prefix||"i18next:",this.logger=e||N,this.options=t,this.debug=t.debug}log(...e){return this.forward(e,"log","",!0)}warn(...e){return this.forward(e,"warn","",!0)}error(...e){return this.forward(e,"error","")}deprecate(...e){return this.forward(e,"warn","WARNING DEPRECATED: ",!0)}forward(e,t,s,i){return i&&!this.debug?null:(l(e[0])&&(e[0]=`${s}${this.prefix} ${e[0]}`),this.logger[t](e))}create(e){return new $(this.logger,{...{prefix:`${this.prefix}:${e}:`},...this.options})}clone(e){return(e=e||this.options).prefix=e.prefix||this.prefix,new $(this.logger,e)}}var j=new $;class I{constructor(){this.observers={}}on(e,t){return e.split(" ").forEach(e=>{this.observers[e]||(this.observers[e]=new Map);let s=this.observers[e].get(t)||0;this.observers[e].set(t,s+1)}),this}off(e,t){if(this.observers[e]){if(!t)return void delete this.observers[e];this.observers[e].delete(t)}}emit(e,...t){this.observers[e]&&Array.from(this.observers[e].entries()).forEach(([e,s])=>{for(let i=0;i<s;i++)e(...t)}),this.observers["*"]&&Array.from(this.observers["*"].entries()).forEach(([s,i])=>{for(let a=0;a<i;a++)s.apply(s,[e,...t])})}}class D extends I{constructor(e,t={ns:["translation"],defaultNS:"translation"}){super(),this.data=e||{},this.options=t,void 0===this.options.keySeparator&&(this.options.keySeparator="."),void 0===this.options.ignoreJSONStructure&&(this.options.ignoreJSONStructure=!0)}addNamespaces(e){0>this.options.ns.indexOf(e)&&this.options.ns.push(e)}removeNamespaces(e){let t=this.options.ns.indexOf(e);t>-1&&this.options.ns.splice(t,1)}getResource(e,t,s,i={}){let a,o=void 0!==i.keySeparator?i.keySeparator:this.options.keySeparator,n=void 0!==i.ignoreJSONStructure?i.ignoreJSONStructure:this.options.ignoreJSONStructure;e.indexOf(".")>-1?a=e.split("."):(a=[e,t],s&&(Array.isArray(s)?a.push(...s):l(s)&&o?a.push(...s.split(o)):a.push(s)));let r=v(this.data,a);return(!r&&!t&&!s&&e.indexOf(".")>-1&&(e=a[0],t=a[1],s=a.slice(2).join(".")),!r&&n&&l(s))?M(this.data?.[e]?.[t],s,o):r}addResource(e,t,s,i,a={silent:!1}){let o=void 0!==a.keySeparator?a.keySeparator:this.options.keySeparator,n=[e,t];s&&(n=n.concat(o?s.split(o):s)),e.indexOf(".")>-1&&(n=e.split("."),i=t,t=n[1]),this.addNamespaces(t),m(this.data,n,i),a.silent||this.emit("added",e,t,s,i)}addResources(e,t,s,i={silent:!1}){for(let i in s)(l(s[i])||Array.isArray(s[i]))&&this.addResource(e,t,i,s[i],{silent:!0});i.silent||this.emit("added",e,t,s)}addResourceBundle(e,t,s,i,a,o={silent:!1,skipCopy:!1}){let n=[e,t];e.indexOf(".")>-1&&(n=e.split("."),i=s,s=t,t=n[1]),this.addNamespaces(t);let r=v(this.data,n)||{};o.skipCopy||(s=JSON.parse(JSON.stringify(s))),i?b(r,s,a):r={...r,...s},m(this.data,n,r),o.silent||this.emit("added",e,t,s)}removeResourceBundle(e,t){this.hasResourceBundle(e,t)&&delete this.data[e][t],this.removeNamespaces(t),this.emit("removed",e,t)}hasResourceBundle(e,t){return void 0!==this.getResource(e,t)}getResourceBundle(e,t){return t||(t=this.options.defaultNS),this.getResource(e,t)}getDataByLanguage(e){return this.data[e]}hasLanguageSomeTranslations(e){let t=this.getDataByLanguage(e);return!!(t&&Object.keys(t)||[]).find(e=>t[e]&&Object.keys(t[e]).length>0)}toJSON(){return this.data}}var A={processors:{},addPostProcessor(e){this.processors[e.name]=e},handle(e,t,s,i,a){return e.forEach(e=>{t=this.processors[e]?.process(t,s,i,a)??t}),t}};let V=Symbol("i18next/PATH_KEY");function F(e,t){let{[V]:s}=e(function(){let e,t=[],s=Object.create(null);return s.get=(i,a)=>(e?.revoke?.(),a===V)?t:(t.push(a),(e=Proxy.revocable(i,s)).proxy),Proxy.revocable(Object.create(null),s).proxy}());return s.join(t?.keySeparator??".")}let U={},B=e=>!l(e)&&"boolean"!=typeof e&&"number"!=typeof e;class H extends I{constructor(e,t={}){super(),d(["resourceStore","languageUtils","pluralResolver","interpolator","backendConnector","i18nFormat","utils"],e,this),this.options=t,void 0===this.options.keySeparator&&(this.options.keySeparator="."),this.logger=j.create("translator")}changeLanguage(e){e&&(this.language=e)}exists(e,t={interpolation:{}}){let s={...t};if(null==e)return!1;let i=this.resolve(e,s);return i?.res!==void 0}extractFromKey(e,t){let s=void 0!==t.nsSeparator?t.nsSeparator:this.options.nsSeparator;void 0===s&&(s=":");let i=void 0!==t.keySeparator?t.keySeparator:this.options.keySeparator,a=t.ns||this.options.defaultNS||[],o=s&&e.indexOf(s)>-1,n=!this.options.userDefinedKeySeparator&&!t.keySeparator&&!this.options.userDefinedNsSeparator&&!t.nsSeparator&&!P(e,s,i);if(o&&!n){let t=e.match(this.interpolator.nestingRegexp);if(t&&t.length>0)return{key:e,namespaces:l(a)?[a]:a};let o=e.split(s);(s!==i||s===i&&this.options.ns.indexOf(o[0])>-1)&&(a=o.shift()),e=o.join(i)}return{key:e,namespaces:l(a)?[a]:a}}translate(e,t,s){let i="object"==typeof t?{...t}:t;if("object"!=typeof i&&this.options.overloadTranslationOptionHandler&&(i=this.options.overloadTranslationOptionHandler(arguments)),"object"==typeof i&&(i={...i}),i||(i={}),null==e)return"";"function"==typeof e&&(e=F(e,{...this.options,...i})),Array.isArray(e)||(e=[String(e)]);let a=void 0!==i.returnDetails?i.returnDetails:this.options.returnDetails,o=void 0!==i.keySeparator?i.keySeparator:this.options.keySeparator,{key:n,namespaces:r}=this.extractFromKey(e[e.length-1],i),c=r[r.length-1],h=void 0!==i.nsSeparator?i.nsSeparator:this.options.nsSeparator;void 0===h&&(h=":");let d=i.lng||this.language,p=i.appendNamespaceToCIMode||this.options.appendNamespaceToCIMode;if(d?.toLowerCase()==="cimode")return p?a?{res:`${c}${h}${n}`,usedKey:n,exactUsedKey:n,usedLng:d,usedNS:c,usedParams:this.getUsedParamsDetails(i)}:`${c}${h}${n}`:a?{res:n,usedKey:n,exactUsedKey:n,usedLng:d,usedNS:c,usedParams:this.getUsedParamsDetails(i)}:n;let u=this.resolve(e,i),g=u?.res,f=u?.usedKey||n,m=u?.exactUsedKey||n,y=void 0!==i.joinArrays?i.joinArrays:this.options.joinArrays,v=!this.i18nFormat||this.i18nFormat.handleAsObject,x=void 0!==i.count&&!l(i.count),b=H.hasDefaultValue(i),_=x?this.pluralResolver.getSuffix(d,i.count,i):"",w=i.ordinal&&x?this.pluralResolver.getSuffix(d,i.count,{ordinal:!1}):"",k=x&&!i.ordinal&&0===i.count,S=k&&i[`defaultValue${this.options.pluralSeparator}zero`]||i[`defaultValue${_}`]||i[`defaultValue${w}`]||i.defaultValue,E=g;v&&!g&&b&&(E=S);let O=B(E),R=Object.prototype.toString.apply(E);if(v&&E&&O&&0>["[object Number]","[object Function]","[object RegExp]"].indexOf(R)&&!(l(y)&&Array.isArray(E))){if(!i.returnObjects&&!this.options.returnObjects){this.options.returnedObjectHandler||this.logger.warn("accessing an object - but returnObjects options is not enabled!");let e=this.options.returnedObjectHandler?this.options.returnedObjectHandler(f,E,{...i,ns:r}):`key '${n} (${this.language})' returned an object instead of string.`;return a?(u.res=e,u.usedParams=this.getUsedParamsDetails(i),u):e}if(o){let e=Array.isArray(E),t=e?[]:{},s=e?m:f;for(let e in E)if(Object.prototype.hasOwnProperty.call(E,e)){let a=`${s}${o}${e}`;b&&!g?t[e]=this.translate(a,{...i,defaultValue:B(S)?S[e]:void 0,...{joinArrays:!1,ns:r}}):t[e]=this.translate(a,{...i,joinArrays:!1,ns:r}),t[e]===a&&(t[e]=E[e])}g=t}}else if(v&&l(y)&&Array.isArray(g))(g=g.join(y))&&(g=this.extendTranslation(g,e,i,s));else{let t=!1,a=!1;!this.isValidLookup(g)&&b&&(t=!0,g=S),this.isValidLookup(g)||(a=!0,g=n);let r=(i.missingKeyNoValueFallbackToKey||this.options.missingKeyNoValueFallbackToKey)&&a?void 0:g,l=b&&S!==g&&this.options.updateMissing;if(a||t||l){if(this.logger.log(l?"updateKey":"missingKey",d,c,n,l?S:g),o){let e=this.resolve(n,{...i,keySeparator:!1});e&&e.res&&this.logger.warn("Seems the loaded translations were in flat JSON format instead of nested. Either set keySeparator: false on init or make sure your translations are published in nested format.")}let e=[],t=this.languageUtils.getFallbackCodes(this.options.fallbackLng,i.lng||this.language);if("fallback"===this.options.saveMissingTo&&t&&t[0])for(let s=0;s<t.length;s++)e.push(t[s]);else"all"===this.options.saveMissingTo?e=this.languageUtils.toResolveHierarchy(i.lng||this.language):e.push(i.lng||this.language);let s=(e,t,s)=>{let a=b&&s!==g?s:r;this.options.missingKeyHandler?this.options.missingKeyHandler(e,c,t,a,l,i):this.backendConnector?.saveMissing&&this.backendConnector.saveMissing(e,c,t,a,l,i),this.emit("missingKey",e,c,t,g)};this.options.saveMissing&&(this.options.saveMissingPlurals&&x?e.forEach(e=>{let t=this.pluralResolver.getSuffixes(e,i);k&&i[`defaultValue${this.options.pluralSeparator}zero`]&&0>t.indexOf(`${this.options.pluralSeparator}zero`)&&t.push(`${this.options.pluralSeparator}zero`),t.forEach(t=>{s([e],n+t,i[`defaultValue${t}`]||S)})}):s(e,n,S))}g=this.extendTranslation(g,e,i,u,s),a&&g===n&&this.options.appendNamespaceToMissingKey&&(g=`${c}${h}${n}`),(a||t)&&this.options.parseMissingKeyHandler&&(g=this.options.parseMissingKeyHandler(this.options.appendNamespaceToMissingKey?`${c}${h}${n}`:n,t?g:void 0,i))}return a?(u.res=g,u.usedParams=this.getUsedParamsDetails(i),u):g}extendTranslation(e,t,s,i,a){if(this.i18nFormat?.parse)e=this.i18nFormat.parse(e,{...this.options.interpolation.defaultVariables,...s},s.lng||this.language||i.usedLng,i.usedNS,i.usedKey,{resolved:i});else if(!s.skipInterpolation){let o;s.interpolation&&this.interpolator.init({...s,...{interpolation:{...this.options.interpolation,...s.interpolation}}});let n=l(e)&&(s?.interpolation?.skipOnVariables!==void 0?s.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables);if(n){let t=e.match(this.interpolator.nestingRegexp);o=t&&t.length}let r=s.replace&&!l(s.replace)?s.replace:s;if(this.options.interpolation.defaultVariables&&(r={...this.options.interpolation.defaultVariables,...r}),e=this.interpolator.interpolate(e,r,s.lng||this.language||i.usedLng,s),n){let t=e.match(this.interpolator.nestingRegexp);o<(t&&t.length)&&(s.nest=!1)}!s.lng&&i&&i.res&&(s.lng=this.language||i.usedLng),!1!==s.nest&&(e=this.interpolator.nest(e,(...e)=>a?.[0]!==e[0]||s.context?this.translate(...e,t):(this.logger.warn(`It seems you are nesting recursively key: ${e[0]} in key: ${t[0]}`),null),s)),s.interpolation&&this.interpolator.reset()}let o=s.postProcess||this.options.postProcess,n=l(o)?[o]:o;return null!=e&&n?.length&&!1!==s.applyPostProcessor&&(e=A.handle(n,e,t,this.options&&this.options.postProcessPassResolved?{i18nResolved:{...i,usedParams:this.getUsedParamsDetails(s)},...s}:s,this)),e}resolve(e,t={}){let s,i,a,o,n;return l(e)&&(e=[e]),e.forEach(e=>{if(this.isValidLookup(s))return;let r=this.extractFromKey(e,t),c=r.key;i=c;let h=r.namespaces;this.options.fallbackNS&&(h=h.concat(this.options.fallbackNS));let d=void 0!==t.count&&!l(t.count),p=d&&!t.ordinal&&0===t.count,u=void 0!==t.context&&(l(t.context)||"number"==typeof t.context)&&""!==t.context,g=t.lngs?t.lngs:this.languageUtils.toResolveHierarchy(t.lng||this.language,t.fallbackLng);h.forEach(e=>{this.isValidLookup(s)||(n=e,!U[`${g[0]}-${e}`]&&this.utils?.hasLoadedNamespace&&!this.utils?.hasLoadedNamespace(n)&&(U[`${g[0]}-${e}`]=!0,this.logger.warn(`key "${i}" for languages "${g.join(", ")}" won't get resolved as namespace "${n}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!")),g.forEach(i=>{let n;if(this.isValidLookup(s))return;o=i;let r=[c];if(this.i18nFormat?.addLookupKeys)this.i18nFormat.addLookupKeys(r,c,i,e,t);else{let e;d&&(e=this.pluralResolver.getSuffix(i,t.count,t));let s=`${this.options.pluralSeparator}zero`,a=`${this.options.pluralSeparator}ordinal${this.options.pluralSeparator}`;if(d&&(t.ordinal&&0===e.indexOf(a)&&r.push(c+e.replace(a,this.options.pluralSeparator)),r.push(c+e),p&&r.push(c+s)),u){let i=`${c}${this.options.contextSeparator||"_"}${t.context}`;r.push(i),d&&(t.ordinal&&0===e.indexOf(a)&&r.push(i+e.replace(a,this.options.pluralSeparator)),r.push(i+e),p&&r.push(i+s))}}for(;n=r.pop();)this.isValidLookup(s)||(a=n,s=this.getResource(i,e,n,t))}))})}),{res:s,usedKey:i,exactUsedKey:a,usedLng:o,usedNS:n}}isValidLookup(e){return void 0!==e&&!(!this.options.returnNull&&null===e)&&!(!this.options.returnEmptyString&&""===e)}getResource(e,t,s,i={}){return this.i18nFormat?.getResource?this.i18nFormat.getResource(e,t,s,i):this.resourceStore.getResource(e,t,s,i)}getUsedParamsDetails(e={}){let t=e.replace&&!l(e.replace),s=t?e.replace:e;if(t&&void 0!==e.count&&(s.count=e.count),this.options.interpolation.defaultVariables&&(s={...this.options.interpolation.defaultVariables,...s}),!t)for(let e of(s={...s},["defaultValue","ordinal","context","replace","lng","lngs","fallbackLng","ns","keySeparator","nsSeparator","returnObjects","returnDetails","joinArrays","postProcess","interpolation"]))delete s[e];return s}static hasDefaultValue(e){let t="defaultValue";for(let s in e)if(Object.prototype.hasOwnProperty.call(e,s)&&t===s.substring(0,t.length)&&void 0!==e[s])return!0;return!1}}class K{constructor(e){this.options=e,this.supportedLngs=this.options.supportedLngs||!1,this.logger=j.create("languageUtils")}getScriptPartFromCode(e){if(!(e=T(e))||0>e.indexOf("-"))return null;let t=e.split("-");return 2===t.length||(t.pop(),"x"===t[t.length-1].toLowerCase())?null:this.formatLanguageCode(t.join("-"))}getLanguagePartFromCode(e){if(!(e=T(e))||0>e.indexOf("-"))return e;let t=e.split("-");return this.formatLanguageCode(t[0])}formatLanguageCode(e){if(l(e)&&e.indexOf("-")>-1){let t;try{t=Intl.getCanonicalLocales(e)[0]}catch(e){}return(t&&this.options.lowerCaseLng&&(t=t.toLowerCase()),t)?t:this.options.lowerCaseLng?e.toLowerCase():e}return this.options.cleanCode||this.options.lowerCaseLng?e.toLowerCase():e}isSupportedCode(e){return("languageOnly"===this.options.load||this.options.nonExplicitSupportedLngs)&&(e=this.getLanguagePartFromCode(e)),!this.supportedLngs||!this.supportedLngs.length||this.supportedLngs.indexOf(e)>-1}getBestMatchFromCodes(e){let t;return e?(e.forEach(e=>{if(t)return;let s=this.formatLanguageCode(e);(!this.options.supportedLngs||this.isSupportedCode(s))&&(t=s)}),!t&&this.options.supportedLngs&&e.forEach(e=>{if(t)return;let s=this.getScriptPartFromCode(e);if(this.isSupportedCode(s))return t=s;let i=this.getLanguagePartFromCode(e);if(this.isSupportedCode(i))return t=i;t=this.options.supportedLngs.find(e=>{if(e===i||!(0>e.indexOf("-")&&0>i.indexOf("-"))&&(e.indexOf("-")>0&&0>i.indexOf("-")&&e.substring(0,e.indexOf("-"))===i||0===e.indexOf(i)&&i.length>1))return e})}),t||(t=this.getFallbackCodes(this.options.fallbackLng)[0]),t):null}getFallbackCodes(e,t){if(!e)return[];if("function"==typeof e&&(e=e(t)),l(e)&&(e=[e]),Array.isArray(e))return e;if(!t)return e.default||[];let s=e[t];return s||(s=e[this.getScriptPartFromCode(t)]),s||(s=e[this.formatLanguageCode(t)]),s||(s=e[this.getLanguagePartFromCode(t)]),s||(s=e.default),s||[]}toResolveHierarchy(e,t){let s=this.getFallbackCodes((!1===t?[]:t)||this.options.fallbackLng||[],e),i=[],a=e=>{e&&(this.isSupportedCode(e)?i.push(e):this.logger.warn(`rejecting language code not found in supportedLngs: ${e}`))};return l(e)&&(e.indexOf("-")>-1||e.indexOf("_")>-1)?("languageOnly"!==this.options.load&&a(this.formatLanguageCode(e)),"languageOnly"!==this.options.load&&"currentOnly"!==this.options.load&&a(this.getScriptPartFromCode(e)),"currentOnly"!==this.options.load&&a(this.getLanguagePartFromCode(e))):l(e)&&a(this.formatLanguageCode(e)),s.forEach(e=>{0>i.indexOf(e)&&a(this.formatLanguageCode(e))}),i}}let z={zero:0,one:1,two:2,few:3,many:4,other:5},q={select:e=>1===e?"one":"other",resolvedOptions:()=>({pluralCategories:["one","other"]})};class J{constructor(e,t={}){this.languageUtils=e,this.options=t,this.logger=j.create("pluralResolver"),this.pluralRulesCache={}}addRule(e,t){this.rules[e]=t}clearCache(){this.pluralRulesCache={}}getRule(e,t={}){let s,i=T("dev"===e?"en":e),a=t.ordinal?"ordinal":"cardinal",o=JSON.stringify({cleanedCode:i,type:a});if(o in this.pluralRulesCache)return this.pluralRulesCache[o];try{s=new Intl.PluralRules(i,{type:a})}catch(a){if(!Intl)return this.logger.error("No Intl support, please use an Intl polyfill!"),q;if(!e.match(/-|_/))return q;let i=this.languageUtils.getLanguagePartFromCode(e);s=this.getRule(i,t)}return this.pluralRulesCache[o]=s,s}needsPlural(e,t={}){let s=this.getRule(e,t);return s||(s=this.getRule("dev",t)),s?.resolvedOptions().pluralCategories.length>1}getPluralFormsOfKey(e,t,s={}){return this.getSuffixes(e,s).map(e=>`${t}${e}`)}getSuffixes(e,t={}){let s=this.getRule(e,t);return(s||(s=this.getRule("dev",t)),s)?s.resolvedOptions().pluralCategories.sort((e,t)=>z[e]-z[t]).map(e=>`${this.options.prepend}${t.ordinal?`ordinal${this.options.prepend}`:""}${e}`):[]}getSuffix(e,t,s={}){let i=this.getRule(e,s);return i?`${this.options.prepend}${s.ordinal?`ordinal${this.options.prepend}`:""}${i.select(t)}`:(this.logger.warn(`no plural rule found for: ${e}`),this.getSuffix("dev",t,s))}}let Y=(e,t,s,i=".",a=!0)=>{let o=x(e,t,s);return!o&&a&&l(s)&&void 0===(o=M(e,s,i))&&(o=M(t,s,i)),o},W=e=>e.replace(/\$/g,"$$$$");class G{constructor(e={}){this.logger=j.create("interpolator"),this.options=e,this.format=e?.interpolation?.format||(e=>e),this.init(e)}init(e={}){e.interpolation||(e.interpolation={escapeValue:!0});let{escape:t,escapeValue:s,useRawValueToEscape:i,prefix:a,prefixEscaped:o,suffix:n,suffixEscaped:r,formatSeparator:l,unescapeSuffix:c,unescapePrefix:h,nestingPrefix:d,nestingPrefixEscaped:p,nestingSuffix:u,nestingSuffixEscaped:g,nestingOptionsSeparator:f,maxReplaces:m,alwaysFormat:y}=e.interpolation;this.escape=void 0!==t?t:R,this.escapeValue=void 0===s||s,this.useRawValueToEscape=void 0!==i&&i,this.prefix=a?_(a):o||"{{",this.suffix=n?_(n):r||"}}",this.formatSeparator=l||",",this.unescapePrefix=c?"":h||"-",this.unescapeSuffix=this.unescapePrefix?"":c||"",this.nestingPrefix=d?_(d):p||_("$t("),this.nestingSuffix=u?_(u):g||_(")"),this.nestingOptionsSeparator=f||",",this.maxReplaces=m||1e3,this.alwaysFormat=void 0!==y&&y,this.resetRegExp()}reset(){this.options&&this.init(this.options)}resetRegExp(){let e=(e,t)=>e?.source===t?(e.lastIndex=0,e):RegExp(t,"g");this.regexp=e(this.regexp,`${this.prefix}(.+?)${this.suffix}`),this.regexpUnescape=e(this.regexpUnescape,`${this.prefix}${this.unescapePrefix}(.+?)${this.unescapeSuffix}${this.suffix}`),this.nestingRegexp=e(this.nestingRegexp,`${this.nestingPrefix}((?:[^()"']+|"[^"]*"|'[^']*'|\\((?:[^()]|"[^"]*"|'[^']*')*\\))*?)${this.nestingSuffix}`)}interpolate(e,t,s,i){let a,o,n,r=this.options&&this.options.interpolation&&this.options.interpolation.defaultVariables||{},c=e=>{if(0>e.indexOf(this.formatSeparator)){let a=Y(t,r,e,this.options.keySeparator,this.options.ignoreJSONStructure);return this.alwaysFormat?this.format(a,void 0,s,{...i,...t,interpolationkey:e}):a}let a=e.split(this.formatSeparator),o=a.shift().trim(),n=a.join(this.formatSeparator).trim();return this.format(Y(t,r,o,this.options.keySeparator,this.options.ignoreJSONStructure),n,s,{...i,...t,interpolationkey:o})};this.resetRegExp();let d=i?.missingInterpolationHandler||this.options.missingInterpolationHandler,p=i?.interpolation?.skipOnVariables!==void 0?i.interpolation.skipOnVariables:this.options.interpolation.skipOnVariables;return[{regex:this.regexpUnescape,safeValue:e=>W(e)},{regex:this.regexp,safeValue:e=>this.escapeValue?W(this.escape(e)):W(e)}].forEach(t=>{for(n=0;a=t.regex.exec(e);){let s=a[1].trim();if(void 0===(o=c(s)))if("function"==typeof d){let t=d(e,a,i);o=l(t)?t:""}else if(i&&Object.prototype.hasOwnProperty.call(i,s))o="";else if(p){o=a[0];continue}else this.logger.warn(`missed to pass in variable ${s} for interpolating ${e}`),o="";else l(o)||this.useRawValueToEscape||(o=h(o));let r=t.safeValue(o);if(e=e.replace(a[0],r),p?(t.regex.lastIndex+=o.length,t.regex.lastIndex-=a[0].length):t.regex.lastIndex=0,++n>=this.maxReplaces)break}}),e}nest(e,t,s={}){let i,a,o,n=(e,t)=>{let s=this.nestingOptionsSeparator;if(0>e.indexOf(s))return e;let i=e.split(RegExp(`${s}[ ]*{`)),a=`{${i[1]}`;e=i[0];let n=(a=this.interpolate(a,o)).match(/'/g),r=a.match(/"/g);((n?.length??0)%2!=0||r)&&r.length%2==0||(a=a.replace(/'/g,'"'));try{o=JSON.parse(a),t&&(o={...t,...o})}catch(t){return this.logger.warn(`failed parsing options string in nesting for key ${e}`,t),`${e}${s}${a}`}return o.defaultValue&&o.defaultValue.indexOf(this.prefix)>-1&&delete o.defaultValue,e};for(;i=this.nestingRegexp.exec(e);){let r=[];(o=(o={...s}).replace&&!l(o.replace)?o.replace:o).applyPostProcessor=!1,delete o.defaultValue;let c=/{.*}/.test(i[1])?i[1].lastIndexOf("}")+1:i[1].indexOf(this.formatSeparator);if(-1!==c&&(r=i[1].slice(c).split(this.formatSeparator).map(e=>e.trim()).filter(Boolean),i[1]=i[1].slice(0,c)),(a=t(n.call(this,i[1].trim(),o),o))&&i[0]===e&&!l(a))return a;l(a)||(a=h(a)),a||(this.logger.warn(`missed to resolve ${i[1]} for nesting ${e}`),a=""),r.length&&(a=r.reduce((e,t)=>this.format(e,t,s.lng,{...s,interpolationkey:i[1].trim()}),a.trim())),e=e.replace(i[0],a),this.regexp.lastIndex=0}return e}}let Q=e=>{let t=e.toLowerCase().trim(),s={};if(e.indexOf("(")>-1){let i=e.split("(");t=i[0].toLowerCase().trim();let a=i[1].substring(0,i[1].length-1);"currency"===t&&0>a.indexOf(":")?s.currency||(s.currency=a.trim()):"relativetime"===t&&0>a.indexOf(":")?s.range||(s.range=a.trim()):a.split(";").forEach(e=>{if(e){let[t,...i]=e.split(":"),a=i.join(":").trim().replace(/^'+|'+$/g,""),o=t.trim();s[o]||(s[o]=a),"false"===a&&(s[o]=!1),"true"===a&&(s[o]=!0),isNaN(a)||(s[o]=parseInt(a,10))}})}return{formatName:t,formatOptions:s}},X=e=>{let t={};return(s,i,a)=>{let o=a;a&&a.interpolationkey&&a.formatParams&&a.formatParams[a.interpolationkey]&&a[a.interpolationkey]&&(o={...o,[a.interpolationkey]:void 0});let n=i+JSON.stringify(o),r=t[n];return r||(r=e(T(i),a),t[n]=r),r(s)}},Z=e=>(t,s,i)=>e(T(s),i)(t);class ee{constructor(e={}){this.logger=j.create("formatter"),this.options=e,this.init(e)}init(e,t={interpolation:{}}){this.formatSeparator=t.interpolation.formatSeparator||",";let s=t.cacheInBuiltFormats?X:Z;this.formats={number:s((e,t)=>{let s=new Intl.NumberFormat(e,{...t});return e=>s.format(e)}),currency:s((e,t)=>{let s=new Intl.NumberFormat(e,{...t,style:"currency"});return e=>s.format(e)}),datetime:s((e,t)=>{let s=new Intl.DateTimeFormat(e,{...t});return e=>s.format(e)}),relativetime:s((e,t)=>{let s=new Intl.RelativeTimeFormat(e,{...t});return e=>s.format(e,t.range||"day")}),list:s((e,t)=>{let s=new Intl.ListFormat(e,{...t});return e=>s.format(e)})}}add(e,t){this.formats[e.toLowerCase().trim()]=t}addCached(e,t){this.formats[e.toLowerCase().trim()]=X(t)}format(e,t,s,i={}){let a=t.split(this.formatSeparator);if(a.length>1&&a[0].indexOf("(")>1&&0>a[0].indexOf(")")&&a.find(e=>e.indexOf(")")>-1)){let e=a.findIndex(e=>e.indexOf(")")>-1);a[0]=[a[0],...a.splice(1,e)].join(this.formatSeparator)}return a.reduce((e,t)=>{let{formatName:a,formatOptions:o}=Q(t);if(this.formats[a]){let t=e;try{let n=i?.formatParams?.[i.interpolationkey]||{},r=n.locale||n.lng||i.locale||i.lng||s;t=this.formats[a](e,r,{...o,...i,...n})}catch(e){this.logger.warn(e)}return t}return this.logger.warn(`there was no format function for ${a}`),e},e)}}let et=(e,t)=>{void 0!==e.pending[t]&&(delete e.pending[t],e.pendingCount--)};class es extends I{constructor(e,t,s,i={}){super(),this.backend=e,this.store=t,this.services=s,this.languageUtils=s.languageUtils,this.options=i,this.logger=j.create("backendConnector"),this.waitingReads=[],this.maxParallelReads=i.maxParallelReads||10,this.readingCalls=0,this.maxRetries=i.maxRetries>=0?i.maxRetries:5,this.retryTimeout=i.retryTimeout>=1?i.retryTimeout:350,this.state={},this.queue=[],this.backend?.init?.(s,i.backend,i)}queueLoad(e,t,s,i){let a={},o={},n={},r={};return e.forEach(e=>{let i=!0;t.forEach(t=>{let n=`${e}|${t}`;!s.reload&&this.store.hasResourceBundle(e,t)?this.state[n]=2:this.state[n]<0||(1===this.state[n]?void 0===o[n]&&(o[n]=!0):(this.state[n]=1,i=!1,void 0===o[n]&&(o[n]=!0),void 0===a[n]&&(a[n]=!0),void 0===r[t]&&(r[t]=!0)))}),i||(n[e]=!0)}),(Object.keys(a).length||Object.keys(o).length)&&this.queue.push({pending:o,pendingCount:Object.keys(o).length,loaded:{},errors:[],callback:i}),{toLoad:Object.keys(a),pending:Object.keys(o),toLoadLanguages:Object.keys(n),toLoadNamespaces:Object.keys(r)}}loaded(e,t,s){let i=e.split("|"),a=i[0],o=i[1];t&&this.emit("failedLoading",a,o,t),!t&&s&&this.store.addResourceBundle(a,o,s,void 0,void 0,{skipCopy:!0}),this.state[e]=t?-1:2,t&&s&&(this.state[e]=0);let n={};this.queue.forEach(s=>{y(s.loaded,[a],o),et(s,e),t&&s.errors.push(t),0!==s.pendingCount||s.done||(Object.keys(s.loaded).forEach(e=>{n[e]||(n[e]={});let t=s.loaded[e];t.length&&t.forEach(t=>{void 0===n[e][t]&&(n[e][t]=!0)})}),s.done=!0,s.errors.length?s.callback(s.errors):s.callback())}),this.emit("loaded",n),this.queue=this.queue.filter(e=>!e.done)}read(e,t,s,i=0,a=this.retryTimeout,o){if(!e.length)return o(null,{});if(this.readingCalls>=this.maxParallelReads)return void this.waitingReads.push({lng:e,ns:t,fcName:s,tried:i,wait:a,callback:o});this.readingCalls++;let n=(n,r)=>{if(this.readingCalls--,this.waitingReads.length>0){let e=this.waitingReads.shift();this.read(e.lng,e.ns,e.fcName,e.tried,e.wait,e.callback)}if(n&&r&&i<this.maxRetries)return void setTimeout(()=>{this.read.call(this,e,t,s,i+1,2*a,o)},a);o(n,r)},r=this.backend[s].bind(this.backend);if(2===r.length){try{let s=r(e,t);s&&"function"==typeof s.then?s.then(e=>n(null,e)).catch(n):n(null,s)}catch(e){n(e)}return}return r(e,t,n)}prepareLoading(e,t,s={},i){if(!this.backend)return this.logger.warn("No backend was added via i18next.use. Will not load resources."),i&&i();l(e)&&(e=this.languageUtils.toResolveHierarchy(e)),l(t)&&(t=[t]);let a=this.queueLoad(e,t,s,i);if(!a.toLoad.length)return a.pending.length||i(),null;a.toLoad.forEach(e=>{this.loadOne(e)})}load(e,t,s){this.prepareLoading(e,t,{},s)}reload(e,t,s){this.prepareLoading(e,t,{reload:!0},s)}loadOne(e,t=""){let s=e.split("|"),i=s[0],a=s[1];this.read(i,a,"read",void 0,void 0,(s,o)=>{s&&this.logger.warn(`${t}loading namespace ${a} for language ${i} failed`,s),!s&&o&&this.logger.log(`${t}loaded namespace ${a} for language ${i}`,o),this.loaded(e,s,o)})}saveMissing(e,t,s,i,a,o={},n=()=>{}){if(this.services?.utils?.hasLoadedNamespace&&!this.services?.utils?.hasLoadedNamespace(t))return void this.logger.warn(`did not save key "${s}" as the namespace "${t}" was not yet loaded`,"This means something IS WRONG in your setup. You access the t function before i18next.init / i18next.loadNamespace / i18next.changeLanguage was done. Wait for the callback or Promise to resolve before accessing it!!!");if(null!=s&&""!==s){if(this.backend?.create){let r={...o,isUpdate:a},l=this.backend.create.bind(this.backend);if(l.length<6)try{let a;(a=5===l.length?l(e,t,s,i,r):l(e,t,s,i))&&"function"==typeof a.then?a.then(e=>n(null,e)).catch(n):n(null,a)}catch(e){n(e)}else l(e,t,s,i,n,r)}e&&e[0]&&this.store.addResource(e[0],t,s,i)}}}let ei=()=>({debug:!1,initAsync:!0,ns:["translation"],defaultNS:["translation"],fallbackLng:["dev"],fallbackNS:!1,supportedLngs:!1,nonExplicitSupportedLngs:!1,load:"all",preload:!1,simplifyPluralSuffix:!0,keySeparator:".",nsSeparator:":",pluralSeparator:"_",contextSeparator:"_",partialBundledLanguages:!1,saveMissing:!1,updateMissing:!1,saveMissingTo:"fallback",saveMissingPlurals:!0,missingKeyHandler:!1,missingInterpolationHandler:!1,postProcess:!1,postProcessPassResolved:!1,returnNull:!1,returnEmptyString:!0,returnObjects:!1,joinArrays:!1,returnedObjectHandler:!1,parseMissingKeyHandler:!1,appendNamespaceToMissingKey:!1,appendNamespaceToCIMode:!1,overloadTranslationOptionHandler:e=>{let t={};if("object"==typeof e[1]&&(t=e[1]),l(e[1])&&(t.defaultValue=e[1]),l(e[2])&&(t.tDescription=e[2]),"object"==typeof e[2]||"object"==typeof e[3]){let s=e[3]||e[2];Object.keys(s).forEach(e=>{t[e]=s[e]})}return t},interpolation:{escapeValue:!0,format:e=>e,prefix:"{{",suffix:"}}",formatSeparator:",",unescapePrefix:"-",nestingPrefix:"$t(",nestingSuffix:")",nestingOptionsSeparator:",",maxReplaces:1e3,skipOnVariables:!0},cacheInBuiltFormats:!0}),ea=e=>(l(e.ns)&&(e.ns=[e.ns]),l(e.fallbackLng)&&(e.fallbackLng=[e.fallbackLng]),l(e.fallbackNS)&&(e.fallbackNS=[e.fallbackNS]),e.supportedLngs?.indexOf?.("cimode")<0&&(e.supportedLngs=e.supportedLngs.concat(["cimode"])),"boolean"==typeof e.initImmediate&&(e.initAsync=e.initImmediate),e),eo=()=>{},en=e=>{Object.getOwnPropertyNames(Object.getPrototypeOf(e)).forEach(t=>{"function"==typeof e[t]&&(e[t]=e[t].bind(e))})};class er extends I{constructor(e={},t){if(super(),this.options=ea(e),this.services={},this.logger=j,this.modules={external:[]},en(this),t&&!this.isInitialized&&!e.isClone){if(!this.options.initAsync)return this.init(e,t),this;setTimeout(()=>{this.init(e,t)},0)}}init(e={},t){this.isInitializing=!0,"function"==typeof e&&(t=e,e={}),null==e.defaultNS&&e.ns&&(l(e.ns)?e.defaultNS=e.ns:0>e.ns.indexOf("translation")&&(e.defaultNS=e.ns[0]));let s=ei();this.options={...s,...this.options,...ea(e)},this.options.interpolation={...s.interpolation,...this.options.interpolation},void 0!==e.keySeparator&&(this.options.userDefinedKeySeparator=e.keySeparator),void 0!==e.nsSeparator&&(this.options.userDefinedNsSeparator=e.nsSeparator);let i=e=>e?"function"==typeof e?new e:e:null;if(!this.options.isClone){let e;this.modules.logger?j.init(i(this.modules.logger),this.options):j.init(null,this.options),e=this.modules.formatter?this.modules.formatter:ee;let t=new K(this.options);this.store=new D(this.options.resources,this.options);let a=this.services;a.logger=j,a.resourceStore=this.store,a.languageUtils=t,a.pluralResolver=new J(t,{prepend:this.options.pluralSeparator,simplifyPluralSuffix:this.options.simplifyPluralSuffix}),this.options.interpolation.format&&this.options.interpolation.format!==s.interpolation.format&&this.logger.deprecate("init: you are still using the legacy format function, please use the new approach: https://www.i18next.com/translation-function/formatting"),e&&(!this.options.interpolation.format||this.options.interpolation.format===s.interpolation.format)&&(a.formatter=i(e),a.formatter.init&&a.formatter.init(a,this.options),this.options.interpolation.format=a.formatter.format.bind(a.formatter)),a.interpolator=new G(this.options),a.utils={hasLoadedNamespace:this.hasLoadedNamespace.bind(this)},a.backendConnector=new es(i(this.modules.backend),a.resourceStore,a,this.options),a.backendConnector.on("*",(e,...t)=>{this.emit(e,...t)}),this.modules.languageDetector&&(a.languageDetector=i(this.modules.languageDetector),a.languageDetector.init&&a.languageDetector.init(a,this.options.detection,this.options)),this.modules.i18nFormat&&(a.i18nFormat=i(this.modules.i18nFormat),a.i18nFormat.init&&a.i18nFormat.init(this)),this.translator=new H(this.services,this.options),this.translator.on("*",(e,...t)=>{this.emit(e,...t)}),this.modules.external.forEach(e=>{e.init&&e.init(this)})}if(this.format=this.options.interpolation.format,t||(t=eo),this.options.fallbackLng&&!this.services.languageDetector&&!this.options.lng){let e=this.services.languageUtils.getFallbackCodes(this.options.fallbackLng);e.length>0&&"dev"!==e[0]&&(this.options.lng=e[0])}this.services.languageDetector||this.options.lng||this.logger.warn("init: no languageDetector is used and no lng is defined"),["getResource","hasResourceBundle","getResourceBundle","getDataByLanguage"].forEach(e=>{this[e]=(...t)=>this.store[e](...t)}),["addResource","addResources","addResourceBundle","removeResourceBundle"].forEach(e=>{this[e]=(...t)=>(this.store[e](...t),this)});let a=c(),o=()=>{let e=(e,s)=>{this.isInitializing=!1,this.isInitialized&&!this.initializedStoreOnce&&this.logger.warn("init: i18next is already initialized. You should call init just once!"),this.isInitialized=!0,this.options.isClone||this.logger.log("initialized",this.options),this.emit("initialized",this.options),a.resolve(s),t(e,s)};if(this.languages&&!this.isInitialized)return e(null,this.t.bind(this));this.changeLanguage(this.options.lng,e)};return this.options.resources||!this.options.initAsync?o():setTimeout(o,0),a}loadResources(e,t=eo){let s=t,i=l(e)?e:this.language;if("function"==typeof e&&(s=e),!this.options.resources||this.options.partialBundledLanguages){if(i?.toLowerCase()==="cimode"&&(!this.options.preload||0===this.options.preload.length))return s();let e=[],t=t=>{t&&"cimode"!==t&&this.services.languageUtils.toResolveHierarchy(t).forEach(t=>{"cimode"!==t&&0>e.indexOf(t)&&e.push(t)})};i?t(i):this.services.languageUtils.getFallbackCodes(this.options.fallbackLng).forEach(e=>t(e)),this.options.preload?.forEach?.(e=>t(e)),this.services.backendConnector.load(e,this.options.ns,e=>{e||this.resolvedLanguage||!this.language||this.setResolvedLanguage(this.language),s(e)})}else s(null)}reloadResources(e,t,s){let i=c();return"function"==typeof e&&(s=e,e=void 0),"function"==typeof t&&(s=t,t=void 0),e||(e=this.languages),t||(t=this.options.ns),s||(s=eo),this.services.backendConnector.reload(e,t,e=>{i.resolve(),s(e)}),i}use(e){if(!e)throw Error("You are passing an undefined module! Please check the object you are passing to i18next.use()");if(!e.type)throw Error("You are passing a wrong module! Please check the object you are passing to i18next.use()");return"backend"===e.type&&(this.modules.backend=e),("logger"===e.type||e.log&&e.warn&&e.error)&&(this.modules.logger=e),"languageDetector"===e.type&&(this.modules.languageDetector=e),"i18nFormat"===e.type&&(this.modules.i18nFormat=e),"postProcessor"===e.type&&A.addPostProcessor(e),"formatter"===e.type&&(this.modules.formatter=e),"3rdParty"===e.type&&this.modules.external.push(e),this}setResolvedLanguage(e){if(e&&this.languages&&!(["cimode","dev"].indexOf(e)>-1)){for(let e=0;e<this.languages.length;e++){let t=this.languages[e];if(!(["cimode","dev"].indexOf(t)>-1)&&this.store.hasLanguageSomeTranslations(t)){this.resolvedLanguage=t;break}}!this.resolvedLanguage&&0>this.languages.indexOf(e)&&this.store.hasLanguageSomeTranslations(e)&&(this.resolvedLanguage=e,this.languages.unshift(e))}}changeLanguage(e,t){this.isLanguageChangingTo=e;let s=c();this.emit("languageChanging",e);let i=e=>{this.language=e,this.languages=this.services.languageUtils.toResolveHierarchy(e),this.resolvedLanguage=void 0,this.setResolvedLanguage(e)},a=(a,o)=>{o?this.isLanguageChangingTo===e&&(i(o),this.translator.changeLanguage(o),this.isLanguageChangingTo=void 0,this.emit("languageChanged",o),this.logger.log("languageChanged",o)):this.isLanguageChangingTo=void 0,s.resolve((...e)=>this.t(...e)),t&&t(a,(...e)=>this.t(...e))},o=t=>{e||t||!this.services.languageDetector||(t=[]);let s=l(t)?t:t&&t[0],o=this.store.hasLanguageSomeTranslations(s)?s:this.services.languageUtils.getBestMatchFromCodes(l(t)?[t]:t);o&&(this.language||i(o),this.translator.language||this.translator.changeLanguage(o),this.services.languageDetector?.cacheUserLanguage?.(o)),this.loadResources(o,e=>{a(e,o)})};return e||!this.services.languageDetector||this.services.languageDetector.async?!e&&this.services.languageDetector&&this.services.languageDetector.async?0===this.services.languageDetector.detect.length?this.services.languageDetector.detect().then(o):this.services.languageDetector.detect(o):o(e):o(this.services.languageDetector.detect()),s}getFixedT(e,t,s){let i=(e,t,...a)=>{let o,n;(o="object"!=typeof t?this.options.overloadTranslationOptionHandler([e,t].concat(a)):{...t}).lng=o.lng||i.lng,o.lngs=o.lngs||i.lngs,o.ns=o.ns||i.ns,""!==o.keyPrefix&&(o.keyPrefix=o.keyPrefix||s||i.keyPrefix);let r=this.options.keySeparator||".";return o.keyPrefix&&Array.isArray(e)?n=e.map(e=>("function"==typeof e&&(e=F(e,{...this.options,...t})),`${o.keyPrefix}${r}${e}`)):("function"==typeof e&&(e=F(e,{...this.options,...t})),n=o.keyPrefix?`${o.keyPrefix}${r}${e}`:e),this.t(n,o)};return l(e)?i.lng=e:i.lngs=e,i.ns=t,i.keyPrefix=s,i}t(...e){return this.translator?.translate(...e)}exists(...e){return this.translator?.exists(...e)}setDefaultNamespace(e){this.options.defaultNS=e}hasLoadedNamespace(e,t={}){if(!this.isInitialized)return this.logger.warn("hasLoadedNamespace: i18next was not initialized",this.languages),!1;if(!this.languages||!this.languages.length)return this.logger.warn("hasLoadedNamespace: i18n.languages were undefined or empty",this.languages),!1;let s=t.lng||this.resolvedLanguage||this.languages[0],i=!!this.options&&this.options.fallbackLng,a=this.languages[this.languages.length-1];if("cimode"===s.toLowerCase())return!0;let o=(e,t)=>{let s=this.services.backendConnector.state[`${e}|${t}`];return -1===s||0===s||2===s};if(t.precheck){let e=t.precheck(this,o);if(void 0!==e)return e}return!!(this.hasResourceBundle(s,e)||!this.services.backendConnector.backend||this.options.resources&&!this.options.partialBundledLanguages||o(s,e)&&(!i||o(a,e)))}loadNamespaces(e,t){let s=c();return this.options.ns?(l(e)&&(e=[e]),e.forEach(e=>{0>this.options.ns.indexOf(e)&&this.options.ns.push(e)}),this.loadResources(e=>{s.resolve(),t&&t(e)}),s):(t&&t(),Promise.resolve())}loadLanguages(e,t){let s=c();l(e)&&(e=[e]);let i=this.options.preload||[],a=e.filter(e=>0>i.indexOf(e)&&this.services.languageUtils.isSupportedCode(e));return a.length?(this.options.preload=i.concat(a),this.loadResources(e=>{s.resolve(),t&&t(e)}),s):(t&&t(),Promise.resolve())}dir(e){if(e||(e=this.resolvedLanguage||(this.languages?.length>0?this.languages[0]:this.language)),!e)return"rtl";try{let t=new Intl.Locale(e);if(t&&t.getTextInfo){let e=t.getTextInfo();if(e&&e.direction)return e.direction}}catch(e){}let t=this.services?.languageUtils||new K(ei());return e.toLowerCase().indexOf("-latn")>1?"ltr":["ar","shu","sqr","ssh","xaa","yhd","yud","aao","abh","abv","acm","acq","acw","acx","acy","adf","ads","aeb","aec","afb","ajp","apc","apd","arb","arq","ars","ary","arz","auz","avl","ayh","ayl","ayn","ayp","bbz","pga","he","iw","ps","pbt","pbu","pst","prp","prd","ug","ur","ydd","yds","yih","ji","yi","hbo","men","xmn","fa","jpr","peo","pes","prs","dv","sam","ckb"].indexOf(t.getLanguagePartFromCode(e))>-1||e.toLowerCase().indexOf("-arab")>1?"rtl":"ltr"}static createInstance(e={},t){return new er(e,t)}cloneInstance(e={},t=eo){let s=e.forkResourceStore;s&&delete e.forkResourceStore;let i={...this.options,...e,isClone:!0},a=new er(i);return(void 0!==e.debug||void 0!==e.prefix)&&(a.logger=a.logger.clone(e)),["store","services","language"].forEach(e=>{a[e]=this[e]}),a.services={...this.services},a.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},s&&(a.store=new D(Object.keys(this.store.data).reduce((e,t)=>(e[t]={...this.store.data[t]},e[t]=Object.keys(e[t]).reduce((s,i)=>(s[i]={...e[t][i]},s),e[t]),e),{}),i),a.services.resourceStore=a.store),a.translator=new H(a.services,i),a.translator.on("*",(e,...t)=>{a.emit(e,...t)}),a.init(i,t),a.translator.options=i,a.translator.backendConnector.services.utils={hasLoadedNamespace:a.hasLoadedNamespace.bind(a)},a}toJSON(){return{options:this.options,store:this.store,language:this.language,languages:this.languages,resolvedLanguage:this.resolvedLanguage}}}let el=er.createInstance();el.createInstance=er.createInstance,el.createInstance,el.dir,el.init,el.loadResources,el.reloadResources,el.use,el.changeLanguage,el.getFixedT;let ec=el.t;el.exists,el.setDefaultNamespace,el.hasLoadedNamespace,el.loadNamespaces,el.loadLanguages;class eh extends Error{static createEngineError(e,t){let s=new eh(ec("执行错误"));return s.code=e,s.message=t,s}code;origin}class ed{aggregateRuleRegistration;static listFromRawMessage(e,t){let s=new ed(t);return s.fromMessage(e),s.aggregate(e),s}name;contentType;payload;visibleScope;constructor(e){this.aggregateRuleRegistration=e,this.name="",this.contentType="",this.payload=null,this.visibleScope=void 0}aggregate(e){e.visibleScope?this.visibleScope!==e.visibleScope&&console.warn("visible scope conflict"):this.visibleScope=e.visibleScope;let t=this.aggregateRuleRegistration.get(this.contentType);if(!t)return void console.warn(`No rule found for content type ${this.contentType}`);this.payload=t.execute(e.payload,this.payload)}fromMessage(e){this.contentType=e.contentType,this.visibleScope=e.visibleScope,this.name=e.contentName}toJSON(){return{contentType:this.contentType,name:this.name,payload:this.payload,visibleScope:this.visibleScope}}}let ep=Symbol("unscheduledEventId");class eu{aggregateRuleRegistration;static action="";static resource="";static liftFromEventMessage(e,t,s){let i=new(this===eu?eg:this)(t);return s?.contentConstructor&&(i.contentConstructor=s.contentConstructor),i.id=e.event.id,i.name=e.event.name,i.status=e.event.status,i.parentEventId=e.parentEventId,i.isStop=e.event.is_stop??!1,i.render=e.event.render,i.task_id=e.event.task_id,i.parent_task_id=e.event.parent_task_id,i.task_name=e.event.task_name,i.name_cn=e.event.render?.component_detail?.name_cn||e.event.render?.component_detail?.name,i}static parseEventName(e){let t=e.slice(1).split("/");return[t[0],t[1],t[2]??""]}id;task_id;parent_task_id;task_name;status;name;name_cn;error_code;error_message;contents;nameToContentMap;parentEventId;isStop;render;contentConstructor;get resource(){return eu.parseEventName(this.name)[1]}get action(){return eu.parseEventName(this.name)[0]}constructor(e){this.aggregateRuleRegistration=e,this.id="",this.parent_task_id="",this.task_name="",this.status="preparing",this.name="",this.name_cn="",this.error_code=null,this.error_message="",this.contents=[],this.nameToContentMap=new Map,this.parentEventId=[],this.isStop=!1,this.render=void 0,this.contentConstructor=null}receiveContentMessageMessage(e){let t=this.nameToContentMap.get(e.contentName);if(this.render=e.event.render,this.status=e.event.status,e.event.error_code&&(this.error_code=e.event.error_code,this.error_message=e.event.error_message),!t){t=this.contentConstructor?this.contentConstructor.listFromRawMessage(e,this.aggregateRuleRegistration):ed.listFromRawMessage(e,this.aggregateRuleRegistration),this.contents.push(t),this.nameToContentMap.set(e.contentName,t),this.onReceiveNewContent(t);return}this.aggregateContent?this.aggregateContent(t,e):t.aggregate(e),this.onReceiveNewContent(t)}onReceiveNewContent(e){}onAggregateContent(e){}getContentByType(e){return this.userOutputContents.filter(t=>t.contentType===e)}get userOutputContents(){return this.contents.filter(e=>"user"===e.visibleScope)}toJSON(){return{id:this.id,status:this.status,contents:this.contents.map(e=>e.toJSON()),nameToContentMap:this.nameToContentMap,name:this.name,action:this.action,resource:this.resource,isStop:this.isStop,userOutputContents:this.userOutputContents.map(e=>e.toJSON())}}}class eg extends eu{}class ef{static fromRawMessage(e){let t=[];if(!e.content||0===e.content.length){let t=new ef;return t.conversationId=e.conversation_id,[t]}for(let s of e.content){let i=new ef;i.conversationId=e.conversation_id,i.traceId=e.trace_id;let a=s.event;i.payload=s.text,i.visibleScope=s.visible_scope,i.contentName=s.name||s.type,i.contentType=s.type,i.error_code=s.error_code,i.error_message=s.error_message,a?i.event=a:i.event.id=ep;let o=s.render;if(o){i.event.render=o;let e=o.component_detail?.path||[];e.length>0&&(i.parentEventId=e.at(-1).parents_id||[])}s.usage&&(s.usage.prompt_tokens&&(i.usage.prompt_tokens=s.usage.prompt_tokens),s.usage.completion_tokens&&(i.usage.completion_tokens=s.usage.completion_tokens),s.usage.total_tokens&&(i.usage.total_tokens=s.usage.total_tokens)),t.push(i)}return t}static isErrorMessage(e){return!!e.error_code}event={id:"",name:"event_name",status:"preparing",is_stop:!1,error_code:"",error_message:"",render:void 0,task_id:void 0,parent_task_id:void 0,task_name:void 0};usage={prompt_tokens:0,completion_tokens:0,total_tokens:0};payload=null;contentType="";contentName="";visibleScope=void 0;conversationId="";traceId="";parentEventId=[];error_code="";error_message=""}let em=Symbol("receiveNewMessage"),ey=Symbol("receiveNewEvent");w=Symbol.asyncIterator;class ev{response;static viewName="";completed;constructor(e){this.response=e,this.completed=!1}complete(){this.completed=!0}[ey](e){throw Error("Method not implemented.")}[em](e){}restoreCompleted(e,t){}abortAction(e,t){}[w](){throw Error("Method not implemented.")}}class ex{options;events;conversationId;traceId;views;completed;message_id;error;eventTarget;get finished(){return this.finishedResolver.promise}get viewNames(){return[...this.nameToViewMap.keys()]}idToEventMap;aggregateRuleRegistration;activeViews;nameToViewMap;finishedResolver;actionBaseEventPluginsMap;actionResourceBaseEventPluginsMap;constructor(e){for(let t of(this.options=e,this.events=[],this.conversationId="",this.traceId="",this.completed=!1,this.message_id="",this.error=null,this.eventTarget=new EventTarget,this.idToEventMap=new Map,this.aggregateRuleRegistration=new Map,this.nameToViewMap=new Map,this.finishedResolver=Promise.withResolvers(),this.actionBaseEventPluginsMap=new Map,this.actionResourceBaseEventPluginsMap=new Map,this.receiveEventMessage=e=>{let t=ef.fromRawMessage(e);for(let s of(this.message_id=e.message_id,t)){let e;if(ef.isErrorMessage(s)&&this.receiveErrorMessage(s),!this.conversationId&&s.conversationId&&this.eventTarget.dispatchEvent(new CustomEvent("onConversationIdRefreshed",{detail:{id:s.conversationId}})),this.conversationId=s.conversationId,this.traceId=s.traceId,!s.event.id)return;if(this.idToEventMap.has(s.event.id))e=this.idToEventMap.get(s.event.id);else{let t,[i,a]=eu.parseEventName(s.event.name),o=`/${i}/${a}`;for(let t of(e=(this.actionResourceBaseEventPluginsMap.has(o)?this.actionResourceBaseEventPluginsMap.get(o):this.actionBaseEventPluginsMap.has(i)?this.actionBaseEventPluginsMap.get(i):eg).liftFromEventMessage(s,this.aggregateRuleRegistration,{contentConstructor:this.options?.executorOptions?.factory?.EventOutputContent}),this.idToEventMap.set(s.event.id,e),this.events.push(e),this.activeViews))t[ey](e)}for(let t of(e.receiveContentMessageMessage(s),this.activeViews))t[em](s)}},this.receiveErrorMessage=e=>{let t=eh.createEngineError(e.error_code,e.error_message);this.error=t,this.complete(t)},this.activeViews=e?.views.map(e=>{let t=new e(this);if(this.nameToViewMap.has(e.viewName))throw Error("View conflict");return this.nameToViewMap.set(e.viewName,t),t})??[],e?.aggregateRules??o)){let e=new t;if(this.aggregateRuleRegistration.has(t.contentType))throw Error("Rule conflict");this.aggregateRuleRegistration.set(t.contentType,e)}this.views=new Proxy({},{get:(e,t)=>{if(this.nameToViewMap.has(t))return this.nameToViewMap.get(t)},set(){throw Error("Cannot set views")}}),e?.eventPlugins&&(this.actionBaseEventPluginsMap=e.eventPlugins.actionBaseEventPluginsMap,this.actionResourceBaseEventPluginsMap=e.eventPlugins.actionResourceBaseEventPluginsMap)}complete(e){for(let e of(this.completed=!0,this.activeViews))e.complete();e?this.finishedResolver.reject(e):this.finishedResolver.resolve()}receiveEventMessage;receiveErrorMessage}class eb{resolver=null;event=null;transferCompleted=!1;completed=!1;hasYield=!1;complete(){this.completed=!0,this.iterate()}iterate(){this.resolver&&(this.resolver.resolve({done:!1,value:this.event?.contents.map(e=>e.toJSON())||[]}),this.hasYield=!0)}async next(){return this.completed?this.hasYield?Promise.resolve({done:!0,value:void 0}):(this.hasYield=!0,Promise.resolve({done:!1,value:this.event?.contents.map(e=>e.toJSON())||[]})):(this.resolver=Promise.withResolvers(),this.resolver.promise)}}k=Symbol.asyncIterator;class e_ extends ev{static viewName="toolUse";event=null;completed=!1;asyncIterators=[];[em](){for(let e of this.asyncIterators)e.iterate()}complete(){for(let e of(super.complete(),this.asyncIterators))e.complete()}[ey](e){if(this.event){if(this.event!==e)throw Error("tool use event id conflict")}else for(let t of(this.event=e,this.asyncIterators))t.event=e}[k](){let e=new eb;return e.event=this.event,e.transferCompleted=this.completed,this.asyncIterators.push(e),this.completed&&e.complete(),e}get contents(){return this.event?.contents||[]}}class ew{event;siblings;children;parent;constructor(e){this.event=e,this.siblings=[],this.children=[],this.parent=null}}class ek{topLevelEvent;resolver;completed;hasYield;constructor(e){this.topLevelEvent=e,this.resolver=null,this.completed=!1,this.hasYield=!1}complete(){this.completed=!0,this.iterate()}iterate(){this.resolver?.resolve({done:!1,value:this.topLevelEvent}),this.hasYield=!0}async next(){return this.completed?this.hasYield?Promise.resolve({done:!0,value:void 0}):(this.hasYield=!0,Promise.resolve({done:!1,value:this.topLevelEvent})):(this.resolver=Promise.withResolvers(),this.resolver.promise)}}S=Symbol.asyncIterator;class eS extends ev{static viewName="treeView";static splitActionNames=["toolcall","thought","chat","tools","references"];static topLevelResourceNames=[];topLevelEvents=[];idToEventTreeNodeMap=new Map;asyncIterators=[];complete(){for(let e of(super.complete(),this.asyncIterators))e.complete()}[em](){for(let e of this.asyncIterators)e.iterate()}[ey](e){if(this.idToEventTreeNodeMap.has(e.id))throw Error("event id conflict");let t=new ew(e);if(this.idToEventTreeNodeMap.set(e.id,t),eS.splitActionNames.includes(e.action))return void this.topLevelEvents.push(t);for(let s of e.parentEventId){let e=this.idToEventTreeNodeMap.get(s);if(!e)throw Error("parent event not found");for(let s of(t.parent=e,e.children.push(t),e.children))s!==t&&t.siblings.push(s)}}[S](){let e=new ek(this.topLevelEvents);return this.asyncIterators.push(e),e}}class eE{options;transport;aggregateRules;actionBaseEventPluginsMap;actionResourceBaseEventPluginsMap;constructor(e){if(this.options=e,this.aggregateRules=o,this.actionBaseEventPluginsMap=new Map,this.actionResourceBaseEventPluginsMap=new Map,this.genResponseOptions=()=>({views:this.options.views,eventPlugins:{actionBaseEventPluginsMap:this.actionBaseEventPluginsMap,actionResourceBaseEventPluginsMap:this.actionResourceBaseEventPluginsMap},aggregateRules:this.aggregateRules,executorOptions:this.options}),this.invoke=(e,t)=>{let s=new ex(this.genResponseOptions());return t?.abortController?.signal.addEventListener("abort",()=>{s.eventTarget.dispatchEvent(new Event("abort"))}),this.transport.send(e,{onMessage:e=>{let t=JSON.parse(e);if(s.receiveEventMessage(t),this.options.onMessage?.(s),t.code){let e=eh.createEngineError(t.code,t.message);s.error=e,s.complete(e)}},onCompleted(){s.complete()},onError(e){s.complete(e),s.error=e}},t),s},this.transport=e.transport,e.events){for(let t of e.events)if(t.prototype instanceof eu&&t.action){if(t.resource){let e=`/${t.action}/${t.resource}`;this.actionResourceBaseEventPluginsMap.has(e)&&console.warn(ec("存在action, resource均重名的插件, 重复注册")),this.actionResourceBaseEventPluginsMap.set(e,t);continue}this.actionBaseEventPluginsMap.has(t.action)&&console.warn(ec("存在action重名的插件, 重复注册")),this.actionBaseEventPluginsMap.set(t.action,t)}}e.aggregateRules&&(this.aggregateRules=e.aggregateRules)}genResponseOptions;invoke}let eO=async(e,t,i)=>{let a=i.headers.get("Content-Type");if(!a?.includes("text/event-stream")){if(a?.includes("application/json")){let e=i.clone();(await e.json()).code}throw new s(i,e,t)}return i};class eR{options;constructor(e){this.options=e,this.changeEndPoint=e=>{this.options.endpoint=e},this.send=(e,s,a)=>{let o=i({onData:s.onMessage,onCompleted:s.onCompleted});if(!this.options.endpoint)throw Error("endpoint is not set");t.post(this.options.endpoint,{json:e,headers:{...this.options?.header,...a?.headers},signal:a?.abortController?.signal,timeout:this.options.timeout??18e5,hooks:{afterResponse:[eO,o]}}).catch(s.onError)}}changeEndPoint;send}let eC=[239,187,191],eL={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)},eP=new Uint8Array(16),eM=[];for(let e=0;e<256;++e)eM.push((e+256).toString(16).slice(1));let eT=function(t,s,i){if(eL.randomUUID&&!s&&!t)return eL.randomUUID();let a=(t=t||{}).random??t.rng?.()??function(){if(!e){if("undefined"==typeof crypto||!crypto.getRandomValues)throw Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");e=crypto.getRandomValues.bind(crypto)}return e(eP)}();if(a.length<16)throw Error("Random bytes length must be >= 16");if(a[6]=15&a[6]|64,a[8]=63&a[8]|128,s){if((i=i||0)<0||i+16>s.length)throw RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let e=0;e<16;++e)s[i+e]=a[e];return s}return function(e,t=0){return(eM[e[t+0]]+eM[e[t+1]]+eM[e[t+2]]+eM[e[t+3]]+"-"+eM[e[t+4]]+eM[e[t+5]]+"-"+eM[e[t+6]]+eM[e[t+7]]+"-"+eM[e[t+8]]+eM[e[t+9]]+"-"+eM[e[t+10]]+eM[e[t+11]]+eM[e[t+12]]+eM[e[t+13]]+eM[e[t+14]]+eM[e[t+15]]).toLowerCase()}(a)};var eN={},e$=function(){if(E)return eN;E=1,eN.parse=function(e,s){if("string"!=typeof e)throw TypeError("argument str must be a string");var i={},a=e.length;if(a<2)return i;var o=s&&s.decode||l,c=0,h=0,d=0;do{if(-1===(h=e.indexOf("=",c)))break;if(-1===(d=e.indexOf(";",c)))d=a;else if(h>d){c=e.lastIndexOf(";",h-1)+1;continue}var p=n(e,c,h),u=r(e,h,p),g=e.slice(p,u);if(!t.call(i,g)){var f=n(e,h+1,d),m=r(e,d,f);34===e.charCodeAt(f)&&34===e.charCodeAt(m-1)&&(f++,m--);var y=e.slice(f,m);i[g]=function(e,t){try{return t(e)}catch(t){return e}}(y,o)}c=d+1}while(c<a);return i},eN.serialize=function(t,n,r){var l=r&&r.encode||encodeURIComponent;if("function"!=typeof l)throw TypeError("option encode is invalid");if(!s.test(t))throw TypeError("argument name is invalid");var c=l(n);if(!i.test(c))throw TypeError("argument val is invalid");var h=t+"="+c;if(!r)return h;if(null!=r.maxAge){var d=Math.floor(r.maxAge);if(!isFinite(d))throw TypeError("option maxAge is invalid");h+="; Max-Age="+d}if(r.domain){if(!a.test(r.domain))throw TypeError("option domain is invalid");h+="; Domain="+r.domain}if(r.path){if(!o.test(r.path))throw TypeError("option path is invalid");h+="; Path="+r.path}if(r.expires){var p,u=r.expires;if(p=u,"[object Date]"!==e.call(p)||isNaN(u.valueOf()))throw TypeError("option expires is invalid");h+="; Expires="+u.toUTCString()}if(r.httpOnly&&(h+="; HttpOnly"),r.secure&&(h+="; Secure"),r.partitioned&&(h+="; Partitioned"),r.priority)switch("string"==typeof r.priority?r.priority.toLowerCase():r.priority){case"low":h+="; Priority=Low";break;case"medium":h+="; Priority=Medium";break;case"high":h+="; Priority=High";break;default:throw TypeError("option priority is invalid")}if(r.sameSite)switch("string"==typeof r.sameSite?r.sameSite.toLowerCase():r.sameSite){case!0:case"strict":h+="; SameSite=Strict";break;case"lax":h+="; SameSite=Lax";break;case"none":h+="; SameSite=None";break;default:throw TypeError("option sameSite is invalid")}return h};var e=Object.prototype.toString,t=Object.prototype.hasOwnProperty,s=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,i=/^("?)[\u0021\u0023-\u002B\u002D-\u003A\u003C-\u005B\u005D-\u007E]*\1$/,a=/^([.]?[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)([.][a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?)*$/i,o=/^[\u0020-\u003A\u003D-\u007E]*$/;function n(e,t,s){do{var i=e.charCodeAt(t);if(32!==i&&9!==i)return t}while(++t<s);return s}function r(e,t,s){for(;t>s;){var i=e.charCodeAt(--t);if(32!==i&&9!==i)return t+1}return s}function l(e){return -1!==e.indexOf("%")?decodeURIComponent(e):e}return eN}();function ej(e,t={}){var s;let i=(s=e)&&"j"===s[0]&&":"===s[1]?s.substr(2):s;if(!t.doNotParse)try{return JSON.parse(i)}catch(e){}return e}class eI{constructor(e,t={}){var s;this.changeListeners=[],this.HAS_DOCUMENT_COOKIE=!1,this.update=()=>{if(!this.HAS_DOCUMENT_COOKIE)return;let e=this.cookies;this.cookies=e$.parse(document.cookie),this._checkChanges(e)};let i="undefined"==typeof document?"":document.cookie;this.cookies="string"==typeof(s=e||i)?e$.parse(s):"object"==typeof s&&null!==s?s:{},this.defaultSetOptions=t,this.HAS_DOCUMENT_COOKIE=function(){let e="undefined"==typeof global?void 0:global.TEST_HAS_DOCUMENT_COOKIE;return"boolean"==typeof e?e:"object"==typeof document&&"string"==typeof document.cookie}()}_emitChange(e){for(let t=0;t<this.changeListeners.length;++t)this.changeListeners[t](e)}_checkChanges(e){new Set(Object.keys(e).concat(Object.keys(this.cookies))).forEach(t=>{e[t]!==this.cookies[t]&&this._emitChange({name:t,value:ej(this.cookies[t])})})}_startPolling(){this.pollingInterval=setInterval(this.update,300)}_stopPolling(){this.pollingInterval&&clearInterval(this.pollingInterval)}get(e,t={}){return t.doNotUpdate||this.update(),ej(this.cookies[e],t)}getAll(e={}){e.doNotUpdate||this.update();let t={};for(let s in this.cookies)t[s]=ej(this.cookies[s],e);return t}set(e,t,s){s=s?Object.assign(Object.assign({},this.defaultSetOptions),s):this.defaultSetOptions;let i="string"==typeof t?t:JSON.stringify(t);this.cookies=Object.assign(Object.assign({},this.cookies),{[e]:i}),this.HAS_DOCUMENT_COOKIE&&(document.cookie=e$.serialize(e,i,s)),this._emitChange({name:e,value:t,options:s})}remove(e,t){let s=t=Object.assign(Object.assign(Object.assign({},this.defaultSetOptions),t),{expires:new Date(1970,1,1,0,0,1),maxAge:0});this.cookies=Object.assign({},this.cookies),delete this.cookies[e],this.HAS_DOCUMENT_COOKIE&&(document.cookie=e$.serialize(e,"",s)),this._emitChange({name:e,value:void 0,options:t})}addChangeListener(e){this.changeListeners.push(e),this.HAS_DOCUMENT_COOKIE&&1===this.changeListeners.length&&("object"==typeof window&&"cookieStore"in window?window.cookieStore.addEventListener("change",this.update):this._startPolling())}removeChangeListener(e){let t=this.changeListeners.indexOf(e);t>=0&&this.changeListeners.splice(t,1),this.HAS_DOCUMENT_COOKIE&&0===this.changeListeners.length&&("object"==typeof window&&"cookieStore"in window?window.cookieStore.removeEventListener("change",this.update):this._stopPolling())}}class eD{options;constructor(e){this.options=e,this.changeEndPoint=e=>{this.options.endpoint=e},this.send=(e,t,s)=>{let i=function(e){let t,s,i,a,o,n,r;return l(),{feed:function(l){var c;s=s?s+l:l,t&&(c=s,eC.every((e,t)=>c.charCodeAt(t)===e))&&(s=s.slice(eC.length)),t=!1;let h=s.length,d=0,p=!1;for(;d<h;){let t;p&&("\n"===s[d]&&++d,p=!1);let l=-1,c=a;for(let e=i;l<0&&e<h;++e)":"===(t=s[e])&&c<0?c=e-d:"\r"===t?(p=!0,l=e-d):"\n"===t&&(l=e-d);if(l<0){i=h-d,a=c;break}i=0,a=-1,function(t,s,i,a){if(0===a){r.length>0&&(e({type:"event",id:o,event:n||void 0,data:r.slice(0,-1)}),r="",o=void 0),n=void 0;return}let l=i<0,c=t.slice(s,s+(l?a:i)),h=0;h=l?a:" "===t[s+i+1]?i+2:i+1;let d=s+h,p=a-h,u=t.slice(d,d+p).toString();if("data"===c)r+=u?"".concat(u,"\n"):"\n";else if("event"===c)n=u;else if("id"!==c||u.includes("\0")){if("retry"===c){let t=parseInt(u,10);Number.isNaN(t)||e({type:"reconnect-interval",value:t})}}else o=u}(s,d,c,l),d+=l+1}d===h?s="":d>0&&(s=s.slice(d))},reset:l};function l(){t=!0,s="",i=0,a=-1,o=void 0,n=void 0,r=""}}(e=>{"event"===e.type&&e.data&&t.onMessage(e.data)}),a=new XMLHttpRequest;a.open("POST",this.options.endpoint.toString(),!0),a.setRequestHeader("X-Bce-Request-Id",eT());let o=new eI().get("bce-user-info")||"";a.setRequestHeader("csrfToken",o),a.setRequestHeader("Bce-Long-Term-Session","True"),a.setRequestHeader("Content-Type","application/json");let n=this.options.headers??s?.headers;if(n)if(Array.isArray(n))for(let e of n)a.setRequestHeader(e[0],e[1]);else if(n instanceof Headers)n.forEach((e,t)=>{a.setRequestHeader(t,e)});else for(let[e,t]of Object.entries(n))a.setRequestHeader(e,t);a.timeout=this.options.timeout??6e5,a.addEventListener("progress",()=>{let e=a.getResponseHeader("Content-Type");if(!e?.includes("text/event-stream"))return;let t=a.responseText,s=t.slice(a.prevLen);a.prevLen=t.length,i.feed(s)}),a.addEventListener("load",()=>{let e=a.getResponseHeader("Content-Type");if(a.status<200||a.status>=300||!e?.includes("text/event-stream"))return void t.onError(Error("Request failed"));t.onCompleted()}),a.addEventListener("error",()=>{t.onError(Error("Request failed"))}),a.addEventListener("readystatechange",()=>{4===a.readyState&&a.status>=200&&a.status<300&&t.onCompleted?.()}),a.send(e),s?.abortController?.signal?.addEventListener("abort",()=>{a.abort();let e=Error("Request aborted");e.name="AbortError",t.onError(e)})}}changeEndPoint;send}class eA extends eu{static action="thought";static resource="action";get thoughtText(){let e=this.contents.find(e=>"text"===e.contentType);return e&&e.payload?.info||""}}class eV extends eu{static action="toolcall";static resource="";get componentDetail(){if(!this.render)throw Error("render is not defined");return this.render.component_detail}get isOfficialComponent(){return!this.componentDetail.is_workflow}get inputs(){return this.componentDetail?.arguments||{}}get thought(){return this.render?.thought||""}get componentName(){return this.componentDetail?.name||""}get componentOutputs(){let e={};for(let t of this.contents)t.payload&&Object.keys(t.payload).length>0&&Object.assign(e,{[t.name]:t.payload});return e}}class eF extends eu{static action="chat";static resource="chat_agent";get content(){let e=this.contents.find(e=>"text"===e.contentType);return e?e.payload.info:""}}class eU{id="";segment_id="";title="";source_child_chunks=[];segments_type=0;content="";dataset_id="";dataset_name="";document_id="";document_name="";score=0;is_expanded_segment=!1;is_virtual_chunk=!1;child_chunks=[];original_chunk_id="";data_source_type="upload_file";row_line=[];meta={para_type:"text",para_format:"",chart_img:[]};coord={box:[],page_num:[]};getAllBoxDataForOnePage=e=>{let t=[];if(!this.coord)return t;for(let s=0;s<this.coord.page_num.length;++s)this.coord.page_num[s]===e&&this.coord.box[s]&&t.push(this.coord.box[s]);return t};get textTableData(){let e={title:"",stringifyHtml:""},t=/<table[\s\S]*?<\/table>/g.exec(this.content);return t&&(e.title=this.content.slice(0,t.index).trim(),e.stringifyHtml=t[0]),e}get isLatexContent(){return null!==/\$(.*?)\$/g.exec(this.content)}get tableHtmlIsParseable(){return!new DOMParser().parseFromString(this.textTableData.stringifyHtml,"text/html").querySelector("parsererror")}get sortedTableRowLineData(){return this.row_line.toSorted((e,t)=>e.index-t.index)}get tableRowLineDataMap(){let e={};for(let t of this.sortedTableRowLineData)e[t.key]=t.value;return e.key="table_data",e}get associatedImageDataInSourceFile(){if(this.is_virtual_chunk)return[];let e=this.child_chunks,t=[];for(let s of e)t.push({page_num:s.meta.page_num,image_url:s.meta.url,boxData:this.getAllBoxDataForOnePage(s.meta.page_num)});return t.toSorted((e,t)=>e.page_num-t.page_num)}}class eB{database_id="";database_name="";datasheet_id="";datasheet_name=""}class eH{doc_id="";icon="";site_name="";title="";content="";resource_type="web";reference_id=0;get url(){return this.doc_id}get favIcon(){return this.icon}}class eK{database_id="";database_name="";datasheet_id="";datasheet_name=""}class ez{id="";title="";content="";intervention_id="";doc_id="";dataset_id="";query=""}class eq{id="";title="";content="";from="query"}class eJ{static source="database";static fromMessagePayload(e){let t=new eJ;return t.fromMessagePayload(e),t}type="engine";source="search_db_sheet";payload=new eB;fromMessagePayload(e){this.payload.database_id=e.extra.database_id,this.payload.database_name=e.extra.database_name,this.payload.datasheet_id=e.extra.table_id,this.payload.datasheet_name=e.extra.table_name}}class eY{static source="search_db";static fromMessagePayload(e){let t=new eY;return t.fromMessagePayload(e),t}type="engine";source="search_db";payload=new eU;fromMessagePayload(e){this.payload.content=e.content,this.payload.segment_id=e.extra.id||e.id,this.payload.document_id=e.extra.document_id,this.payload.document_name=e.extra.document_name,this.payload.dataset_name=e.extra.dataset_name,this.payload.dataset_id=e.extra.dataset_id,this.payload.coord=e.extra.coord,this.payload.meta=e.extra.meta,this.payload.data_source_type=e.extra.data_source_type,this.payload.row_line=e.extra.row_line,this.payload.child_chunks=e.extra.child_chunks,this.payload.id=e.id,this.payload.source_child_chunks=e.extra.child_chunks,this.payload.is_virtual_chunk=e.extra.is_virtual_chunk,this.payload.title=e.title,this.payload.segments_type=e.extra.segments_type,this.payload.score=e.extra.score,e.extra.is_virtual_chunk&&(this.payload.child_chunks=Array.isArray(e.extra.child_chunks)?e.extra.child_chunks.map(e=>{let t=new eU;return t.content=e.content,t.segment_id=e.id,t.document_id=e.document_id,t.document_name=e.document_name,t.dataset_name=e.dataset_name,t.dataset_id=e.dataset_id,t.coord=e.coord,t.meta=e.meta,t.data_source_type=e.data_source_type,t.row_line=e.row_line,t.original_chunk_id=e.original_chunk_id,t.score=e.score,t.is_expanded_segment=e.is_expanded_segment,t}):[])}}class eW{static source="search_baidu";static fromMessagePayload(e){let t=new eW;return t.fromMessagePayload(e),t}type="web";source="search_baidu";payload=new eH;fromMessagePayload(e){this.payload.doc_id=e.extra.id||e.doc_id,this.payload.site_name=e.extra.site_name||e.extra.website,this.payload.icon=e.extra.icon||e.icon,this.payload.title=e.title,this.payload.content=e.content,this.payload.resource_type=e.extra.resource_type,this.payload.reference_id=e.extra.reference_id}}class eG{static source="search_bing";static fromMessagePayload(e){let t=new eG;return t.fromMessagePayload(e),t}type="web";source="search_bing";payload=new eH;fromMessagePayload(e){this.payload.doc_id=e.extra.id||e.doc_id,this.payload.site_name=e.extra.site_name,this.payload.icon=e.extra.icon,this.payload.title=e.title,this.payload.content=e.content,this.payload.resource_type=e.extra.resource_type}}class eQ{static source="search_db_sheet";static fromMessagePayload(e){let t=new eQ;return t.fromMessagePayload(e),t}type="engine";source="search_db_sheet";payload=new eK;fromMessagePayload(e){this.payload.database_id=e.extra.database_id,this.payload.database_name=e.extra.database_name,this.payload.datasheet_id=e.extra.datasheet_id,this.payload.datasheet_name=e.extra.datasheet_name}}class eX{static fromMessagePayload(e){let t=new eX;return t.fromMessagePayload(e),t}type="engine";source="search_db";payload=new ez;fromMessagePayload(e){this.payload.id=e.id,this.payload.title=e.title,this.payload.content=e.content,this.payload.intervention_id=e.chunk_id,this.payload.doc_id=e.doc_id,this.payload.dataset_id=e.dataset_id,this.payload.query=e.query}}class eZ{static fromMessagePayload(e){let t=new eZ;return t.fromMessagePayload(e),t}type="rule_intervention";source="search_db";payload=new eq;fromMessagePayload(e){this.payload.id=e.id,this.payload.title=e.title,this.payload.content=e.content,this.payload.from=e.source}}class e0{factories=[eJ,eY,eW,eG,eQ,{fromMessagePayload:eW.fromMessagePayload,source:"ai_search"},{fromMessagePayload:eW.fromMessagePayload,source:"aiapi"}];createReference(e){let t=this.factories.find(t=>e.source===t.source);return t?t.fromMessagePayload(e):e}}let e1=new e0;class e8 extends eu{static action="toolcall";static resource="rag";get references(){let e=this.contents.find(e=>"references"===e.name);return e?e.payload.map(e=>e1.createReference(e)):[]}get finalAnswer(){let e=this.contents.find(e=>["content","answer"].includes(e.name));return e?e.payload.info:""}get componentOutputs(){let e={};for(let t of this.contents)t.payload&&Object.keys(t.payload).length>0&&Object.assign(e,{[t.name]:t.payload});return e}get componentDetail(){if(!this.render)throw Error("render is not defined");return this.render.component_detail}}class e2 extends eu{static action="toolcall";static resource="database_agent";get sqlCode(){let e=this.contents.find(e=>"code"===e.contentType);return e?.payload?e.payload.code:null}get chartContent(){let e=this.contents.find(e=>"chart"===e.contentType);return e||null}get dataset(){return this.chartContent?.payload?this.chartContent.payload.chart_data.dataset:null}get references(){let e=this.contents.find(e=>"references"===e.name);return e?e.payload.map(e=>e1.createReference(e)):[]}get componentDetail(){if(!this.render)throw Error("render is not defined");return this.render.component_detail}get inputs(){return this.componentDetail?.arguments||{}}}class e3 extends eu{static action="toolcall";static resource="data_sheet_agent";get references(){let e=this.contents.find(e=>"references"===e.name);return e?e.payload.map(e=>e1.createReference(e)):[]}get componentOutputs(){let e={};for(let t of this.contents)t.payload&&Object.keys(t.payload).length>0&&Object.assign(e,{[t.name]:t.payload});return e}get componentDetail(){if(!this.render)throw Error("render is not defined");return this.render.component_detail}}class e6 extends eu{static action="agent_file_parser";get fileParserInfo(){let e=this.contents.find(e=>"json"===e.contentType);return e?JSON.parse(e.payload?.data):{files:[]}}}class e5 extends eu{static action="deep_search_agent";static resource="step";get thought(){let e=this.contents.find(e=>"text"===e.contentType);return e?e.payload.info:""}}let e9=()=>{let e=Error("Delay aborted");return e.name="AbortError",e},e4=new WeakMap;!function({clearTimeout:e,setTimeout:t}={}){}();export{a as AggregateRule,ev as BaseView,eF as ChatEvent,e3 as DataSheetEvent,e2 as DatabaseEvent,e5 as DeepSearchStepEvent,ef as EventMessage,ed as EventOutputContent,eh as ExecutionError,eu as ExecutionEvent,ex as ExecutionResponse,eE as Executor,eR as FetchSSETransport,e6 as FileParserEvent,e8 as RAGEvent,eA as ThoughtEvent,eV as ToolCallEvent,e_ as ToolUseView,eS as TreeView,eD as XHRSSETransport,r as assistantAgentAggregatePresets,o as defaultAggregatePresets,n as multiAgentAggregatePresets,ey as receiveNewEvent,em as receiveNewMessage};
|
package/package.json
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@baiducloud/qianfan-mutil-agent",
|
|
3
|
+
"version": "0.1.0-beta.0",
|
|
4
|
+
"description": "Qianfan SSE message protocol SDK - parse and handle streaming AI responses",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"private": false,
|
|
7
|
+
"type": "module",
|
|
8
|
+
"main": "./dist/esm/index.js",
|
|
9
|
+
"module": "./dist/esm/index.js",
|
|
10
|
+
"types": "./dist/esm/index.d.ts",
|
|
11
|
+
"exports": {
|
|
12
|
+
".": {
|
|
13
|
+
"types": "./dist/esm/index.d.ts",
|
|
14
|
+
"import": "./dist/esm/index.js",
|
|
15
|
+
"default": "./dist/esm/index.js"
|
|
16
|
+
}
|
|
17
|
+
},
|
|
18
|
+
"files": [
|
|
19
|
+
"dist"
|
|
20
|
+
],
|
|
21
|
+
"sideEffects": false,
|
|
22
|
+
"engines": {
|
|
23
|
+
"node": ">=18"
|
|
24
|
+
},
|
|
25
|
+
"scripts": {
|
|
26
|
+
"build": "npx rslib build"
|
|
27
|
+
},
|
|
28
|
+
"dependencies": {
|
|
29
|
+
"@baidu/ky-sse-hook": "^0.4.0",
|
|
30
|
+
"ky": "^1.0.0"
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"qianfan",
|
|
34
|
+
"sse",
|
|
35
|
+
"server-sent-events",
|
|
36
|
+
"message-protocol",
|
|
37
|
+
"streaming",
|
|
38
|
+
"ai",
|
|
39
|
+
"llm"
|
|
40
|
+
],
|
|
41
|
+
"publishConfig": {
|
|
42
|
+
"access": "public",
|
|
43
|
+
"registry": "https://registry.npmjs.org/"
|
|
44
|
+
}
|
|
45
|
+
}
|