@core-pilot/sdk 0.1.0 → 0.1.1

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