wi-chat 0.6.2 → 0.7.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.
Files changed (79) hide show
  1. package/dist/core/index.cjs +1 -1
  2. package/dist/core/index.d.ts +12 -0
  3. package/dist/core/index.js +921 -342
  4. package/dist/core/useAnswerActions.d.ts +61 -0
  5. package/dist/core/useChat.d.ts +29 -3
  6. package/dist/core/useChatAuth.d.ts +175 -0
  7. package/dist/core/useChatRooms.d.ts +66 -0
  8. package/dist/core/useKeepAlive.d.ts +41 -0
  9. package/dist/core/useLlm.d.ts +73 -0
  10. package/dist/core/useRunningGroups.d.ts +58 -0
  11. package/dist/index.cjs +1 -1
  12. package/dist/index.d.ts +3 -1
  13. package/dist/index.js +119 -108
  14. package/dist/mobile-ui/chat/ChatContainer.vue.d.ts +3 -3
  15. package/dist/mobile-ui/inputbox/Inputbox.vue.d.ts +1 -1
  16. package/dist/parser/answerCom/generic/parseGeneric.d.ts +52 -0
  17. package/dist/parser/answerCom/generic/types.d.ts +75 -0
  18. package/dist/parser/answerCom/outputFile/parseOutputFile.d.ts +7 -6
  19. package/dist/parser/answerCom/outputFile/types.d.ts +15 -5
  20. package/dist/parser/answerCom/presentFiles/parsePresentFiles.d.ts +58 -0
  21. package/dist/parser/answerCom/presentFiles/types.d.ts +27 -0
  22. package/dist/parser/answerMeta.d.ts +71 -0
  23. package/dist/parser/deepThinking/parseDeepThinking.d.ts +8 -0
  24. package/dist/parser/history/history.d.ts +9 -0
  25. package/dist/parser/history/index.d.ts +1 -1
  26. package/dist/parser/index.cjs +6 -2
  27. package/dist/parser/index.d.ts +11 -2
  28. package/dist/parser/index.js +591 -366
  29. package/dist/parser/message.d.ts +9 -0
  30. package/dist/parser/runTime.d.ts +29 -0
  31. package/dist/renderers/TextAnswer-BgKGvG_o.cjs +2 -0
  32. package/dist/renderers/TextAnswer-PQwV3K7v.js +5 -0
  33. package/dist/renderers/answerCard/AnswerCard.vue.d.ts +65 -0
  34. package/dist/renderers/answerCard/AnswerToolbar.vue.d.ts +42 -0
  35. package/dist/renderers/answerConfig.d.ts +33 -0
  36. package/dist/renderers/deviceLastValue/DeviceLastValue.vue.d.ts +37 -0
  37. package/dist/renderers/index.cjs +6 -1
  38. package/dist/renderers/index.d.ts +14 -0
  39. package/dist/renderers/index.js +1485 -574
  40. package/dist/renderers/media/MediaAnswer.vue.d.ts +19 -0
  41. package/dist/renderers/outputFile/OutputFileLink.vue.d.ts +19 -0
  42. package/dist/renderers/outputFile/localFile.d.ts +46 -0
  43. package/dist/renderers/outputFile/useOutputFile.d.ts +32 -3
  44. package/dist/renderers/presentFiles/PresentFiles.vue.d.ts +19 -0
  45. package/dist/renderers/recordset/RecordsetView.vue.d.ts +19 -0
  46. package/dist/renderers/sqlQuery/SqlQuery.vue.d.ts +19 -0
  47. package/dist/renderers/style.css +1 -1
  48. package/dist/renderers/text/TextAnswer.vue.d.ts +19 -0
  49. package/dist/request/api.d.ts +121 -1
  50. package/dist/request/client.d.ts +12 -0
  51. package/dist/request/index.cjs +4 -2
  52. package/dist/request/index.d.ts +6 -4
  53. package/dist/request/index.js +780 -179
  54. package/dist/request/login.d.ts +36 -0
  55. package/dist/request/ws.d.ts +11 -86
  56. package/dist/request/wsCore.d.ts +104 -0
  57. package/dist/request/wsSession.d.ts +353 -0
  58. package/dist/right-panel/RightPanelTabs.vue.d.ts +4 -0
  59. package/dist/right-panel/index.cjs +1 -1
  60. package/dist/right-panel/index.d.ts +1 -1
  61. package/dist/right-panel/index.js +598 -499
  62. package/dist/right-panel/style.css +1 -1
  63. package/dist/right-panel/types.d.ts +10 -0
  64. package/dist/tools/index.cjs +5 -5
  65. package/dist/tools/index.d.ts +2 -2
  66. package/dist/tools/index.js +323 -208
  67. package/dist/tools/markdown/index.d.ts +2 -0
  68. package/dist/tools/markdown/interactions.d.ts +39 -0
  69. package/dist/tools/markdown/sanitize.d.ts +6 -0
  70. package/dist/tools/style.css +1 -1
  71. package/dist/web-ui/attach/AttachmentCard.vue.d.ts +1 -1
  72. package/dist/web-ui/attach/AttachmentList.vue.d.ts +1 -1
  73. package/dist/web-ui/chat/ChatContainer.vue.d.ts +5 -5
  74. package/dist/web-ui/envswitch/EnvSwitch.vue.d.ts +1 -1
  75. package/dist/web-ui/index.cjs +1 -1
  76. package/dist/web-ui/index.js +1 -1
  77. package/dist/web-ui/inputbox/Inputbox.vue.d.ts +5 -5
  78. package/dist/web-ui/style.css +1 -1
  79. package/package.json +2 -2
