@core-pilot/sdk 0.0.0-beta.8 → 0.1.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/dist/index.js CHANGED
@@ -1,165 +1,194 @@
1
- import { createApp, createVNode, defineComponent, onBeforeUnmount, ref, watch } from "vue";
1
+ import { createApp, createVNode, defineComponent, onBeforeUnmount, ref, useTemplateRef, watch } from "vue";
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(e) {
6
- return e.map((e) => {
7
- if (typeof e == "string") return e;
8
- if (e instanceof Error) return e.stack || e.message;
5
+ function formatArgs(n) {
6
+ return n.map((n) => {
7
+ if (typeof n == "string") return n;
8
+ if (n instanceof Error) return n.stack || n.message;
9
9
  try {
10
- return JSON.stringify(e);
10
+ return JSON.stringify(n);
11
11
  } catch {
12
- return String(e);
12
+ return String(n);
13
13
  }
14
14
  }).join(" ");
15
15
  }
16
- function createLogger(e, s, c) {
17
- let l = "[CorePilot]", u = [], d = null, f = c?.batchSize ?? 20, p = c?.flushInterval ?? 15e3, m = () => {
18
- if (!c || u.length === 0) return;
19
- let s = [...u];
20
- u = [], e && console.log(`${l} Uploading ${s.length} log(s) to ${c.url}`);
21
- let d = JSON.stringify(s);
22
- navigator.sendBeacon ? navigator.sendBeacon(c.url, d) : fetch(c.url, {
16
+ function createLogger(n, l, u) {
17
+ let d = "[CorePilot]", f = [], p = null, m = u?.batchSize ?? 20, h = u?.flushInterval ?? 15e3, g = () => {
18
+ if (!u || f.length === 0) return;
19
+ let l = [...f];
20
+ f = [], n && console.log(`${d} Uploading ${l.length} log(s) to ${u.url}`);
21
+ let p = JSON.stringify(l);
22
+ navigator.sendBeacon ? navigator.sendBeacon(u.url, p) : fetch(u.url, {
23
23
  method: "POST",
24
- body: d,
24
+ body: p,
25
25
  headers: { "Content-Type": "application/json" },
26
26
  keepalive: !0
27
- }).catch((c) => {
28
- e && (console.error(`${l} Log upload failed:`, c), u.unshift(...s));
27
+ }).catch((u) => {
28
+ n && (console.error(`${d} Log upload failed:`, u), f.unshift(...l));
29
29
  });
30
- }, h = (e, ...l) => {
31
- c && (u.push({
32
- level: e,
30
+ }, _ = (n, ...d) => {
31
+ u && (f.push({
32
+ level: n,
33
33
  timestamp: (/* @__PURE__ */ new Date()).toISOString(),
34
- message: formatArgs(l),
35
- appId: s
36
- }), u.length >= f && (d && clearTimeout(d), m(), d = window.setTimeout(m, p)));
34
+ message: formatArgs(d),
35
+ appId: l
36
+ }), f.length >= m && (p && clearTimeout(p), g(), p = window.setTimeout(g, h)));
37
37
  };
38
- return c && (d = window.setTimeout(m, p)), {
39
- log(...s) {
40
- e && console.log(l, ...s), h("log", ...s);
38
+ return u && (p = window.setTimeout(g, h)), {
39
+ log(...l) {
40
+ n && console.log(d, ...l), _("log", ...l);
41
41
  },
42
- error(...s) {
43
- e && console.error(l, ...s), h("error", ...s);
42
+ error(...l) {
43
+ n && console.error(d, ...l), _("error", ...l);
44
44
  },
45
45
  destroy() {
46
- d && clearTimeout(d), m();
46
+ p && clearTimeout(p), g();
47
47
  }
48
48
  };
49
49
  }
50
- function createAuthManager(e, s) {
51
- let c = "";
52
- return { async getToken() {
53
- if (e.mode === "client") {
54
- if (!e.token) throw Error("AuthManager: Missing token in client mode");
55
- return c = e.token, c;
50
+ function createAuthManager(n, l) {
51
+ let u = n.token || "";
52
+ return {
53
+ async getToken() {
54
+ if (!u) throw Error("AuthManager: Missing token");
55
+ return u;
56
+ },
57
+ async setToken(n) {
58
+ return n ? (u = n, !0) : !1;
59
+ },
60
+ isServerMode() {
61
+ return n.mode === "server";
62
+ },
63
+ getAppId() {
64
+ if (!l) throw Error("AuthManager: Missing appId");
65
+ return l;
56
66
  }
57
- if (e.mode === "server") return c ||= await new Promise((e) => setTimeout(() => {
58
- e("9269ca5c-5b35-46de-915f-b2e3ff41da13");
59
- }, 1e3)), c;
60
- throw Error("AuthManager: Invalid configuration or missing token.");
61
- } };
67
+ };
62
68
  }
63
- var createStoreImpl = (e) => {
64
- let s, c = /* @__PURE__ */ new Set(), l = (e, l) => {
65
- let u = typeof e == "function" ? e(s) : e;
66
- if (!Object.is(u, s)) {
67
- let e = s;
68
- s = l ?? (typeof u != "object" || !u) ? u : Object.assign({}, s, u), c.forEach((c) => c(s, e));
69
+ var createStoreImpl = (n) => {
70
+ let l, u = /* @__PURE__ */ new Set(), d = (n, d) => {
71
+ let f = typeof n == "function" ? n(l) : n;
72
+ if (!Object.is(f, l)) {
73
+ let n = l;
74
+ l = d ?? (typeof f != "object" || !f) ? f : Object.assign({}, l, f), u.forEach((u) => u(l, n));
69
75
  }
70
- }, u = () => s, d = {
71
- setState: l,
72
- getState: u,
73
- getInitialState: () => f,
74
- subscribe: (e) => (c.add(e), () => c.delete(e))
75
- }, f = s = e(l, u, d);
76
- return d;
76
+ }, f = () => l, p = {
77
+ setState: d,
78
+ getState: f,
79
+ getInitialState: () => m,
80
+ subscribe: (n) => (u.add(n), () => u.delete(n))
81
+ }, m = l = n(d, f, p);
82
+ return p;
77
83
  };
78
- const pilotStore = ((e) => e ? createStoreImpl(e) : createStoreImpl)((e) => ({
84
+ const pilotStore = ((n) => n ? createStoreImpl(n) : createStoreImpl)((n) => ({
79
85
  currentMessage: void 0,
80
86
  isLoading: !1,
81
87
  messageHistory: [],
82
88
  activeScence: "ANC",
83
- setActiveScence: (s) => e({ activeScence: s }),
84
- updateMessage: (s) => e((e) => {
85
- let c = {
86
- ...s,
89
+ setActiveScence: (l) => n({ activeScence: l }),
90
+ updateMessage: (l) => n((n) => {
91
+ let u = {
92
+ ...l,
87
93
  role: "ai",
88
94
  showActions: !1,
89
95
  maxWidth: "100%"
90
- }, l = [...e.messageHistory];
91
- if (l.forEach((e) => {
92
- e.isHistoryMessage = !0;
93
- }), e.currentMessage) {
94
- let u = {
95
- ...c,
96
- content: e.currentMessage.content + (s.content || "")
96
+ }, d = [...n.messageHistory];
97
+ if (d.forEach((n) => {
98
+ n.isHistoryMessage = !0;
99
+ }), n.currentMessage) {
100
+ let f = {
101
+ ...u,
102
+ content: n.currentMessage.content + (l.content || "")
97
103
  };
98
- return l.pop(), l.push(u), {
99
- currentMessage: u,
100
- messageHistory: l
104
+ return d.pop(), d.push(f), {
105
+ currentMessage: f,
106
+ messageHistory: d
101
107
  };
102
108
  }
103
- return l.push(c), {
104
- currentMessage: c,
105
- messageHistory: l
109
+ return console.log("updateMessage", u), d.push(u), {
110
+ currentMessage: u,
111
+ messageHistory: d
106
112
  };
107
113
  }),
108
- setLoading: (s) => e({ isLoading: s }),
109
- resetCurrentMessage: () => e({ currentMessage: void 0 }),
110
- resetMessageHistory: (s) => e({ messageHistory: s || [] }),
111
- updateMessageHistory: (s) => e((e) => {
112
- let c = [...e.messageHistory];
113
- return c.forEach((e) => {
114
- e.isHistoryMessage = !0;
115
- }), Array.isArray(s) ? { messageHistory: [...c, ...s] } : { messageHistory: [...c, s] };
114
+ setLoading: (l) => n({ isLoading: l }),
115
+ resetCurrentMessage: () => n({ currentMessage: void 0 }),
116
+ resetMessageHistory: (l) => n({ messageHistory: l || [] }),
117
+ resetQuestions: () => n((n) => {
118
+ let l = [...n.messageHistory];
119
+ return l.forEach((n) => {
120
+ n.questions = [];
121
+ }), { messageHistory: l };
122
+ }),
123
+ updateMessageHistory: (l) => n((n) => {
124
+ let u = [...n.messageHistory];
125
+ return u.forEach((n) => {
126
+ n.isHistoryMessage = !0, n.questions = [];
127
+ }), Array.isArray(l) ? { messageHistory: [...u, ...l] } : { messageHistory: [...u, l] };
128
+ }),
129
+ updateSuggestionQuestions: (l) => n((n) => {
130
+ let u = [...n.messageHistory];
131
+ return u[u.length - 1].questions = l, { messageHistory: u };
116
132
  })
117
133
  }));
118
- var MAX_RETRY_TIME = 0, EventStreamContentType = "text/event-stream", FatalError = class extends Error {
119
- constructor(e) {
120
- super(e), this.name = "FatalError";
134
+ var MAX_RETRY_TIME = 0, TOKEN_EXPIRED_HANDLED_FLAG$1 = "__token_expired_handled__", FatalError = class extends Error {
135
+ constructor(n) {
136
+ super(n), this.name = "FatalError";
121
137
  }
138
+ }, createFatalError = (n, l) => {
139
+ let u = new FatalError(n instanceof Error ? n.message : l);
140
+ return n?.[TOKEN_EXPIRED_HANDLED_FLAG$1] && (u[TOKEN_EXPIRED_HANDLED_FLAG$1] = !0), u;
122
141
  };
123
- const sseRequester = function(e, s) {
124
- let { url: c, config: l = {} } = e, u = new AbortController();
125
- function d() {
126
- s.onCancel(pilotStore.getState().currentMessage, u), pilotStore.getState().setLoading(!1), pilotStore.getState().resetCurrentMessage();
142
+ const sseRequester = function(n, l, u) {
143
+ let { url: d, config: f = {} } = n, p = new AbortController(), m = !1, h = !1;
144
+ function g() {
145
+ p.abort(), l.onCancel(pilotStore.getState().currentMessage, p), pilotStore.getState().setLoading(!1), pilotStore.getState().resetCurrentMessage();
127
146
  }
128
- function f(e) {
129
- let c = s.onMessage(e);
130
- c.event === "message" && pilotStore.getState().updateMessage({
131
- taskId: c.task_id,
132
- messageId: c.message_id,
133
- conversationId: c.conversation_id,
134
- role: "ai",
135
- content: c.answer
136
- });
147
+ function v(n) {
148
+ try {
149
+ let u = l.onMessage(n);
150
+ u.event === "message" && (pilotStore.getState().updateMessage({
151
+ taskId: u.task_id,
152
+ messageId: u.message_id,
153
+ conversationId: u.conversation_id,
154
+ role: "ai",
155
+ content: u.answer
156
+ }), pilotStore.getState().resetQuestions());
157
+ } catch (n) {
158
+ throw b(), n instanceof Error && n.message === "Token expired" ? createFatalError(n, n.message) : n;
159
+ }
160
+ }
161
+ async function y(n) {
162
+ try {
163
+ await l.onOpen(n), pilotStore.getState().setLoading(!0);
164
+ } catch (l) {
165
+ throw n.status === 500 || l instanceof Error && l.message === "Token expired" ? (await b(), createFatalError(l, "SSE request failed with status 500")) : l;
166
+ }
137
167
  }
138
- function p() {
139
- pilotStore.getState().setLoading(!0), s.onOpen();
168
+ async function b() {
169
+ m || (m = !0, pilotStore.getState().setLoading(!1), await l.onClose());
140
170
  }
141
- function h() {
142
- pilotStore.getState().setLoading(!1), pilotStore.getState().resetCurrentMessage(), s.onClose();
171
+ async function x(n) {
172
+ h || (h = !0, await l.onError(n));
143
173
  }
144
- let g = Math.max(MAX_RETRY_TIME - 1, 0);
145
- return fetchEventSource(c, {
146
- ...l,
147
- signal: u.signal,
174
+ let S = Math.max(MAX_RETRY_TIME - 1, 0), w = {
175
+ ...f,
176
+ signal: p.signal,
148
177
  openWhenHidden: !0,
149
- onmessage: f,
150
- onclose: h,
151
- onopen: async (e) => {
152
- let s = e.headers.get("content-type");
153
- if (!s || !s.includes(EventStreamContentType)) throw Error(`Expected content-type to be ${EventStreamContentType}, Actual: ${s}`);
154
- p();
178
+ onmessage: v,
179
+ onclose: async () => await b(),
180
+ onopen: async (n) => {
181
+ await y(n);
155
182
  },
156
- onerror: (e) => {
157
- if (g--, g < 0 && (h(), e instanceof TypeError)) throw new FatalError(e.message);
158
- s.onError(e);
183
+ onerror: (n) => {
184
+ if (n instanceof FatalError) throw b(), n;
185
+ if (S--, S < 0 && (b(), n instanceof TypeError)) throw new FatalError(n.message);
186
+ x(n);
159
187
  }
160
- }).catch((e) => {
161
- h(), s.onError(e);
162
- }), { cancel: d };
188
+ };
189
+ return u?.fetchFn && (w.fetch = u.fetchFn), fetchEventSource(d, w).catch((n) => {
190
+ b(), x(n);
191
+ }), { cancel: g };
163
192
  }, CorePilotHost = /* @__PURE__ */ defineComponent({
164
193
  props: {
165
194
  adapter: {
@@ -177,82 +206,121 @@ const sseRequester = function(e, s) {
177
206
  provider: {
178
207
  type: Object,
179
208
  required: !0
209
+ },
210
+ authManager: {
211
+ type: Object,
212
+ required: !0
213
+ },
214
+ appId: {
215
+ type: String,
216
+ required: !0
180
217
  }
181
218
  },
182
- setup(e) {
183
- let s = ref([]), c = ref([]), f = ref(!1), p = ref(), m = ref("ANC"), h = ref(), g = pilotStore.subscribe((e) => {
184
- let { isLoading: s, messageHistory: l } = e;
185
- c.value = l, f.value = s, m.value = e.activeScence;
219
+ setup(n) {
220
+ let l = useTemplateRef("bubbleList"), u = ref([]), h = ref([]), g = ref(!1), _ = ref(), v = ref("ANC"), y = ref(), b = ref("");
221
+ watch(() => n.authManager, async (n) => {
222
+ b.value = await n.getToken();
223
+ }, { immediate: !0 });
224
+ let x = pilotStore.subscribe((n) => {
225
+ let { isLoading: l, messageHistory: u } = n;
226
+ h.value = u, g.value = l, v.value = n.activeScence;
186
227
  });
187
- return watch(() => f.value, (e) => {
188
- e && (h.value = void 0);
189
- }), watch(() => h.value, (s, l) => {
190
- s && c.value[c.value.length - 1]?.role === "ai" && e.hitlManager.submit({ hitlData: {
228
+ watch(() => g.value, (l) => {
229
+ l && (y.value = void 0, n.hitlManager.submit({ hitlData: {
230
+ action: "cust_ai_output_start",
231
+ payload: {}
232
+ } }));
233
+ }), watch(() => y.value, (l, u) => {
234
+ l && h.value[h.value.length - 1]?.role === "ai" && n.hitlManager.submit({ hitlData: {
191
235
  action: "cust_ai_output_finish",
192
236
  payload: {
193
- refConfig: h.value,
194
- conversationId: c.value[c.value.length - 1]?.conversationId
237
+ refConfig: y.value,
238
+ conversationId: h.value[h.value.length - 1]?.conversationId,
239
+ messageId: [...h.value].reverse().find((n) => n.messageId)?.messageId
195
240
  }
196
241
  } });
197
- }), onBeforeUnmount(() => {
198
- g?.();
242
+ });
243
+ let S = async (l) => {
244
+ let u = {
245
+ messageId: void 0,
246
+ content: l.text,
247
+ role: "user",
248
+ placement: "end",
249
+ showActions: !1,
250
+ maxWidth: "100%"
251
+ };
252
+ T();
253
+ let d = h.value[h.value.length - 1];
254
+ pilotStore.getState().updateMessageHistory([u]), pilotStore.getState().resetCurrentMessage(), _.value = sseRequester(await n.adapter.formatRequest({
255
+ text: l.text,
256
+ prevMessage: d,
257
+ inputs: { scence: v.value },
258
+ files: l.file
259
+ }), n.adapter).cancel;
260
+ }, C = () => {
261
+ n.logger.log("Cancel handler called"), _.value?.(), pilotStore.getState().resetCurrentMessage();
262
+ }, w = async (l, u) => {
263
+ pilotStore.getState().resetCurrentMessage(), pilotStore.getState().updateMessageHistory([]), T(), await n.hitlManager.submit({
264
+ hitlData: l,
265
+ prevMessage: u,
266
+ inputs: { scence: v.value }
267
+ });
268
+ }, T = () => {
269
+ l.value?.scrollToBottom();
270
+ };
271
+ return onBeforeUnmount(() => {
272
+ x?.();
199
273
  }), {
200
- messages: c,
201
- isLoading: f,
202
- handleSendMessage: async (s) => {
203
- let l = {
204
- messageId: void 0,
205
- content: s.text,
206
- role: "user",
207
- placement: "end",
208
- showActions: !1,
209
- maxWidth: "100%"
210
- }, u = c.value[c.value.length - 1];
211
- pilotStore.getState().updateMessageHistory([l]), pilotStore.getState().resetCurrentMessage(), p.value = sseRequester(await e.adapter.formatReuqest({
212
- text: s.text,
213
- prevMessage: u,
214
- inputs: { scence: m.value }
215
- }), e.adapter).cancel;
216
- },
217
- cancelHandler: () => {
218
- e.logger.log("Cancel handler called"), p.value?.(), pilotStore.getState().resetCurrentMessage();
219
- },
220
- handleScenceChange: (s) => {
221
- e.hitlManager.submit({ hitlData: {
274
+ messages: h,
275
+ isLoading: g,
276
+ authToken: b,
277
+ activeScence: v,
278
+ tagList: u,
279
+ handleSendMessage: S,
280
+ cancelHandler: C,
281
+ handleScenceChange: (l) => {
282
+ n.hitlManager.submit({ hitlData: {
222
283
  action: "cust_scence_change",
223
- payload: { scence: s.id }
284
+ payload: { scence: l.id }
224
285
  } });
225
286
  },
226
- tagList: s,
227
- coreSubmit: async (s, c) => {
228
- pilotStore.getState().resetCurrentMessage(), await e.hitlManager.submit({
229
- hitlData: s,
230
- prevMessage: c,
231
- inputs: { scence: m.value }
232
- });
287
+ coreSubmit: w,
288
+ handleRefConfigUpdate: (n) => {
289
+ y.value = n;
233
290
  },
234
- handleRefConfigUpdate: (e) => {
235
- h.value = e;
291
+ handleSceneUpdate: (n) => {
292
+ pilotStore.getState().setActiveScence(n);
236
293
  },
237
- activeScence: m,
238
- handleSceneUpdate: (e) => {
239
- pilotStore.getState().setActiveScence(e);
294
+ handleQuestionClick: (n) => {
295
+ S({
296
+ text: n,
297
+ file: []
298
+ });
240
299
  }
241
300
  };
242
301
  },
243
302
  render() {
244
303
  return createVNode("div", { class: "core-pilot-host" }, [createVNode(BubbleList, {
304
+ ref: "bubbleList",
245
305
  class: "bubble-list",
246
306
  list: this.messages,
247
307
  maxHeight: "100%",
308
+ user: this.provider.extensions.user,
309
+ authToken: this.authManager.getToken(),
310
+ appId: this.appId,
248
311
  btnLoading: this.isLoading,
249
312
  onCoreSubmit: this.coreSubmit,
250
- onRefConfigUpdate: this.handleRefConfigUpdate
313
+ onRefConfigUpdate: this.handleRefConfigUpdate,
314
+ onQuestionClick: this.handleQuestionClick
251
315
  }, null), createVNode(EditorSender, {
252
316
  tagList: this.tagList,
253
317
  loading: this.isLoading,
254
318
  agentName: "",
255
319
  scene: this.activeScence,
320
+ user: this.provider.extensions.user,
321
+ authToken: this.authToken,
322
+ appId: this.appId,
323
+ showUpload: !1,
256
324
  onSubmit: this.handleSendMessage,
257
325
  onCancel: this.cancelHandler,
258
326
  onSceneChange: this.handleScenceChange,
@@ -260,116 +328,118 @@ const sseRequester = function(e, s) {
260
328
  }, null)]);
261
329
  }
262
330
  });
263
- function createMountManager(s, c, l, u, d) {
264
- let f = null, p = null, m = () => {
265
- let e = (s.container || document).querySelector(s.selector);
266
- if (e && !e.querySelector("[data-corepilot-host]")) {
267
- let s = document.createElement("div");
268
- return s.setAttribute("data-corepilot-host", "true"), s.style.width = "100%", s.style.height = "100%", e.appendChild(s), s;
331
+ function createMountManager(l, u, d, f, p) {
332
+ let m = null, h = null, g = { ...l.mount }, _ = { ...l.provider }, v = l.appId, y = () => {
333
+ let n = (g.container || document).querySelector(g.selector);
334
+ if (n && !n.querySelector("[data-corepilot-host]")) {
335
+ let l = document.createElement("div");
336
+ return l.setAttribute("data-corepilot-host", "true"), l.style.width = "100%", l.style.height = "100%", n.appendChild(l), l;
269
337
  }
270
- return e?.querySelector("[data-corepilot-host]");
338
+ return n?.querySelector("[data-corepilot-host]");
271
339
  };
272
340
  return {
273
341
  mount() {
274
- if (p = m(), !p) {
275
- u.error(`Mount point "${s.selector}" not found or already in use.`);
342
+ if (h = y(), !h) {
343
+ f.error(`Mount point "${g.selector}" not found or already in use.`);
276
344
  return;
277
345
  }
278
- f && (u.log("An app instance already exists. Unmounting first."), this.unmount()), f = createApp(CorePilotHost, {
279
- adapter: c,
280
- hitlManager: l,
281
- logger: u,
282
- provider: d
283
- }), f.mount(p), u.log("Vue CorePilotHost mounted.");
346
+ m && (f.log("An app instance already exists. Unmounting first."), this.unmount()), m = createApp(CorePilotHost, {
347
+ adapter: u,
348
+ hitlManager: d,
349
+ logger: f,
350
+ provider: _,
351
+ authManager: p,
352
+ appId: v
353
+ }), m.mount(h), f.log("Vue CorePilotHost mounted.");
284
354
  },
285
355
  unmount() {
286
- f && (f.unmount(), f = null, u.log("Vue CorePilotHost unmounted.")), p && p.parentElement && (p.parentElement.innerHTML = "");
356
+ m && (m.unmount(), m = null, f.log("Vue CorePilotHost unmounted.")), h && h.parentElement && (h.parentElement.innerHTML = "");
287
357
  }
288
358
  };
289
359
  }
290
360
  var HttpError = class extends Error {
291
- constructor(e, s, c, l) {
292
- super(e), this.name = "HttpError", this.code = s, this.data = c, this.originalError = l;
361
+ constructor(n, l, u, d) {
362
+ super(n), this.name = "HttpError", this.code = l, this.data = u, this.originalError = d;
293
363
  }
294
364
  }, axios_default = new class {
295
- constructor(e) {
365
+ constructor(n) {
296
366
  this.instance = axios.create({
297
367
  timeout: 3e4,
298
368
  headers: { "Content-Type": "application/json;charset=utf-8" },
299
369
  withCredentials: !0,
300
- ...e
370
+ ...n
301
371
  }), this.setupInterceptors();
302
372
  }
303
373
  setupInterceptors() {
304
- this.instance.interceptors.response.use((e) => e.data, (e) => Promise.reject(this.handleError(e)));
374
+ this.instance.interceptors.response.use((n) => n.data, (n) => Promise.reject(this.handleError(n)));
305
375
  }
306
- handleError(e) {
307
- let s = "请求失败,请稍后重试", c = -1, l = null;
308
- if (axios.isAxiosError(e)) if (e.response) switch (c = e.response.status, l = e.response.data, c) {
376
+ handleError(n) {
377
+ let l = "请求失败,请稍后重试", u = -1, d = null;
378
+ if (axios.isAxiosError(n)) if (n.response) switch (u = n.response.status, d = n.response.data, u) {
309
379
  case 400:
310
- s = "请求参数错误";
380
+ l = "请求参数错误";
311
381
  break;
312
382
  case 401:
313
- s = "未授权,请重新登录";
383
+ l = "未授权,请重新登录";
314
384
  break;
315
385
  case 403:
316
- s = "拒绝访问";
386
+ l = "拒绝访问";
317
387
  break;
318
388
  case 404:
319
- s = "请求资源不存在";
389
+ l = "请求资源不存在";
320
390
  break;
321
391
  case 405:
322
- s = "请求方法不允许";
392
+ l = "请求方法不允许";
323
393
  break;
324
394
  case 408:
325
- s = "请求超时";
395
+ l = "请求超时";
326
396
  break;
327
397
  case 500:
328
- s = "服务器内部错误";
398
+ l = "服务器内部错误";
329
399
  break;
330
400
  case 501:
331
- s = "服务未实现";
401
+ l = "服务未实现";
332
402
  break;
333
403
  case 502:
334
- s = "网关错误";
404
+ l = "网关错误";
335
405
  break;
336
406
  case 503:
337
- s = "服务不可用";
407
+ l = "服务不可用";
338
408
  break;
339
409
  case 504:
340
- s = "网关超时";
410
+ l = "网关超时";
341
411
  break;
342
- default: s = e.response.statusText || `连接错误 ${c}`;
412
+ default: l = n.response.statusText || `连接错误 ${u}`;
343
413
  }
344
- else e.request ? (s = "网络连接失败,请检查网络设置", c = 0) : s = e.message;
345
- else s = e.message || "未知错误";
346
- return console.error(`[HttpClient] Error: ${s}`, {
347
- code: c,
348
- data: l,
349
- original: e
350
- }), new HttpError(s, c, l, e);
414
+ else n.request ? (l = "网络连接失败,请检查网络设置", u = 0) : l = n.message;
415
+ else l = n.message || "未知错误";
416
+ return console.error(`[HttpClient] Error: ${l}`, {
417
+ code: u,
418
+ data: d,
419
+ original: n
420
+ }), new HttpError(l, u, d, n);
351
421
  }
352
- get(e, s) {
353
- return this.instance.get(e, s);
422
+ get(n, l) {
423
+ return this.instance.get(n, l);
354
424
  }
355
- post(e, s, c) {
356
- return this.instance.post(e, s, c);
425
+ post(n, l, u) {
426
+ return this.instance.post(n, l, u);
357
427
  }
358
- put(e, s, c) {
359
- return this.instance.put(e, s, c);
428
+ put(n, l, u) {
429
+ return this.instance.put(n, l, u);
360
430
  }
361
- delete(e, s) {
362
- return this.instance.delete(e, s);
431
+ delete(n, l) {
432
+ return this.instance.delete(n, l);
363
433
  }
364
- patch(e, s, c) {
365
- return this.instance.patch(e, s, c);
434
+ patch(n, l, u) {
435
+ return this.instance.patch(n, l, u);
366
436
  }
367
- upload(e, s, c = "file", l) {
368
- let u = new FormData();
369
- return u.append(c, s), this.instance.post(e, u, {
370
- ...l,
437
+ upload(n, l, u = "file", d) {
438
+ let f = new FormData();
439
+ return f.append(u, l), this.instance.post(n, f, {
440
+ ...d,
371
441
  headers: {
372
- ...l?.headers,
442
+ ...d?.headers,
373
443
  "Content-Type": "multipart/form-data"
374
444
  }
375
445
  });
@@ -378,266 +448,441 @@ var HttpError = class extends Error {
378
448
  return this.instance;
379
449
  }
380
450
  }({});
381
- function createCoreAgentAdapter(e, s, c) {
382
- let { appId: l, provider: u } = e, { extensions: d } = u, { user: f = "default" } = d || {}, p = async (e, c) => {
383
- let u = e.taskId, d = await s.getToken();
384
- return await axios_default.post(`/openapi/v1/app/chat-messages/${u}/stop`, { user: f }, { headers: {
385
- Authorization: `Bearer ${d}`,
386
- appId: l
387
- } }), Promise.resolve();
388
- }, m = async (e) => {
389
- let c = e.messageId, u = await s.getToken(), d = await axios_default.post(`/openapi/v1/app/chat-messages/${c}/suggested`, { user: f }, { headers: {
390
- Authorization: `Bearer ${u}`,
391
- appId: l
392
- } });
393
- return d.result === "success" ? d.data : [];
394
- }, h = async (e) => {
395
- let c = await s.getToken();
396
- return await axios_default.get(`/openapi/v1/app/conversations?${new URLSearchParams(e).toString()}`, { headers: {
397
- Authorization: `Bearer ${c}`,
398
- appId: l
399
- } });
400
- }, g = async (e) => {
401
- let c = await s.getToken();
402
- return await axios_default.get(`/openapi/v1/app/messages?${new URLSearchParams(e).toString()}`, { headers: {
403
- Authorization: `Bearer ${c}`,
404
- appId: l
405
- } });
406
- }, _ = async (e) => {
407
- let { hitlData: c, prevMessage: u, text: d, inputs: p } = e, m = {
408
- query: d || JSON.stringify(c || {}),
409
- inputs: p || {},
451
+ const eventHub = new class {
452
+ constructor() {
453
+ this.listeners = [];
454
+ }
455
+ subscribeEvent(n) {
456
+ this.listeners.includes(n) || this.listeners.push(n);
457
+ }
458
+ unsubscribeEvent(n) {
459
+ let l = this.listeners.indexOf(n);
460
+ l > -1 && this.listeners.splice(l, 1);
461
+ }
462
+ emitEvent(n) {
463
+ this.listeners.forEach((l) => {
464
+ try {
465
+ l(n);
466
+ } catch (n) {
467
+ console.error("[EventHub] Event callback error:", n);
468
+ }
469
+ });
470
+ }
471
+ }();
472
+ var TOKEN_EXPIRED_CODE = 40100, TOKEN_EXPIRED_CODES = [
473
+ 401,
474
+ 10001,
475
+ TOKEN_EXPIRED_CODE
476
+ ], SSE_CONTENT_TYPE = "text/event-stream", TOKEN_EXPIRED_HANDLED_FLAG = "__token_expired_handled__";
477
+ function createCoreAgentAdapter(n, l, u) {
478
+ let { appId: d, provider: f, baseUrl: p } = n, { extensions: m } = f, { user: h = "default", accessToken: g = "" } = m || {}, _ = () => {
479
+ eventHub.emitEvent({
480
+ action: "cust_token_expired",
481
+ code: TOKEN_EXPIRED_CODE,
482
+ message: "凭证已过期"
483
+ });
484
+ }, v = () => {
485
+ let n = /* @__PURE__ */ Error("Token expired");
486
+ return n[TOKEN_EXPIRED_HANDLED_FLAG] = !0, n;
487
+ }, y = (n) => !!n?.[TOKEN_EXPIRED_HANDLED_FLAG], b = (n) => {
488
+ if (typeof n == "number") return n;
489
+ if (typeof n == "string") {
490
+ let l = n.trim();
491
+ if (!l) return;
492
+ let u = Number(l);
493
+ return Number.isNaN(u) ? l : u;
494
+ }
495
+ }, x = (n) => {
496
+ let l = n?.code ?? n?.errorCode ?? n?.error_code ?? n?.status;
497
+ return l == null && n?.data && (l = n.data.code ?? n.data.errorCode ?? n.data.error_code ?? n.data.status), b(l);
498
+ }, S = (n) => {
499
+ let l = x(n);
500
+ return l !== void 0 && TOKEN_EXPIRED_CODES.includes(Number(l));
501
+ }, C = (n) => {
502
+ if (!n.trim()) return;
503
+ let l = n.match(/"(?:code|errorCode|error_code|status)"\s*:\s*"?(\d+)"?/i);
504
+ if (!l?.[1]) return;
505
+ let u = Number(l[1]);
506
+ return Number.isNaN(u) ? void 0 : u;
507
+ }, w = async (n) => {
508
+ if ((n.headers?.get?.("content-type")?.toLowerCase() || "").includes(SSE_CONTENT_TYPE)) return !1;
509
+ try {
510
+ let l = n.clone();
511
+ if (typeof l.text == "function") {
512
+ let n = await l.text();
513
+ if (u.log("SSE non-stream body state", n.trim() ? "present" : "empty"), n.trim()) try {
514
+ let l = JSON.parse(n);
515
+ return u.log("SSE non-stream code", x(l)), S(l);
516
+ } catch {
517
+ let l = C(n);
518
+ return u.log("SSE non-stream text code", l), l !== void 0 && TOKEN_EXPIRED_CODES.includes(l);
519
+ }
520
+ }
521
+ if (typeof l.json == "function") {
522
+ let n = await l.json();
523
+ return u.log("SSE non-stream code", x(n)), S(n);
524
+ }
525
+ return u.log("SSE non-stream payload unavailable"), !1;
526
+ } catch {
527
+ return u.log("SSE non-stream payload parse failed"), !1;
528
+ }
529
+ }, T = () => l.isServerMode() ? p + "/api/proxy/ca" : p, E = async () => {
530
+ let n = { Authorization: `Bearer ${await l.getToken()}` };
531
+ return d && (n.appId = d), n;
532
+ }, D = (n) => !!(n instanceof Error && n.message === "Token expired" || S(n?.data) && (n?.code === 401 || n?.code === 500 || n?.code === 200) || n?.code === 500 && S(n?.data)), O = (n) => {
533
+ l.isServerMode() && D(n) && _();
534
+ }, k = async (n, l) => {
535
+ let u = n.taskId, d = T(), f = await E();
536
+ return await axios_default.post(`${d}/openapi/v1/app/chat-messages/${u}/stop`, { user: h }, { headers: f }), Promise.resolve();
537
+ }, A = async (n, u, d) => {
538
+ n.messageId;
539
+ let f = T(), p = await l.getToken(), m = {
540
+ query: JSON.stringify(u || []),
541
+ inputs: { scence: d },
542
+ response_mode: "blocking",
543
+ conversation_id: null,
544
+ parent_message_id: null,
545
+ user: h,
546
+ files: []
547
+ }, g = { Authorization: `Bearer ${p}` };
548
+ g.appId = "b7886345-d200-486d-8318-8c234a19ccb9";
549
+ let _ = await axios_default.post(`${f}/openapi/v1/app/chat-messages`, m, { headers: g });
550
+ try {
551
+ let n = JSON.parse(_.answer || "[]");
552
+ return console.log("data", n), n;
553
+ } catch {
554
+ return [];
555
+ }
556
+ }, j = async (n) => {
557
+ let l = T(), u = await E();
558
+ try {
559
+ return await axios_default.get(`${l}/openapi/v1/app/conversations?${new URLSearchParams(n).toString()}`, { headers: u });
560
+ } catch (n) {
561
+ throw O(n), n;
562
+ }
563
+ }, M = async (n) => {
564
+ let l = T(), u = await E();
565
+ try {
566
+ return await axios_default.get(`${l}/openapi/v1/app/messages?${new URLSearchParams(n).toString()}`, { headers: u });
567
+ } catch (n) {
568
+ throw O(n), n;
569
+ }
570
+ }, N = (n) => {
571
+ switch (n.toLowerCase()) {
572
+ case "txt":
573
+ case "doc":
574
+ case "docx":
575
+ case "pdf":
576
+ case "ppt":
577
+ case "pptx":
578
+ case "xls":
579
+ case "xlsx":
580
+ case "csv": return "document";
581
+ case "jpg":
582
+ case "jpeg":
583
+ case "png":
584
+ case "gif":
585
+ case "webp":
586
+ case "svg": return "image";
587
+ case "mp3":
588
+ case "wav": return "audio";
589
+ case "mp4":
590
+ case "mov":
591
+ case "ogg": return "video";
592
+ default: return "custom";
593
+ }
594
+ }, P = async (n) => {
595
+ let { hitlData: l, prevMessage: u, text: d, inputs: f, files: p } = n, m = l?.payload?.__files__ || {}, _ = [];
596
+ Object.values(m).flat().forEach((n) => {
597
+ _.push({
598
+ transfer_method: "local_file",
599
+ type: N(n.extension || ""),
600
+ upload_file_id: n.id,
601
+ url: n.url || ""
602
+ });
603
+ }), p?.forEach((n) => {
604
+ _.push({
605
+ transfer_method: "local_file",
606
+ type: N(n.extension || ""),
607
+ upload_file_id: n.id,
608
+ url: n.url || ""
609
+ });
610
+ });
611
+ let v = {
612
+ query: d || JSON.stringify(l || {}),
613
+ inputs: {
614
+ ...f || {},
615
+ accessToken: g
616
+ },
410
617
  response_mode: "streaming",
411
618
  conversation_id: u?.conversationId || null,
412
619
  parent_message_id: u?.messageId || null,
413
- user: f,
414
- files: []
415
- }, h = await s.getToken();
620
+ user: h,
621
+ files: _
622
+ }, y = T(), b = await E();
416
623
  return {
417
- url: "/openapi/v1/app/chat-messages",
624
+ url: `${y}/openapi/v1/app/chat-messages`,
418
625
  config: {
419
626
  method: "POST",
420
627
  headers: {
421
628
  "Content-Type": "application/json",
422
- Authorization: `Bearer ${h}`,
423
- appId: l
629
+ ...b
424
630
  },
425
- body: JSON.stringify(m)
631
+ body: JSON.stringify(v)
426
632
  }
427
633
  };
428
- }, v = (e) => {
429
- let { data: s } = e;
430
- return JSON.parse(s || "{}");
431
- }, y = async () => {
432
- c.log("onClose");
433
- }, b = async (e) => {
434
- c.log("onError", e);
435
- }, x = async () => {
436
- c.log("onOpen");
437
- }, S = (e) => {
634
+ }, F = (n) => {
635
+ let { data: l } = n, d = l || "{}";
636
+ d.startsWith("data: ") ? d = d.substring(6) : d.startsWith("data:") && (d = d.substring(5));
637
+ try {
638
+ let n = JSON.parse(d);
639
+ if (u.log("SSE stream code", x(n)), S(n)) throw _(), v();
640
+ return n;
641
+ } catch (n) {
642
+ if (n instanceof Error && n.message === "Token expired") throw n;
643
+ return console.error("[SSE] Failed to parse message:", d, n), {};
644
+ }
645
+ }, I = async () => {
646
+ u.log("onClose");
647
+ }, L = async (n) => {
648
+ u.log("onError", n), l.isServerMode() && D(n) && (y(n) || _());
649
+ }, R = async (n) => {
650
+ u.log("onOpen", n);
651
+ let l = n.headers?.get?.("content-type")?.toLowerCase() || "";
652
+ if (u.log("contentType", l), !l.includes(SSE_CONTENT_TYPE)) throw await w(n) ? (_(), v()) : Error(`Expected content-type to be ${SSE_CONTENT_TYPE}, Actual: ${l || "unknown"}`);
653
+ }, z = (n) => {
438
654
  try {
439
- return JSON.parse(e || "{}")?.action?.startsWith("core_") || !1;
655
+ return JSON.parse(n || "{}")?.action?.startsWith("core_") || !1;
440
656
  } catch {
441
657
  return !1;
442
658
  }
443
- }, C = async (e) => {
444
- sseRequester(await _(e), {
445
- formatReuqest: _,
446
- getSuggestionQuestions: m,
447
- getConversationList: h,
448
- getMessageHistory: g,
449
- onMessage: v,
450
- onClose: y,
451
- onError: b,
452
- onOpen: x,
453
- onCancel: p
454
- });
455
- }, w = async (e) => {
456
- let s = [], c;
457
- if (e.data.forEach((e) => {
458
- if (e.parent_message_id === c) s.pop(), s.push({
659
+ }, B = async (n) => {
660
+ let { inputs: u } = n, d = u?.scence;
661
+ d && pilotStore.getState().setActiveScence(d);
662
+ let f = await P(n), p = l.isServerMode() ? U() : void 0;
663
+ sseRequester(f, {
664
+ formatRequest: P,
665
+ getSuggestionQuestions: A,
666
+ getConversationList: j,
667
+ getMessageHistory: M,
668
+ onMessage: F,
669
+ onClose: I,
670
+ onError: L,
671
+ onOpen: R,
672
+ onCancel: k
673
+ }, { fetchFn: p });
674
+ }, V = async (n) => {
675
+ let l = [], u;
676
+ if (n.data.forEach((n) => {
677
+ if (n.parent_message_id === u) l.pop(), l.push({
459
678
  role: "ai",
460
679
  showActions: !1,
461
- content: e.answer,
680
+ content: n.answer,
462
681
  maxWidth: "100%",
463
- files: e.message_files.map((e) => ({
464
- id: e.id,
465
- extension: e.type,
466
- name: e.filename
682
+ files: n.message_files.map((n) => ({
683
+ id: n.id,
684
+ extension: n.type,
685
+ name: n.filename
467
686
  })),
468
- placement: "start"
687
+ placement: "start",
688
+ conversationId: n.conversation_id,
689
+ messageId: n.id
469
690
  });
470
691
  else {
471
- if (c = e.parent_message_id, !S(e.query)) s.push({
692
+ if (u = n.parent_message_id, !z(n.query)) l.push({
472
693
  role: "user",
473
- messageId: e.id,
474
- content: e.query,
694
+ messageId: n.id,
695
+ content: n.query,
475
696
  showActions: !1,
476
697
  maxWidth: "100%",
477
698
  placement: "end",
478
- isHistoryMessage: !0
699
+ isHistoryMessage: !0,
700
+ conversationId: n.conversation_id
479
701
  });
480
702
  else {
481
- let c = JSON.parse(e.query || "{}");
482
- if (c?.payload) {
483
- let e = s[s.length - 1];
484
- e && (e.historyInputs = c.payload);
703
+ let u = JSON.parse(n.query || "{}");
704
+ if (u?.payload) {
705
+ let n = l[l.length - 1];
706
+ n && (n.historyInputs = u.payload);
485
707
  }
486
708
  }
487
- s.push({
709
+ l.push({
488
710
  role: "ai",
489
- content: e.answer,
711
+ content: n.answer,
490
712
  showActions: !1,
491
713
  maxWidth: "100%",
492
714
  placement: "start",
493
- files: e.message_files.map((e) => ({
494
- id: e.id,
495
- extension: e.type,
496
- name: e.filename
715
+ files: n.message_files.map((n) => ({
716
+ id: n.id,
717
+ extension: n.type,
718
+ name: n.filename
497
719
  })),
498
- isHistoryMessage: !0
720
+ isHistoryMessage: !0,
721
+ conversationId: n.conversation_id,
722
+ messageId: n.id
499
723
  });
500
724
  }
501
- }), e.has_more) {
502
- let e = await g({
503
- conversation_id: s[s.length - 1].conversationId,
504
- user: f,
505
- first_id: s[0].messageId
725
+ }), n.has_more) {
726
+ let n = await M({
727
+ conversation_id: l[l.length - 1].conversationId,
728
+ user: h,
729
+ first_id: l[0].messageId
506
730
  });
507
- if (e.data) {
508
- let c = await w(e);
509
- s.unshift(...c);
731
+ if (n.data) {
732
+ let u = await V(n);
733
+ l.unshift(...u);
510
734
  }
511
735
  }
512
- return s;
513
- }, T = async () => (pilotStore.getState().resetMessageHistory(), !0), E = async (e) => {
514
- let s = {
736
+ return l;
737
+ }, H = async () => (pilotStore.getState().resetMessageHistory(), !0), U = () => async (n, u) => {
738
+ console.log("[TokenCheck] createSseFetch 被调用了!URL:", n);
739
+ let d = await l.getToken(), f = l.getAppId(), p = {
740
+ ...u?.headers || {},
741
+ Authorization: `Bearer ${d}`,
742
+ ...f ? { appId: f } : {}
743
+ };
744
+ return await fetch(n, {
745
+ ...u,
746
+ headers: p
747
+ });
748
+ }, W = async (n) => {
749
+ let u = {
515
750
  messageId: void 0,
516
- content: e.text,
751
+ content: n.text,
517
752
  role: "user",
518
753
  placement: "end",
519
754
  showActions: !1,
520
755
  maxWidth: "100%"
521
756
  };
522
- pilotStore.getState().updateMessageHistory([s]), pilotStore.getState().resetCurrentMessage();
523
- let c = await _({
524
- text: e.text,
757
+ pilotStore.getState().updateMessageHistory([u]), pilotStore.getState().resetCurrentMessage();
758
+ let d = await P({
759
+ text: n.text,
525
760
  prevMessage: void 0,
526
- inputs: e.inputs
527
- });
528
- return pilotStore.getState().setActiveScence(e.inputs?.scence), sseRequester(c, {
529
- formatReuqest: _,
530
- getSuggestionQuestions: m,
531
- getConversationList: h,
532
- getMessageHistory: g,
533
- onMessage: v,
534
- onClose: y,
535
- onError: b,
536
- onOpen: x,
537
- onCancel: p
761
+ inputs: n.inputs
538
762
  });
763
+ pilotStore.getState().setActiveScence(n.inputs?.scence);
764
+ let f = l.isServerMode() ? U() : void 0;
765
+ return sseRequester(d, {
766
+ formatRequest: P,
767
+ getSuggestionQuestions: A,
768
+ getConversationList: j,
769
+ getMessageHistory: M,
770
+ onMessage: F,
771
+ onClose: I,
772
+ onError: L,
773
+ onOpen: R,
774
+ onCancel: k
775
+ }, { fetchFn: f });
539
776
  };
540
777
  return {
541
- formatReuqest: _,
542
- getSuggestionQuestions: m,
543
- getConversationList: h,
544
- getMessageHistory: g,
545
- onMessage: v,
546
- onClose: y,
547
- onError: b,
548
- onOpen: x,
549
- onCancel: p,
550
- triggerEvent: async (e) => {
551
- switch (e.action) {
552
- case "get_suggestion_questions": return await m(e.payload);
553
- case "get_conversation_list": return await h(e.payload);
778
+ formatRequest: P,
779
+ getSuggestionQuestions: A,
780
+ getConversationList: j,
781
+ getMessageHistory: M,
782
+ onMessage: F,
783
+ onClose: I,
784
+ onError: L,
785
+ onOpen: R,
786
+ onCancel: k,
787
+ triggerEvent: async (n) => {
788
+ switch (n.action) {
789
+ case "get_suggestion_questions": return await A(n.payload);
790
+ case "get_conversation_list": return await j(n.payload);
554
791
  case "get_message_history":
555
- let s = await w(await g(e.payload));
556
- return pilotStore.getState().resetMessageHistory(s), s;
557
- case "submit_core_action": return await C(e.payload);
558
- case "new_message": return await T();
559
- case "submit_message": return await E(e.payload);
792
+ let l = await V(await M(n.payload));
793
+ return pilotStore.getState().resetMessageHistory(l), l;
794
+ case "submit_core_action": return await B(n.payload);
795
+ case "new_message": return await H();
796
+ case "submit_message": return await W(n.payload);
560
797
  default: throw Error("Invalid event action.");
561
798
  }
562
799
  }
563
800
  };
564
801
  }
565
- function createProtocolAdapter(e, s, c, l) {
566
- switch (l.log(`Creating adapter for provider: ${s}`), s.name) {
567
- case "coreagent": return createCoreAgentAdapter(e, c, l);
568
- default: throw Error(`Unsupported provider: ${s.name}`);
802
+ function createProtocolAdapter(n, l, u, d) {
803
+ switch (d.log(`Creating adapter for provider: ${l}`), l.name) {
804
+ case "coreagent": return createCoreAgentAdapter(n, u, d);
805
+ default: throw Error(`Unsupported provider: ${l.name}`);
569
806
  }
570
807
  }
571
- function createHitlManager(e, s, c) {
572
- let l = (e) => e.split("_")[0], u = [], d = async (s) => {
573
- let l = await e.formatReuqest(s);
808
+ function createHitlManager(n, l, u) {
809
+ let d = (n) => n.split("_")[0], f = [], p = async (l) => {
810
+ let d = await n.formatRequest(l);
574
811
  sseRequester({
575
- url: l.url,
576
- config: l.config
577
- }, e), c.log("HITL data submitted successfully.");
578
- }, f = async (e) => {
579
- u.forEach((s) => s(e.hitlData));
580
- }, p = async (e) => {};
812
+ url: d.url,
813
+ config: d.config
814
+ }, n), u.log("HITL data submitted successfully.");
815
+ }, m = async (n) => {
816
+ f.forEach((l) => l(n.hitlData));
817
+ }, h = async (n) => {};
581
818
  return {
582
- async submit(e) {
819
+ async submit(n) {
583
820
  try {
584
- let s = l(e.hitlData?.action ?? "");
585
- switch (c.log("[HITL] Submitting HITL data...", e), s) {
821
+ let l = d(n.hitlData?.action ?? "");
822
+ switch (u.log("[HITL] Submitting HITL data...", n), l) {
586
823
  case "core":
587
- await d(e);
824
+ await p(n);
588
825
  break;
589
826
  case "cust":
590
- await f(e);
827
+ await m(n);
591
828
  break;
592
829
  case "inner":
593
- await p(e);
830
+ await h(n);
594
831
  break;
595
832
  default: throw Error("Invalid action type.");
596
833
  }
597
- } catch (e) {
598
- throw c.error("Error submitting HITL data:", e), e;
834
+ } catch (n) {
835
+ throw u.error("Error submitting HITL data:", n), n;
599
836
  }
600
837
  },
601
- subscribeEvent(e) {
602
- u.includes(e) || u.push(e);
838
+ subscribeEvent(n) {
839
+ f.includes(n) || f.push(n);
603
840
  },
604
- unsubscribeEvent(e) {
605
- u.splice(u.indexOf(e), 1);
841
+ unsubscribeEvent(n) {
842
+ f.splice(f.indexOf(n), 1);
606
843
  }
607
844
  };
608
845
  }
609
- function createCorePilot(e) {
610
- if (!e.appId) throw Error("CorePilot SDK: `appId` is required.");
611
- if (!e.mount.selector) throw Error("CorePilot SDK: `mount.selector` is required.");
612
- let s = createLogger(e.debug ?? !1, e.appId, e.eventTracker);
613
- s.log("CorePilot SDK Initializing...", e);
614
- let c = { ...e }, l = createAuthManager(c.auth, c.baseUrl), u = createProtocolAdapter(c, c.provider, l, s), d = createHitlManager(u, l, s), f = createMountManager(c.mount, u, d, s, c.provider);
846
+ function createCorePilot(n) {
847
+ if (n.auth.mode, !n.appId) throw Error("CorePilot SDK: `appId` is required.");
848
+ if (!n.mount.selector) throw Error("CorePilot SDK: `mount.selector` is required.");
849
+ let l = createLogger(n.debug ?? !1, n.appId || "", n.eventTracker);
850
+ l.log("CorePilot SDK Initializing...", n);
851
+ let u = { ...n }, d = createAuthManager(u.auth, u.appId), f = createProtocolAdapter(u, u.provider, d, l), p = createHitlManager(f, d, l), m = createMountManager(u, f, p, l, d), h = {
852
+ inner_set_token: async (n) => (await d.setToken(n), !0),
853
+ inner_get_token: async () => await d.getToken()
854
+ };
615
855
  return {
616
856
  mount() {
617
- s.log("Mounting CorePilot UI..."), f.mount();
857
+ l.log("Mounting CorePilot UI..."), m.mount();
618
858
  },
619
859
  unmount() {
620
- s.log("Unmounting CorePilot UI..."), f.unmount();
860
+ l.log("Unmounting CorePilot UI..."), m.unmount();
621
861
  },
622
- reload(e) {
623
- s.log("Reloading CorePilot instance...", e), f.unmount(), c = {
624
- ...c,
625
- ...e
626
- }, u = createProtocolAdapter(c, c.provider, l, s);
627
- let p = createMountManager(c.mount, u, d, s, c.provider);
628
- f.mount = p.mount, f.unmount = p.unmount, s.log("CorePilot reloaded. Remounting UI..."), f.mount();
862
+ reload(n) {
863
+ l.log("Reloading CorePilot instance...", n), m.unmount(), u = {
864
+ ...u,
865
+ ...n
866
+ }, f = createProtocolAdapter(u, u.provider, d, l);
867
+ let h = createMountManager(u, f, p, l, d);
868
+ m.mount = h.mount, m.unmount = h.unmount, l.log("CorePilot reloaded. Remounting UI..."), m.mount();
629
869
  },
630
870
  destroy() {
631
- s.log("Destroying CorePilot instance..."), f.unmount(), s.destroy();
871
+ l.log("Destroying CorePilot instance..."), m.unmount(), l.destroy();
632
872
  },
633
- async triggerEvent(e) {
634
- return await u.triggerEvent(e);
873
+ async triggerEvent(n) {
874
+ let l = h[n.action];
875
+ if (l) {
876
+ let u = n.payload;
877
+ return await l(u);
878
+ }
879
+ return await f.triggerEvent(n);
635
880
  },
636
- subscribeEvent(e) {
637
- d.subscribeEvent(e);
881
+ subscribeEvent(n) {
882
+ p.subscribeEvent(n), eventHub.subscribeEvent(n);
638
883
  },
639
- unsubscribeEvent(e) {
640
- d.unsubscribeEvent(e);
884
+ unsubscribeEvent(n) {
885
+ p.unsubscribeEvent(n), eventHub.unsubscribeEvent(n);
641
886
  }
642
887
  };
643
888
  }