@core-pilot/sdk 0.1.1 → 0.1.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +8 -8
- package/dist/index.js +325 -324
- package/dist/index.umd.cjs +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -38,7 +38,7 @@ import '@core-pilot/sdk/dist/index.css'; // 引入样式
|
|
|
38
38
|
// 1. 初始化 SDK 实例
|
|
39
39
|
const pilot = createCorePilot({
|
|
40
40
|
// 基础配置
|
|
41
|
-
|
|
41
|
+
agentId: 'your-app-id',
|
|
42
42
|
provider: {
|
|
43
43
|
name: 'coreagent', // 目前支持 'coreagent' | 'dify'
|
|
44
44
|
extensions: {
|
|
@@ -320,7 +320,7 @@ SDK 支持两种鉴权模式,适应不同的安全需求。
|
|
|
320
320
|
|
|
321
321
|
```typescript
|
|
322
322
|
const pilot = createCorePilot({
|
|
323
|
-
|
|
323
|
+
agentId: 'your-app-id',
|
|
324
324
|
provider: { name: 'coreagent' },
|
|
325
325
|
auth: {
|
|
326
326
|
mode: 'client',
|
|
@@ -340,7 +340,7 @@ const pilot = createCorePilot({
|
|
|
340
340
|
|
|
341
341
|
```typescript
|
|
342
342
|
const pilot = createCorePilot({
|
|
343
|
-
|
|
343
|
+
agentId: 'your-app-id',
|
|
344
344
|
provider: { name: 'coreagent' },
|
|
345
345
|
auth: {
|
|
346
346
|
mode: 'server',
|
|
@@ -367,7 +367,7 @@ SDK 内置了完善的日志系统,支持本地调试和远程日志上报。
|
|
|
367
367
|
|
|
368
368
|
```typescript
|
|
369
369
|
const pilot = createCorePilot({
|
|
370
|
-
|
|
370
|
+
agentId: 'your-app-id',
|
|
371
371
|
provider: { name: 'coreagent' },
|
|
372
372
|
auth: { mode: 'client', token: 'sk-xxx' },
|
|
373
373
|
mount: { selector: '#agent-container' },
|
|
@@ -412,7 +412,7 @@ SDK 支持多种 AI Provider,目前内置了 CoreAgent 协议。
|
|
|
412
412
|
|
|
413
413
|
```typescript
|
|
414
414
|
const pilot = createCorePilot({
|
|
415
|
-
|
|
415
|
+
agentId: 'your-app-id',
|
|
416
416
|
provider: {
|
|
417
417
|
name: 'coreagent',
|
|
418
418
|
extensions: {
|
|
@@ -427,7 +427,7 @@ const pilot = createCorePilot({
|
|
|
427
427
|
|
|
428
428
|
```typescript
|
|
429
429
|
const pilot = createCorePilot({
|
|
430
|
-
|
|
430
|
+
agentId: 'your-app-id',
|
|
431
431
|
provider: {
|
|
432
432
|
name: 'dify',
|
|
433
433
|
extensions: {
|
|
@@ -448,7 +448,7 @@ const pilot = createCorePilot({
|
|
|
448
448
|
|
|
449
449
|
| 属性 | 类型 | 必填 | 默认值 | 说明 |
|
|
450
450
|
|------|------|------|--------|------|
|
|
451
|
-
| `
|
|
451
|
+
| `agentId` | `string` | ✅ | - | Agent 应用 ID |
|
|
452
452
|
| `provider` | `AgentProvider` | ✅ | - | 协议提供商配置 |
|
|
453
453
|
| `auth` | `AuthOptions` | ✅ | - | 鉴权配置 |
|
|
454
454
|
| `mount` | `MountOptions` | ✅ | - | 挂载配置 |
|
|
@@ -690,7 +690,7 @@ useEffect(() => {
|
|
|
690
690
|
**解决方案**:
|
|
691
691
|
- 检查 `auth.token` 是否正确
|
|
692
692
|
- 确认 Token 未过期
|
|
693
|
-
- 验证 `
|
|
693
|
+
- 验证 `agentId` 与 Token 匹配
|
|
694
694
|
|
|
695
695
|
### 3. 事件回调未触发
|
|
696
696
|
|
package/dist/index.js
CHANGED
|
@@ -2,22 +2,22 @@ import { createApp, createVNode, defineComponent, onBeforeUnmount, ref, useTempl
|
|
|
2
2
|
import { BubbleList, EditorSender } from "@core-pilot/client-vue";
|
|
3
3
|
import { fetchEventSource } from "@microsoft/fetch-event-source";
|
|
4
4
|
import axios from "axios";
|
|
5
|
-
function formatArgs(
|
|
6
|
-
return
|
|
7
|
-
if (typeof
|
|
8
|
-
if (
|
|
5
|
+
function formatArgs(r) {
|
|
6
|
+
return r.map((r) => {
|
|
7
|
+
if (typeof r == "string") return r;
|
|
8
|
+
if (r instanceof Error) return r.stack || r.message;
|
|
9
9
|
try {
|
|
10
|
-
return JSON.stringify(
|
|
10
|
+
return JSON.stringify(r);
|
|
11
11
|
} catch {
|
|
12
|
-
return String(
|
|
12
|
+
return String(r);
|
|
13
13
|
}
|
|
14
14
|
}).join(" ");
|
|
15
15
|
}
|
|
16
|
-
function createLogger(
|
|
16
|
+
function createLogger(r, o, s) {
|
|
17
17
|
let c = "[CorePilot]", l = [], u = null, d = s?.batchSize ?? 20, f = s?.flushInterval ?? 15e3, p = () => {
|
|
18
18
|
if (!s || l.length === 0) return;
|
|
19
19
|
let o = [...l];
|
|
20
|
-
l = [],
|
|
20
|
+
l = [], r && console.log(`${c} Uploading ${o.length} log(s) to ${s.url}`);
|
|
21
21
|
let u = JSON.stringify(o);
|
|
22
22
|
navigator.sendBeacon ? navigator.sendBeacon(s.url, u) : fetch(s.url, {
|
|
23
23
|
method: "POST",
|
|
@@ -25,11 +25,11 @@ function createLogger(e, o, s) {
|
|
|
25
25
|
headers: { "Content-Type": "application/json" },
|
|
26
26
|
keepalive: !0
|
|
27
27
|
}).catch((s) => {
|
|
28
|
-
|
|
28
|
+
r && (console.error(`${c} Log upload failed:`, s), l.unshift(...o));
|
|
29
29
|
});
|
|
30
|
-
}, m = (
|
|
30
|
+
}, m = (r, ...c) => {
|
|
31
31
|
s && (l.push({
|
|
32
|
-
level:
|
|
32
|
+
level: r,
|
|
33
33
|
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
34
34
|
message: formatArgs(c),
|
|
35
35
|
appId: o
|
|
@@ -37,73 +37,73 @@ function createLogger(e, o, s) {
|
|
|
37
37
|
};
|
|
38
38
|
return s && (u = window.setTimeout(p, f)), {
|
|
39
39
|
log(...o) {
|
|
40
|
-
|
|
40
|
+
r && console.log(c, ...o), m("log", ...o);
|
|
41
41
|
},
|
|
42
42
|
error(...o) {
|
|
43
|
-
|
|
43
|
+
r && console.error(c, ...o), m("error", ...o);
|
|
44
44
|
},
|
|
45
45
|
destroy() {
|
|
46
46
|
u && clearTimeout(u), p();
|
|
47
47
|
}
|
|
48
48
|
};
|
|
49
49
|
}
|
|
50
|
-
function createAuthManager(
|
|
51
|
-
let s =
|
|
50
|
+
function createAuthManager(r, o) {
|
|
51
|
+
let s = r.token || "", c = null;
|
|
52
52
|
return {
|
|
53
53
|
async getToken() {
|
|
54
54
|
if (!s) throw Error("AuthManager: Missing token");
|
|
55
55
|
return s;
|
|
56
56
|
},
|
|
57
|
-
async setToken(
|
|
58
|
-
return
|
|
57
|
+
async setToken(r) {
|
|
58
|
+
return r ? (s = r, c && c(), !0) : !1;
|
|
59
59
|
},
|
|
60
|
-
onTokenRefreshed(
|
|
61
|
-
c =
|
|
60
|
+
onTokenRefreshed(r) {
|
|
61
|
+
c = r;
|
|
62
62
|
},
|
|
63
63
|
isServerMode() {
|
|
64
|
-
return
|
|
64
|
+
return r.mode === "server";
|
|
65
65
|
},
|
|
66
|
-
|
|
67
|
-
if (!o) throw Error("AuthManager: Missing
|
|
66
|
+
getAgentId() {
|
|
67
|
+
if (!o) throw Error("AuthManager: Missing agentId");
|
|
68
68
|
return o;
|
|
69
69
|
}
|
|
70
70
|
};
|
|
71
71
|
}
|
|
72
|
-
var createStoreImpl = (
|
|
73
|
-
let o, s = /* @__PURE__ */ new Set(), c = (
|
|
74
|
-
let l = typeof
|
|
72
|
+
var createStoreImpl = (r) => {
|
|
73
|
+
let o, s = /* @__PURE__ */ new Set(), c = (r, c) => {
|
|
74
|
+
let l = typeof r == "function" ? r(o) : r;
|
|
75
75
|
if (!Object.is(l, o)) {
|
|
76
|
-
let
|
|
77
|
-
o = c ?? (typeof l != "object" || !l) ? l : Object.assign({}, o, l), s.forEach((s) => s(o,
|
|
76
|
+
let r = o;
|
|
77
|
+
o = c ?? (typeof l != "object" || !l) ? l : Object.assign({}, o, l), s.forEach((s) => s(o, r));
|
|
78
78
|
}
|
|
79
79
|
}, l = () => o, u = {
|
|
80
80
|
setState: c,
|
|
81
81
|
getState: l,
|
|
82
82
|
getInitialState: () => d,
|
|
83
|
-
subscribe: (
|
|
84
|
-
}, d = o =
|
|
83
|
+
subscribe: (r) => (s.add(r), () => s.delete(r))
|
|
84
|
+
}, d = o = r(c, l, u);
|
|
85
85
|
return u;
|
|
86
86
|
};
|
|
87
|
-
const pilotStore = ((
|
|
87
|
+
const pilotStore = ((r) => r ? createStoreImpl(r) : createStoreImpl)((r) => ({
|
|
88
88
|
currentMessage: void 0,
|
|
89
89
|
isLoading: !1,
|
|
90
90
|
messageHistory: [],
|
|
91
91
|
activeScence: "ANC",
|
|
92
92
|
pendingRetryRequest: null,
|
|
93
|
-
setActiveScence: (o) =>
|
|
94
|
-
updateMessage: (o) =>
|
|
93
|
+
setActiveScence: (o) => r({ activeScence: o }),
|
|
94
|
+
updateMessage: (o) => r((r) => {
|
|
95
95
|
let s = {
|
|
96
96
|
...o,
|
|
97
97
|
role: "ai",
|
|
98
98
|
showActions: !1,
|
|
99
99
|
maxWidth: "100%"
|
|
100
|
-
}, c = [...
|
|
101
|
-
if (c.forEach((
|
|
102
|
-
|
|
103
|
-
}),
|
|
100
|
+
}, c = [...r.messageHistory];
|
|
101
|
+
if (c.forEach((r) => {
|
|
102
|
+
r.isHistoryMessage = !0;
|
|
103
|
+
}), r.currentMessage) {
|
|
104
104
|
let l = {
|
|
105
105
|
...s,
|
|
106
|
-
content:
|
|
106
|
+
content: r.currentMessage.content + (o.content || "")
|
|
107
107
|
};
|
|
108
108
|
return c.pop(), c.push(l), {
|
|
109
109
|
currentMessage: l,
|
|
@@ -115,45 +115,45 @@ const pilotStore = ((e) => e ? createStoreImpl(e) : createStoreImpl)((e) => ({
|
|
|
115
115
|
messageHistory: c
|
|
116
116
|
};
|
|
117
117
|
}),
|
|
118
|
-
setLoading: (o) =>
|
|
119
|
-
resetCurrentMessage: () =>
|
|
120
|
-
resetMessageHistory: (o) =>
|
|
121
|
-
resetQuestions: () =>
|
|
122
|
-
let o = [...
|
|
123
|
-
return o.forEach((
|
|
124
|
-
|
|
118
|
+
setLoading: (o) => r({ isLoading: o }),
|
|
119
|
+
resetCurrentMessage: () => r({ currentMessage: void 0 }),
|
|
120
|
+
resetMessageHistory: (o) => r({ messageHistory: o || [] }),
|
|
121
|
+
resetQuestions: () => r((r) => {
|
|
122
|
+
let o = [...r.messageHistory];
|
|
123
|
+
return o.forEach((r) => {
|
|
124
|
+
r.questions = [];
|
|
125
125
|
}), { messageHistory: o };
|
|
126
126
|
}),
|
|
127
|
-
updateMessageHistory: (o) =>
|
|
128
|
-
let s = [...
|
|
129
|
-
return s.forEach((
|
|
130
|
-
|
|
127
|
+
updateMessageHistory: (o) => r((r) => {
|
|
128
|
+
let s = [...r.messageHistory];
|
|
129
|
+
return s.forEach((r) => {
|
|
130
|
+
r.isHistoryMessage = !0, r.questions = [];
|
|
131
131
|
}), Array.isArray(o) ? { messageHistory: [...s, ...o] } : { messageHistory: [...s, o] };
|
|
132
132
|
}),
|
|
133
|
-
updateSuggestionQuestions: (o) =>
|
|
134
|
-
let s = [...
|
|
133
|
+
updateSuggestionQuestions: (o) => r((r) => {
|
|
134
|
+
let s = [...r.messageHistory];
|
|
135
135
|
return s[s.length - 1].questions = o, { messageHistory: s };
|
|
136
136
|
}),
|
|
137
137
|
setPendingRetryRequest: (o) => {
|
|
138
|
-
|
|
138
|
+
r({ pendingRetryRequest: o });
|
|
139
139
|
},
|
|
140
140
|
clearPendingRetryRequest: () => {
|
|
141
|
-
|
|
141
|
+
r({ pendingRetryRequest: null });
|
|
142
142
|
}
|
|
143
143
|
}));
|
|
144
144
|
var MAX_RETRY_TIME = 0, FatalError = class extends Error {
|
|
145
|
-
constructor(
|
|
146
|
-
super(
|
|
145
|
+
constructor(r) {
|
|
146
|
+
super(r), this.name = "FatalError";
|
|
147
147
|
}
|
|
148
148
|
};
|
|
149
|
-
const sseRequester = function(
|
|
150
|
-
let { url: c, config: l = {} } =
|
|
149
|
+
const sseRequester = function(r, o, s) {
|
|
150
|
+
let { url: c, config: l = {} } = r, u = new AbortController(), d = !1, f = !1;
|
|
151
151
|
function p() {
|
|
152
152
|
u.abort(), o.onCancel(pilotStore.getState().currentMessage, u), pilotStore.getState().setLoading(!1), pilotStore.getState().resetCurrentMessage();
|
|
153
153
|
}
|
|
154
|
-
function h(
|
|
154
|
+
function h(r) {
|
|
155
155
|
try {
|
|
156
|
-
let s = o.onMessage(
|
|
156
|
+
let s = o.onMessage(r);
|
|
157
157
|
if (!s) return;
|
|
158
158
|
s.event === "message" && (pilotStore.getState().updateMessage({
|
|
159
159
|
taskId: s.task_id,
|
|
@@ -162,22 +162,22 @@ const sseRequester = function(e, o, s) {
|
|
|
162
162
|
role: "ai",
|
|
163
163
|
content: s.answer
|
|
164
164
|
}), pilotStore.getState().resetQuestions());
|
|
165
|
-
} catch (
|
|
166
|
-
throw _(),
|
|
165
|
+
} catch (r) {
|
|
166
|
+
throw _(), r;
|
|
167
167
|
}
|
|
168
168
|
}
|
|
169
|
-
async function g(
|
|
169
|
+
async function g(r) {
|
|
170
170
|
try {
|
|
171
|
-
await o.onOpen(
|
|
171
|
+
await o.onOpen(r);
|
|
172
172
|
} catch (o) {
|
|
173
|
-
throw (
|
|
173
|
+
throw (r.status === 500 || o instanceof Error && o.message === "Token expired") && await _(), o;
|
|
174
174
|
}
|
|
175
175
|
}
|
|
176
176
|
async function _() {
|
|
177
177
|
d || (d = !0, pilotStore.getState().setLoading(!1), await o.onClose());
|
|
178
178
|
}
|
|
179
|
-
async function v(
|
|
180
|
-
f || (f = !0, d || await o.onError(
|
|
179
|
+
async function v(r) {
|
|
180
|
+
f || (f = !0, d || await o.onError(r));
|
|
181
181
|
}
|
|
182
182
|
let y = MAX_RETRY_TIME, S = {
|
|
183
183
|
...l,
|
|
@@ -185,20 +185,20 @@ const sseRequester = function(e, o, s) {
|
|
|
185
185
|
openWhenHidden: !0,
|
|
186
186
|
onmessage: h,
|
|
187
187
|
onclose: async () => await _(),
|
|
188
|
-
onopen: async (
|
|
189
|
-
await g(
|
|
188
|
+
onopen: async (r) => {
|
|
189
|
+
await g(r);
|
|
190
190
|
},
|
|
191
|
-
onerror: (
|
|
192
|
-
if (
|
|
191
|
+
onerror: (r) => {
|
|
192
|
+
if (r instanceof FatalError) throw _(), r;
|
|
193
193
|
if (y--, y < 0) {
|
|
194
|
-
if (_(),
|
|
194
|
+
if (_(), r instanceof TypeError) throw new FatalError(r.message);
|
|
195
195
|
return;
|
|
196
196
|
}
|
|
197
|
-
v(
|
|
197
|
+
v(r);
|
|
198
198
|
}
|
|
199
199
|
};
|
|
200
|
-
return s?.fetchFn && (S.fetch = s.fetchFn), fetchEventSource(c, S).catch((
|
|
201
|
-
_(), v(
|
|
200
|
+
return s?.fetchFn && (S.fetch = s.fetchFn), fetchEventSource(c, S).catch((r) => {
|
|
201
|
+
_(), v(r);
|
|
202
202
|
}), { cancel: p };
|
|
203
203
|
}, CorePilotHost = /* @__PURE__ */ defineComponent({
|
|
204
204
|
props: {
|
|
@@ -222,36 +222,37 @@ const sseRequester = function(e, o, s) {
|
|
|
222
222
|
type: Object,
|
|
223
223
|
required: !0
|
|
224
224
|
},
|
|
225
|
-
|
|
225
|
+
agentId: {
|
|
226
226
|
type: String,
|
|
227
227
|
required: !0
|
|
228
228
|
}
|
|
229
229
|
},
|
|
230
|
-
setup(
|
|
230
|
+
setup(r) {
|
|
231
231
|
let o = useTemplateRef("bubbleList"), s = ref([]), f = ref([]), p = ref(!1), m = ref(), h = ref("ANC"), g = ref(), _ = ref("");
|
|
232
|
-
watch(() =>
|
|
233
|
-
_.value = await
|
|
232
|
+
watch(() => r.authManager, async (r) => {
|
|
233
|
+
_.value = await r.getToken();
|
|
234
234
|
}, { immediate: !0 });
|
|
235
|
-
let v = pilotStore.subscribe((
|
|
236
|
-
let { isLoading: o, messageHistory: s } =
|
|
237
|
-
f.value = s, p.value = o, h.value =
|
|
235
|
+
let v = pilotStore.subscribe((r) => {
|
|
236
|
+
let { isLoading: o, messageHistory: s } = r;
|
|
237
|
+
f.value = s, p.value = o, h.value = r.activeScence;
|
|
238
238
|
});
|
|
239
239
|
watch(() => p.value, (o) => {
|
|
240
|
-
o && (g.value = void 0,
|
|
240
|
+
o && (g.value = void 0, r.hitlManager.submit({ hitlData: {
|
|
241
241
|
action: "cust_ai_output_start",
|
|
242
242
|
payload: {}
|
|
243
243
|
} }));
|
|
244
244
|
}), watch(() => g.value, (o, s) => {
|
|
245
|
-
o && f.value[f.value.length - 1]?.role === "ai" &&
|
|
245
|
+
o && f.value[f.value.length - 1]?.role === "ai" && r.hitlManager.submit({ hitlData: {
|
|
246
246
|
action: "cust_ai_output_finish",
|
|
247
247
|
payload: {
|
|
248
248
|
refConfig: g.value,
|
|
249
249
|
conversationId: f.value[f.value.length - 1]?.conversationId,
|
|
250
|
-
messageId: [...f.value].reverse().find((
|
|
250
|
+
messageId: [...f.value].reverse().find((r) => r.messageId)?.messageId
|
|
251
251
|
}
|
|
252
252
|
} });
|
|
253
253
|
});
|
|
254
254
|
let y = async (o, s = !1) => {
|
|
255
|
+
pilotStore.getState().setLoading(!0);
|
|
255
256
|
let c = {
|
|
256
257
|
messageId: void 0,
|
|
257
258
|
content: o.text,
|
|
@@ -270,20 +271,20 @@ const sseRequester = function(e, o, s) {
|
|
|
270
271
|
file: o.file?.[0]
|
|
271
272
|
}
|
|
272
273
|
})), pilotStore.getState().resetCurrentMessage();
|
|
273
|
-
let u = await
|
|
274
|
+
let u = await r.adapter.formatRequest({
|
|
274
275
|
text: o.text,
|
|
275
276
|
prevMessage: l,
|
|
276
277
|
inputs: { scence: h.value },
|
|
277
278
|
files: o.file
|
|
278
|
-
}), d =
|
|
279
|
-
m.value = sseRequester(u,
|
|
279
|
+
}), d = r.authManager.isServerMode() ? r.adapter.createSseFetch?.() : void 0;
|
|
280
|
+
m.value = sseRequester(u, r.adapter, {
|
|
280
281
|
fetchFn: d,
|
|
281
282
|
isRetry: s
|
|
282
283
|
}).cancel;
|
|
283
284
|
}, b = () => {
|
|
284
|
-
|
|
285
|
+
r.logger.log("Cancel handler called"), m.value?.(), pilotStore.getState().resetCurrentMessage();
|
|
285
286
|
}, x = async (o, s) => {
|
|
286
|
-
pilotStore.getState().resetCurrentMessage(), pilotStore.getState().updateMessageHistory([]), C(), await
|
|
287
|
+
pilotStore.getState().resetCurrentMessage(), pilotStore.getState().updateMessageHistory([]), C(), await r.hitlManager.submit({
|
|
287
288
|
hitlData: o,
|
|
288
289
|
prevMessage: s,
|
|
289
290
|
inputs: { scence: h.value }
|
|
@@ -302,21 +303,21 @@ const sseRequester = function(e, o, s) {
|
|
|
302
303
|
handleSendMessage: y,
|
|
303
304
|
cancelHandler: b,
|
|
304
305
|
handleScenceChange: (o) => {
|
|
305
|
-
|
|
306
|
+
r.hitlManager.submit({ hitlData: {
|
|
306
307
|
action: "cust_scence_change",
|
|
307
308
|
payload: { scence: o.id }
|
|
308
309
|
} });
|
|
309
310
|
},
|
|
310
311
|
coreSubmit: x,
|
|
311
|
-
handleRefConfigUpdate: (
|
|
312
|
-
g.value =
|
|
312
|
+
handleRefConfigUpdate: (r) => {
|
|
313
|
+
g.value = r;
|
|
313
314
|
},
|
|
314
|
-
handleSceneUpdate: (
|
|
315
|
-
pilotStore.getState().setActiveScence(
|
|
315
|
+
handleSceneUpdate: (r) => {
|
|
316
|
+
pilotStore.getState().setActiveScence(r);
|
|
316
317
|
},
|
|
317
|
-
handleQuestionClick: (
|
|
318
|
+
handleQuestionClick: (r) => {
|
|
318
319
|
y({
|
|
319
|
-
text:
|
|
320
|
+
text: r,
|
|
320
321
|
file: []
|
|
321
322
|
});
|
|
322
323
|
}
|
|
@@ -330,7 +331,7 @@ const sseRequester = function(e, o, s) {
|
|
|
330
331
|
maxHeight: "100%",
|
|
331
332
|
user: this.provider.extensions.user,
|
|
332
333
|
authToken: this.authManager.getToken(),
|
|
333
|
-
appId: this.
|
|
334
|
+
appId: this.agentId,
|
|
334
335
|
btnLoading: this.isLoading,
|
|
335
336
|
onCoreSubmit: this.coreSubmit,
|
|
336
337
|
onRefConfigUpdate: this.handleRefConfigUpdate,
|
|
@@ -342,7 +343,7 @@ const sseRequester = function(e, o, s) {
|
|
|
342
343
|
scene: this.activeScence,
|
|
343
344
|
user: this.provider.extensions.user,
|
|
344
345
|
authToken: this.authToken,
|
|
345
|
-
appId: this.
|
|
346
|
+
appId: this.agentId,
|
|
346
347
|
showUpload: !1,
|
|
347
348
|
onSubmit: this.handleSendMessage,
|
|
348
349
|
onCancel: this.cancelHandler,
|
|
@@ -352,13 +353,13 @@ const sseRequester = function(e, o, s) {
|
|
|
352
353
|
}
|
|
353
354
|
});
|
|
354
355
|
function createMountManager(o, s, c, l, u) {
|
|
355
|
-
let d = null, f = null, p = { ...o.mount }, m = { ...o.provider }, h = o.
|
|
356
|
-
let
|
|
357
|
-
if (
|
|
356
|
+
let d = null, f = null, p = { ...o.mount }, m = { ...o.provider }, h = o.agentId, g = () => {
|
|
357
|
+
let r = (p.container || document).querySelector(p.selector);
|
|
358
|
+
if (r && !r.querySelector("[data-corepilot-host]")) {
|
|
358
359
|
let o = document.createElement("div");
|
|
359
|
-
return o.setAttribute("data-corepilot-host", "true"), o.style.width = "100%", o.style.height = "100%",
|
|
360
|
+
return o.setAttribute("data-corepilot-host", "true"), o.style.width = "100%", o.style.height = "100%", r.appendChild(o), o;
|
|
360
361
|
}
|
|
361
|
-
return
|
|
362
|
+
return r?.querySelector("[data-corepilot-host]");
|
|
362
363
|
};
|
|
363
364
|
return {
|
|
364
365
|
mount() {
|
|
@@ -372,7 +373,7 @@ function createMountManager(o, s, c, l, u) {
|
|
|
372
373
|
logger: l,
|
|
373
374
|
provider: m,
|
|
374
375
|
authManager: u,
|
|
375
|
-
|
|
376
|
+
agentId: h
|
|
376
377
|
}), d.mount(f), l.log("Vue CorePilotHost mounted.");
|
|
377
378
|
},
|
|
378
379
|
unmount() {
|
|
@@ -381,24 +382,24 @@ function createMountManager(o, s, c, l, u) {
|
|
|
381
382
|
};
|
|
382
383
|
}
|
|
383
384
|
var HttpError = class extends Error {
|
|
384
|
-
constructor(
|
|
385
|
-
super(
|
|
385
|
+
constructor(r, o, s, c) {
|
|
386
|
+
super(r), this.name = "HttpError", this.code = o, this.data = s, this.originalError = c;
|
|
386
387
|
}
|
|
387
388
|
}, axios_default = new class {
|
|
388
|
-
constructor(
|
|
389
|
+
constructor(r) {
|
|
389
390
|
this.instance = axios.create({
|
|
390
391
|
timeout: 3e4,
|
|
391
392
|
headers: { "Content-Type": "application/json;charset=utf-8" },
|
|
392
393
|
withCredentials: !0,
|
|
393
|
-
...
|
|
394
|
+
...r
|
|
394
395
|
}), this.setupInterceptors();
|
|
395
396
|
}
|
|
396
397
|
setupInterceptors() {
|
|
397
|
-
this.instance.interceptors.response.use((
|
|
398
|
+
this.instance.interceptors.response.use((r) => r.data, (r) => Promise.reject(this.handleError(r)));
|
|
398
399
|
}
|
|
399
|
-
handleError(
|
|
400
|
+
handleError(r) {
|
|
400
401
|
let o = "请求失败,请稍后重试", s = -1, c = null;
|
|
401
|
-
if (axios.isAxiosError(
|
|
402
|
+
if (axios.isAxiosError(r)) if (r.response) switch (s = r.response.status, c = r.response.data, s) {
|
|
402
403
|
case 400:
|
|
403
404
|
o = "请求参数错误";
|
|
404
405
|
break;
|
|
@@ -432,34 +433,34 @@ var HttpError = class extends Error {
|
|
|
432
433
|
case 504:
|
|
433
434
|
o = "网关超时";
|
|
434
435
|
break;
|
|
435
|
-
default: o =
|
|
436
|
+
default: o = r.response.statusText || `连接错误 ${s}`;
|
|
436
437
|
}
|
|
437
|
-
else
|
|
438
|
-
else o =
|
|
438
|
+
else r.request ? (o = "网络连接失败,请检查网络设置", s = 0) : o = r.message;
|
|
439
|
+
else o = r.message || "未知错误";
|
|
439
440
|
return console.error(`[HttpClient] Error: ${o}`, {
|
|
440
441
|
code: s,
|
|
441
442
|
data: c,
|
|
442
|
-
original:
|
|
443
|
-
}), new HttpError(o, s, c,
|
|
443
|
+
original: r
|
|
444
|
+
}), new HttpError(o, s, c, r);
|
|
444
445
|
}
|
|
445
|
-
get(
|
|
446
|
-
return this.instance.get(
|
|
446
|
+
get(r, o) {
|
|
447
|
+
return this.instance.get(r, o);
|
|
447
448
|
}
|
|
448
|
-
post(
|
|
449
|
-
return this.instance.post(
|
|
449
|
+
post(r, o, s) {
|
|
450
|
+
return this.instance.post(r, o, s);
|
|
450
451
|
}
|
|
451
|
-
put(
|
|
452
|
-
return this.instance.put(
|
|
452
|
+
put(r, o, s) {
|
|
453
|
+
return this.instance.put(r, o, s);
|
|
453
454
|
}
|
|
454
|
-
delete(
|
|
455
|
-
return this.instance.delete(
|
|
455
|
+
delete(r, o) {
|
|
456
|
+
return this.instance.delete(r, o);
|
|
456
457
|
}
|
|
457
|
-
patch(
|
|
458
|
-
return this.instance.patch(
|
|
458
|
+
patch(r, o, s) {
|
|
459
|
+
return this.instance.patch(r, o, s);
|
|
459
460
|
}
|
|
460
|
-
upload(
|
|
461
|
+
upload(r, o, s = "file", c) {
|
|
461
462
|
let l = new FormData();
|
|
462
|
-
return l.append(s, o), this.instance.post(
|
|
463
|
+
return l.append(s, o), this.instance.post(r, l, {
|
|
463
464
|
...c,
|
|
464
465
|
headers: {
|
|
465
466
|
...c?.headers,
|
|
@@ -475,46 +476,46 @@ const eventHub = new class {
|
|
|
475
476
|
constructor() {
|
|
476
477
|
this.listeners = [];
|
|
477
478
|
}
|
|
478
|
-
subscribeEvent(
|
|
479
|
-
this.listeners.includes(
|
|
479
|
+
subscribeEvent(r) {
|
|
480
|
+
this.listeners.includes(r) || this.listeners.push(r);
|
|
480
481
|
}
|
|
481
|
-
unsubscribeEvent(
|
|
482
|
-
let o = this.listeners.indexOf(
|
|
482
|
+
unsubscribeEvent(r) {
|
|
483
|
+
let o = this.listeners.indexOf(r);
|
|
483
484
|
o > -1 && this.listeners.splice(o, 1);
|
|
484
485
|
}
|
|
485
|
-
emitEvent(
|
|
486
|
+
emitEvent(r) {
|
|
486
487
|
this.listeners.forEach((o) => {
|
|
487
488
|
try {
|
|
488
|
-
o(
|
|
489
|
-
} catch (
|
|
490
|
-
console.error("[EventHub] Event callback error:",
|
|
489
|
+
o(r);
|
|
490
|
+
} catch (r) {
|
|
491
|
+
console.error("[EventHub] Event callback error:", r);
|
|
491
492
|
}
|
|
492
493
|
});
|
|
493
494
|
}
|
|
494
495
|
}();
|
|
495
496
|
var TOKEN_EXPIRED_CODE = 40100, APPID_INVALID_CODE = 403;
|
|
496
|
-
function createCoreAgentAdapter(
|
|
497
|
-
let {
|
|
498
|
-
eventHub.emitEvent({
|
|
497
|
+
function createCoreAgentAdapter(r, o, s) {
|
|
498
|
+
let { agentId: c, provider: l, baseUrl: u } = r, { extensions: d } = l, { user: f = "default", accessToken: p = "" } = d || {}, m = !1, h = () => {
|
|
499
|
+
m || (m = !0, eventHub.emitEvent({
|
|
499
500
|
action: "cust_token_expired",
|
|
500
501
|
code: TOKEN_EXPIRED_CODE,
|
|
501
502
|
message: "凭证已过期"
|
|
502
|
-
});
|
|
503
|
-
},
|
|
503
|
+
}));
|
|
504
|
+
}, g = (r) => {
|
|
504
505
|
eventHub.emitEvent({
|
|
505
506
|
action: "cust_request_error",
|
|
506
|
-
code:
|
|
507
|
-
message:
|
|
507
|
+
code: r.code,
|
|
508
|
+
message: r.message || "请求失败"
|
|
508
509
|
});
|
|
509
|
-
},
|
|
510
|
-
Authorization: `Bearer ${await o.getToken()}
|
|
511
|
-
|
|
512
|
-
}
|
|
513
|
-
let s =
|
|
510
|
+
}, _ = () => o.isServerMode() ? u + "/api/proxy/ca" : u, v = async () => {
|
|
511
|
+
let r = { Authorization: `Bearer ${await o.getToken()}` };
|
|
512
|
+
return o.isServerMode() ? r["X-Agent-Id"] = c : r.appId = c, r;
|
|
513
|
+
}, y = async (r, o) => {
|
|
514
|
+
let s = r.taskId, c = _(), l = await v();
|
|
514
515
|
return await axios_default.post(`${c}/openapi/v1/app/chat-messages/${s}/stop`, { user: f }, { headers: l }), Promise.resolve();
|
|
515
|
-
},
|
|
516
|
-
|
|
517
|
-
let l =
|
|
516
|
+
}, b = async (r, s, c) => {
|
|
517
|
+
r.messageId;
|
|
518
|
+
let l = _(), u = await o.getToken(), d = {
|
|
518
519
|
query: JSON.stringify(s || []),
|
|
519
520
|
inputs: { scence: c },
|
|
520
521
|
response_mode: "blocking",
|
|
@@ -526,27 +527,27 @@ function createCoreAgentAdapter(e, o, s) {
|
|
|
526
527
|
p.appId = "b7886345-d200-486d-8318-8c234a19ccb9";
|
|
527
528
|
let m = await axios_default.post(`${l}/openapi/v1/app/chat-messages`, d, { headers: p });
|
|
528
529
|
try {
|
|
529
|
-
let
|
|
530
|
-
return console.log("data",
|
|
530
|
+
let r = JSON.parse(m.answer || "[]");
|
|
531
|
+
return console.log("data", r), r;
|
|
531
532
|
} catch {
|
|
532
533
|
return [];
|
|
533
534
|
}
|
|
534
|
-
},
|
|
535
|
-
let o =
|
|
535
|
+
}, x = async (r) => {
|
|
536
|
+
let o = _(), s = await v();
|
|
536
537
|
try {
|
|
537
|
-
return await axios_default.get(`${o}/openapi/v1/app/conversations?${new URLSearchParams(
|
|
538
|
-
} catch (
|
|
539
|
-
throw
|
|
538
|
+
return await axios_default.get(`${o}/openapi/v1/app/conversations?${new URLSearchParams(r).toString()}`, { headers: s });
|
|
539
|
+
} catch (r) {
|
|
540
|
+
throw r;
|
|
540
541
|
}
|
|
541
|
-
},
|
|
542
|
-
let o =
|
|
542
|
+
}, C = async (r) => {
|
|
543
|
+
let o = _(), s = await v();
|
|
543
544
|
try {
|
|
544
|
-
return await axios_default.get(`${o}/openapi/v1/app/messages?${new URLSearchParams(
|
|
545
|
-
} catch (
|
|
546
|
-
throw
|
|
545
|
+
return await axios_default.get(`${o}/openapi/v1/app/messages?${new URLSearchParams(r).toString()}`, { headers: s });
|
|
546
|
+
} catch (r) {
|
|
547
|
+
throw r;
|
|
547
548
|
}
|
|
548
|
-
},
|
|
549
|
-
switch (
|
|
549
|
+
}, w = (r) => {
|
|
550
|
+
switch (r.toLowerCase()) {
|
|
550
551
|
case "txt":
|
|
551
552
|
case "doc":
|
|
552
553
|
case "docx":
|
|
@@ -569,21 +570,21 @@ function createCoreAgentAdapter(e, o, s) {
|
|
|
569
570
|
case "ogg": return "video";
|
|
570
571
|
default: return "custom";
|
|
571
572
|
}
|
|
572
|
-
},
|
|
573
|
-
let { hitlData: o, prevMessage: s, text: c, inputs: l, files: u } =
|
|
574
|
-
Object.values(d).flat().forEach((
|
|
573
|
+
}, T = async (r) => {
|
|
574
|
+
let { hitlData: o, prevMessage: s, text: c, inputs: l, files: u } = r, d = o?.payload?.__files__ || {}, m = [];
|
|
575
|
+
Object.values(d).flat().forEach((r) => {
|
|
575
576
|
m.push({
|
|
576
577
|
transfer_method: "local_file",
|
|
577
|
-
type:
|
|
578
|
-
upload_file_id:
|
|
579
|
-
url:
|
|
578
|
+
type: w(r.extension || ""),
|
|
579
|
+
upload_file_id: r.id,
|
|
580
|
+
url: r.url || ""
|
|
580
581
|
});
|
|
581
|
-
}), u?.forEach((
|
|
582
|
+
}), u?.forEach((r) => {
|
|
582
583
|
m.push({
|
|
583
584
|
transfer_method: "local_file",
|
|
584
|
-
type:
|
|
585
|
-
upload_file_id:
|
|
586
|
-
url:
|
|
585
|
+
type: w(r.extension || ""),
|
|
586
|
+
upload_file_id: r.id,
|
|
587
|
+
url: r.url || ""
|
|
587
588
|
});
|
|
588
589
|
});
|
|
589
590
|
let h = {
|
|
@@ -597,9 +598,9 @@ function createCoreAgentAdapter(e, o, s) {
|
|
|
597
598
|
parent_message_id: s?.messageId || null,
|
|
598
599
|
user: f,
|
|
599
600
|
files: m
|
|
600
|
-
},
|
|
601
|
+
}, g = _(), y = await v();
|
|
601
602
|
return {
|
|
602
|
-
url: `${
|
|
603
|
+
url: `${g}/openapi/v1/app/chat-messages`,
|
|
603
604
|
config: {
|
|
604
605
|
method: "POST",
|
|
605
606
|
headers: {
|
|
@@ -609,257 +610,257 @@ function createCoreAgentAdapter(e, o, s) {
|
|
|
609
610
|
body: JSON.stringify(h)
|
|
610
611
|
}
|
|
611
612
|
};
|
|
612
|
-
},
|
|
613
|
-
let { data: o } =
|
|
614
|
-
return s.code === TOKEN_EXPIRED_CODE ? (
|
|
615
|
-
},
|
|
613
|
+
}, E = (r) => {
|
|
614
|
+
let { data: o } = r, s = JSON.parse(o || "{}");
|
|
615
|
+
return s.code === TOKEN_EXPIRED_CODE ? (h(), null) : s.code === APPID_INVALID_CODE ? (g(s), null) : s;
|
|
616
|
+
}, D = async () => {
|
|
616
617
|
s.log("onClose");
|
|
617
|
-
},
|
|
618
|
-
s.log("onError",
|
|
619
|
-
},
|
|
620
|
-
s.log("onOpen");
|
|
621
|
-
},
|
|
618
|
+
}, O = async (r) => {
|
|
619
|
+
s.log("onError", r);
|
|
620
|
+
}, k = async (r) => {
|
|
621
|
+
if (s.log("onOpen"), !(r.headers.get("content-type") || "").includes("text/event-stream")) throw Error("Invalid content type");
|
|
622
|
+
}, A = (r) => {
|
|
622
623
|
try {
|
|
623
|
-
return JSON.parse(
|
|
624
|
+
return JSON.parse(r || "{}")?.action?.startsWith("core_") || !1;
|
|
624
625
|
} catch {
|
|
625
626
|
return !1;
|
|
626
627
|
}
|
|
627
|
-
},
|
|
628
|
-
let { inputs: c } =
|
|
628
|
+
}, j = async (r, s = !1) => {
|
|
629
|
+
let { inputs: c } = r, l = c?.scence;
|
|
629
630
|
l && pilotStore.getState().setActiveScence(l);
|
|
630
|
-
let u = await
|
|
631
|
+
let u = await T(r), d = o.isServerMode() ? P() : void 0;
|
|
631
632
|
sseRequester(u, {
|
|
632
|
-
formatRequest:
|
|
633
|
-
getSuggestionQuestions:
|
|
634
|
-
getConversationList:
|
|
635
|
-
getMessageHistory:
|
|
636
|
-
onMessage:
|
|
637
|
-
onClose:
|
|
638
|
-
onError:
|
|
639
|
-
onOpen:
|
|
640
|
-
onCancel:
|
|
633
|
+
formatRequest: T,
|
|
634
|
+
getSuggestionQuestions: b,
|
|
635
|
+
getConversationList: x,
|
|
636
|
+
getMessageHistory: C,
|
|
637
|
+
onMessage: E,
|
|
638
|
+
onClose: D,
|
|
639
|
+
onError: O,
|
|
640
|
+
onOpen: k,
|
|
641
|
+
onCancel: y
|
|
641
642
|
}, {
|
|
642
643
|
fetchFn: d,
|
|
643
644
|
isRetry: s
|
|
644
645
|
});
|
|
645
|
-
},
|
|
646
|
+
}, M = async (r) => {
|
|
646
647
|
let o = [], s;
|
|
647
|
-
if (
|
|
648
|
-
if (
|
|
648
|
+
if (r.data.forEach((r) => {
|
|
649
|
+
if (r.parent_message_id === s) o.pop(), o.push({
|
|
649
650
|
role: "ai",
|
|
650
651
|
showActions: !1,
|
|
651
|
-
content:
|
|
652
|
+
content: r.answer,
|
|
652
653
|
maxWidth: "100%",
|
|
653
|
-
files:
|
|
654
|
-
id:
|
|
655
|
-
extension:
|
|
656
|
-
name:
|
|
654
|
+
files: r.message_files.map((r) => ({
|
|
655
|
+
id: r.id,
|
|
656
|
+
extension: r.type,
|
|
657
|
+
name: r.filename
|
|
657
658
|
})),
|
|
658
659
|
placement: "start",
|
|
659
|
-
conversationId:
|
|
660
|
-
messageId:
|
|
660
|
+
conversationId: r.conversation_id,
|
|
661
|
+
messageId: r.id
|
|
661
662
|
});
|
|
662
663
|
else {
|
|
663
|
-
if (s =
|
|
664
|
+
if (s = r.parent_message_id, !A(r.query)) o.push({
|
|
664
665
|
role: "user",
|
|
665
|
-
messageId:
|
|
666
|
-
content:
|
|
666
|
+
messageId: r.id,
|
|
667
|
+
content: r.query,
|
|
667
668
|
showActions: !1,
|
|
668
669
|
maxWidth: "100%",
|
|
669
670
|
placement: "end",
|
|
670
671
|
isHistoryMessage: !0,
|
|
671
|
-
conversationId:
|
|
672
|
+
conversationId: r.conversation_id
|
|
672
673
|
});
|
|
673
674
|
else {
|
|
674
|
-
let s = JSON.parse(
|
|
675
|
+
let s = JSON.parse(r.query || "{}");
|
|
675
676
|
if (s?.payload) {
|
|
676
|
-
let
|
|
677
|
-
|
|
677
|
+
let r = o[o.length - 1];
|
|
678
|
+
r && (r.historyInputs = s.payload);
|
|
678
679
|
}
|
|
679
680
|
}
|
|
680
681
|
o.push({
|
|
681
682
|
role: "ai",
|
|
682
|
-
content:
|
|
683
|
+
content: r.answer,
|
|
683
684
|
showActions: !1,
|
|
684
685
|
maxWidth: "100%",
|
|
685
686
|
placement: "start",
|
|
686
|
-
files:
|
|
687
|
-
id:
|
|
688
|
-
extension:
|
|
689
|
-
name:
|
|
687
|
+
files: r.message_files.map((r) => ({
|
|
688
|
+
id: r.id,
|
|
689
|
+
extension: r.type,
|
|
690
|
+
name: r.filename
|
|
690
691
|
})),
|
|
691
692
|
isHistoryMessage: !0,
|
|
692
|
-
conversationId:
|
|
693
|
-
messageId:
|
|
693
|
+
conversationId: r.conversation_id,
|
|
694
|
+
messageId: r.id
|
|
694
695
|
});
|
|
695
696
|
}
|
|
696
|
-
}),
|
|
697
|
-
let
|
|
697
|
+
}), r.has_more) {
|
|
698
|
+
let r = await C({
|
|
698
699
|
conversation_id: o[o.length - 1].conversationId,
|
|
699
700
|
user: f,
|
|
700
701
|
first_id: o[0].messageId
|
|
701
702
|
});
|
|
702
|
-
if (
|
|
703
|
-
let s = await
|
|
703
|
+
if (r.data) {
|
|
704
|
+
let s = await M(r);
|
|
704
705
|
o.unshift(...s);
|
|
705
706
|
}
|
|
706
707
|
}
|
|
707
708
|
return o;
|
|
708
|
-
},
|
|
709
|
-
let c = await o.getToken(), l = o.
|
|
709
|
+
}, N = async () => (pilotStore.getState().resetMessageHistory(), !0), P = () => async (r, s) => {
|
|
710
|
+
let c = await o.getToken(), l = o.getAgentId(), u = {
|
|
710
711
|
...s?.headers || {},
|
|
711
712
|
Authorization: `Bearer ${c}`,
|
|
712
|
-
...
|
|
713
|
+
...o.isServerMode() ? { "X-Agent-Id": l } : { appId: l }
|
|
713
714
|
};
|
|
714
|
-
return await fetch(
|
|
715
|
+
return await fetch(r, {
|
|
715
716
|
...s,
|
|
716
717
|
headers: u
|
|
717
718
|
});
|
|
718
|
-
},
|
|
719
|
+
}, F = async (r, s = !1) => {
|
|
719
720
|
let c = {
|
|
720
721
|
messageId: void 0,
|
|
721
|
-
content:
|
|
722
|
+
content: r.text,
|
|
722
723
|
role: "user",
|
|
723
724
|
placement: "end",
|
|
724
725
|
showActions: !1,
|
|
725
726
|
maxWidth: "100%"
|
|
726
727
|
};
|
|
727
728
|
s || pilotStore.getState().updateMessageHistory([c]), pilotStore.getState().resetCurrentMessage();
|
|
728
|
-
let l = await
|
|
729
|
-
text:
|
|
729
|
+
let l = await T({
|
|
730
|
+
text: r.text,
|
|
730
731
|
prevMessage: void 0,
|
|
731
|
-
inputs:
|
|
732
|
+
inputs: r.inputs
|
|
732
733
|
});
|
|
733
|
-
pilotStore.getState().setActiveScence(
|
|
734
|
-
let u = o.isServerMode() ?
|
|
734
|
+
pilotStore.getState().setActiveScence(r.inputs?.scence);
|
|
735
|
+
let u = o.isServerMode() ? P() : void 0;
|
|
735
736
|
return sseRequester(l, {
|
|
736
|
-
formatRequest:
|
|
737
|
-
getSuggestionQuestions:
|
|
738
|
-
getConversationList:
|
|
739
|
-
getMessageHistory:
|
|
740
|
-
onMessage:
|
|
741
|
-
onClose:
|
|
742
|
-
onError:
|
|
743
|
-
onOpen:
|
|
744
|
-
onCancel:
|
|
737
|
+
formatRequest: T,
|
|
738
|
+
getSuggestionQuestions: b,
|
|
739
|
+
getConversationList: x,
|
|
740
|
+
getMessageHistory: C,
|
|
741
|
+
onMessage: E,
|
|
742
|
+
onClose: D,
|
|
743
|
+
onError: O,
|
|
744
|
+
onOpen: k,
|
|
745
|
+
onCancel: y
|
|
745
746
|
}, {
|
|
746
747
|
fetchFn: u,
|
|
747
748
|
isRetry: s
|
|
748
749
|
});
|
|
749
|
-
},
|
|
750
|
-
let
|
|
751
|
-
if (!
|
|
750
|
+
}, I = async () => {
|
|
751
|
+
let r = pilotStore.getState().pendingRetryRequest;
|
|
752
|
+
if (!r) return;
|
|
752
753
|
pilotStore.getState().clearPendingRetryRequest();
|
|
753
|
-
let s = o.isServerMode() ?
|
|
754
|
-
if (
|
|
755
|
-
let o =
|
|
756
|
-
sseRequester(await
|
|
754
|
+
let s = o.isServerMode() ? P() : void 0;
|
|
755
|
+
if (r.type === "submit_message") {
|
|
756
|
+
let o = r.payload;
|
|
757
|
+
sseRequester(await T({
|
|
757
758
|
text: o.text,
|
|
758
759
|
prevMessage: void 0,
|
|
759
760
|
inputs: o.inputs
|
|
760
761
|
}), {
|
|
761
|
-
formatRequest:
|
|
762
|
-
getSuggestionQuestions:
|
|
763
|
-
getConversationList:
|
|
764
|
-
getMessageHistory:
|
|
765
|
-
onMessage:
|
|
766
|
-
onClose:
|
|
767
|
-
onError:
|
|
768
|
-
onOpen:
|
|
769
|
-
onCancel:
|
|
762
|
+
formatRequest: T,
|
|
763
|
+
getSuggestionQuestions: b,
|
|
764
|
+
getConversationList: x,
|
|
765
|
+
getMessageHistory: C,
|
|
766
|
+
onMessage: E,
|
|
767
|
+
onClose: D,
|
|
768
|
+
onError: O,
|
|
769
|
+
onOpen: k,
|
|
770
|
+
onCancel: y
|
|
770
771
|
}, {
|
|
771
772
|
fetchFn: s,
|
|
772
773
|
isRetry: !0
|
|
773
774
|
});
|
|
774
|
-
} else
|
|
775
|
+
} else r.type === "submit_core_action" && await j(r.payload, !0);
|
|
775
776
|
};
|
|
776
777
|
return o.onTokenRefreshed(() => {
|
|
777
|
-
setTimeout(() => {
|
|
778
|
-
|
|
778
|
+
m = !1, setTimeout(() => {
|
|
779
|
+
I();
|
|
779
780
|
}, 0);
|
|
780
781
|
}), {
|
|
781
|
-
formatRequest:
|
|
782
|
-
getSuggestionQuestions:
|
|
783
|
-
getConversationList:
|
|
784
|
-
getMessageHistory:
|
|
785
|
-
onMessage:
|
|
786
|
-
onClose:
|
|
787
|
-
onError:
|
|
788
|
-
onOpen:
|
|
789
|
-
onCancel:
|
|
790
|
-
triggerEvent: async (
|
|
791
|
-
switch (
|
|
792
|
-
case "get_suggestion_questions": return await
|
|
793
|
-
case "get_conversation_list": return await
|
|
782
|
+
formatRequest: T,
|
|
783
|
+
getSuggestionQuestions: b,
|
|
784
|
+
getConversationList: x,
|
|
785
|
+
getMessageHistory: C,
|
|
786
|
+
onMessage: E,
|
|
787
|
+
onClose: D,
|
|
788
|
+
onError: O,
|
|
789
|
+
onOpen: k,
|
|
790
|
+
onCancel: y,
|
|
791
|
+
triggerEvent: async (r) => {
|
|
792
|
+
switch (r.action) {
|
|
793
|
+
case "get_suggestion_questions": return await b(r.payload);
|
|
794
|
+
case "get_conversation_list": return await x(r.payload);
|
|
794
795
|
case "get_message_history":
|
|
795
|
-
let o = await
|
|
796
|
+
let o = await M(await C(r.payload));
|
|
796
797
|
return pilotStore.getState().resetMessageHistory(o), o;
|
|
797
798
|
case "submit_core_action": return pilotStore.getState().setPendingRetryRequest({
|
|
798
799
|
type: "submit_core_action",
|
|
799
|
-
payload:
|
|
800
|
-
}), await
|
|
801
|
-
case "new_message": return await
|
|
800
|
+
payload: r.payload
|
|
801
|
+
}), await j(r.payload);
|
|
802
|
+
case "new_message": return await N();
|
|
802
803
|
case "submit_message": return pilotStore.getState().setPendingRetryRequest({
|
|
803
804
|
type: "submit_message",
|
|
804
|
-
payload:
|
|
805
|
-
}), await
|
|
805
|
+
payload: r.payload
|
|
806
|
+
}), await F(r.payload);
|
|
806
807
|
default: throw Error("Invalid event action.");
|
|
807
808
|
}
|
|
808
809
|
},
|
|
809
|
-
createSseFetch:
|
|
810
|
+
createSseFetch: P
|
|
810
811
|
};
|
|
811
812
|
}
|
|
812
|
-
function createProtocolAdapter(
|
|
813
|
+
function createProtocolAdapter(r, o, s, c) {
|
|
813
814
|
switch (c.log(`Creating adapter for provider: ${o}`), o.name) {
|
|
814
|
-
case "coreagent": return createCoreAgentAdapter(
|
|
815
|
+
case "coreagent": return createCoreAgentAdapter(r, s, c);
|
|
815
816
|
default: throw Error(`Unsupported provider: ${o.name}`);
|
|
816
817
|
}
|
|
817
818
|
}
|
|
818
|
-
function createHitlManager(
|
|
819
|
-
let c = (
|
|
820
|
-
let c = await
|
|
819
|
+
function createHitlManager(r, o, s) {
|
|
820
|
+
let c = (r) => r.split("_")[0], l = [], u = async (o) => {
|
|
821
|
+
let c = await r.formatRequest(o);
|
|
821
822
|
sseRequester({
|
|
822
823
|
url: c.url,
|
|
823
824
|
config: c.config
|
|
824
|
-
},
|
|
825
|
-
}, d = async (
|
|
826
|
-
l.forEach((o) => o(
|
|
827
|
-
}, f = async (
|
|
825
|
+
}, r), s.log("HITL data submitted successfully.");
|
|
826
|
+
}, d = async (r) => {
|
|
827
|
+
l.forEach((o) => o(r.hitlData));
|
|
828
|
+
}, f = async (r) => {};
|
|
828
829
|
return {
|
|
829
|
-
async submit(
|
|
830
|
+
async submit(r) {
|
|
830
831
|
try {
|
|
831
|
-
let o = c(
|
|
832
|
-
switch (s.log("[HITL] Submitting HITL data...",
|
|
832
|
+
let o = c(r.hitlData?.action ?? "");
|
|
833
|
+
switch (s.log("[HITL] Submitting HITL data...", r), o) {
|
|
833
834
|
case "core":
|
|
834
|
-
await u(
|
|
835
|
+
await u(r);
|
|
835
836
|
break;
|
|
836
837
|
case "cust":
|
|
837
|
-
await d(
|
|
838
|
+
await d(r);
|
|
838
839
|
break;
|
|
839
840
|
case "inner":
|
|
840
|
-
await f(
|
|
841
|
+
await f(r);
|
|
841
842
|
break;
|
|
842
843
|
default: throw Error("Invalid action type.");
|
|
843
844
|
}
|
|
844
|
-
} catch (
|
|
845
|
-
throw s.error("Error submitting HITL data:",
|
|
845
|
+
} catch (r) {
|
|
846
|
+
throw s.error("Error submitting HITL data:", r), r;
|
|
846
847
|
}
|
|
847
848
|
},
|
|
848
|
-
subscribeEvent(
|
|
849
|
-
l.includes(
|
|
849
|
+
subscribeEvent(r) {
|
|
850
|
+
l.includes(r) || l.push(r);
|
|
850
851
|
},
|
|
851
|
-
unsubscribeEvent(
|
|
852
|
-
l.splice(l.indexOf(
|
|
852
|
+
unsubscribeEvent(r) {
|
|
853
|
+
l.splice(l.indexOf(r), 1);
|
|
853
854
|
}
|
|
854
855
|
};
|
|
855
856
|
}
|
|
856
|
-
function createCorePilot(
|
|
857
|
-
if (
|
|
858
|
-
if (!
|
|
859
|
-
let o = createLogger(
|
|
860
|
-
o.log("CorePilot SDK Initializing...",
|
|
861
|
-
let s = { ...
|
|
862
|
-
inner_set_token: async (
|
|
857
|
+
function createCorePilot(r) {
|
|
858
|
+
if (r.auth.mode, !r.agentId) throw Error("CorePilot SDK: `agentId` is required.");
|
|
859
|
+
if (!r.mount.selector) throw Error("CorePilot SDK: `mount.selector` is required.");
|
|
860
|
+
let o = createLogger(r.debug ?? !1, r.agentId || "", r.eventTracker);
|
|
861
|
+
o.log("CorePilot SDK Initializing...", r);
|
|
862
|
+
let s = { ...r }, c = createAuthManager(s.auth, s.agentId), l = createProtocolAdapter(s, s.provider, c, o), u = createHitlManager(l, c, o), d = createMountManager(s, l, u, o, c), f = {
|
|
863
|
+
inner_set_token: async (r) => (await c.setToken(r), !0),
|
|
863
864
|
inner_get_token: async () => await c.getToken()
|
|
864
865
|
};
|
|
865
866
|
return {
|
|
@@ -869,10 +870,10 @@ function createCorePilot(e) {
|
|
|
869
870
|
unmount() {
|
|
870
871
|
o.log("Unmounting CorePilot UI..."), d.unmount();
|
|
871
872
|
},
|
|
872
|
-
reload(
|
|
873
|
-
o.log("Reloading CorePilot instance...",
|
|
873
|
+
reload(r) {
|
|
874
|
+
o.log("Reloading CorePilot instance...", r), d.unmount(), s = {
|
|
874
875
|
...s,
|
|
875
|
-
...
|
|
876
|
+
...r
|
|
876
877
|
}, l = createProtocolAdapter(s, s.provider, c, o);
|
|
877
878
|
let f = createMountManager(s, l, u, o, c);
|
|
878
879
|
d.mount = f.mount, d.unmount = f.unmount, o.log("CorePilot reloaded. Remounting UI..."), d.mount();
|
|
@@ -880,19 +881,19 @@ function createCorePilot(e) {
|
|
|
880
881
|
destroy() {
|
|
881
882
|
o.log("Destroying CorePilot instance..."), d.unmount(), o.destroy();
|
|
882
883
|
},
|
|
883
|
-
async triggerEvent(
|
|
884
|
-
let o = f[
|
|
884
|
+
async triggerEvent(r) {
|
|
885
|
+
let o = f[r.action];
|
|
885
886
|
if (o) {
|
|
886
|
-
let s =
|
|
887
|
+
let s = r.payload;
|
|
887
888
|
return await o(s);
|
|
888
889
|
}
|
|
889
|
-
return await l.triggerEvent(
|
|
890
|
+
return await l.triggerEvent(r);
|
|
890
891
|
},
|
|
891
|
-
subscribeEvent(
|
|
892
|
-
u.subscribeEvent(
|
|
892
|
+
subscribeEvent(r) {
|
|
893
|
+
u.subscribeEvent(r), eventHub.subscribeEvent(r);
|
|
893
894
|
},
|
|
894
|
-
unsubscribeEvent(
|
|
895
|
-
u.unsubscribeEvent(
|
|
895
|
+
unsubscribeEvent(r) {
|
|
896
|
+
u.unsubscribeEvent(r), eventHub.unsubscribeEvent(r);
|
|
896
897
|
}
|
|
897
898
|
};
|
|
898
899
|
}
|
package/dist/index.umd.cjs
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`vue`),require(`@core-pilot/client-vue`),require(`@microsoft/fetch-event-source`),require(`axios`)):typeof define==`function`&&define.amd?define([`exports`,`vue`,`@core-pilot/client-vue`,`@microsoft/fetch-event-source`,`axios`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.CorePilotSDK={},e.Vue,e.CorePilotClientVue,e.FetchEventSource,e.axios))})(this,function(e,t,n,r,i){var a=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,c=Object.getOwnPropertyNames,l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=c(t),a=0,l=i.length,d;a<l;a++)d=i[a],!u.call(e,d)&&d!==n&&o(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=s(t,d))||r.enumerable});return e};i=((e,t,n)=>(n=e==null?{}:a(l(e)),d(t||!e||!e.__esModule?o(n,`default`,{value:e,enumerable:!0}):n,e)))(i);function f(e){return e.map(e=>{if(typeof e==`string`)return e;if(e instanceof Error)return e.stack||e.message;try{return JSON.stringify(e)}catch{return String(e)}}).join(` `)}function p(e,t,n){let r=`[CorePilot]`,i=[],a=null,o=n?.batchSize??20,s=n?.flushInterval??15e3,c=()=>{if(!n||i.length===0)return;let t=[...i];i=[],e&&console.log(`${r} Uploading ${t.length} log(s) to ${n.url}`);let a=JSON.stringify(t);navigator.sendBeacon?navigator.sendBeacon(n.url,a):fetch(n.url,{method:`POST`,body:a,headers:{"Content-Type":`application/json`},keepalive:!0}).catch(n=>{e&&(console.error(`${r} Log upload failed:`,n),i.unshift(...t))})},l=(e,...r)=>{n&&(i.push({level:e,timestamp:new Date().toISOString(),message:f(r),appId:t}),i.length>=o&&(a&&clearTimeout(a),c(),a=window.setTimeout(c,s)))};return n&&(a=window.setTimeout(c,s)),{log(...t){e&&console.log(r,...t),l(`log`,...t)},error(...t){e&&console.error(r,...t),l(`error`,...t)},destroy(){a&&clearTimeout(a),c()}}}function m(e,t){let n=e.token||``,r=null;return{async getToken(){if(!n)throw Error(`AuthManager: Missing token`);return n},async setToken(e){return e?(n=e,r&&r(),!0):!1},onTokenRefreshed(e){r=e},isServerMode(){return e.mode===`server`},getAppId(){if(!t)throw Error(`AuthManager: Missing appId`);return t}}}var h=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a};let g=(e=>e?h(e):h)(e=>({currentMessage:void 0,isLoading:!1,messageHistory:[],activeScence:`ANC`,pendingRetryRequest:null,setActiveScence:t=>e({activeScence:t}),updateMessage:t=>e(e=>{let n={...t,role:`ai`,showActions:!1,maxWidth:`100%`},r=[...e.messageHistory];if(r.forEach(e=>{e.isHistoryMessage=!0}),e.currentMessage){let i={...n,content:e.currentMessage.content+(t.content||``)};return r.pop(),r.push(i),{currentMessage:i,messageHistory:r}}return r.push(n),{currentMessage:n,messageHistory:r}}),setLoading:t=>e({isLoading:t}),resetCurrentMessage:()=>e({currentMessage:void 0}),resetMessageHistory:t=>e({messageHistory:t||[]}),resetQuestions:()=>e(e=>{let t=[...e.messageHistory];return t.forEach(e=>{e.questions=[]}),{messageHistory:t}}),updateMessageHistory:t=>e(e=>{let n=[...e.messageHistory];return n.forEach(e=>{e.isHistoryMessage=!0,e.questions=[]}),Array.isArray(t)?{messageHistory:[...n,...t]}:{messageHistory:[...n,t]}}),updateSuggestionQuestions:t=>e(e=>{let n=[...e.messageHistory];return n[n.length-1].questions=t,{messageHistory:n}}),setPendingRetryRequest:t=>{e({pendingRetryRequest:t})},clearPendingRetryRequest:()=>{e({pendingRetryRequest:null})}}));var _=0,v=class extends Error{constructor(e){super(e),this.name=`FatalError`}};let y=function(e,t,n){let{url:i,config:a={}}=e,o=new AbortController,s=!1,c=!1;function l(){o.abort(),t.onCancel(g.getState().currentMessage,o),g.getState().setLoading(!1),g.getState().resetCurrentMessage()}function u(e){try{let n=t.onMessage(e);if(!n)return;n.event===`message`&&(g.getState().updateMessage({taskId:n.task_id,messageId:n.message_id,conversationId:n.conversation_id,role:`ai`,content:n.answer}),g.getState().resetQuestions())}catch(e){throw f(),e}}async function d(e){try{await t.onOpen(e),g.getState().setLoading(!0)}catch(t){throw(e.status===500||t instanceof Error&&t.message===`Token expired`)&&await f(),t}}async function f(){s||(s=!0,g.getState().setLoading(!1),await t.onClose())}async function p(e){c||(c=!0,s||await t.onError(e))}let m=_,h={...a,signal:o.signal,openWhenHidden:!0,onmessage:u,onclose:async()=>await f(),onopen:async e=>{await d(e)},onerror:e=>{if(e instanceof v)throw f(),e;if(m--,m<0){if(f(),e instanceof TypeError)throw new v(e.message);return}p(e)}};return n?.fetchFn&&(h.fetch=n.fetchFn),(0,r.fetchEventSource)(i,h).catch(e=>{f(),p(e)}),{cancel:l}},b=(0,t.defineComponent)({props:{adapter:{type:Object,required:!0},hitlManager:{type:Object,required:!0},logger:{type:Object,required:!0},provider:{type:Object,required:!0},authManager:{type:Object,required:!0},appId:{type:String,required:!0}},setup(e){let n=(0,t.useTemplateRef)(`bubbleList`),r=(0,t.ref)([]),i=(0,t.ref)([]),a=(0,t.ref)(!1),o=(0,t.ref)(),s=(0,t.ref)(`ANC`),c=(0,t.ref)(),l=(0,t.ref)(``);(0,t.watch)(()=>e.authManager,async e=>{l.value=await e.getToken()},{immediate:!0});let u=g.subscribe(e=>{let{isLoading:t,messageHistory:n}=e;i.value=n,a.value=t,s.value=e.activeScence});(0,t.watch)(()=>a.value,t=>{t&&(c.value=void 0,e.hitlManager.submit({hitlData:{action:`cust_ai_output_start`,payload:{}}}))}),(0,t.watch)(()=>c.value,(t,n)=>{t&&i.value[i.value.length-1]?.role===`ai`&&e.hitlManager.submit({hitlData:{action:`cust_ai_output_finish`,payload:{refConfig:c.value,conversationId:i.value[i.value.length-1]?.conversationId,messageId:[...i.value].reverse().find(e=>e.messageId)?.messageId}}})});let d=async(t,n=!1)=>{let r={messageId:void 0,content:t.text,role:`user`,placement:`end`,showActions:!1,maxWidth:`100%`};m();let a=i.value[i.value.length-1];n||(g.getState().updateMessageHistory([r]),g.getState().setPendingRetryRequest({type:`submit_message`,payload:{text:t.text,inputs:{scence:s.value},file:t.file?.[0]}})),g.getState().resetCurrentMessage();let c=await e.adapter.formatRequest({text:t.text,prevMessage:a,inputs:{scence:s.value},files:t.file}),l=e.authManager.isServerMode()?e.adapter.createSseFetch?.():void 0;o.value=y(c,e.adapter,{fetchFn:l,isRetry:n}).cancel},f=()=>{e.logger.log(`Cancel handler called`),o.value?.(),g.getState().resetCurrentMessage()},p=async(t,n)=>{g.getState().resetCurrentMessage(),g.getState().updateMessageHistory([]),m(),await e.hitlManager.submit({hitlData:t,prevMessage:n,inputs:{scence:s.value}})},m=()=>{n.value?.scrollToBottom()};return(0,t.onBeforeUnmount)(()=>{u?.()}),{messages:i,isLoading:a,authToken:l,activeScence:s,tagList:r,handleSendMessage:d,cancelHandler:f,handleScenceChange:t=>{e.hitlManager.submit({hitlData:{action:`cust_scence_change`,payload:{scence:t.id}}})},coreSubmit:p,handleRefConfigUpdate:e=>{c.value=e},handleSceneUpdate:e=>{g.getState().setActiveScence(e)},handleQuestionClick:e=>{d({text:e,file:[]})}}},render(){return(0,t.createVNode)(`div`,{class:`core-pilot-host`},[(0,t.createVNode)(n.BubbleList,{ref:`bubbleList`,class:`bubble-list`,list:this.messages,maxHeight:`100%`,user:this.provider.extensions.user,authToken:this.authManager.getToken(),appId:this.appId,btnLoading:this.isLoading,onCoreSubmit:this.coreSubmit,onRefConfigUpdate:this.handleRefConfigUpdate,onQuestionClick:this.handleQuestionClick},null),(0,t.createVNode)(n.EditorSender,{tagList:this.tagList,loading:this.isLoading,agentName:``,scene:this.activeScence,user:this.provider.extensions.user,authToken:this.authToken,appId:this.appId,showUpload:!1,onSubmit:this.handleSendMessage,onCancel:this.cancelHandler,onSceneChange:this.handleScenceChange,"onUpdate:scene":this.handleSceneUpdate},null)])}});function x(e,n,r,i,a){let o=null,s=null,c={...e.mount},l={...e.provider},u=e.appId,d=()=>{let e=(c.container||document).querySelector(c.selector);if(e&&!e.querySelector(`[data-corepilot-host]`)){let t=document.createElement(`div`);return t.setAttribute(`data-corepilot-host`,`true`),t.style.width=`100%`,t.style.height=`100%`,e.appendChild(t),t}return e?.querySelector(`[data-corepilot-host]`)};return{mount(){if(s=d(),!s){i.error(`Mount point "${c.selector}" not found or already in use.`);return}o&&(i.log(`An app instance already exists. Unmounting first.`),this.unmount()),o=(0,t.createApp)(b,{adapter:n,hitlManager:r,logger:i,provider:l,authManager:a,appId:u}),o.mount(s),i.log(`Vue CorePilotHost mounted.`)},unmount(){o&&(o.unmount(),o=null,i.log(`Vue CorePilotHost unmounted.`)),s&&s.parentElement&&(s.parentElement.innerHTML=``)}}}var S=class extends Error{constructor(e,t,n,r){super(e),this.name=`HttpError`,this.code=t,this.data=n,this.originalError=r}},C=new class{constructor(e){this.instance=i.default.create({timeout:3e4,headers:{"Content-Type":`application/json;charset=utf-8`},withCredentials:!0,...e}),this.setupInterceptors()}setupInterceptors(){this.instance.interceptors.response.use(e=>e.data,e=>Promise.reject(this.handleError(e)))}handleError(e){let t=`请求失败,请稍后重试`,n=-1,r=null;if(i.default.isAxiosError(e))if(e.response)switch(n=e.response.status,r=e.response.data,n){case 400:t=`请求参数错误`;break;case 401:t=`未授权,请重新登录`;break;case 403:t=`拒绝访问`;break;case 404:t=`请求资源不存在`;break;case 405:t=`请求方法不允许`;break;case 408:t=`请求超时`;break;case 500:t=`服务器内部错误`;break;case 501:t=`服务未实现`;break;case 502:t=`网关错误`;break;case 503:t=`服务不可用`;break;case 504:t=`网关超时`;break;default:t=e.response.statusText||`连接错误 ${n}`}else e.request?(t=`网络连接失败,请检查网络设置`,n=0):t=e.message;else t=e.message||`未知错误`;return console.error(`[HttpClient] Error: ${t}`,{code:n,data:r,original:e}),new S(t,n,r,e)}get(e,t){return this.instance.get(e,t)}post(e,t,n){return this.instance.post(e,t,n)}put(e,t,n){return this.instance.put(e,t,n)}delete(e,t){return this.instance.delete(e,t)}patch(e,t,n){return this.instance.patch(e,t,n)}upload(e,t,n=`file`,r){let i=new FormData;return i.append(n,t),this.instance.post(e,i,{...r,headers:{...r?.headers,"Content-Type":`multipart/form-data`}})}getAxiosInstance(){return this.instance}}({});let w=new class{constructor(){this.listeners=[]}subscribeEvent(e){this.listeners.includes(e)||this.listeners.push(e)}unsubscribeEvent(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}emitEvent(e){this.listeners.forEach(t=>{try{t(e)}catch(e){console.error(`[EventHub] Event callback error:`,e)}})}};var T=40100,E=403;function D(e,t,n){let{appId:r,provider:i,baseUrl:a}=e,{extensions:o}=i,{user:s=`default`,accessToken:c=``}=o||{},l=()=>{w.emitEvent({action:`cust_token_expired`,code:T,message:`凭证已过期`})},u=e=>{w.emitEvent({action:`cust_request_error`,code:e.code,message:e.message||`请求失败`})},d=()=>t.isServerMode()?a+`/api/proxy/ca`:a,f=async()=>({Authorization:`Bearer ${await t.getToken()}`,appId:r}),p=async(e,t)=>{let n=e.taskId,r=d(),i=await f();return await C.post(`${r}/openapi/v1/app/chat-messages/${n}/stop`,{user:s},{headers:i}),Promise.resolve()},m=async(e,n,r)=>{e.messageId;let i=d(),a=await t.getToken(),o={query:JSON.stringify(n||[]),inputs:{scence:r},response_mode:`blocking`,conversation_id:null,parent_message_id:null,user:s,files:[]},c={Authorization:`Bearer ${a}`};c.appId=`b7886345-d200-486d-8318-8c234a19ccb9`;let l=await C.post(`${i}/openapi/v1/app/chat-messages`,o,{headers:c});try{let e=JSON.parse(l.answer||`[]`);return console.log(`data`,e),e}catch{return[]}},h=async e=>{let t=d(),n=await f();try{return await C.get(`${t}/openapi/v1/app/conversations?${new URLSearchParams(e).toString()}`,{headers:n})}catch(e){throw e}},_=async e=>{let t=d(),n=await f();try{return await C.get(`${t}/openapi/v1/app/messages?${new URLSearchParams(e).toString()}`,{headers:n})}catch(e){throw e}},v=e=>{switch(e.toLowerCase()){case`txt`:case`doc`:case`docx`:case`pdf`:case`ppt`:case`pptx`:case`xls`:case`xlsx`:case`csv`:return`document`;case`jpg`:case`jpeg`:case`png`:case`gif`:case`webp`:case`svg`:return`image`;case`mp3`:case`wav`:return`audio`;case`mp4`:case`mov`:case`ogg`:return`video`;default:return`custom`}},b=async e=>{let{hitlData:t,prevMessage:n,text:r,inputs:i,files:a}=e,o=t?.payload?.__files__||{},l=[];Object.values(o).flat().forEach(e=>{l.push({transfer_method:`local_file`,type:v(e.extension||``),upload_file_id:e.id,url:e.url||``})}),a?.forEach(e=>{l.push({transfer_method:`local_file`,type:v(e.extension||``),upload_file_id:e.id,url:e.url||``})});let u={query:r||JSON.stringify(t||{}),inputs:{...i||{},accessToken:c},response_mode:`streaming`,conversation_id:n?.conversationId||null,parent_message_id:n?.messageId||null,user:s,files:l},p=d(),m=await f();return{url:`${p}/openapi/v1/app/chat-messages`,config:{method:`POST`,headers:{"Content-Type":`application/json`,...m},body:JSON.stringify(u)}}},x=e=>{let{data:t}=e,n=JSON.parse(t||`{}`);return n.code===T?(l(),null):n.code===E?(u(n),null):n},S=async()=>{n.log(`onClose`)},D=async e=>{n.log(`onError`,e)},O=async e=>{n.log(`onOpen`)},k=e=>{try{return JSON.parse(e||`{}`)?.action?.startsWith(`core_`)||!1}catch{return!1}},A=async(e,n=!1)=>{let{inputs:r}=e,i=r?.scence;i&&g.getState().setActiveScence(i);let a=await b(e),o=t.isServerMode()?N():void 0;y(a,{formatRequest:b,getSuggestionQuestions:m,getConversationList:h,getMessageHistory:_,onMessage:x,onClose:S,onError:D,onOpen:O,onCancel:p},{fetchFn:o,isRetry:n})},j=async e=>{let t=[],n;if(e.data.forEach(e=>{if(e.parent_message_id===n)t.pop(),t.push({role:`ai`,showActions:!1,content:e.answer,maxWidth:`100%`,files:e.message_files.map(e=>({id:e.id,extension:e.type,name:e.filename})),placement:`start`,conversationId:e.conversation_id,messageId:e.id});else{if(n=e.parent_message_id,!k(e.query))t.push({role:`user`,messageId:e.id,content:e.query,showActions:!1,maxWidth:`100%`,placement:`end`,isHistoryMessage:!0,conversationId:e.conversation_id});else{let n=JSON.parse(e.query||`{}`);if(n?.payload){let e=t[t.length-1];e&&(e.historyInputs=n.payload)}}t.push({role:`ai`,content:e.answer,showActions:!1,maxWidth:`100%`,placement:`start`,files:e.message_files.map(e=>({id:e.id,extension:e.type,name:e.filename})),isHistoryMessage:!0,conversationId:e.conversation_id,messageId:e.id})}}),e.has_more){let e=await _({conversation_id:t[t.length-1].conversationId,user:s,first_id:t[0].messageId});if(e.data){let n=await j(e);t.unshift(...n)}}return t},M=async()=>(g.getState().resetMessageHistory(),!0),N=()=>async(e,n)=>{let r=await t.getToken(),i=t.getAppId(),a={...n?.headers||{},Authorization:`Bearer ${r}`,...i?{appId:i}:{}};return await fetch(e,{...n,headers:a})},P=async(e,n=!1)=>{let r={messageId:void 0,content:e.text,role:`user`,placement:`end`,showActions:!1,maxWidth:`100%`};n||g.getState().updateMessageHistory([r]),g.getState().resetCurrentMessage();let i=await b({text:e.text,prevMessage:void 0,inputs:e.inputs});g.getState().setActiveScence(e.inputs?.scence);let a=t.isServerMode()?N():void 0;return y(i,{formatRequest:b,getSuggestionQuestions:m,getConversationList:h,getMessageHistory:_,onMessage:x,onClose:S,onError:D,onOpen:O,onCancel:p},{fetchFn:a,isRetry:n})},F=async()=>{let e=g.getState().pendingRetryRequest;if(!e)return;g.getState().clearPendingRetryRequest();let n=t.isServerMode()?N():void 0;if(e.type===`submit_message`){let t=e.payload;y(await b({text:t.text,prevMessage:void 0,inputs:t.inputs}),{formatRequest:b,getSuggestionQuestions:m,getConversationList:h,getMessageHistory:_,onMessage:x,onClose:S,onError:D,onOpen:O,onCancel:p},{fetchFn:n,isRetry:!0})}else e.type===`submit_core_action`&&await A(e.payload,!0)};return t.onTokenRefreshed(()=>{setTimeout(()=>{F()},0)}),{formatRequest:b,getSuggestionQuestions:m,getConversationList:h,getMessageHistory:_,onMessage:x,onClose:S,onError:D,onOpen:O,onCancel:p,triggerEvent:async e=>{switch(e.action){case`get_suggestion_questions`:return await m(e.payload);case`get_conversation_list`:return await h(e.payload);case`get_message_history`:let t=await j(await _(e.payload));return g.getState().resetMessageHistory(t),t;case`submit_core_action`:return g.getState().setPendingRetryRequest({type:`submit_core_action`,payload:e.payload}),await A(e.payload);case`new_message`:return await M();case`submit_message`:return g.getState().setPendingRetryRequest({type:`submit_message`,payload:e.payload}),await P(e.payload);default:throw Error(`Invalid event action.`)}},createSseFetch:N}}function O(e,t,n,r){switch(r.log(`Creating adapter for provider: ${t}`),t.name){case`coreagent`:return D(e,n,r);default:throw Error(`Unsupported provider: ${t.name}`)}}function k(e,t,n){let r=e=>e.split(`_`)[0],i=[],a=async t=>{let r=await e.formatRequest(t);y({url:r.url,config:r.config},e),n.log(`HITL data submitted successfully.`)},o=async e=>{i.forEach(t=>t(e.hitlData))},s=async e=>{};return{async submit(e){try{let t=r(e.hitlData?.action??``);switch(n.log(`[HITL] Submitting HITL data...`,e),t){case`core`:await a(e);break;case`cust`:await o(e);break;case`inner`:await s(e);break;default:throw Error(`Invalid action type.`)}}catch(e){throw n.error(`Error submitting HITL data:`,e),e}},subscribeEvent(e){i.includes(e)||i.push(e)},unsubscribeEvent(e){i.splice(i.indexOf(e),1)}}}function A(e){if(e.auth.mode,!e.appId)throw Error("CorePilot SDK: `appId` is required.");if(!e.mount.selector)throw Error("CorePilot SDK: `mount.selector` is required.");let t=p(e.debug??!1,e.appId||``,e.eventTracker);t.log(`CorePilot SDK Initializing...`,e);let n={...e},r=m(n.auth,n.appId),i=O(n,n.provider,r,t),a=k(i,r,t),o=x(n,i,a,t,r),s={inner_set_token:async e=>(await r.setToken(e),!0),inner_get_token:async()=>await r.getToken()};return{mount(){t.log(`Mounting CorePilot UI...`),o.mount()},unmount(){t.log(`Unmounting CorePilot UI...`),o.unmount()},reload(e){t.log(`Reloading CorePilot instance...`,e),o.unmount(),n={...n,...e},i=O(n,n.provider,r,t);let s=x(n,i,a,t,r);o.mount=s.mount,o.unmount=s.unmount,t.log(`CorePilot reloaded. Remounting UI...`),o.mount()},destroy(){t.log(`Destroying CorePilot instance...`),o.unmount(),t.destroy()},async triggerEvent(e){let t=s[e.action];if(t){let n=e.payload;return await t(n)}return await i.triggerEvent(e)},subscribeEvent(e){a.subscribeEvent(e),w.subscribeEvent(e)},unsubscribeEvent(e){a.unsubscribeEvent(e),w.unsubscribeEvent(e)}}}typeof window<`u`&&(window.createCorePilot=A),e.createCorePilot=A});
|
|
1
|
+
(function(e,t){typeof exports==`object`&&typeof module<`u`?t(exports,require(`vue`),require(`@core-pilot/client-vue`),require(`@microsoft/fetch-event-source`),require(`axios`)):typeof define==`function`&&define.amd?define([`exports`,`vue`,`@core-pilot/client-vue`,`@microsoft/fetch-event-source`,`axios`],t):(e=typeof globalThis<`u`?globalThis:e||self,t(e.CorePilotSDK={},e.Vue,e.CorePilotClientVue,e.FetchEventSource,e.axios))})(this,function(e,t,n,r,i){var a=Object.create,o=Object.defineProperty,s=Object.getOwnPropertyDescriptor,c=Object.getOwnPropertyNames,l=Object.getPrototypeOf,u=Object.prototype.hasOwnProperty,d=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=c(t),a=0,l=i.length,d;a<l;a++)d=i[a],!u.call(e,d)&&d!==n&&o(e,d,{get:(e=>t[e]).bind(null,d),enumerable:!(r=s(t,d))||r.enumerable});return e};i=((e,t,n)=>(n=e==null?{}:a(l(e)),d(t||!e||!e.__esModule?o(n,`default`,{value:e,enumerable:!0}):n,e)))(i);function f(e){return e.map(e=>{if(typeof e==`string`)return e;if(e instanceof Error)return e.stack||e.message;try{return JSON.stringify(e)}catch{return String(e)}}).join(` `)}function p(e,t,n){let r=`[CorePilot]`,i=[],a=null,o=n?.batchSize??20,s=n?.flushInterval??15e3,c=()=>{if(!n||i.length===0)return;let t=[...i];i=[],e&&console.log(`${r} Uploading ${t.length} log(s) to ${n.url}`);let a=JSON.stringify(t);navigator.sendBeacon?navigator.sendBeacon(n.url,a):fetch(n.url,{method:`POST`,body:a,headers:{"Content-Type":`application/json`},keepalive:!0}).catch(n=>{e&&(console.error(`${r} Log upload failed:`,n),i.unshift(...t))})},l=(e,...r)=>{n&&(i.push({level:e,timestamp:new Date().toISOString(),message:f(r),appId:t}),i.length>=o&&(a&&clearTimeout(a),c(),a=window.setTimeout(c,s)))};return n&&(a=window.setTimeout(c,s)),{log(...t){e&&console.log(r,...t),l(`log`,...t)},error(...t){e&&console.error(r,...t),l(`error`,...t)},destroy(){a&&clearTimeout(a),c()}}}function m(e,t){let n=e.token||``,r=null;return{async getToken(){if(!n)throw Error(`AuthManager: Missing token`);return n},async setToken(e){return e?(n=e,r&&r(),!0):!1},onTokenRefreshed(e){r=e},isServerMode(){return e.mode===`server`},getAgentId(){if(!t)throw Error(`AuthManager: Missing agentId`);return t}}}var h=e=>{let t,n=new Set,r=(e,r)=>{let i=typeof e==`function`?e(t):e;if(!Object.is(i,t)){let e=t;t=r??(typeof i!=`object`||!i)?i:Object.assign({},t,i),n.forEach(n=>n(t,e))}},i=()=>t,a={setState:r,getState:i,getInitialState:()=>o,subscribe:e=>(n.add(e),()=>n.delete(e))},o=t=e(r,i,a);return a};let g=(e=>e?h(e):h)(e=>({currentMessage:void 0,isLoading:!1,messageHistory:[],activeScence:`ANC`,pendingRetryRequest:null,setActiveScence:t=>e({activeScence:t}),updateMessage:t=>e(e=>{let n={...t,role:`ai`,showActions:!1,maxWidth:`100%`},r=[...e.messageHistory];if(r.forEach(e=>{e.isHistoryMessage=!0}),e.currentMessage){let i={...n,content:e.currentMessage.content+(t.content||``)};return r.pop(),r.push(i),{currentMessage:i,messageHistory:r}}return r.push(n),{currentMessage:n,messageHistory:r}}),setLoading:t=>e({isLoading:t}),resetCurrentMessage:()=>e({currentMessage:void 0}),resetMessageHistory:t=>e({messageHistory:t||[]}),resetQuestions:()=>e(e=>{let t=[...e.messageHistory];return t.forEach(e=>{e.questions=[]}),{messageHistory:t}}),updateMessageHistory:t=>e(e=>{let n=[...e.messageHistory];return n.forEach(e=>{e.isHistoryMessage=!0,e.questions=[]}),Array.isArray(t)?{messageHistory:[...n,...t]}:{messageHistory:[...n,t]}}),updateSuggestionQuestions:t=>e(e=>{let n=[...e.messageHistory];return n[n.length-1].questions=t,{messageHistory:n}}),setPendingRetryRequest:t=>{e({pendingRetryRequest:t})},clearPendingRetryRequest:()=>{e({pendingRetryRequest:null})}}));var _=0,v=class extends Error{constructor(e){super(e),this.name=`FatalError`}};let y=function(e,t,n){let{url:i,config:a={}}=e,o=new AbortController,s=!1,c=!1;function l(){o.abort(),t.onCancel(g.getState().currentMessage,o),g.getState().setLoading(!1),g.getState().resetCurrentMessage()}function u(e){try{let n=t.onMessage(e);if(!n)return;n.event===`message`&&(g.getState().updateMessage({taskId:n.task_id,messageId:n.message_id,conversationId:n.conversation_id,role:`ai`,content:n.answer}),g.getState().resetQuestions())}catch(e){throw f(),e}}async function d(e){try{await t.onOpen(e)}catch(t){throw(e.status===500||t instanceof Error&&t.message===`Token expired`)&&await f(),t}}async function f(){s||(s=!0,g.getState().setLoading(!1),await t.onClose())}async function p(e){c||(c=!0,s||await t.onError(e))}let m=_,h={...a,signal:o.signal,openWhenHidden:!0,onmessage:u,onclose:async()=>await f(),onopen:async e=>{await d(e)},onerror:e=>{if(e instanceof v)throw f(),e;if(m--,m<0){if(f(),e instanceof TypeError)throw new v(e.message);return}p(e)}};return n?.fetchFn&&(h.fetch=n.fetchFn),(0,r.fetchEventSource)(i,h).catch(e=>{f(),p(e)}),{cancel:l}},b=(0,t.defineComponent)({props:{adapter:{type:Object,required:!0},hitlManager:{type:Object,required:!0},logger:{type:Object,required:!0},provider:{type:Object,required:!0},authManager:{type:Object,required:!0},agentId:{type:String,required:!0}},setup(e){let n=(0,t.useTemplateRef)(`bubbleList`),r=(0,t.ref)([]),i=(0,t.ref)([]),a=(0,t.ref)(!1),o=(0,t.ref)(),s=(0,t.ref)(`ANC`),c=(0,t.ref)(),l=(0,t.ref)(``);(0,t.watch)(()=>e.authManager,async e=>{l.value=await e.getToken()},{immediate:!0});let u=g.subscribe(e=>{let{isLoading:t,messageHistory:n}=e;i.value=n,a.value=t,s.value=e.activeScence});(0,t.watch)(()=>a.value,t=>{t&&(c.value=void 0,e.hitlManager.submit({hitlData:{action:`cust_ai_output_start`,payload:{}}}))}),(0,t.watch)(()=>c.value,(t,n)=>{t&&i.value[i.value.length-1]?.role===`ai`&&e.hitlManager.submit({hitlData:{action:`cust_ai_output_finish`,payload:{refConfig:c.value,conversationId:i.value[i.value.length-1]?.conversationId,messageId:[...i.value].reverse().find(e=>e.messageId)?.messageId}}})});let d=async(t,n=!1)=>{g.getState().setLoading(!0);let r={messageId:void 0,content:t.text,role:`user`,placement:`end`,showActions:!1,maxWidth:`100%`};m();let a=i.value[i.value.length-1];n||(g.getState().updateMessageHistory([r]),g.getState().setPendingRetryRequest({type:`submit_message`,payload:{text:t.text,inputs:{scence:s.value},file:t.file?.[0]}})),g.getState().resetCurrentMessage();let c=await e.adapter.formatRequest({text:t.text,prevMessage:a,inputs:{scence:s.value},files:t.file}),l=e.authManager.isServerMode()?e.adapter.createSseFetch?.():void 0;o.value=y(c,e.adapter,{fetchFn:l,isRetry:n}).cancel},f=()=>{e.logger.log(`Cancel handler called`),o.value?.(),g.getState().resetCurrentMessage()},p=async(t,n)=>{g.getState().resetCurrentMessage(),g.getState().updateMessageHistory([]),m(),await e.hitlManager.submit({hitlData:t,prevMessage:n,inputs:{scence:s.value}})},m=()=>{n.value?.scrollToBottom()};return(0,t.onBeforeUnmount)(()=>{u?.()}),{messages:i,isLoading:a,authToken:l,activeScence:s,tagList:r,handleSendMessage:d,cancelHandler:f,handleScenceChange:t=>{e.hitlManager.submit({hitlData:{action:`cust_scence_change`,payload:{scence:t.id}}})},coreSubmit:p,handleRefConfigUpdate:e=>{c.value=e},handleSceneUpdate:e=>{g.getState().setActiveScence(e)},handleQuestionClick:e=>{d({text:e,file:[]})}}},render(){return(0,t.createVNode)(`div`,{class:`core-pilot-host`},[(0,t.createVNode)(n.BubbleList,{ref:`bubbleList`,class:`bubble-list`,list:this.messages,maxHeight:`100%`,user:this.provider.extensions.user,authToken:this.authManager.getToken(),appId:this.agentId,btnLoading:this.isLoading,onCoreSubmit:this.coreSubmit,onRefConfigUpdate:this.handleRefConfigUpdate,onQuestionClick:this.handleQuestionClick},null),(0,t.createVNode)(n.EditorSender,{tagList:this.tagList,loading:this.isLoading,agentName:``,scene:this.activeScence,user:this.provider.extensions.user,authToken:this.authToken,appId:this.agentId,showUpload:!1,onSubmit:this.handleSendMessage,onCancel:this.cancelHandler,onSceneChange:this.handleScenceChange,"onUpdate:scene":this.handleSceneUpdate},null)])}});function x(e,n,r,i,a){let o=null,s=null,c={...e.mount},l={...e.provider},u=e.agentId,d=()=>{let e=(c.container||document).querySelector(c.selector);if(e&&!e.querySelector(`[data-corepilot-host]`)){let t=document.createElement(`div`);return t.setAttribute(`data-corepilot-host`,`true`),t.style.width=`100%`,t.style.height=`100%`,e.appendChild(t),t}return e?.querySelector(`[data-corepilot-host]`)};return{mount(){if(s=d(),!s){i.error(`Mount point "${c.selector}" not found or already in use.`);return}o&&(i.log(`An app instance already exists. Unmounting first.`),this.unmount()),o=(0,t.createApp)(b,{adapter:n,hitlManager:r,logger:i,provider:l,authManager:a,agentId:u}),o.mount(s),i.log(`Vue CorePilotHost mounted.`)},unmount(){o&&(o.unmount(),o=null,i.log(`Vue CorePilotHost unmounted.`)),s&&s.parentElement&&(s.parentElement.innerHTML=``)}}}var S=class extends Error{constructor(e,t,n,r){super(e),this.name=`HttpError`,this.code=t,this.data=n,this.originalError=r}},C=new class{constructor(e){this.instance=i.default.create({timeout:3e4,headers:{"Content-Type":`application/json;charset=utf-8`},withCredentials:!0,...e}),this.setupInterceptors()}setupInterceptors(){this.instance.interceptors.response.use(e=>e.data,e=>Promise.reject(this.handleError(e)))}handleError(e){let t=`请求失败,请稍后重试`,n=-1,r=null;if(i.default.isAxiosError(e))if(e.response)switch(n=e.response.status,r=e.response.data,n){case 400:t=`请求参数错误`;break;case 401:t=`未授权,请重新登录`;break;case 403:t=`拒绝访问`;break;case 404:t=`请求资源不存在`;break;case 405:t=`请求方法不允许`;break;case 408:t=`请求超时`;break;case 500:t=`服务器内部错误`;break;case 501:t=`服务未实现`;break;case 502:t=`网关错误`;break;case 503:t=`服务不可用`;break;case 504:t=`网关超时`;break;default:t=e.response.statusText||`连接错误 ${n}`}else e.request?(t=`网络连接失败,请检查网络设置`,n=0):t=e.message;else t=e.message||`未知错误`;return console.error(`[HttpClient] Error: ${t}`,{code:n,data:r,original:e}),new S(t,n,r,e)}get(e,t){return this.instance.get(e,t)}post(e,t,n){return this.instance.post(e,t,n)}put(e,t,n){return this.instance.put(e,t,n)}delete(e,t){return this.instance.delete(e,t)}patch(e,t,n){return this.instance.patch(e,t,n)}upload(e,t,n=`file`,r){let i=new FormData;return i.append(n,t),this.instance.post(e,i,{...r,headers:{...r?.headers,"Content-Type":`multipart/form-data`}})}getAxiosInstance(){return this.instance}}({});let w=new class{constructor(){this.listeners=[]}subscribeEvent(e){this.listeners.includes(e)||this.listeners.push(e)}unsubscribeEvent(e){let t=this.listeners.indexOf(e);t>-1&&this.listeners.splice(t,1)}emitEvent(e){this.listeners.forEach(t=>{try{t(e)}catch(e){console.error(`[EventHub] Event callback error:`,e)}})}};var T=40100,E=403;function D(e,t,n){let{agentId:r,provider:i,baseUrl:a}=e,{extensions:o}=i,{user:s=`default`,accessToken:c=``}=o||{},l=!1,u=()=>{l||(l=!0,w.emitEvent({action:`cust_token_expired`,code:T,message:`凭证已过期`}))},d=e=>{w.emitEvent({action:`cust_request_error`,code:e.code,message:e.message||`请求失败`})},f=()=>t.isServerMode()?a+`/api/proxy/ca`:a,p=async()=>{let e={Authorization:`Bearer ${await t.getToken()}`};return t.isServerMode()?e[`X-Agent-Id`]=r:e.appId=r,e},m=async(e,t)=>{let n=e.taskId,r=f(),i=await p();return await C.post(`${r}/openapi/v1/app/chat-messages/${n}/stop`,{user:s},{headers:i}),Promise.resolve()},h=async(e,n,r)=>{e.messageId;let i=f(),a=await t.getToken(),o={query:JSON.stringify(n||[]),inputs:{scence:r},response_mode:`blocking`,conversation_id:null,parent_message_id:null,user:s,files:[]},c={Authorization:`Bearer ${a}`};c.appId=`b7886345-d200-486d-8318-8c234a19ccb9`;let l=await C.post(`${i}/openapi/v1/app/chat-messages`,o,{headers:c});try{let e=JSON.parse(l.answer||`[]`);return console.log(`data`,e),e}catch{return[]}},_=async e=>{let t=f(),n=await p();try{return await C.get(`${t}/openapi/v1/app/conversations?${new URLSearchParams(e).toString()}`,{headers:n})}catch(e){throw e}},v=async e=>{let t=f(),n=await p();try{return await C.get(`${t}/openapi/v1/app/messages?${new URLSearchParams(e).toString()}`,{headers:n})}catch(e){throw e}},b=e=>{switch(e.toLowerCase()){case`txt`:case`doc`:case`docx`:case`pdf`:case`ppt`:case`pptx`:case`xls`:case`xlsx`:case`csv`:return`document`;case`jpg`:case`jpeg`:case`png`:case`gif`:case`webp`:case`svg`:return`image`;case`mp3`:case`wav`:return`audio`;case`mp4`:case`mov`:case`ogg`:return`video`;default:return`custom`}},x=async e=>{let{hitlData:t,prevMessage:n,text:r,inputs:i,files:a}=e,o=t?.payload?.__files__||{},l=[];Object.values(o).flat().forEach(e=>{l.push({transfer_method:`local_file`,type:b(e.extension||``),upload_file_id:e.id,url:e.url||``})}),a?.forEach(e=>{l.push({transfer_method:`local_file`,type:b(e.extension||``),upload_file_id:e.id,url:e.url||``})});let u={query:r||JSON.stringify(t||{}),inputs:{...i||{},accessToken:c},response_mode:`streaming`,conversation_id:n?.conversationId||null,parent_message_id:n?.messageId||null,user:s,files:l},d=f(),m=await p();return{url:`${d}/openapi/v1/app/chat-messages`,config:{method:`POST`,headers:{"Content-Type":`application/json`,...m},body:JSON.stringify(u)}}},S=e=>{let{data:t}=e,n=JSON.parse(t||`{}`);return n.code===T?(u(),null):n.code===E?(d(n),null):n},D=async()=>{n.log(`onClose`)},O=async e=>{n.log(`onError`,e)},k=async e=>{if(n.log(`onOpen`),!(e.headers.get(`content-type`)||``).includes(`text/event-stream`))throw Error(`Invalid content type`)},A=e=>{try{return JSON.parse(e||`{}`)?.action?.startsWith(`core_`)||!1}catch{return!1}},j=async(e,n=!1)=>{let{inputs:r}=e,i=r?.scence;i&&g.getState().setActiveScence(i);let a=await x(e),o=t.isServerMode()?P():void 0;y(a,{formatRequest:x,getSuggestionQuestions:h,getConversationList:_,getMessageHistory:v,onMessage:S,onClose:D,onError:O,onOpen:k,onCancel:m},{fetchFn:o,isRetry:n})},M=async e=>{let t=[],n;if(e.data.forEach(e=>{if(e.parent_message_id===n)t.pop(),t.push({role:`ai`,showActions:!1,content:e.answer,maxWidth:`100%`,files:e.message_files.map(e=>({id:e.id,extension:e.type,name:e.filename})),placement:`start`,conversationId:e.conversation_id,messageId:e.id});else{if(n=e.parent_message_id,!A(e.query))t.push({role:`user`,messageId:e.id,content:e.query,showActions:!1,maxWidth:`100%`,placement:`end`,isHistoryMessage:!0,conversationId:e.conversation_id});else{let n=JSON.parse(e.query||`{}`);if(n?.payload){let e=t[t.length-1];e&&(e.historyInputs=n.payload)}}t.push({role:`ai`,content:e.answer,showActions:!1,maxWidth:`100%`,placement:`start`,files:e.message_files.map(e=>({id:e.id,extension:e.type,name:e.filename})),isHistoryMessage:!0,conversationId:e.conversation_id,messageId:e.id})}}),e.has_more){let e=await v({conversation_id:t[t.length-1].conversationId,user:s,first_id:t[0].messageId});if(e.data){let n=await M(e);t.unshift(...n)}}return t},N=async()=>(g.getState().resetMessageHistory(),!0),P=()=>async(e,n)=>{let r=await t.getToken(),i=t.getAgentId(),a={...n?.headers||{},Authorization:`Bearer ${r}`,...t.isServerMode()?{"X-Agent-Id":i}:{appId:i}};return await fetch(e,{...n,headers:a})},F=async(e,n=!1)=>{let r={messageId:void 0,content:e.text,role:`user`,placement:`end`,showActions:!1,maxWidth:`100%`};n||g.getState().updateMessageHistory([r]),g.getState().resetCurrentMessage();let i=await x({text:e.text,prevMessage:void 0,inputs:e.inputs});g.getState().setActiveScence(e.inputs?.scence);let a=t.isServerMode()?P():void 0;return y(i,{formatRequest:x,getSuggestionQuestions:h,getConversationList:_,getMessageHistory:v,onMessage:S,onClose:D,onError:O,onOpen:k,onCancel:m},{fetchFn:a,isRetry:n})},I=async()=>{let e=g.getState().pendingRetryRequest;if(!e)return;g.getState().clearPendingRetryRequest();let n=t.isServerMode()?P():void 0;if(e.type===`submit_message`){let t=e.payload;y(await x({text:t.text,prevMessage:void 0,inputs:t.inputs}),{formatRequest:x,getSuggestionQuestions:h,getConversationList:_,getMessageHistory:v,onMessage:S,onClose:D,onError:O,onOpen:k,onCancel:m},{fetchFn:n,isRetry:!0})}else e.type===`submit_core_action`&&await j(e.payload,!0)};return t.onTokenRefreshed(()=>{l=!1,setTimeout(()=>{I()},0)}),{formatRequest:x,getSuggestionQuestions:h,getConversationList:_,getMessageHistory:v,onMessage:S,onClose:D,onError:O,onOpen:k,onCancel:m,triggerEvent:async e=>{switch(e.action){case`get_suggestion_questions`:return await h(e.payload);case`get_conversation_list`:return await _(e.payload);case`get_message_history`:let t=await M(await v(e.payload));return g.getState().resetMessageHistory(t),t;case`submit_core_action`:return g.getState().setPendingRetryRequest({type:`submit_core_action`,payload:e.payload}),await j(e.payload);case`new_message`:return await N();case`submit_message`:return g.getState().setPendingRetryRequest({type:`submit_message`,payload:e.payload}),await F(e.payload);default:throw Error(`Invalid event action.`)}},createSseFetch:P}}function O(e,t,n,r){switch(r.log(`Creating adapter for provider: ${t}`),t.name){case`coreagent`:return D(e,n,r);default:throw Error(`Unsupported provider: ${t.name}`)}}function k(e,t,n){let r=e=>e.split(`_`)[0],i=[],a=async t=>{let r=await e.formatRequest(t);y({url:r.url,config:r.config},e),n.log(`HITL data submitted successfully.`)},o=async e=>{i.forEach(t=>t(e.hitlData))},s=async e=>{};return{async submit(e){try{let t=r(e.hitlData?.action??``);switch(n.log(`[HITL] Submitting HITL data...`,e),t){case`core`:await a(e);break;case`cust`:await o(e);break;case`inner`:await s(e);break;default:throw Error(`Invalid action type.`)}}catch(e){throw n.error(`Error submitting HITL data:`,e),e}},subscribeEvent(e){i.includes(e)||i.push(e)},unsubscribeEvent(e){i.splice(i.indexOf(e),1)}}}function A(e){if(e.auth.mode,!e.agentId)throw Error("CorePilot SDK: `agentId` is required.");if(!e.mount.selector)throw Error("CorePilot SDK: `mount.selector` is required.");let t=p(e.debug??!1,e.agentId||``,e.eventTracker);t.log(`CorePilot SDK Initializing...`,e);let n={...e},r=m(n.auth,n.agentId),i=O(n,n.provider,r,t),a=k(i,r,t),o=x(n,i,a,t,r),s={inner_set_token:async e=>(await r.setToken(e),!0),inner_get_token:async()=>await r.getToken()};return{mount(){t.log(`Mounting CorePilot UI...`),o.mount()},unmount(){t.log(`Unmounting CorePilot UI...`),o.unmount()},reload(e){t.log(`Reloading CorePilot instance...`,e),o.unmount(),n={...n,...e},i=O(n,n.provider,r,t);let s=x(n,i,a,t,r);o.mount=s.mount,o.unmount=s.unmount,t.log(`CorePilot reloaded. Remounting UI...`),o.mount()},destroy(){t.log(`Destroying CorePilot instance...`),o.unmount(),t.destroy()},async triggerEvent(e){let t=s[e.action];if(t){let n=e.payload;return await t(n)}return await i.triggerEvent(e)},subscribeEvent(e){a.subscribeEvent(e),w.subscribeEvent(e)},unsubscribeEvent(e){a.unsubscribeEvent(e),w.unsubscribeEvent(e)}}}typeof window<`u`&&(window.createCorePilot=A),e.createCorePilot=A});
|