@core-pilot/sdk 0.1.0 → 0.1.2

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