@@ -1,472 +1,1051 @@
1
- import { ref as p, getCurrentInstance as oe, onBeforeUnmount as Le, reactive as se, onMounted as xe, watch as re } from "vue";
2
- import { clearPendingClarifications as Ae, loadGroupMessagesByStep as ne, createHistoryGroup as ie, nextLocalMessageId as le, createEmptyAnswerValues as Ce, buildChatTitle as Ie, consumeStream as _e, applyAnswerChunk as be, collectThinkingSteps as Re, expirePendingClarificationsForReply as Ee, loadGroupMessages as Se, deleteHistoryGroup as qe, setHistoryGroupTitle as Fe, getHistoryGroups as Me, resolveRemoteFileUrl as Qe } from "wi-chat/parser";
3
- import { createRequest as Ue, createChatApi as Pe, login as Oe, isCancelError as Te } from "wi-chat/request";
4
- const Ke = (e) => {
5
- const l = {
1
+ import { ref as G, getCurrentInstance as we, onBeforeUnmount as Ee, computed as de, getCurrentScope as Ue, onScopeDispose as Me, reactive as ue, onMounted as Pe, shallowReactive as je, effectScope as De, watch as ke } from "vue";
2
+ import { createEmptyAnswerValues as be, nextLocalMessageId as Re, buildChatTitle as Qe, createHistoryGroup as Te, loadGroupMessagesByStep as Le, clearPendingClarifications as Ne, consumeStream as He, parseServerStartTime as Je, normalizeAnswer as Be, collectThinkingSteps as xe, applyAnswerChunk as We, expirePendingClarificationsForReply as $e, mergeAnswerMeta as Ve, readAnswerMeta as Ke, loadGroupMessages as ze, deleteHistoryGroup as Ye, setHistoryGroupTitle as Xe, getHistoryGroups as Ze, resolveRemoteFileUrl as et, collectAnswerMarkdown as Ge, markdownToPlainText as tt } from "wi-chat/parser";
3
+ import { AuthExpiredError as ce, createRequest as se, createChatApi as Oe, login as fe, makeEncryptLoginStatus as rt, pwdEncrypt as nt, loginByEncryptKey as st, isCancelError as at } from "wi-chat/request";
4
+ const ot = (e) => {
5
+ const { api: t, interval: y = 5 * 60 * 1e3, renew: h, onExpired: l, immediate: A = !0 } = e, w = G(!1), u = G(0);
6
+ let R = null, x = null;
7
+ const m = async () => {
8
+ const d = h ? await h().catch(() => !1) : !1;
9
+ return d || l == null || l(), d;
10
+ }, c = () => x || (x = (async () => {
11
+ if (!t.pingLogin) return !0;
12
+ try {
13
+ const d = await t.pingLogin();
14
+ return u.value = Date.now(), (d == null ? void 0 : d.is_login) === !1 ? m() : !0;
15
+ } catch (d) {
16
+ return d instanceof ce ? m() : !0;
17
+ } finally {
18
+ x = null;
19
+ }
20
+ })(), x), n = () => {
21
+ R || (w.value = !0, R = setInterval(() => void c(), y));
22
+ }, f = () => {
23
+ R && clearInterval(R), R = null, w.value = !1;
24
+ };
25
+ return A && n(), we() && Ee(f), { active: w, lastPingAt: u, start: n, stop: f, pingNow: c };
26
+ }, F = {
27
+ get(e) {
28
+ try {
29
+ return typeof localStorage < "u" ? localStorage.getItem(e) : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ },
34
+ set(e, t) {
35
+ try {
36
+ typeof localStorage < "u" && localStorage.setItem(e, t);
37
+ } catch {
38
+ }
39
+ },
40
+ remove(e) {
41
+ try {
42
+ typeof localStorage < "u" && localStorage.removeItem(e);
43
+ } catch {
44
+ }
45
+ }
46
+ }, it = (e) => btoa(unescape(encodeURIComponent(e))), lt = (e) => decodeURIComponent(escape(atob(e))), ge = 24 * 60 * 60 * 1e3, ut = 15 * 1e3, ct = (e) => {
47
+ let t = null;
48
+ return () => (t || (t = Promise.resolve().then(e).catch(() => !1).finally(() => {
49
+ setTimeout(() => t = null, 0);
50
+ })), t);
51
+ }, he = (e) => {
52
+ if (!e || typeof e != "object") return !1;
53
+ const t = e;
54
+ return t.err_code === "AUTH" || t.error_code === "AUTH" || t.err_no_login === !0;
55
+ }, ft = (e) => ({
56
+ get() {
57
+ const t = F.get(e);
58
+ if (!t) return null;
59
+ try {
60
+ const y = JSON.parse(t);
61
+ return y != null && y.encryptKey ? y : null;
62
+ } catch {
63
+ return null;
64
+ }
65
+ },
66
+ set(t) {
67
+ F.set(e, JSON.stringify(t));
68
+ },
69
+ clear() {
70
+ F.remove(e);
71
+ }
72
+ }), dt = (e) => ({
73
+ get() {
74
+ const t = F.get(e);
75
+ if (!t) return null;
76
+ try {
77
+ const y = JSON.parse(lt(t));
78
+ return y != null && y.user && (y != null && y.pass) ? y : null;
79
+ } catch {
80
+ return null;
81
+ }
82
+ },
83
+ set(t) {
84
+ F.set(e, it(JSON.stringify(t)));
85
+ },
86
+ clear() {
87
+ F.remove(e);
88
+ }
89
+ }), yt = () => {
90
+ let e = null;
91
+ return {
92
+ get: () => e,
93
+ set: (t) => {
94
+ e = t;
95
+ },
96
+ clear: () => {
97
+ e = null;
98
+ }
99
+ };
100
+ }, vt = () => {
101
+ let e = null;
102
+ return {
103
+ get: () => e,
104
+ set: (t) => {
105
+ e = t;
106
+ },
107
+ clear: () => {
108
+ e = null;
109
+ }
110
+ };
111
+ }, gt = (e, t) => {
112
+ if (!Number.isFinite(e) || e <= 0 || !Number.isFinite(t) || t <= e)
113
+ throw new Error("登录密钥有效期必须大于保持登录窗口,且两者必须为正数");
114
+ return { rememberDays: e, encryptKeyDays: t };
115
+ }, xt = (e) => {
116
+ const t = e.sessionKey === void 0 ? "wi-chat-session" : e.sessionKey, y = e.remember ?? !1, { rememberDays: h, encryptKeyDays: l } = gt(
117
+ e.rememberDays ?? 7,
118
+ e.encryptKeyDays ?? 10
119
+ ), A = e.touchInterval ?? 30 * 60 * 1e3, w = e.touchMinInterval ?? 6 * 60 * 60 * 1e3, u = e.keyStore ?? (y && t ? ft(`${t}-encrypt-key`) : yt()), R = e.credentialStore ?? (y && t ? dt(`${t}-account`) : vt()), x = t ? `${t}-user` : null, m = y && t ? `${t}-signed-out` : null, c = () => !!(m && F.get(m)), n = () => {
120
+ m && F.set(m, "1");
121
+ }, f = () => {
122
+ m && F.remove(m);
123
+ }, d = G(t ? F.get(t) ?? "" : ""), s = G(null);
124
+ if (x)
125
+ try {
126
+ s.value = JSON.parse(F.get(x) || "null");
127
+ } catch {
128
+ s.value = null;
129
+ }
130
+ const v = de(() => !!d.value), p = (o) => {
131
+ d.value = o.wisession || "", s.value = o, t && F.set(t, d.value), x && F.set(x, JSON.stringify(o)), f();
132
+ }, I = () => {
133
+ d.value = "", s.value = null, t && F.remove(t), x && F.remove(x);
134
+ }, E = se({ baseURL: e.baseURL }), T = (o) => se({ baseURL: e.baseURL, getWisession: () => o });
135
+ let C = 0, q = null, P = 0;
136
+ const O = async ({
137
+ session: o,
138
+ userId: a
139
+ }) => {
140
+ if (!o) return { ok: !1, reason: "missing" };
141
+ const b = C;
142
+ P = Date.now();
143
+ try {
144
+ const i = await rt(T(o), l);
145
+ if (b !== C) return { ok: !1, reason: "superseded" };
146
+ const g = i == null ? void 0 : i.encrypt_key;
147
+ if (i != null && i.json_ok && g) {
148
+ const N = await u.get(), H = await nt(String(g));
149
+ if (b !== C) return { ok: !1, reason: "superseded" };
150
+ const B = Date.now();
151
+ return await u.set({
152
+ encryptKey: H,
153
+ userId: a != null ? String(a) : (N == null ? void 0 : N.userId) || "",
154
+ createdAt: B,
155
+ expiresAt: Math.min(B + h * ge, B + l * ge),
156
+ keyExpiresAt: B + l * ge
157
+ }), q = null, await R.clear(), { ok: !0, reason: "ok", session: o };
158
+ }
159
+ const X = he(i);
160
+ return q && await R.set(q), console.warn("[wi-chat auth] 签发登录密钥失败,回退账号密码兜底:", (i == null ? void 0 : i.json_msg) || (i == null ? void 0 : i.err_code) || ""), { ok: !1, reason: X ? "credential_rejected" : "login_failed", session: o };
161
+ } catch (i) {
162
+ return b !== C ? { ok: !1, reason: "superseded" } : i instanceof ce ? (q && await R.set(q), console.warn("[wi-chat auth] 签发登录密钥被后端拒绝(无权限),回退账号密码兜底"), { ok: !1, reason: "credential_rejected", session: o }) : (console.warn("[wi-chat auth] 签发登录密钥网络异常,保留原有凭据:", i), { ok: !1, reason: "network_error", session: o });
163
+ }
164
+ }, V = async (o) => {
165
+ var b;
166
+ const a = C;
167
+ try {
168
+ const i = await st(E, {
169
+ encrypt_key: o.encryptKey,
170
+ client: e.client
171
+ });
172
+ return a !== C ? { ok: !1, reason: "superseded" } : { ok: !0, reason: "ok", session: i.wisession, userInfo: i };
173
+ } catch (i) {
174
+ return a !== C ? { ok: !1, reason: "superseded" } : i instanceof ce || he((b = i == null ? void 0 : i.response) == null ? void 0 : b.data) ? { ok: !1, reason: "credential_rejected" } : (console.warn("[wi-chat auth] 用登录密钥续期失败(保留凭据):", i), { ok: !1, reason: "network_error" });
175
+ }
176
+ }, j = async (o) => {
177
+ var b;
178
+ const a = C;
179
+ try {
180
+ const i = await fe(E, {
181
+ user: o.user,
182
+ pass: o.pass,
183
+ client: e.client
184
+ });
185
+ return a !== C ? { ok: !1, reason: "superseded" } : { ok: !0, reason: "ok", session: i.wisession, userInfo: i };
186
+ } catch (i) {
187
+ return a !== C ? { ok: !1, reason: "superseded" } : i instanceof ce || he((b = i == null ? void 0 : i.response) == null ? void 0 : b.data) ? { ok: !1, reason: "credential_rejected" } : (console.warn("[wi-chat auth] 用账号密码续期失败(保留凭据):", i), { ok: !1, reason: "network_error" });
188
+ }
189
+ };
190
+ let S = null, k = 0;
191
+ const D = async () => {
192
+ var b, i;
193
+ const o = await u.get();
194
+ if (o != null && o.encryptKey) {
195
+ const g = await V(o);
196
+ if (g.ok)
197
+ return p({
198
+ ...g.userInfo || {},
199
+ wisession: g.session
200
+ }), O({ session: g.session || "", userId: (b = g.userInfo) == null ? void 0 : b.id }), g;
201
+ if (g.reason === "superseded" || g.reason === "network_error") return g;
202
+ }
203
+ const a = await R.get() ?? q;
204
+ if (a != null && a.user && (a != null && a.pass)) {
205
+ const g = await j(a);
206
+ return g.ok && (p({
207
+ ...g.userInfo || {},
208
+ wisession: g.session
209
+ }), O({ session: g.session || "", userId: (i = g.userInfo) == null ? void 0 : i.id })), g;
210
+ }
211
+ return { ok: !1, reason: "missing" };
212
+ };
213
+ let U = null, Q = -1;
214
+ const J = (o) => {
215
+ if (!y)
216
+ return Promise.resolve(
217
+ d.value ? { ok: !1, reason: "credential_rejected" } : { ok: !1, reason: "missing" }
218
+ );
219
+ if (c())
220
+ return Promise.resolve({ ok: !1, reason: "missing" });
221
+ const a = String(o || "");
222
+ if (a && (S != null && S.ok) && S.session === a && (S = null, k = 0), S && Date.now() - k < ut)
223
+ return Promise.resolve(S);
224
+ if (U && Q === C) return U;
225
+ const b = C, i = D().finally(() => {
226
+ U === i && (U = null, Q = -1);
227
+ }).then((g) => (g.reason === "superseded" || g.ok && (S = g, k = Date.now()), g));
228
+ return U = i, Q = b, i;
229
+ }, Z = (o) => o === "missing" || o === "credential_rejected", ee = () => {
230
+ var o;
231
+ d.value && (I(), W.stop(), le(), (o = e.onExpired) == null || o.call(e));
232
+ }, ae = async (o) => {
233
+ const a = await J(o);
234
+ return a.ok ? !0 : (Z(a.reason) && ee(), !1);
235
+ }, te = se({
236
+ baseURL: e.baseURL,
237
+ getWisession: () => d.value,
238
+ // client 层拿到新 session 后会用新 session 自动重试一次原请求
239
+ onAuthExpired: (o) => ae(o == null ? void 0 : o.rejectedSession)
240
+ }), oe = Oe(te, {
241
+ resumable: e.resumable ?? !0,
242
+ // 对话 WS 收到 user not login:用保存的凭据静默重登,失败则按彻底失效处理
243
+ refreshSession: () => ae()
244
+ }), W = ot({
245
+ api: oe,
246
+ interval: e.pingInterval || 5 * 60 * 1e3,
247
+ // ping 的请求拦截器已先行续期;这里兜住「is_login === false 但非 AUTH 错误」的情况。
248
+ // 临时失败(network_error / login_failed)返回 true:保留登录态,等下一次心跳再试,绝不在此清登录态
249
+ renew: async () => {
250
+ if (!d.value) return !1;
251
+ const o = await J(d.value);
252
+ return o.ok || !Z(o.reason);
253
+ },
254
+ onExpired: () => ee(),
255
+ immediate: !1
256
+ }), ie = async () => await u.get() || await R.get() ? !0 : !!q, z = async (o = w) => {
257
+ var g;
258
+ const a = d.value;
259
+ if (!a)
260
+ return await ie() ? J() : { ok: !1, reason: "missing" };
261
+ if (!y) return { ok: !0, reason: "ok", session: a };
262
+ if (c()) return { ok: !1, reason: "missing" };
263
+ const b = await u.get();
264
+ if (b) {
265
+ if (o > 0 && Date.now() - b.createdAt < o)
266
+ return { ok: !0, reason: "ok", session: a };
267
+ } else if (o > 0 && Date.now() - P < o)
268
+ return { ok: !0, reason: "ok", session: a };
269
+ const i = await O({ session: a, userId: (g = s.value) == null ? void 0 : g.id });
270
+ return i.ok ? (S = { ok: !0, reason: "ok", session: a }, k = Date.now(), i) : i.reason === "credential_rejected" ? await ie() ? { ok: !0, reason: "ok", session: a } : J(a) : i;
271
+ };
272
+ let Y = null, re = !1;
273
+ const ye = async () => {
274
+ if (!(re || !d.value)) {
275
+ re = !0;
276
+ try {
277
+ const o = await z();
278
+ !o.ok && Z(o.reason) && ee();
279
+ } finally {
280
+ re = !1;
281
+ }
282
+ }
283
+ }, ne = () => {
284
+ !y || A <= 0 || Y || (Y = setInterval(() => void ye(), A));
285
+ }, le = () => {
286
+ Y && clearInterval(Y), Y = null;
287
+ }, r = () => {
288
+ e.pingInterval !== 0 && W.start();
289
+ }, L = async (o, a, b = {}) => {
290
+ const i = { ...b, user: o, pass: a, client: e.client }, g = await fe(E, i);
291
+ return p(g), y ? (q = { user: o, pass: a }, await O({ session: g.wisession || "", userId: g.id }), r(), ne(), g) : (r(), g);
292
+ }, _ = async () => {
293
+ if (!y) return !1;
294
+ const o = await J();
295
+ return o.ok && (r(), ne(), z()), o.ok;
296
+ }, M = async (o = !0) => {
297
+ n(), C += 1, I(), W.stop(), le(), S = null, k = 0, U = null, Q = -1, o && (q = null, await u.clear(), await R.clear());
298
+ };
299
+ return d.value && (r(), ne(), W.pingNow()), {
300
+ session: d,
301
+ userInfo: s,
302
+ isLoggedIn: v,
303
+ request: te,
304
+ api: oe,
305
+ keepAlive: W,
306
+ login: L,
307
+ autoLogin: _,
308
+ renew: async () => (await J()).ok,
309
+ restore: J,
310
+ touch: z,
311
+ logout: M
312
+ };
313
+ }, ht = (e) => {
314
+ const t = {
6
315
  requestId: e,
7
316
  sender: null,
8
317
  queue: [],
9
318
  closed: !1,
10
- reply: (h) => ce(l, h)
319
+ reply: (y) => qe(t, y)
11
320
  };
12
- return l;
13
- }, ce = (e, l, h) => {
321
+ return t;
322
+ }, qe = (e, t, y) => {
14
323
  if (e.closed) return !1;
15
- const w = typeof l == "string" ? l : JSON.stringify(l) ?? "";
16
- return e.sender ? e.sender(w, h) !== !1 : (e.queue.push({ payloadText: w, chunkSize: h }), !0);
17
- }, ue = (e) => {
18
- e.closed || (e.closed = !0, e.queue.length = 0, e.sender = null, Ee(e.reply));
19
- }, ke = (e) => {
20
- const l = e.login, h = e.defaultGroupTitle ?? "新对话", w = e.lastCount ?? 10, u = e.autoSetGroupTitleOnFirstQuestion ?? !0, L = {
324
+ const h = typeof t == "string" ? t : JSON.stringify(t) ?? "";
325
+ return e.sender ? e.sender(h, y) !== !1 : (e.queue.push({ payloadText: h, chunkSize: y }), !0);
326
+ }, Ie = (e) => {
327
+ e.closed || (e.closed = !0, e.queue.length = 0, e.sender = null, $e(e.reply));
328
+ }, Fe = (e) => {
329
+ const t = e.login, y = e.defaultGroupTitle ?? "新对话", h = e.lastCount ?? 10, l = e.autoSetGroupTitleOnFirstQuestion ?? !0, A = {
21
330
  beforeKnowledgeRender: e.beforeKnowledgeRender,
22
331
  parsers: e.parsers,
23
332
  actionExecute: {
24
333
  ...e.actionExecute,
25
334
  reply: () => !1
26
335
  }
27
- }, v = p(""), o = p([]), C = p(""), Q = p(e.incPrevQuestion ?? "Y"), s = p(!1), i = p(!1), t = p(""), n = p(!1), m = p(""), d = p(!0), y = p(!1), A = p(0), W = e.api ? null : Ue({
336
+ }, w = G(""), u = G([]), R = G(""), x = G(e.incPrevQuestion ?? "Y"), m = G(!1), c = G(!1), n = G(""), f = G(!1), d = G(""), s = G(!0), v = G(!1), p = G(0), I = e.api ? null : se({
28
337
  baseURL: e.baseURL ?? "",
29
- getWisession: () => v.value
30
- }), U = e.api ?? Pe(W);
31
- let I = null, R = null, D = 0, _ = 0, j = 0, E = null;
32
- const V = async () => {
33
- if (m.value = "", !W || !l) {
34
- n.value = !0;
338
+ getWisession: () => w.value,
339
+ onAuthExpired: () => C()
340
+ }), E = e.api ?? Oe(I, { resumable: e.resumable, refreshSession: () => C() }), T = I ? se({ baseURL: e.baseURL ?? "" }) : null, C = ct(async () => {
341
+ if (e.onAuthExpired) return e.onAuthExpired();
342
+ if (!I || !t || !T) return !1;
343
+ const r = await fe(T, t);
344
+ return w.value = r.wisession || "", !!w.value;
345
+ }), q = (r, L) => {
346
+ var _;
347
+ r && ((_ = e.onRunningChange) == null || _.call(e, r, L));
348
+ };
349
+ let P = null, O = null, V = 0, j = 0, S = 0, k = null;
350
+ const D = async () => {
351
+ if (d.value = "", !I || !t) {
352
+ f.value = !0;
35
353
  return;
36
354
  }
37
355
  try {
38
- const r = await Oe(W, l);
39
- return v.value = r.wisession || "", n.value = !0, r;
356
+ const r = await fe(T ?? I, t);
357
+ return w.value = r.wisession || "", f.value = !0, r;
40
358
  } catch (r) {
41
- throw m.value = r instanceof Error ? r.message : String(r), r;
42
- }
43
- }, a = (r) => r === D, f = (r) => {
44
- typeof URL > "u" || typeof URL.revokeObjectURL != "function" || r.forEach((G) => {
45
- G.role !== "user" || !G.attachments || G.attachments.forEach((x) => {
46
- var b;
47
- const S = (b = x.attachContent) == null ? void 0 : b.url;
48
- S && S.startsWith("blob:") && URL.revokeObjectURL(S);
359
+ throw d.value = r instanceof Error ? r.message : String(r), r;
360
+ }
361
+ }, U = (r) => r === V, Q = (r) => {
362
+ typeof URL > "u" || typeof URL.revokeObjectURL != "function" || r.forEach((L) => {
363
+ L.role !== "user" || !L.attachments || L.attachments.forEach((_) => {
364
+ var o;
365
+ const M = (o = _.attachContent) == null ? void 0 : o.url;
366
+ M && M.startsWith("blob:") && URL.revokeObjectURL(M);
49
367
  });
50
368
  });
51
- }, P = (r) => ({
369
+ }, J = (r) => ({
52
370
  beforeKnowledgeRender: e.beforeKnowledgeRender,
53
371
  parsers: e.parsers,
54
372
  actionExecute: {
55
373
  ...e.actionExecute,
56
374
  reply: r.reply
57
375
  }
58
- }), F = async (r) => {
59
- const G = ++_;
60
- j += 1, s.value = !0, f(o.value), E && Ae(E.reply), o.value = [], t.value = r, d.value = !0, y.value = !1, A.value = 0;
61
- const x = [], S = () => {
62
- const g = [];
63
- x.forEach((O) => {
64
- g.push(O.user), O.assistant && g.push(O.assistant);
65
- }), G === _ && (o.value = g);
66
- }, b = (g) => {
67
- G === _ && (g.type === "users" ? (x.length = 0, g.users.forEach((O) => x.push({ user: O }))) : x[g.index] && (g.user && (x[g.index].user = g.user), x[g.index].assistant = g.assistant), S());
376
+ }), Z = async (r) => {
377
+ const L = ++j;
378
+ S += 1, m.value = !0, Q(u.value), k && Ne(k.reply), u.value = [], n.value = r, s.value = !0, v.value = !1, p.value = 0;
379
+ const _ = [], M = () => {
380
+ const a = [];
381
+ _.forEach((b) => {
382
+ a.push(b.user), b.assistant && a.push(b.assistant);
383
+ }), L === j && (u.value = a);
384
+ }, o = (a) => {
385
+ L === j && (a.type === "users" ? (_.length = 0, a.users.forEach((b) => _.push({ user: b }))) : _[a.index] && (a.user && (_[a.index].user = a.user), _[a.index].assistant = a.assistant), M());
68
386
  };
69
387
  try {
70
- await ne(U, r, w, b, 0, L), S(), G === _ && (A.value = x.length, x.length < w && (d.value = !1));
388
+ await Le(E, r, h, o, 0, A), M(), L === j && (p.value = _.length, _.length < h && (s.value = !1));
71
389
  } finally {
72
- j -= 1, j <= 0 && (j = 0, s.value = !1);
390
+ S -= 1, S <= 0 && (S = 0, m.value = !1);
73
391
  }
74
- }, Y = async () => {
75
- if (!t.value || s.value || !d.value || y.value) return;
76
- const r = t.value, G = _, x = A.value;
77
- y.value = !0;
392
+ }, ee = async () => {
393
+ if (!n.value || m.value || !s.value || v.value) return;
394
+ const r = n.value, L = j, _ = p.value;
395
+ v.value = !0;
78
396
  try {
79
- const S = await ne(U, r, w, void 0, x, L), b = S.filter((g) => g.role === "user").length;
80
- if (b < w && (d.value = !1), G === _ && t.value === r) {
81
- const g = /* @__PURE__ */ new Set();
82
- o.value.forEach((q) => {
83
- q.historyId && g.add(q.historyId), q.id && g.add(q.id);
397
+ const M = await Le(E, r, h, void 0, _, A), o = M.filter((a) => a.role === "user").length;
398
+ if (o < h && (s.value = !1), L === j && n.value === r) {
399
+ const a = /* @__PURE__ */ new Set();
400
+ u.value.forEach((i) => {
401
+ i.historyId && a.add(i.historyId), i.id && a.add(i.id);
84
402
  });
85
- const O = S.filter((q) => !(q.historyId && g.has(q.historyId) || q.id && g.has(q.id)));
86
- o.value = [...O, ...o.value], A.value += b;
403
+ const b = M.filter((i) => !(i.historyId && a.has(i.historyId) || i.id && a.has(i.id)));
404
+ u.value = [...b, ...u.value], p.value += o;
87
405
  }
88
406
  } finally {
89
- y.value = !1;
90
- }
91
- }, de = async (r = h) => {
92
- const G = await ie(U, r);
93
- return t.value = G, G;
94
- }, Z = () => {
95
- D += 1, _ += 1, R && (R.stopped = !0, R.thinking.expanded = !1), I == null || I.abort(), I = null, E && ue(E), E = null, R = null, i.value = !1;
96
- }, fe = () => {
97
- R && (R.error = !0, R.thinking.expanded = !1);
98
- }, ge = async (r) => {
99
- var ee, te;
100
- const G = typeof r == "string" ? { text: r } : r || {}, { text: x, entryId: S, files: b, attachments: g, extArgs: O, ...q } = G, B = (x !== void 0 ? x : C.value).trim(), pe = O ?? e.extArgs ?? {}, he = b && b.length > 0 ? b : (g ?? []).map((k) => {
101
- var z;
102
- return (z = k.attachContent) == null ? void 0 : z.raw;
103
- }).filter((k) => !!k);
104
- if (!B || i.value || !t.value) return;
105
- const T = D + 1;
106
- D = T, _ += 1;
107
- const K = Ke(T);
108
- E = K;
109
- const we = P(K);
110
- let $ = !1;
407
+ v.value = !1;
408
+ }
409
+ }, ae = async (r = y) => {
410
+ const L = await Te(E, r);
411
+ return n.value = L, L;
412
+ }, te = (r = !0) => {
413
+ var L;
414
+ r !== !1 && c.value && n.value && ((L = E.stopChat) == null || L.call(E, n.value)), V += 1, j += 1, O && (O.stopped = !0, O.thinking.expanded = !1, z(O)), P == null || P.abort(), P = null, k && Ie(k), k = null, O = null, c.value = !1;
415
+ }, oe = () => {
416
+ O && (O.error = !0, O.thinking.expanded = !1, z(O));
417
+ }, W = async (r, L, _, M) => {
418
+ const o = V + 1;
419
+ V = o, j += 1;
420
+ const a = ht(o);
421
+ k = a;
422
+ const b = J(a), i = M || n.value;
423
+ O = r, c.value = !0, q(i, !0);
424
+ let g = !1;
111
425
  try {
112
- i.value = !0;
113
- const k = t.value, z = g || (b || []).map((c) => {
426
+ P = new AbortController();
427
+ const X = await _((N) => {
428
+ if (!U(o) || a.closed) return;
429
+ a.sender = N;
430
+ const H = a.queue;
431
+ a.queue = [], H.forEach(({ payloadText: B, chunkSize: ve }) => N(B, ve));
432
+ }, P.signal);
433
+ await He(X, (N) => {
114
434
  var H;
115
- const J = c.name.includes(".") && ((H = c.name.split(".").pop()) == null ? void 0 : H.toLowerCase()) || "";
116
- return {
117
- type: "file",
118
- name: c.name,
119
- description: J ? J.toUpperCase() : "",
120
- attachContent: {
121
- file_name: c.name,
122
- size: c.size,
123
- suffix: J,
124
- raw: c
125
- }
126
- };
127
- }), me = A.value === 0 && !o.value.some((c) => c.role === "user"), X = k, ae = se({
128
- id: le("user"),
129
- role: "user",
130
- content: B,
131
- attachments: z.length > 0 ? z : void 0
132
- });
133
- o.value.push(ae);
134
- const M = se({
135
- id: le("answer"),
136
- role: "assistant",
137
- answer: Ce("", B),
138
- error: !1,
139
- stopped: !1,
140
- thinking: { steps: [], expanded: !0 }
141
- });
142
- if (R = M, o.value.push(M), C.value = "", (ee = e.onSubmitQuestion) == null || ee.call(e, B), me && X) {
143
- const c = Ie(B);
144
- e.onFirstQuestion ? e.onFirstQuestion({ question: c, groupId: X }) : u && c && U.setHistoryGroupTitle(X, c).catch(() => {
145
- });
435
+ U(o) && (ie(r, L, N, b), (H = e.onChunk) == null || H.call(e, N));
436
+ }), U(o) && (g = !0, r.thinking.expanded = !1, z(r));
437
+ } catch (X) {
438
+ U(o) && !at(X) && oe();
439
+ } finally {
440
+ Ie(a), k === a && (k = null), q(i, !1), U(o) && (c.value = !1, P = null, O = null);
441
+ }
442
+ return g && Y(r), g;
443
+ }, ie = (r, L, _, M) => {
444
+ if (_.mode === "history_id") {
445
+ const a = typeof _.value == "object" && _.value !== null ? _.value.history_id : _.value;
446
+ a && (L && (L.historyId = String(a)), r.historyId = String(a), r.answer.id = String(a));
447
+ return;
448
+ }
449
+ if (_.mode === "start") {
450
+ const a = Je(_.value ?? _.time, r.runStartAt);
451
+ a != null && r.runStartAt != null && (r.runStartAt = a);
452
+ return;
453
+ }
454
+ if (_.mode === "history_answer") {
455
+ const a = Be(_.value, r.historyId ?? "", r.answer.question ?? "", A);
456
+ r.answer = a, r.thinking.steps = xe(a);
457
+ return;
458
+ }
459
+ We(r.answer, _, M).includes("deep_thinking") && (r.thinking.steps = xe(r.answer)), _.mode === "finish" && (r.thinking.expanded = !1);
460
+ }, z = (r) => {
461
+ !r || r.runStartAt == null || (r.runMs = Math.max(0, Date.now() - r.runStartAt), delete r.runStartAt);
462
+ }, Y = async (r) => {
463
+ if (!(!e.syncMetaOnFinish || !r.historyId))
464
+ try {
465
+ const L = await E.getHistoryAnswer(r.historyId);
466
+ Ve(r.answer, L);
467
+ const _ = Ke(r.answer).runMs;
468
+ _ != null && (r.runMs = _);
469
+ } catch {
146
470
  }
147
- I = new AbortController();
148
- const Ge = await U.questionStream(
471
+ }, re = async (r) => {
472
+ var Se, _e;
473
+ const L = typeof r == "string" ? { text: r } : r || {}, { text: _, entryId: M, files: o, attachments: a, extArgs: b, ...i } = L, g = (_ !== void 0 ? _ : R.value).trim(), X = b ?? e.extArgs ?? {}, N = o && o.length > 0 ? o : (a ?? []).map((K) => {
474
+ var $;
475
+ return ($ = K.attachContent) == null ? void 0 : $.raw;
476
+ }).filter((K) => !!K);
477
+ if (!g || c.value || !n.value) return;
478
+ const H = n.value, B = a || (o || []).map((K) => {
479
+ var Ae;
480
+ const $ = K.name.includes(".") && ((Ae = K.name.split(".").pop()) == null ? void 0 : Ae.toLowerCase()) || "";
481
+ return {
482
+ type: "file",
483
+ name: K.name,
484
+ description: $ ? $.toUpperCase() : "",
485
+ attachContent: { file_name: K.name, size: K.size, suffix: $, raw: K }
486
+ };
487
+ }), ve = p.value === 0 && !u.value.some((K) => K.role === "user"), pe = ue({
488
+ id: Re("user"),
489
+ role: "user",
490
+ content: g,
491
+ attachments: B.length > 0 ? B : void 0
492
+ });
493
+ u.value.push(pe);
494
+ const me = ue({
495
+ id: Re("answer"),
496
+ role: "assistant",
497
+ answer: be("", g),
498
+ error: !1,
499
+ stopped: !1,
500
+ runStartAt: Date.now(),
501
+ thinking: { steps: [], expanded: !0 }
502
+ });
503
+ if (u.value.push(me), R.value = "", (Se = e.onSubmitQuestion) == null || Se.call(e, g), ve) {
504
+ const K = Qe(g);
505
+ e.onFirstQuestion ? e.onFirstQuestion({ question: K, groupId: H }) : l && K && E.setHistoryGroupTitle(H, K).catch(() => {
506
+ });
507
+ }
508
+ p.value += 1, await W(
509
+ me,
510
+ pe,
511
+ (K, $) => E.questionStream(
149
512
  {
150
- // 先铺开外部透传的额外字段(raw_mode / tables / metrics / group_type 等),
151
- // 已知字段随后覆盖,避免同名额外字段篡改核心参数
152
- ...q,
153
- question: B,
154
- historyGroupId: k,
155
- entryId: S,
156
- files: he,
157
- ext_args: JSON.stringify(pe),
158
- incPrevQuestion: Q.value,
159
- // 连接建立且首包发完后接收分片发送器,并按序补发连接建立前入队的追发消息
160
- // (sendWsMessage / wait_reply 在连接未就绪时调用会先入队,见 sendViaChannel)
161
- onOpen: (c) => {
162
- if (!a(T) || K.closed) return;
163
- K.sender = c;
164
- const J = K.queue;
165
- K.queue = [], J.forEach(({ payloadText: H, chunkSize: N }) => c(H, N));
166
- }
513
+ // 先铺开外部透传的额外字段,已知字段随后覆盖,避免同名额外字段篡改核心参数
514
+ ...i,
515
+ question: g,
516
+ historyGroupId: H,
517
+ entryId: M,
518
+ files: N,
519
+ ext_args: JSON.stringify(X),
520
+ incPrevQuestion: x.value,
521
+ onOpen: K
167
522
  },
168
- I.signal
169
- );
170
- A.value += 1, await _e(Ge, (c) => {
171
- var H;
172
- if (!a(T)) return;
173
- if (c.mode === "history_id") {
174
- const N = typeof c.value == "object" && c.value !== null ? c.value.history_id : c.value;
175
- N && (ae.historyId = String(N), M.historyId = String(N), M.answer && (M.answer.id = String(N)));
176
- }
177
- be(M.answer, c, we).includes("deep_thinking") && (M.thinking.steps = Re(M.answer)), c.mode === "finish" && (M.thinking.expanded = !1), (H = e.onChunk) == null || H.call(e, c);
178
- }), a(T) && (M.thinking.expanded = !1), a(T) && ($ = !0);
179
- } catch (k) {
180
- a(T) && !Te(k) && fe();
181
- } finally {
182
- ue(K), E === K && (E = null), a(T) && (i.value = !1, I = null, R = null);
183
- }
184
- $ && ((te = e.onFinish) == null || te.call(e));
185
- }, ve = (r, G) => !i.value || !E ? !1 : ce(E, r, G), ye = e.autoLogin !== !1 ? V().then(() => {
523
+ $
524
+ )
525
+ ) && ((_e = e.onFinish) == null || _e.call(e));
526
+ }, ye = async (r) => {
527
+ var b;
528
+ if (c.value || !(r != null && r.history_id) || n.value && r.history_group_id && r.history_group_id !== n.value) return !1;
529
+ !n.value && r.history_group_id && (n.value = r.history_group_id);
530
+ const L = u.value.find((i) => i.role === "user" && i.historyId === r.history_id);
531
+ u.value = u.value.filter((i) => !(i.role === "assistant" && i.historyId === r.history_id));
532
+ let _ = L ?? null;
533
+ _ || (_ = ue({
534
+ id: r.history_id,
535
+ historyId: r.history_id,
536
+ role: "user",
537
+ content: r.question ?? ""
538
+ }), u.value.push(_), p.value += 1);
539
+ const M = ue({
540
+ id: `${r.history_id}-answer`,
541
+ historyId: r.history_id,
542
+ role: "assistant",
543
+ answer: be(r.history_id, r.question ?? ""),
544
+ error: !1,
545
+ stopped: !1,
546
+ runStartAt: Date.now(),
547
+ thinking: { steps: [], expanded: !0 }
548
+ }), o = u.value.indexOf(_);
549
+ u.value.splice(o + 1, 0, M);
550
+ const a = await W(
551
+ M,
552
+ _,
553
+ (i, g) => E.questionStream(
554
+ {
555
+ question: r.question ?? "",
556
+ historyGroupId: r.history_group_id || n.value,
557
+ resumeTask: r,
558
+ onOpen: i
559
+ },
560
+ g
561
+ ),
562
+ r.history_group_id || n.value
563
+ );
564
+ return a && ((b = e.onFinish) == null || b.call(e)), a;
565
+ }, ne = (r, L) => !c.value || !k ? !1 : qe(k, r, L), le = e.autoLogin !== !1 ? D().then(() => {
186
566
  }).catch(() => {
187
567
  }) : Promise.resolve();
188
- return oe() && Le(() => {
189
- Z(), f(o.value);
568
+ return Ue() && Me(() => {
569
+ te(!1), Q(u.value);
190
570
  }), {
191
571
  /** 当前分组的消息列表(user / assistant 交错;loadGroup / loadOlder / submitQuestion 会更新) */
192
- messages: o,
572
+ messages: u,
193
573
  /** 输入框内容(v-model 绑定;submitQuestion 成功后清空) */
194
- question: C,
574
+ question: R,
195
575
  /**
196
576
  * 提问是否携带之前对话上下文(inc_prev_question:'Y' 不忽略 / 'N' 忽略,默认 'Y')。
197
577
  * submitQuestion 提交时读取当前值发送;可在外部随时修改(如绑定输入框组件的勾选开关)。
198
578
  */
199
- incPrevQuestion: Q,
579
+ incPrevQuestion: x,
200
580
  /** 会话发送 / 流式回答进行中(true 时 submitQuestion 不再受理新提问) */
201
- talking: i,
581
+ talking: c,
202
582
  /** 历史加载中(首屏 loadGroup 及并发加载全部完成后结束) */
203
- loading: s,
583
+ loading: m,
204
584
  /** 当前会话 token(自动登录写入;未自动登录时可自行赋值) */
205
- session: v,
585
+ session: w,
206
586
  /** 自动登录流程已结束(成功 / 失败 / 跳过均置 true;UI 可等待它再渲染登录状态) */
207
- autoLoginDone: n,
587
+ autoLoginDone: f,
208
588
  /** 最近一次自动登录的错误信息(UI 可据此提示重试) */
209
- autoLoginError: m,
589
+ autoLoginError: d,
210
590
  /** 自动登录完成时机(无论成败都会 resolve;宿主用它编排"登录后才能发"的请求,如加载历史分组) */
211
- loginDone: ye,
591
+ loginDone: le,
212
592
  /** 当前会话所在的历史分组 id */
213
- historyGroupId: t,
593
+ historyGroupId: n,
214
594
  /** 内部自建的 request 客户端(注入 api 时为 null,无使用价值) */
215
- selfRequest: W,
595
+ selfRequest: I,
216
596
  /** 实际使用的业务 API(外部注入的实例或内部自建) */
217
- api: U,
597
+ api: E,
218
598
  /** 手动触发一次自动登录(成功返回登录结果;失败抛错并记录到 autoLoginError) */
219
- doAutoLogin: V,
599
+ doAutoLogin: D,
220
600
  /** 按分组加载消息(插空式渐进渲染;并发调用时仅最新一次生效) */
221
- loadGroup: F,
601
+ loadGroup: Z,
222
602
  /** 加载更早一页历史(向上翻页),前插到消息列表顶部 */
223
- loadOlder: Y,
603
+ loadOlder: ee,
224
604
  /** 是否仍可能有更早历史(向上翻页) */
225
- hasMore: d,
605
+ hasMore: s,
226
606
  /** 向上翻页加载中(触顶防重) */
227
- loadMoreLoading: y,
607
+ loadMoreLoading: v,
228
608
  /** 新建历史分组并选中(返回分组 id) */
229
- createGroup: de,
609
+ createGroup: ae,
230
610
  /** 提交问题并走 SSE 流式问答(支持传参 entryId、files 与文本;无文本 / 发送中 / 无分组时不发送) */
231
- submitQuestion: ge,
611
+ submitQuestion: re,
232
612
  /**
233
613
  * 向当前提问的 WebSocket 连接追发自定义消息(B/M/E 分帧):
234
614
  * 连接就绪立即发出、未就绪入队待连接建立后按序补发;仅在 talking 期间受理,
235
615
  * 无在途会话返回 false。见 sendWsMessage 的 JSDoc。
236
616
  */
237
- sendWsMessage: ve,
238
- /** 停止在途会话:中断流、把当前回答标记为 stopped,并复位 talking */
239
- stopQuestion: Z
617
+ sendWsMessage: ne,
618
+ /** 停止在途会话:向后端发 STOP(可续传模式)、中断流、把当前回答标记为 stopped,并复位 talking */
619
+ stopQuestion: te,
620
+ /** 接管当前分组正在进行的任务(刷新 / 切回房间后 CONNECT 重放),需 resumable */
621
+ resumeTask: ye,
622
+ /** 手动触发一次登录态续期(并发调用合并为一次) */
623
+ renewSession: C
240
624
  };
241
- }, De = "wi-chat-history-groups", He = (e) => {
242
- var V;
625
+ }, wt = "wi-chat-history-groups", pt = (e) => {
626
+ var j;
243
627
  const {
244
- api: l,
245
- defaultGroupTitle: h = "新对话",
246
- lastCount: w = 10,
247
- ensureGroup: u = !0,
248
- autoSelectFirst: L = !0,
249
- autoLoadMessages: v = !0
250
- } = e, o = e.persistGroups ?? !1, C = e.storageKey ?? De, Q = e.beforeKnowledgeRender || (V = e.parsers) != null && V.length ? { beforeKnowledgeRender: e.beforeKnowledgeRender, parsers: e.parsers } : void 0, s = p([]), i = p(""), t = p([]), n = p(!1);
251
- let m = !1, d = null;
252
- const y = () => {
253
- if (d === !1) return null;
254
- let a;
628
+ api: t,
629
+ defaultGroupTitle: y = "新对话",
630
+ lastCount: h = 10,
631
+ ensureGroup: l = !0,
632
+ autoSelectFirst: A = !0,
633
+ autoLoadMessages: w = !0
634
+ } = e, u = e.persistGroups ?? !1, R = e.storageKey ?? wt, x = e.beforeKnowledgeRender || (j = e.parsers) != null && j.length ? { beforeKnowledgeRender: e.beforeKnowledgeRender, parsers: e.parsers } : void 0, m = G([]), c = G(""), n = G([]), f = G(!1);
635
+ let d = !1, s = null;
636
+ const v = () => {
637
+ if (s === !1) return null;
638
+ let S;
255
639
  try {
256
- a = localStorage.getItem(C);
640
+ S = localStorage.getItem(R);
257
641
  } catch {
258
- return d = !1, null;
642
+ return s = !1, null;
259
643
  }
260
- if (a === null) return [];
644
+ if (S === null) return [];
261
645
  try {
262
- const f = JSON.parse(a);
263
- return Array.isArray(f) ? f : [];
646
+ const k = JSON.parse(S);
647
+ return Array.isArray(k) ? k : [];
264
648
  } catch {
265
649
  return [];
266
650
  }
267
- }, A = (a) => {
268
- if (d !== !1)
651
+ }, p = (S) => {
652
+ if (s !== !1)
269
653
  try {
270
- localStorage.setItem(C, JSON.stringify(a));
654
+ localStorage.setItem(R, JSON.stringify(S));
271
655
  } catch {
272
- d = !1;
656
+ s = !1;
273
657
  }
274
- }, W = (a) => {
275
- const f = y();
276
- f !== null && A([...f, a]);
277
- }, U = async (a, f = w) => {
278
- n.value = !0;
658
+ }, I = (S) => {
659
+ const k = v();
660
+ k !== null && p([...k, S]);
661
+ }, E = async (S, k = h) => {
662
+ f.value = !0;
279
663
  try {
280
- t.value = a ? await Se(l, a, f, 0, Q) : [];
664
+ n.value = S ? await ze(t, S, k, 0, x) : [];
281
665
  } finally {
282
- n.value = !1;
666
+ f.value = !1;
283
667
  }
284
- }, I = async (a) => {
285
- i.value = a, v && await U(a);
286
- }, R = async () => {
287
- if (!m) {
288
- m = !0;
668
+ }, T = async (S) => {
669
+ c.value = S, w && await E(S);
670
+ }, C = async () => {
671
+ if (!d) {
672
+ d = !0;
289
673
  try {
290
- s.value.length === 0 ? u && await _(h) : !i.value && L && await I(s.value[0].group_id);
674
+ m.value.length === 0 ? l && await P(y) : !c.value && A && await T(m.value[0].group_id);
291
675
  } finally {
292
- m = !1;
676
+ d = !1;
293
677
  }
294
678
  }
295
- }, D = async () => {
296
- n.value = !0;
679
+ }, q = async () => {
680
+ f.value = !0;
297
681
  try {
298
- const a = await Me(l);
299
- if (o) {
300
- const f = y();
301
- if (f === null)
302
- s.value = a;
682
+ const S = await Ze(t);
683
+ if (u) {
684
+ const k = v();
685
+ if (k === null)
686
+ m.value = S;
303
687
  else {
304
- const P = new Set(f.map((Y) => Y.group_id)), F = a.filter((Y) => P.has(Y.group_id));
305
- A(F), s.value = F;
688
+ const D = new Set(k.map((Q) => Q.group_id)), U = S.filter((Q) => D.has(Q.group_id));
689
+ p(U), m.value = U;
306
690
  }
307
691
  } else
308
- s.value = a;
309
- await R();
692
+ m.value = S;
693
+ await C();
310
694
  } finally {
311
- n.value = !1;
695
+ f.value = !1;
312
696
  }
313
- }, _ = async (a = h) => {
314
- const f = await ie(l, a);
315
- return o && W({ group_id: f, group_title: a }), await D(), i.value !== f && await I(f), f;
697
+ }, P = async (S = y) => {
698
+ const k = await Te(t, S);
699
+ return u && I({ group_id: k, group_title: S }), await q(), c.value !== k && await T(k), k;
316
700
  };
317
701
  return {
318
- groups: s,
319
- activeGroupId: i,
320
- messages: t,
321
- loading: n,
322
- loadGroups: D,
323
- createGroup: _,
324
- renameGroup: async (a, f) => {
325
- await Fe(l, a, f);
326
- const P = s.value.find((F) => F.group_id === a);
327
- P && (P.group_title = f), o && A(s.value);
702
+ groups: m,
703
+ activeGroupId: c,
704
+ messages: n,
705
+ loading: f,
706
+ loadGroups: q,
707
+ createGroup: P,
708
+ renameGroup: async (S, k) => {
709
+ await Xe(t, S, k);
710
+ const D = m.value.find((U) => U.group_id === S);
711
+ D && (D.group_title = k), u && p(m.value);
328
712
  },
329
- deleteGroup: async (a) => {
330
- const f = s.value.findIndex((F) => F.group_id === a);
331
- if (await qe(l, a), s.value = s.value.filter((F) => F.group_id !== a), o && A(s.value), i.value !== a) return;
332
- const P = s.value[f] ?? s.value[s.value.length - 1];
333
- if (P) {
334
- await I(P.group_id);
713
+ deleteGroup: async (S) => {
714
+ const k = m.value.findIndex((U) => U.group_id === S);
715
+ if (await Ye(t, S), m.value = m.value.filter((U) => U.group_id !== S), u && p(m.value), c.value !== S) return;
716
+ const D = m.value[k] ?? m.value[m.value.length - 1];
717
+ if (D) {
718
+ await T(D.group_id);
335
719
  return;
336
720
  }
337
- u ? await _(h) : (i.value = "", t.value = []);
721
+ l ? await P(y) : (c.value = "", n.value = []);
338
722
  },
339
- selectGroup: I,
340
- loadMessages: U
723
+ selectGroup: T,
724
+ loadMessages: E
341
725
  };
342
- }, We = (e) => {
343
- const { api: l, defaultEntryId: h, entryGroup: w = "智能助手", autoLoad: u = !0 } = e, L = p([]), v = p(null), o = p(!1), C = (i) => i ? typeof l.getFileUrl == "function" ? l.getFileUrl(i) : Qe(i, "", "/algorithm/get_file_data") : "", Q = (i) => {
344
- v.value = i;
345
- }, s = async () => {
346
- var i;
347
- o.value = !0;
726
+ }, mt = (e) => {
727
+ const { api: t, defaultEntryId: y, entryGroup: h = "智能助手", autoLoad: l = !0 } = e, A = G([]), w = G(null), u = G(!1), R = (c) => c ? typeof t.getFileUrl == "function" ? t.getFileUrl(c) : et(c, "", "/algorithm/get_file_data") : "", x = (c) => {
728
+ w.value = c;
729
+ }, m = async () => {
730
+ var c;
731
+ u.value = !0;
348
732
  try {
349
- let t = h || ((i = v.value) == null ? void 0 : i.entry_id);
350
- if (!t)
733
+ let n = y || ((c = w.value) == null ? void 0 : c.entry_id);
734
+ if (!n)
351
735
  try {
352
- const y = await l.getDefaultLlmId();
353
- t = y == null ? void 0 : y.default_entry_id;
354
- } catch (y) {
355
- console.warn("[useAgent] 获取默认智能体 ID 失败:", y);
736
+ const v = await t.getDefaultLlmId();
737
+ n = v == null ? void 0 : v.default_entry_id;
738
+ } catch (v) {
739
+ console.warn("[useAgent] 获取默认智能体 ID 失败:", v);
356
740
  }
357
- const n = await l.getLlmEntryListByRole({ entry_group: w }), d = ((n == null ? void 0 : n.values) || []).filter((y) => y.entry_enable !== !1);
358
- if (L.value = d, t) {
359
- const y = d.find((A) => A.entry_id === t);
360
- y ? v.value = y : d.length > 0 && (v.value = d[0]);
361
- } else d.length > 0 && !v.value && (v.value = d[0]);
741
+ const f = await t.getLlmEntryListByRole({ entry_group: h }), s = ((f == null ? void 0 : f.values) || []).filter((v) => v.entry_enable !== !1);
742
+ if (A.value = s, n) {
743
+ const v = s.find((p) => p.entry_id === n);
744
+ v ? w.value = v : s.length > 0 && (w.value = s[0]);
745
+ } else s.length > 0 && !w.value && (w.value = s[0]);
746
+ } finally {
747
+ u.value = !1;
748
+ }
749
+ };
750
+ return l && (we() ? Pe(() => {
751
+ m();
752
+ }) : m()), {
753
+ agentList: A,
754
+ currentAgent: w,
755
+ loading: u,
756
+ getFileUrl: R,
757
+ loadAgents: m,
758
+ selectAgent: x
759
+ };
760
+ }, St = (e) => {
761
+ const { api: t, interval: y = 5e3, immediate: h = !1 } = e, l = G([]), A = G(/* @__PURE__ */ new Set());
762
+ let w = null, u = null;
763
+ const R = de(() => {
764
+ const s = new Set(A.value);
765
+ return l.value.forEach((v) => v.history_group && s.add(String(v.history_group))), s;
766
+ }), x = (s) => !!s && R.value.has(s), m = (s, v) => {
767
+ if (!s) return;
768
+ const p = new Set(A.value);
769
+ if (v ? p.add(s) : p.delete(s), A.value = p, !v) {
770
+ const I = u;
771
+ (async () => (I && await I, await n()))();
772
+ }
773
+ }, c = (s) => l.value.find(
774
+ (v) => String(v.history_group) === s && v.is_connected !== !0 && !A.value.has(s)
775
+ ), n = () => u || (u = (async () => {
776
+ if (!t.getChatTaskList) return l.value;
777
+ try {
778
+ const s = (await t.getChatTaskList()).filter((v) => v && v.is_stop !== !0);
779
+ if (l.value = s, e.onUnknownGroups && e.isKnownGroup) {
780
+ const v = s.map((p) => String(p.history_group)).filter((p) => p && !e.isKnownGroup(p));
781
+ v.length && e.onUnknownGroups(v);
782
+ }
783
+ } catch {
362
784
  } finally {
363
- o.value = !1;
785
+ u = null;
364
786
  }
787
+ return l.value;
788
+ })(), u), f = () => {
789
+ w || !y || (n(), w = setInterval(() => void n(), y));
790
+ }, d = () => {
791
+ w && clearInterval(w), w = null, l.value = [];
365
792
  };
366
- return u && (oe() ? xe(() => {
367
- s();
368
- }) : s()), {
369
- agentList: L,
370
- currentAgent: v,
371
- loading: o,
372
- getFileUrl: C,
373
- loadAgents: s,
374
- selectAgent: Q
793
+ return h && f(), we() && Ee(d), { tasks: l, runningIds: R, isRunning: x, setLocalRunning: m, findResumableTask: c, refresh: n, start: f, stop: d };
794
+ }, Gt = (e) => {
795
+ const { api: t, maxRooms: y = 10 } = e, h = je(/* @__PURE__ */ new Map()), l = G(""), A = St({
796
+ api: t,
797
+ interval: e.taskPollInterval ?? 5e3,
798
+ onUnknownGroups: e.onUnknownGroups,
799
+ isKnownGroup: e.isKnownGroup
800
+ }), w = (n) => {
801
+ if (h.size <= y) return;
802
+ const f = [...h.entries()].filter(([d, s]) => d !== l.value && d !== n && !s.chat.talking.value).sort((d, s) => d[1].touchedAt - s[1].touchedAt);
803
+ for (; h.size > y && f.length; ) {
804
+ const [d] = f.shift();
805
+ x(d);
806
+ }
807
+ }, u = (n) => {
808
+ const f = h.get(n);
809
+ if (f)
810
+ return f.touchedAt = Date.now(), f.chat;
811
+ const d = De(!0), s = d.run(
812
+ () => {
813
+ var p;
814
+ return Fe({
815
+ ...(p = e.roomOptions) == null ? void 0 : p.call(e, n),
816
+ api: t,
817
+ autoLogin: !1,
818
+ parsers: e.parsers,
819
+ beforeKnowledgeRender: e.beforeKnowledgeRender,
820
+ actionExecute: e.actionExecute,
821
+ lastCount: e.lastCount,
822
+ syncMetaOnFinish: !0,
823
+ onRunningChange: A.setLocalRunning
824
+ });
825
+ }
826
+ ), v = { chat: s, scope: d, loaded: s.loadGroup(n).catch(() => {
827
+ }), touchedAt: Date.now() };
828
+ return h.set(n, v), w(n), s;
829
+ }, R = async (n) => {
830
+ var s;
831
+ if (l.value = n, !n) return;
832
+ const f = u(n);
833
+ if (await ((s = h.get(n)) == null ? void 0 : s.loaded), f.talking.value) return;
834
+ await A.refresh();
835
+ const d = A.findResumableTask(n);
836
+ d && l.value === n && f.resumeTask({ history_id: d.history_id, history_group_id: String(d.history_group), question: d.question });
837
+ }, x = (n) => {
838
+ const f = h.get(n);
839
+ f && (f.chat.stopQuestion(!1), f.scope.stop(), h.delete(n), l.value === n && (l.value = ""));
840
+ }, m = () => {
841
+ [...h.keys()].forEach(x), A.stop();
842
+ }, c = de(() => {
843
+ var n;
844
+ return l.value ? ((n = h.get(l.value)) == null ? void 0 : n.chat) ?? null : null;
845
+ });
846
+ return Ue() && Me(m), { activeId: l, active: c, running: A, getRoom: u, open: R, dispose: x, disposeAll: m };
847
+ }, _t = (e) => {
848
+ if (!e || typeof localStorage > "u") return {};
849
+ try {
850
+ const t = JSON.parse(localStorage.getItem(e) || "{}");
851
+ return t && typeof t == "object" ? t : {};
852
+ } catch {
853
+ return {};
854
+ }
855
+ }, At = (e, t) => {
856
+ if (!(!e || typeof localStorage > "u"))
857
+ try {
858
+ localStorage.setItem(e, JSON.stringify(t));
859
+ } catch {
860
+ }
861
+ }, It = (e) => {
862
+ const t = e.storageKey === void 0 ? "wi-chat-room-llm" : e.storageKey, y = G([]), h = G(!1), l = G(_t(t)), A = de(() => new Set(y.value.flatMap((s) => (s.children ?? []).map((v) => v.id)))), w = (s) => {
863
+ l.value = s, At(t, s);
375
864
  };
376
- }, je = (e = {}) => {
377
- const l = e.parsers ?? [];
378
- let h = null, w;
379
- const u = ke({
865
+ let u = null;
866
+ const R = () => h.value ? Promise.resolve() : u || (u = (async () => {
867
+ var s, v;
868
+ try {
869
+ const p = await ((v = (s = e.api).getLlmInfoList) == null ? void 0 : v.call(s));
870
+ if (!p) return;
871
+ const I = p.connections ?? [];
872
+ y.value = (p.factorys ?? []).map((T) => ({
873
+ id: T.factory_id,
874
+ name: T.factory_title,
875
+ type: "factory",
876
+ children: I.filter((C) => C.factory_id === T.factory_id).map((C) => ({ id: C.connect_id, name: C.connect_title, type: "connection" }))
877
+ })).filter((T) => T.children.length > 0), h.value = !0;
878
+ const E = Object.entries(l.value).filter(([, T]) => A.value.has(T));
879
+ E.length !== Object.keys(l.value).length && w(Object.fromEntries(E));
880
+ } catch {
881
+ } finally {
882
+ u = null;
883
+ }
884
+ })(), u), x = (s) => !!s && (!h.value || A.value.has(s));
885
+ return { llmTree: y, loaded: h, roomLlmMap: l, validIds: A, load: R, resolve: (s, v) => {
886
+ const p = s ? l.value[s] : "";
887
+ return p && x(p) ? p : v || "";
888
+ }, select: (s, v, p) => {
889
+ if (!s) return;
890
+ const I = { ...l.value };
891
+ v && v !== p ? I[s] = v : delete I[s], w(I);
892
+ }, migrate: (s, v) => {
893
+ const p = l.value[s];
894
+ if (!p || s === v) return;
895
+ const I = { ...l.value, [v]: p };
896
+ delete I[s], w(I);
897
+ }, nameOf: (s) => {
898
+ var v;
899
+ if (!s) return "";
900
+ for (const p of y.value) {
901
+ const I = (v = p.children) == null ? void 0 : v.find((E) => E.id === s);
902
+ if (I) return I.name;
903
+ }
904
+ return "";
905
+ }, isUnavailable: (s) => !!s && h.value && !A.value.has(s) };
906
+ }, Ce = async (e) => {
907
+ var h;
908
+ if (typeof navigator < "u" && ((h = navigator.clipboard) != null && h.writeText))
909
+ try {
910
+ await navigator.clipboard.writeText(e);
911
+ return;
912
+ } catch {
913
+ }
914
+ if (typeof document > "u") throw new Error("当前环境不支持剪贴板");
915
+ const t = document.createElement("textarea");
916
+ t.value = e, t.style.position = "fixed", t.style.opacity = "0", document.body.appendChild(t), t.select();
917
+ const y = document.execCommand("copy");
918
+ if (document.body.removeChild(t), !y) throw new Error("复制失败");
919
+ }, Ct = (e) => {
920
+ const { api: t, buildShareUrl: y, shareDays: h = 1 } = e, l = (c) => !!Ge(c.answer), A = async (c, n = !1) => {
921
+ const f = Ge(c.answer);
922
+ if (!f) return !1;
923
+ try {
924
+ return await Ce(n ? f : tt(f)), !0;
925
+ } catch {
926
+ return !1;
927
+ }
928
+ }, w = (c) => Ke(c.answer).state, u = /* @__PURE__ */ new WeakSet();
929
+ return { canCopy: l, copy: A, stateOf: w, toggleState: async (c, n) => {
930
+ if (!(!c.historyId || !t.setHistoryAnswerState || u.has(c))) {
931
+ u.add(c);
932
+ try {
933
+ const f = w(c) === n ? null : n;
934
+ await t.setHistoryAnswerState(c.historyId, f), c.answer.answer || (c.answer.answer = { reports: [] }), c.answer.answer.state = f;
935
+ } finally {
936
+ u.delete(c);
937
+ }
938
+ }
939
+ }, feedback: async (c, n) => {
940
+ !c.historyId || !n.trim() || !t.reportHistoryProblem || await t.reportHistoryProblem(c.historyId, n.trim());
941
+ }, share: async (c) => {
942
+ if (!c.historyId || !t.shareChatHistory) throw new Error("当前回答暂不支持分享");
943
+ const n = await t.shareChatHistory([c.historyId], h), f = y(n);
944
+ return await Ce(f), f;
945
+ } };
946
+ }, Et = (e = {}) => {
947
+ const t = e.parsers ?? [];
948
+ let y = null, h;
949
+ const l = Fe({
380
950
  ...e.chat,
381
- parsers: l,
382
- onFirstQuestion: ({ question: t, groupId: n }) => {
383
- w == null || w(n, t);
951
+ parsers: t,
952
+ onFirstQuestion: ({ question: n, groupId: f }) => {
953
+ h == null || h(f, n);
384
954
  }
385
- }), L = He({
955
+ }), A = pt({
386
956
  ...e.history,
387
- api: u.api,
957
+ api: l.api,
388
958
  autoLoadMessages: !1,
389
- parsers: l
959
+ parsers: t
390
960
  });
391
- w = (t, n) => {
392
- h = L.renameGroup(t, n).catch((m) => {
393
- var d;
394
- (d = e.onError) == null || d.call(e, m, "groups");
961
+ h = (n, f) => {
962
+ y = A.renameGroup(n, f).catch((d) => {
963
+ var s;
964
+ (s = e.onError) == null || s.call(e, d, "groups");
395
965
  });
396
966
  };
397
- const v = We({
967
+ const w = mt({
398
968
  ...e.agent,
399
- api: u.api,
969
+ api: l.api,
400
970
  autoLoad: !1
401
- }), o = (t, n) => {
402
- var m;
403
- (m = e.onError) == null || m.call(e, t, n);
404
- }, C = async () => {
971
+ }), u = (n, f) => {
972
+ var d;
973
+ (d = e.onError) == null || d.call(e, n, f);
974
+ }, R = async () => {
405
975
  try {
406
- await L.loadGroups();
407
- } catch (t) {
408
- o(t, "groups");
976
+ await A.loadGroups();
977
+ } catch (n) {
978
+ u(n, "groups");
409
979
  }
410
- }, Q = async (t) => {
980
+ }, x = async (n) => {
411
981
  try {
412
- await u.loadGroup(t);
413
- } catch (n) {
414
- o(n, "messages");
982
+ await l.loadGroup(n);
983
+ } catch (f) {
984
+ u(f, "messages");
415
985
  }
416
- }, s = async () => {
986
+ }, m = async () => {
417
987
  try {
418
- await v.loadAgents();
419
- } catch (t) {
420
- o(t, "agents");
988
+ await w.loadAgents();
989
+ } catch (n) {
990
+ u(n, "agents");
421
991
  }
422
- }, i = async (t) => {
423
- var d;
424
- const n = typeof t == "string" ? { text: t } : t;
425
- await u.submitQuestion({
426
- ...n,
427
- entryId: (n == null ? void 0 : n.entryId) ?? ((d = v.currentAgent.value) == null ? void 0 : d.entry_id)
992
+ }, c = async (n) => {
993
+ var s;
994
+ const f = typeof n == "string" ? { text: n } : n;
995
+ await l.submitQuestion({
996
+ ...f,
997
+ entryId: (f == null ? void 0 : f.entryId) ?? ((s = w.currentAgent.value) == null ? void 0 : s.entry_id)
428
998
  });
429
- const m = h;
430
- h = null, m && await m, await C();
999
+ const d = y;
1000
+ y = null, d && await d, await R();
431
1001
  };
432
- return re(u.session, (t) => {
433
- t && (C(), s());
434
- }), re(L.activeGroupId, (t) => {
435
- t && Q(t);
1002
+ return ke(l.session, (n) => {
1003
+ n && (R(), m());
1004
+ }), ke(A.activeGroupId, (n) => {
1005
+ n && x(n);
436
1006
  }), {
437
- chat: u,
438
- history: L,
439
- agent: v,
440
- parsers: l,
441
- messages: u.messages,
442
- question: u.question,
443
- incPrevQuestion: u.incPrevQuestion,
444
- talking: u.talking,
445
- loading: u.loading,
446
- session: u.session,
447
- groups: L.groups,
448
- activeGroupId: L.activeGroupId,
449
- historyLoading: L.loading,
450
- agentList: v.agentList,
451
- currentAgent: v.currentAgent,
452
- agentLoading: v.loading,
453
- hasMore: u.hasMore,
454
- loadMoreLoading: u.loadMoreLoading,
455
- loadGroup: Q,
456
- loadOlder: u.loadOlder,
457
- refreshGroups: C,
458
- loadAgents: s,
459
- selectAgent: v.selectAgent,
460
- getFileUrl: v.getFileUrl,
461
- submitQuestion: i,
462
- sendWsMessage: u.sendWsMessage,
463
- stopQuestion: u.stopQuestion
1007
+ chat: l,
1008
+ history: A,
1009
+ agent: w,
1010
+ parsers: t,
1011
+ messages: l.messages,
1012
+ question: l.question,
1013
+ incPrevQuestion: l.incPrevQuestion,
1014
+ talking: l.talking,
1015
+ loading: l.loading,
1016
+ session: l.session,
1017
+ groups: A.groups,
1018
+ activeGroupId: A.activeGroupId,
1019
+ historyLoading: A.loading,
1020
+ agentList: w.agentList,
1021
+ currentAgent: w.currentAgent,
1022
+ agentLoading: w.loading,
1023
+ hasMore: l.hasMore,
1024
+ loadMoreLoading: l.loadMoreLoading,
1025
+ loadGroup: x,
1026
+ loadOlder: l.loadOlder,
1027
+ refreshGroups: R,
1028
+ loadAgents: m,
1029
+ selectAgent: w.selectAgent,
1030
+ getFileUrl: w.getFileUrl,
1031
+ submitQuestion: c,
1032
+ sendWsMessage: l.sendWsMessage,
1033
+ stopQuestion: l.stopQuestion
464
1034
  };
465
1035
  };
466
1036
  export {
467
- We as useAgent,
468
- ke as useChat,
469
- je as useChatSession,
470
- He as useHistory
1037
+ dt as createLocalCredentialStore,
1038
+ ft as createLocalKeyCredentialStore,
1039
+ ct as createRenewer,
1040
+ mt as useAgent,
1041
+ Ct as useAnswerActions,
1042
+ Fe as useChat,
1043
+ xt as useChatAuth,
1044
+ Gt as useChatRooms,
1045
+ Et as useChatSession,
1046
+ pt as useHistory,
1047
+ ot as useKeepAlive,
1048
+ It as useLlm,
1049
+ St as useRunningGroups
471
1050
  };
472
1051
  //# sourceMappingURL=index.js.map