teodor-new-chat-ui 4.3.401 → 4.3.402
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.
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Chat App - Complete chat application with sidebar layout
|
|
3
3
|
* Combines all chat components into a ready-to-use chat interface
|
|
4
4
|
*/
|
|
5
|
-
import { type ChatProvidersProps } from "@/features/
|
|
5
|
+
import { type ChatProvidersProps } from "@/features/core/contexts/providers/ChatProviders";
|
|
6
6
|
export interface ChatAppProps extends Omit<ChatProvidersProps, 'children'> {
|
|
7
7
|
layout?: 'sidebar' | 'fullscreen' | 'tabs';
|
|
8
8
|
layoutSize?: 'phone' | 'tablet' | 'desktop' | 'half-screen';
|
package/dist/index.esm.js
CHANGED
|
@@ -2,7 +2,7 @@ var bg = Object.defineProperty;
|
|
|
2
2
|
var yg = (e, t, n) => t in e ? bg(e, t, { enumerable: !0, configurable: !0, writable: !0, value: n }) : e[t] = n;
|
|
3
3
|
var zl = (e, t, n) => yg(e, typeof t != "symbol" ? t + "" : t, n);
|
|
4
4
|
import * as h from "react";
|
|
5
|
-
import M, { useMemo as He,
|
|
5
|
+
import M, { useMemo as He, useContext as ys, createContext as io, useState as we, useRef as Ze, useEffect as ht, useCallback as be, useReducer as Sg, useLayoutEffect as Tg, createElement as Ho, memo as Cg, useImperativeHandle as kg, forwardRef as Eg, isValidElement as ua } from "react";
|
|
6
6
|
import { Slot as Rg, createSlot as Tr, createSlottable as Ig } from "@radix-ui/react-slot";
|
|
7
7
|
import { cva as lo } from "class-variance-authority";
|
|
8
8
|
import { clsx as Ng } from "clsx";
|
|
@@ -2934,31 +2934,12 @@ async function Fv(e, t = 50, n = 0) {
|
|
|
2934
2934
|
const r = { limit: t, offset: n };
|
|
2935
2935
|
return e && (r.thread_id = e), await en("/files", { params: r });
|
|
2936
2936
|
}
|
|
2937
|
-
|
|
2938
|
-
|
|
2939
|
-
const n = er;
|
|
2940
|
-
if (t) {
|
|
2941
|
-
const o = n.baseUrl, s = n.getAuthToken();
|
|
2942
|
-
t.baseUrl && t.baseUrl !== o && n.updateConfig({
|
|
2943
|
-
baseUrl: t.baseUrl
|
|
2944
|
-
}), t.apiKey !== void 0 && t.apiKey !== s && n.updateConfig({
|
|
2945
|
-
authToken: t.apiKey
|
|
2946
|
-
});
|
|
2947
|
-
}
|
|
2948
|
-
const r = {
|
|
2949
|
-
token: n.getAuthToken(),
|
|
2950
|
-
setToken: (o) => n.setAuthToken(o),
|
|
2951
|
-
api: n,
|
|
2952
|
-
baseUrl: n.baseUrl
|
|
2953
|
-
};
|
|
2954
|
-
return /* @__PURE__ */ u.jsx(rd.Provider, { value: r, children: e });
|
|
2955
|
-
}
|
|
2956
|
-
function od() {
|
|
2957
|
-
const e = ys(rd);
|
|
2937
|
+
function rd() {
|
|
2938
|
+
const e = ys(ld);
|
|
2958
2939
|
if (!e) throw new Error("useApi must be used within ApiProvider");
|
|
2959
2940
|
return e;
|
|
2960
2941
|
}
|
|
2961
|
-
async function
|
|
2942
|
+
async function Bv(e) {
|
|
2962
2943
|
return await new Promise((t, n) => {
|
|
2963
2944
|
const r = new FileReader();
|
|
2964
2945
|
r.onload = () => {
|
|
@@ -2974,11 +2955,11 @@ async function zv(e) {
|
|
|
2974
2955
|
}, r.onerror = (o) => n(o), r.readAsArrayBuffer(e);
|
|
2975
2956
|
});
|
|
2976
2957
|
}
|
|
2977
|
-
async function
|
|
2958
|
+
async function zv(e = []) {
|
|
2978
2959
|
const t = [], n = [];
|
|
2979
2960
|
for (const r of e)
|
|
2980
2961
|
try {
|
|
2981
|
-
const o = await
|
|
2962
|
+
const o = await Bv(r);
|
|
2982
2963
|
n.push({
|
|
2983
2964
|
filename: r.name,
|
|
2984
2965
|
data: o,
|
|
@@ -2992,24 +2973,24 @@ function wr(e) {
|
|
|
2992
2973
|
if (!(typeof globalThis > "u"))
|
|
2993
2974
|
return globalThis[e];
|
|
2994
2975
|
}
|
|
2995
|
-
function
|
|
2976
|
+
function Hv(e) {
|
|
2996
2977
|
if (typeof e != "string") return;
|
|
2997
2978
|
const t = e.trim();
|
|
2998
2979
|
if (t)
|
|
2999
2980
|
return Rn(t);
|
|
3000
2981
|
}
|
|
3001
|
-
function
|
|
2982
|
+
function od() {
|
|
3002
2983
|
const e = [
|
|
3003
2984
|
wr("__API_BASE_URL__"),
|
|
3004
2985
|
wr("__CHAT_API_BASE_URL__"),
|
|
3005
2986
|
wr("__CHAT_API_URL__")
|
|
3006
2987
|
];
|
|
3007
2988
|
for (const t of e) {
|
|
3008
|
-
const n =
|
|
2989
|
+
const n = Hv(t);
|
|
3009
2990
|
if (n) return n;
|
|
3010
2991
|
}
|
|
3011
2992
|
}
|
|
3012
|
-
function
|
|
2993
|
+
function sd() {
|
|
3013
2994
|
const e = [
|
|
3014
2995
|
wr("__API_AUTH_TOKEN__"),
|
|
3015
2996
|
wr("__CHAT_API_KEY__"),
|
|
@@ -3019,25 +3000,25 @@ function ad() {
|
|
|
3019
3000
|
if (typeof t == "string" && t.trim())
|
|
3020
3001
|
return t.trim();
|
|
3021
3002
|
}
|
|
3022
|
-
function
|
|
3003
|
+
function ad(...e) {
|
|
3023
3004
|
for (const t of e)
|
|
3024
3005
|
if (typeof t == "string" && t.trim())
|
|
3025
3006
|
return Rn(t);
|
|
3026
3007
|
return Rn();
|
|
3027
3008
|
}
|
|
3028
|
-
function
|
|
3029
|
-
const e = {}, t =
|
|
3009
|
+
function Uv() {
|
|
3010
|
+
const e = {}, t = od(), n = sd();
|
|
3030
3011
|
return t && (e.baseUrl = t), n && (e.apiKey = n), e;
|
|
3031
3012
|
}
|
|
3032
|
-
function
|
|
3033
|
-
const e =
|
|
3013
|
+
function Wv() {
|
|
3014
|
+
const e = Uv(), t = er.getAuthToken(), n = od();
|
|
3034
3015
|
return {
|
|
3035
|
-
apiBaseUrl:
|
|
3016
|
+
apiBaseUrl: ad(
|
|
3036
3017
|
e.baseUrl,
|
|
3037
3018
|
er.baseUrl,
|
|
3038
3019
|
n
|
|
3039
3020
|
),
|
|
3040
|
-
apiKey: t || e.apiKey ||
|
|
3021
|
+
apiKey: t || e.apiKey || sd() || "",
|
|
3041
3022
|
model: "gpt-4",
|
|
3042
3023
|
temperature: 0.7,
|
|
3043
3024
|
maxTokens: 4096,
|
|
@@ -3049,35 +3030,35 @@ function Vv() {
|
|
|
3049
3030
|
messageHistory: 100
|
|
3050
3031
|
};
|
|
3051
3032
|
}
|
|
3052
|
-
const
|
|
3053
|
-
function
|
|
3033
|
+
const id = "chat-settings";
|
|
3034
|
+
function Vv() {
|
|
3054
3035
|
try {
|
|
3055
|
-
const e = localStorage.getItem(
|
|
3036
|
+
const e = localStorage.getItem(id);
|
|
3056
3037
|
return e ? JSON.parse(e) : {};
|
|
3057
3038
|
} catch (e) {
|
|
3058
3039
|
return console.error("Failed to parse stored settings:", e), {};
|
|
3059
3040
|
}
|
|
3060
3041
|
}
|
|
3061
|
-
function
|
|
3042
|
+
function Kv(e) {
|
|
3062
3043
|
try {
|
|
3063
3044
|
const t = {
|
|
3064
3045
|
...e,
|
|
3065
3046
|
apiBaseUrl: Rn(e.apiBaseUrl)
|
|
3066
3047
|
};
|
|
3067
|
-
localStorage.setItem(
|
|
3048
|
+
localStorage.setItem(id, JSON.stringify(t)), t.apiKey && er.setAuthToken(t.apiKey);
|
|
3068
3049
|
} catch (t) {
|
|
3069
3050
|
console.error("Failed to save settings:", t);
|
|
3070
3051
|
}
|
|
3071
3052
|
}
|
|
3072
3053
|
function FI() {
|
|
3073
|
-
const e =
|
|
3054
|
+
const e = Wv(), t = Vv(), n = er.getAuthToken(), r = typeof t.apiBaseUrl == "string" ? t.apiBaseUrl : void 0;
|
|
3074
3055
|
return {
|
|
3075
3056
|
...e,
|
|
3076
3057
|
...t,
|
|
3077
3058
|
// Always use the current token from API client if available
|
|
3078
3059
|
apiKey: n || t.apiKey || e.apiKey,
|
|
3079
3060
|
// Always use the current base URL from API client
|
|
3080
|
-
apiBaseUrl:
|
|
3061
|
+
apiBaseUrl: ad(
|
|
3081
3062
|
er.baseUrl,
|
|
3082
3063
|
r,
|
|
3083
3064
|
e.apiBaseUrl
|
|
@@ -3088,7 +3069,26 @@ function BI(e) {
|
|
|
3088
3069
|
er.updateConfig({
|
|
3089
3070
|
baseUrl: e.apiBaseUrl,
|
|
3090
3071
|
authToken: e.apiKey ?? void 0
|
|
3091
|
-
}),
|
|
3072
|
+
}), Kv(e);
|
|
3073
|
+
}
|
|
3074
|
+
const ld = io(null);
|
|
3075
|
+
function qv({ children: e, apiConfig: t }) {
|
|
3076
|
+
const n = er;
|
|
3077
|
+
if (t) {
|
|
3078
|
+
const o = n.baseUrl, s = n.getAuthToken();
|
|
3079
|
+
t.baseUrl && t.baseUrl !== o && n.updateConfig({
|
|
3080
|
+
baseUrl: t.baseUrl
|
|
3081
|
+
}), t.apiKey !== void 0 && t.apiKey !== s && n.updateConfig({
|
|
3082
|
+
authToken: t.apiKey
|
|
3083
|
+
});
|
|
3084
|
+
}
|
|
3085
|
+
const r = {
|
|
3086
|
+
token: n.getAuthToken(),
|
|
3087
|
+
setToken: (o) => n.setAuthToken(o),
|
|
3088
|
+
api: n,
|
|
3089
|
+
baseUrl: n.baseUrl
|
|
3090
|
+
};
|
|
3091
|
+
return /* @__PURE__ */ u.jsx(ld.Provider, { value: r, children: e });
|
|
3092
3092
|
}
|
|
3093
3093
|
function Gv({
|
|
3094
3094
|
api: e,
|
|
@@ -4342,7 +4342,7 @@ function Sw({
|
|
|
4342
4342
|
onConnectionError: l,
|
|
4343
4343
|
onToolEnd: c
|
|
4344
4344
|
}) {
|
|
4345
|
-
const { api: d, baseUrl: p } =
|
|
4345
|
+
const { api: d, baseUrl: p } = rd(), m = He(() => Rn(p), [p]), { state: f, seed: v, prepend: g, pushUser: x, onEvent: b } = hw(), {
|
|
4346
4346
|
threads: w,
|
|
4347
4347
|
currentThreadId: y,
|
|
4348
4348
|
setCurrentThreadId: C,
|
|
@@ -4455,7 +4455,7 @@ function Sw({
|
|
|
4455
4455
|
).join("").slice(0, 16);
|
|
4456
4456
|
vt = `${We}${ut}`, L(vt), C(vt);
|
|
4457
4457
|
}
|
|
4458
|
-
const { contentParts: bt, filesInfo: Xe } = await
|
|
4458
|
+
const { contentParts: bt, filesInfo: Xe } = await zv(
|
|
4459
4459
|
Ke
|
|
4460
4460
|
), wt = [...bt];
|
|
4461
4461
|
yt && wt.push({ type: "text", text: st });
|
|
@@ -4603,7 +4603,7 @@ function qo({
|
|
|
4603
4603
|
onThreadChange: c,
|
|
4604
4604
|
onToolEnd: d
|
|
4605
4605
|
}) {
|
|
4606
|
-
return /* @__PURE__ */ u.jsx(
|
|
4606
|
+
return /* @__PURE__ */ u.jsx(qv, { apiConfig: t, children: /* @__PURE__ */ u.jsx(
|
|
4607
4607
|
Sw,
|
|
4608
4608
|
{
|
|
4609
4609
|
initialThreadId: n,
|
|
@@ -16413,7 +16413,7 @@ function ns({
|
|
|
16413
16413
|
onExcelUploadSuccess: v,
|
|
16414
16414
|
onError: g
|
|
16415
16415
|
}) {
|
|
16416
|
-
const { api: x } =
|
|
16416
|
+
const { api: x } = rd(), { currentThreadId: b } = Oi(), {
|
|
16417
16417
|
threadId: w,
|
|
16418
16418
|
messages: y,
|
|
16419
16419
|
isHistoryLoading: C,
|
|
@@ -19212,7 +19212,7 @@ const i1 = ({ ...e }) => {
|
|
|
19212
19212
|
export {
|
|
19213
19213
|
DI as Api,
|
|
19214
19214
|
OI as ApiClient,
|
|
19215
|
-
|
|
19215
|
+
qv as ApiProvider,
|
|
19216
19216
|
ck as Badge,
|
|
19217
19217
|
mt as Button,
|
|
19218
19218
|
Mh as Card,
|
|
@@ -19246,7 +19246,7 @@ export {
|
|
|
19246
19246
|
so as MarkdownContent,
|
|
19247
19247
|
Ol as MessageComponent,
|
|
19248
19248
|
Uh as MessageList,
|
|
19249
|
-
|
|
19249
|
+
id as SETTINGS_STORAGE_KEY,
|
|
19250
19250
|
Up as ScrollArea,
|
|
19251
19251
|
YI as Select,
|
|
19252
19252
|
TE as SelectContent,
|
|
@@ -19280,32 +19280,32 @@ export {
|
|
|
19280
19280
|
mc as del,
|
|
19281
19281
|
$v as downloadFileById,
|
|
19282
19282
|
ql as extractConfigFields,
|
|
19283
|
-
|
|
19283
|
+
Bv as fileToBase64,
|
|
19284
19284
|
en as get,
|
|
19285
19285
|
Pv as getChatToken,
|
|
19286
19286
|
FI as getCurrentSettings,
|
|
19287
|
-
|
|
19288
|
-
|
|
19287
|
+
Uv as getDefaultApiConfig,
|
|
19288
|
+
Wv as getDefaultChatSettings,
|
|
19289
19289
|
gc as getFileContent,
|
|
19290
19290
|
$I as getFileInfo,
|
|
19291
19291
|
_u as getPreviewForMessage,
|
|
19292
19292
|
on as httpClient,
|
|
19293
19293
|
Vn as hydrateHistorySnapshots,
|
|
19294
19294
|
Fv as listFiles,
|
|
19295
|
-
|
|
19295
|
+
Vv as loadStoredSettings,
|
|
19296
19296
|
Mv as onChatTokenChanged,
|
|
19297
19297
|
ga as post,
|
|
19298
|
-
|
|
19298
|
+
zv as processAttachments,
|
|
19299
19299
|
Lv as put,
|
|
19300
19300
|
Qg as readNumber,
|
|
19301
19301
|
pr as readString,
|
|
19302
19302
|
Rn as resolveChatBaseUrl,
|
|
19303
19303
|
qg as resolveMessageMetadata,
|
|
19304
|
-
|
|
19304
|
+
Kv as saveSettings,
|
|
19305
19305
|
Ga as setChatToken,
|
|
19306
19306
|
Wr as toPlainObject,
|
|
19307
19307
|
zt as unwrap,
|
|
19308
|
-
|
|
19308
|
+
rd as useApi,
|
|
19309
19309
|
Zg as useCheckpointIndex,
|
|
19310
19310
|
Gg as useMessageMetadata,
|
|
19311
19311
|
Tw as useStreamingHook,
|
package/dist/index.umd.js
CHANGED
|
@@ -32,11 +32,11 @@ React keys must be passed directly to JSX without using spread:
|
|
|
32
32
|
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(t){return t instanceof this?t:new this(t)}static concat(t,...n){const r=new this(t);return n.forEach(o=>r.set(o)),r}static accessor(t){const r=(this[Sc]=this[Sc]={accessors:{}}).accessors,o=this.prototype;function s(i){const a=Ur(i);r[a]||(Vx(o,i),r[a]=!0)}return B.isArray(t)?t.forEach(s):s(t),this}};$t.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),B.reduceDescriptors($t.prototype,({value:e},t)=>{let n=t[0].toUpperCase()+t.slice(1);return{get:()=>e,set(r){this[n]=r}}}),B.freezeMethods($t);function xi(e,t){const n=this||Hr,r=t||n,o=$t.from(r.headers);let s=r.data;return B.forEach(e,function(a){s=a.call(n,s,o.normalize(),t?t.status:void 0)}),o.normalize(),s}function Cc(e){return!!(e&&e.__CANCEL__)}function fr(e,t,n){Le.call(this,e??"canceled",Le.ERR_CANCELED,t,n),this.name="CanceledError"}B.inherits(fr,Le,{__CANCEL__:!0});function Tc(e,t,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?e(n):t(new Le("Request failed with status code "+n.status,[Le.ERR_BAD_REQUEST,Le.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function Kx(e){const t=/^([-+\w]{1,25})(:?\/\/|:)/.exec(e);return t&&t[1]||""}function qx(e,t){e=e||10;const n=new Array(e),r=new Array(e);let o=0,s=0,i;return t=t!==void 0?t:1e3,function(l){const c=Date.now(),d=r[s];i||(i=c),n[o]=l,r[o]=c;let p=s,m=0;for(;p!==o;)m+=n[p++],p=p%e;if(o=(o+1)%e,o===s&&(s=(s+1)%e),c-i<t)return;const f=d&&c-d;return f?Math.round(m*1e3/f):void 0}}function Gx(e,t){let n=0,r=1e3/t,o,s;const i=(c,d=Date.now())=>{n=d,o=null,s&&(clearTimeout(s),s=null),e(...c)};return[(...c)=>{const d=Date.now(),p=d-n;p>=r?i(c,d):(o=c,s||(s=setTimeout(()=>{s=null,i(o)},r-p)))},()=>o&&i(o)]}const jo=(e,t,n=3)=>{let r=0;const o=qx(50,250);return Gx(s=>{const i=s.loaded,a=s.lengthComputable?s.total:void 0,l=i-r,c=o(l),d=i<=a;r=i;const p={loaded:i,total:a,progress:a?i/a:void 0,bytes:l,rate:c||void 0,estimated:c&&a&&d?(a-i)/c:void 0,event:s,lengthComputable:a!=null,[t?"download":"upload"]:!0};e(p)},n)},kc=(e,t)=>{const n=e!=null;return[r=>t[0]({lengthComputable:n,total:e,loaded:r}),t[1]]},Ec=e=>(...t)=>B.asap(()=>e(...t)),Yx=Nt.hasStandardBrowserEnv?((e,t)=>n=>(n=new URL(n,Nt.origin),e.protocol===n.protocol&&e.host===n.host&&(t||e.port===n.port)))(new URL(Nt.origin),Nt.navigator&&/(msie|trident)/i.test(Nt.navigator.userAgent)):()=>!0,Xx=Nt.hasStandardBrowserEnv?{write(e,t,n,r,o,s){const i=[e+"="+encodeURIComponent(t)];B.isNumber(n)&&i.push("expires="+new Date(n).toGMTString()),B.isString(r)&&i.push("path="+r),B.isString(o)&&i.push("domain="+o),s===!0&&i.push("secure"),document.cookie=i.join("; ")},read(e){const t=document.cookie.match(new RegExp("(^|;\\s*)("+e+")=([^;]*)"));return t?decodeURIComponent(t[3]):null},remove(e){this.write(e,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Jx(e){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(e)}function Zx(e,t){return t?e.replace(/\/?\/$/,"")+"/"+t.replace(/^\/+/,""):e}function Ic(e,t,n){let r=!Jx(t);return e&&(r||n==!1)?Zx(e,t):t}const Nc=e=>e instanceof $t?{...e}:e;function qn(e,t){t=t||{};const n={};function r(c,d,p,m){return B.isPlainObject(c)&&B.isPlainObject(d)?B.merge.call({caseless:m},c,d):B.isPlainObject(d)?B.merge({},d):B.isArray(d)?d.slice():d}function o(c,d,p,m){if(B.isUndefined(d)){if(!B.isUndefined(c))return r(void 0,c,p,m)}else return r(c,d,p,m)}function s(c,d){if(!B.isUndefined(d))return r(void 0,d)}function i(c,d){if(B.isUndefined(d)){if(!B.isUndefined(c))return r(void 0,c)}else return r(void 0,d)}function a(c,d,p){if(p in t)return r(c,d);if(p in e)return r(void 0,c)}const l={url:s,method:s,data:s,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(c,d,p)=>o(Nc(c),Nc(d),p,!0)};return B.forEach(Object.keys({...e,...t}),function(d){const p=l[d]||o,m=p(e[d],t[d],d);B.isUndefined(m)&&p!==a||(n[d]=m)}),n}const Ac=e=>{const t=qn({},e);let{data:n,withXSRFToken:r,xsrfHeaderName:o,xsrfCookieName:s,headers:i,auth:a}=t;if(t.headers=i=$t.from(i),t.url=vc(Ic(t.baseURL,t.url,t.allowAbsoluteUrls),e.params,e.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):""))),B.isFormData(n)){if(Nt.hasStandardBrowserEnv||Nt.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(B.isFunction(n.getHeaders)){const l=n.getHeaders(),c=["content-type","content-length"];Object.entries(l).forEach(([d,p])=>{c.includes(d.toLowerCase())&&i.set(d,p)})}}if(Nt.hasStandardBrowserEnv&&(r&&B.isFunction(r)&&(r=r(t)),r||r!==!1&&Yx(t.url))){const l=o&&s&&Xx.read(s);l&&i.set(o,l)}return t},Qx=typeof XMLHttpRequest<"u"&&function(e){return new Promise(function(n,r){const o=Ac(e);let s=o.data;const i=$t.from(o.headers).normalize();let{responseType:a,onUploadProgress:l,onDownloadProgress:c}=o,d,p,m,f,v;function g(){f&&f(),v&&v(),o.cancelToken&&o.cancelToken.unsubscribe(d),o.signal&&o.signal.removeEventListener("abort",d)}let x=new XMLHttpRequest;x.open(o.method.toUpperCase(),o.url,!0),x.timeout=o.timeout;function y(){if(!x)return;const S=$t.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),C={data:!a||a==="text"||a==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:S,config:e,request:x};Tc(function(E){n(E),g()},function(E){r(E),g()},C),x=null}"onloadend"in x?x.onloadend=y:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.indexOf("file:")===0)||setTimeout(y)},x.onabort=function(){x&&(r(new Le("Request aborted",Le.ECONNABORTED,e,x)),x=null)},x.onerror=function(k){const C=k&&k.message?k.message:"Network Error",T=new Le(C,Le.ERR_NETWORK,e,x);T.event=k||null,r(T),x=null},x.ontimeout=function(){let k=o.timeout?"timeout of "+o.timeout+"ms exceeded":"timeout exceeded";const C=o.transitional||bc;o.timeoutErrorMessage&&(k=o.timeoutErrorMessage),r(new Le(k,C.clarifyTimeoutError?Le.ETIMEDOUT:Le.ECONNABORTED,e,x)),x=null},s===void 0&&i.setContentType(null),"setRequestHeader"in x&&B.forEach(i.toJSON(),function(k,C){x.setRequestHeader(C,k)}),B.isUndefined(o.withCredentials)||(x.withCredentials=!!o.withCredentials),a&&a!=="json"&&(x.responseType=o.responseType),c&&([m,v]=jo(c,!0),x.addEventListener("progress",m)),l&&x.upload&&([p,f]=jo(l),x.upload.addEventListener("progress",p),x.upload.addEventListener("loadend",f)),(o.cancelToken||o.signal)&&(d=S=>{x&&(r(!S||S.type?new fr(null,e,x):S),x.abort(),x=null)},o.cancelToken&&o.cancelToken.subscribe(d),o.signal&&(o.signal.aborted?d():o.signal.addEventListener("abort",d)));const w=Kx(o.url);if(w&&Nt.protocols.indexOf(w)===-1){r(new Le("Unsupported protocol "+w+":",Le.ERR_BAD_REQUEST,e));return}x.send(s||null)})},ev=(e,t)=>{const{length:n}=e=e?e.filter(Boolean):[];if(t||n){let r=new AbortController,o;const s=function(c){if(!o){o=!0,a();const d=c instanceof Error?c:this.reason;r.abort(d instanceof Le?d:new fr(d instanceof Error?d.message:d))}};let i=t&&setTimeout(()=>{i=null,s(new Le(`timeout ${t} of ms exceeded`,Le.ETIMEDOUT))},t);const a=()=>{e&&(i&&clearTimeout(i),i=null,e.forEach(c=>{c.unsubscribe?c.unsubscribe(s):c.removeEventListener("abort",s)}),e=null)};e.forEach(c=>c.addEventListener("abort",s));const{signal:l}=r;return l.unsubscribe=()=>B.asap(a),l}},tv=function*(e,t){let n=e.byteLength;if(n<t){yield e;return}let r=0,o;for(;r<n;)o=r+t,yield e.slice(r,o),r=o},nv=async function*(e,t){for await(const n of rv(e))yield*tv(n,t)},rv=async function*(e){if(e[Symbol.asyncIterator]){yield*e;return}const t=e.getReader();try{for(;;){const{done:n,value:r}=await t.read();if(n)break;yield r}}finally{await t.cancel()}},_c=(e,t,n,r)=>{const o=nv(e,t);let s=0,i,a=l=>{i||(i=!0,r&&r(l))};return new ReadableStream({async pull(l){try{const{done:c,value:d}=await o.next();if(c){a(),l.close();return}let p=d.byteLength;if(n){let m=s+=p;n(m)}l.enqueue(new Uint8Array(d))}catch(c){throw a(c),c}},cancel(l){return a(l),o.return()}},{highWaterMark:2})},jc=64*1024,{isFunction:Po}=B,ov=(({Request:e,Response:t})=>({Request:e,Response:t}))(B.global),{ReadableStream:Pc,TextEncoder:Mc}=B.global,Rc=(e,...t)=>{try{return!!e(...t)}catch{return!1}},sv=e=>{e=B.merge.call({skipUndefined:!0},ov,e);const{fetch:t,Request:n,Response:r}=e,o=t?Po(t):typeof fetch=="function",s=Po(n),i=Po(r);if(!o)return!1;const a=o&&Po(Pc),l=o&&(typeof Mc=="function"?(v=>g=>v.encode(g))(new Mc):async v=>new Uint8Array(await new n(v).arrayBuffer())),c=s&&a&&Rc(()=>{let v=!1;const g=new n(Nt.origin,{body:new Pc,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!g}),d=i&&a&&Rc(()=>B.isReadableStream(new r("").body)),p={stream:d&&(v=>v.body)};o&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!p[v]&&(p[v]=(g,x)=>{let y=g&&g[v];if(y)return y.call(g);throw new Le(`Response type '${v}' is not supported`,Le.ERR_NOT_SUPPORT,x)})});const m=async v=>{if(v==null)return 0;if(B.isBlob(v))return v.size;if(B.isSpecCompliantForm(v))return(await new n(Nt.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if(B.isArrayBufferView(v)||B.isArrayBuffer(v))return v.byteLength;if(B.isURLSearchParams(v)&&(v=v+""),B.isString(v))return(await l(v)).byteLength},f=async(v,g)=>{const x=B.toFiniteNumber(v.getContentLength());return x??m(g)};return async v=>{let{url:g,method:x,data:y,signal:w,cancelToken:S,timeout:k,onDownloadProgress:C,onUploadProgress:T,responseType:E,headers:A,withCredentials:O="same-origin",fetchOptions:F}=Ac(v),U=t||fetch;E=E?(E+"").toLowerCase():"text";let W=ev([w,S&&S.toAbortSignal()],k),z=null;const N=W&&W.unsubscribe&&(()=>{W.unsubscribe()});let K;try{if(T&&c&&x!=="get"&&x!=="head"&&(K=await f(A,y))!==0){let J=new n(g,{method:"POST",body:y,duplex:"half"}),j;if(B.isFormData(y)&&(j=J.headers.get("content-type"))&&A.setContentType(j),J.body){const[R,G]=kc(K,jo(Ec(T)));y=_c(J.body,jc,R,G)}}B.isString(O)||(O=O?"include":"omit");const M=s&&"credentials"in n.prototype,Q={...F,signal:W,method:x.toUpperCase(),headers:A.normalize().toJSON(),body:y,duplex:"half",credentials:M?O:void 0};z=s&&new n(g,Q);let $=await(s?U(z,F):U(g,Q));const _=d&&(E==="stream"||E==="response");if(d&&(C||_&&N)){const J={};["status","statusText","headers"].forEach(Y=>{J[Y]=$[Y]});const j=B.toFiniteNumber($.headers.get("content-length")),[R,G]=C&&kc(j,jo(Ec(C),!0))||[];$=new r(_c($.body,jc,R,()=>{G&&G(),N&&N()}),J)}E=E||"text";let V=await p[B.findKey(p,E)||"text"]($,v);return!_&&N&&N(),await new Promise((J,j)=>{Tc(J,j,{data:V,headers:$t.from($.headers),status:$.status,statusText:$.statusText,config:v,request:z})})}catch(M){throw N&&N(),M&&M.name==="TypeError"&&/Load failed|fetch/i.test(M.message)?Object.assign(new Le("Network Error",Le.ERR_NETWORK,v,z),{cause:M.cause||M}):Le.from(M,M&&M.code,v,z)}}},iv=new Map,Oc=e=>{let t=e?e.env:{};const{fetch:n,Request:r,Response:o}=t,s=[r,o,n];let i=s.length,a=i,l,c,d=iv;for(;a--;)l=s[a],c=d.get(l),c===void 0&&d.set(l,c=a?new Map:sv(t)),d=c;return c};Oc();const vi={http:Nx,xhr:Qx,fetch:{get:Oc}};B.forEach(vi,(e,t)=>{if(e){try{Object.defineProperty(e,"name",{value:t})}catch{}Object.defineProperty(e,"adapterName",{value:t})}});const Dc=e=>`- ${e}`,av=e=>B.isFunction(e)||e===null||e===!1,Lc={getAdapter:(e,t)=>{e=B.isArray(e)?e:[e];const{length:n}=e;let r,o;const s={};for(let i=0;i<n;i++){r=e[i];let a;if(o=r,!av(r)&&(o=vi[(a=String(r)).toLowerCase()],o===void 0))throw new Le(`Unknown adapter '${a}'`);if(o&&(B.isFunction(o)||(o=o.get(t))))break;s[a||"#"+i]=o}if(!o){const i=Object.entries(s).map(([l,c])=>`adapter ${l} `+(c===!1?"is not supported by the environment":"is not available in the build"));let a=n?i.length>1?`since :
|
|
33
33
|
`+i.map(Dc).join(`
|
|
34
34
|
`):" "+Dc(i[0]):"as no adapter specified";throw new Le("There is no suitable adapter to dispatch the request "+a,"ERR_NOT_SUPPORT")}return o},adapters:vi};function wi(e){if(e.cancelToken&&e.cancelToken.throwIfRequested(),e.signal&&e.signal.aborted)throw new fr(null,e)}function $c(e){return wi(e),e.headers=$t.from(e.headers),e.data=xi.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),Lc.getAdapter(e.adapter||Hr.adapter,e)(e).then(function(r){return wi(e),r.data=xi.call(e,e.transformResponse,r),r.headers=$t.from(r.headers),r},function(r){return Cc(r)||(wi(e),r&&r.response&&(r.response.data=xi.call(e,e.transformResponse,r.response),r.response.headers=$t.from(r.response.headers))),Promise.reject(r)})}const Fc="1.12.2",Mo={};["object","boolean","number","function","string","symbol"].forEach((e,t)=>{Mo[e]=function(r){return typeof r===e||"a"+(t<1?"n ":" ")+e}});const Bc={};Mo.transitional=function(t,n,r){function o(s,i){return"[Axios v"+Fc+"] Transitional option '"+s+"'"+i+(r?". "+r:"")}return(s,i,a)=>{if(t===!1)throw new Le(o(i," has been removed"+(n?" in "+n:"")),Le.ERR_DEPRECATED);return n&&!Bc[i]&&(Bc[i]=!0,console.warn(o(i," has been deprecated since v"+n+" and will be removed in the near future"))),t?t(s,i,a):!0}},Mo.spelling=function(t){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${t}`),!0)};function lv(e,t,n){if(typeof e!="object")throw new Le("options must be an object",Le.ERR_BAD_OPTION_VALUE);const r=Object.keys(e);let o=r.length;for(;o-- >0;){const s=r[o],i=t[s];if(i){const a=e[s],l=a===void 0||i(a,s,e);if(l!==!0)throw new Le("option "+s+" must be "+l,Le.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Le("Unknown option "+s,Le.ERR_BAD_OPTION)}}const Ro={assertOptions:lv,validators:Mo},hn=Ro.validators;let Gn=class{constructor(t){this.defaults=t||{},this.interceptors={request:new wc,response:new wc}}async request(t,n){try{return await this._request(t,n)}catch(r){if(r instanceof Error){let o={};Error.captureStackTrace?Error.captureStackTrace(o):o=new Error;const s=o.stack?o.stack.replace(/^.+\n/,""):"";try{r.stack?s&&!String(r.stack).endsWith(s.replace(/^.+\n.+\n/,""))&&(r.stack+=`
|
|
35
|
-
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=qn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Ro.assertOptions(r,{silentJSONParsing:hn.transitional(hn.boolean),forcedJSONParsing:hn.transitional(hn.boolean),clarifyTimeoutError:hn.transitional(hn.boolean)},!1),o!=null&&(B.isFunction(o)?n.paramsSerializer={serialize:o}:Ro.assertOptions(o,{encode:hn.function,serialize:hn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Ro.assertOptions(n,{baseUrl:hn.spelling("baseURL"),withXsrfToken:hn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&B.merge(s.common,s[n.method]);s&&B.forEach(["delete","get","head","post","put","patch","common"],v=>{delete s[v]}),n.headers=$t.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(l=l&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let d,p=0,m;if(!l){const v=[$c.bind(this),void 0];for(v.unshift(...a),v.push(...c),m=v.length,d=Promise.resolve(n);p<m;)d=d.then(v[p++],v[p++]);return d}m=a.length;let f=n;for(;p<m;){const v=a[p++],g=a[p++];try{f=v(f)}catch(x){g.call(this,x);break}}try{d=$c.call(this,f)}catch(v){return Promise.reject(v)}for(p=0,m=c.length;p<m;)d=d.then(c[p++],c[p++]);return d}getUri(t){t=qn(this.defaults,t);const n=Ic(t.baseURL,t.url,t.allowAbsoluteUrls);return vc(n,t.params,t.paramsSerializer)}};B.forEach(["delete","get","head","options"],function(t){Gn.prototype[t]=function(n,r){return this.request(qn(r||{},{method:t,url:n,data:(r||{}).data}))}}),B.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(qn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Gn.prototype[t]=n(),Gn.prototype[t+"Form"]=n(!0)});let cv=class Mg{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new fr(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Mg(function(o){t=o}),cancel:t}}};function uv(e){return function(n){return e.apply(null,n)}}function dv(e){return B.isObject(e)&&e.isAxiosError===!0}const bi={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(bi).forEach(([e,t])=>{bi[t]=e});function zc(e){const t=new Gn(e),n=rc(Gn.prototype.request,t);return B.extend(n,Gn.prototype,t,{allOwnKeys:!0}),B.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return zc(qn(e,o))},n}const vt=zc(Hr);vt.Axios=Gn,vt.CanceledError=fr,vt.CancelToken=cv,vt.isCancel=Cc,vt.VERSION=Fc,vt.toFormData=Ao,vt.AxiosError=Le,vt.Cancel=vt.CanceledError,vt.all=function(t){return Promise.all(t)},vt.spread=uv,vt.isAxiosError=dv,vt.mergeConfig=qn,vt.AxiosHeaders=$t,vt.formToJSON=e=>yc(B.isHTMLForm(e)?new FormData(e):e),vt.getAdapter=Lc.getAdapter,vt.HttpStatusCode=bi,vt.default=vt;const{Axios:MI,AxiosError:RI,CanceledError:OI,isCancel:DI,CancelToken:LI,VERSION:$I,all:FI,Cancel:BI,isAxiosError:zI,spread:HI,toFormData:UI,AxiosHeaders:WI,HttpStatusCode:VI,formToJSON:KI,getAdapter:qI,mergeConfig:GI}=vt,Hc=typeof window<"u"?window.__API_BASE_URL__:void 0,Uc=Hc?mn(Hc):void 0;function mn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Oo=null;const yi=new Set;function Wc(){return Oo}function Do(e){Oo=e,yi.forEach(t=>t(e))}function Vc(e){return yi.add(e),()=>yi.delete(e)}const Kc=3e4,qc=9e4,Kt=vt.create({...Uc?{baseURL:Uc}:{},timeout:Kc,withCredentials:!0});Kt.interceptors.request.use(e=>(Oo&&(e.headers.Authorization=`Bearer ${Oo}`),e)),Kt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),Do(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function qt(e,t){return Kt.defaults.baseURL?(await Kt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Lo(e,t,n){return Kt.defaults.baseURL?(await Kt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Gc(e,t,n){return Kt.defaults.baseURL?(await Kt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Si(e,t){return Kt.defaults.baseURL?(await Kt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Rt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class $o{get baseUrl(){const t=Kt.defaults.baseURL;return t?mn(String(t)):""}updateConfig(t){t.baseUrl&&(Kt.defaults.baseURL=mn(String(t.baseUrl))),t.authToken!==void 0&&Do(t.authToken)}getAuthToken(){return Wc()}setAuthToken(t){Do(t)}onTokenChange(t){return Vc(t)}async listThreads(){const t=await qt("/threads"),n=Rt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await qt("/threads/shared"),n=Rt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Lo("/threads",t?{title:t}:void 0);return Rt(r)}async updateThread(t,n){const r=await Gc(`/threads/${t}`,{title:n});return Rt(r)}async deleteThread(t){const n=await Si(`/threads/${t}`);return Rt(n)}async shareThread(t,n){const r=await Lo(`/threads/${t}/share`,{shared_with_user_id:n});return Rt(r)}async threadInfo(t){const n=await qt(`/threads/${t}/info`);return Rt(n)}async listAgents(){const t=await qt("/agents"),n=Rt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await qt(`/agents/${t}`);return Rt(n)}async getAgentSchema(t){const n=await qt(`/agents/${t}/schema`);return Rt(n)}async getState(t){const n=await qt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Rt(n)}async getStateHistory(t){const n=await qt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:qc});return Rt(n)}async cancelRun(t){const n=await Lo("/runs/cancel",{threadId:t});return Rt(n)}async unshareThread(t,n){const r=await Si(`/threads/${t}/share/${n}`);return Rt(r)}}const An=new $o,fv=$o,pv=$o;async function Ci(e,t){return await qt(e,{responseType:"blob",onDownloadProgress:r=>{try{if(t&&r.lengthComputable){const o=r.loaded/r.total;t(o)}}catch{}},maxBodyLength:1/0})}async function hv(e,t){const n=await Ci(`/files/${e}/view`,t),r=URL.createObjectURL(n);window.open(r,"_blank"),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function Ti(e,t){return await(await Ci(`/files/${e}/view`,t)).text()}async function Yc(e,t){const n=await Ci(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await qt(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function mv(e){return await qt(`/files/${e}`)}async function Xc(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await qt("/files",{params:r})}const Jc=b.createContext(null);function Zc({children:e,apiConfig:t}){const n=An;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(Jc.Provider,{value:r,children:e})}function ki(){const e=b.useContext(Jc);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Qc(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function eu(e=[]){const t=[],n=[];for(const r of e)try{const o=await Qc(r);n.push({filename:r.name,data:o,mime_type:r.type||"application/octet-stream"})}catch{}return{contentParts:t,filesInfo:n}}function pr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function gv(e){if(typeof e!="string")return;const t=e.trim();if(t)return mn(t)}function tu(){const e=[pr("__API_BASE_URL__"),pr("__CHAT_API_BASE_URL__"),pr("__CHAT_API_URL__")];for(const t of e){const n=gv(t);if(n)return n}}function nu(){const e=[pr("__API_AUTH_TOKEN__"),pr("__CHAT_API_KEY__"),pr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function ru(...e){for(const t of e)if(typeof t=="string"&&t.trim())return mn(t);return mn()}function ou(){const e={},t=tu(),n=nu();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function su(){const e=ou(),t=An.getAuthToken(),n=tu();return{apiBaseUrl:ru(e.baseUrl,An.baseUrl,n),apiKey:t||e.apiKey||nu()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Ei="chat-settings";function iu(){try{const e=localStorage.getItem(Ei);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function au(e){try{const t={...e,apiBaseUrl:mn(e.apiBaseUrl)};localStorage.setItem(Ei,JSON.stringify(t)),t.apiKey&&An.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function xv(){const e=su(),t=iu(),n=An.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:ru(An.baseUrl,r,e.apiBaseUrl)}}function vv(e){An.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),au(e)}function lu({api:e,seed:t,prepend:n,onError:r,currentThreadId:o,initialThreadId:s=null,initialCheckpointId:i=null,initialCheckpointNs:a=null,autoLoadInitial:l=!0,isStreaming:c,getMessages:d}){const[p,m]=b.useState(null),v=b.useMemo(()=>Nn(p),[p]).checkpoints,g=Zl(v),x=g.timeline,[y,w]=b.useState(!1),[S,k]=b.useState(null),[C,T]=b.useState(!1),[E,A]=b.useState(!1),[O,F]=b.useState(!1),[U,W]=b.useState(null),z=b.useRef(o),N=b.useRef(null),K=b.useRef(null),M=b.useRef(null),Q=b.useRef(null),$=b.useRef(!1),_=b.useRef(null),V=b.useRef(new Map);b.useEffect(()=>{z.current=o},[o]);const J=b.useCallback(async L=>{var xe,de;if(!L.threadId)return;const oe=L.threadId;(xe=L.onStart)==null||xe.call(L),L.setLoading(!0);try{await L.action(oe)}catch(we){if(z.current===oe){const Me=String(we);(de=L.handleError)==null||de.call(L,Me),r==null||r(Me)}throw we}finally{L.setLoading(!1)}},[r]),j=b.useCallback(async(L,oe)=>{if(!L)return;const xe=`${L}:${oe??"latest"}`,de=V.current.get(xe);if(de)return de;const we=J({threadId:L,setLoading:T,onStart:()=>W(null),handleError:Me=>W(Me),action:async Me=>{const He=await e.getStateHistory({threadId:Me,checkpointId:oe??void 0});if(z.current!==Me){console.log(`[useThreadHistoryState] Thread changed during load (was ${Me}, now ${z.current}), discarding stale data`);return}const{checkpoints:$e}=Nn(He),Ae=$e.find(Fe=>Fe.messages&&Fe.messages.length>0)??(oe?$e.find(Fe=>Fe.checkpointId===oe):null)??$e[0];t((Ae==null?void 0:Ae.messages)??[],{checkpointId:(Ae==null?void 0:Ae.checkpointId)??null,checkpointNs:(Ae==null?void 0:Ae.checkpointNs)??null}),m(He),w(!!(Ae!=null&&Ae.nextCursor)),k((Ae==null?void 0:Ae.nextCursor)??null)}});V.current.set(xe,we);try{await we}finally{V.current.delete(xe)}return z.current===L&&(_.current=xe),we},[e,t,J]),R=b.useCallback(async(L,oe)=>{Q.current=L;try{await j(L,oe)}finally{Q.current===L&&(Q.current=null)}},[j]),G=b.useCallback(L=>{K.current=L},[]),Y=b.useCallback(L=>{M.current=L},[]),ie=b.useCallback(L=>{const oe=L.threadId??z.current;if(!oe||z.current&&z.current!==oe)return;const{checkpoints:xe}=Nn(L);if(!xe.length)return;const de=xe.find(we=>we.messages&&we.messages.length>0)??xe.find(we=>!!we.checkpointId)??xe[0];t((de==null?void 0:de.messages)??[],{checkpointId:(de==null?void 0:de.checkpointId)??null,checkpointNs:(de==null?void 0:de.checkpointNs)??null}),m(L),w(!!(de!=null&&de.nextCursor)),k((de==null?void 0:de.nextCursor)??null),_.current=`${oe}:latest`,K.current=null,M.current=null},[t]),H=b.useCallback(async(L,oe)=>{const xe=z.current;await J({threadId:xe,setLoading:F,action:async de=>{const we=await e.getStateHistory({threadId:de,checkpointId:L,checkpointNs:oe??void 0});if(z.current!==de){console.log(`[useThreadHistoryState] Thread changed during checkpoint navigation (was ${de}, now ${z.current}), discarding stale data`);return}const{checkpoints:Me}=Nn(we),He=Me.find($e=>$e.checkpointId===L&&(oe?$e.checkpointNs===oe:!0));if(!He){console.warn("[useThreadHistoryState] Requested checkpoint not found:",{checkpointId:L,checkpointNs:oe});return}m(we),t(He.messages??[],{checkpointId:He.checkpointId??null,checkpointNs:He.checkpointNs??null})}}).catch(()=>{})},[e,t,J]),D=b.useCallback((L,oe)=>{t(d(),{checkpointId:L??null,checkpointNs:oe??null})},[d,t]),X=b.useCallback(async()=>{z.current&&await R(z.current)},[R]),Z=b.useCallback(async()=>{const L=z.current;!L||!S||await J({threadId:L,setLoading:A,action:async oe=>{const xe=await e.getStateHistory({threadId:oe,checkpointId:S});if(z.current!==oe)return;const{checkpoints:de}=Nn(xe);if(de.length>0){const we=de[de.length-1];n((we==null?void 0:we.messages)??[]),w(!!(we!=null&&we.nextCursor)),k((we==null?void 0:we.nextCursor)??null)}}}).catch(()=>{})},[e,S,r,n,J]);b.useEffect(()=>{if(!l||!o||C||c)return;if(K.current===o){K.current=null,N.current=o;return}if(M.current===o){N.current=o;return}if(Q.current===o){Q.current=null,N.current=o;return}if(N.current===o)return;N.current=o;const L=!$.current&&!!i&&o===s;let oe;L&&i?(oe=i,$.current=!0,console.log("[useThreadHistoryState] Loading thread with checkpoint:",oe,a?`(ns: ${a})`:"")):console.log("[useThreadHistoryState] Loading thread with latest checkpoint");const xe=`${o}:${oe??"latest"}`;_.current!==xe&&R(o,oe)},[l,o,i,a,s,C,c,R]);const ce=b.useCallback(()=>{m(null),w(!1),k(null),T(!1),A(!1),F(!1),W(null),K.current=null,M.current=null,N.current=null,_.current=null,Q.current=null},[]);return{threadCheckpoints:v,threadTimeline:x,checkpointIndex:g,isLoadingThread:C,isHistoryLoading:E,isLoadingCheckpoint:O,threadStateError:U,hasMoreHistory:y,loadThread:R,navigateToCheckpoint:H,loadOlderMessages:Z,setCurrentCheckpointId:D,returnToLatest:X,handleStateHistoryEvent:ie,markSkipNextLoad:G,markStreamPendingThread:Y,resetHistoryState:ce}}const wv=["detail","message","error","description","title"];function Fo(e){if(!e)return null;if(typeof e=="string"){const t=e.trim();return t.length?t:null}if(Array.isArray(e)){for(const t of e){const n=Fo(t);if(n)return n}return null}if(typeof e=="object"){const t=e;for(const n of wv){const r=Fo(t[n]);if(r)return r}if("errors"in t){const n=Fo(t.errors);if(n)return n}}return null}function bv(e){if(!e)return"Request failed";const t=e.response,n=Fo(t==null?void 0:t.data);if(n)return n;if(t!=null&&t.statusText)return t.statusText;if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"){const r=e.trim();if(r.length)return r}return t!=null&&t.status?`Request failed with status code ${t.status}`:"Request failed"}function cu({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:o}){const[s,i]=b.useState([]),[a,l]=b.useState(t),[c,d]=b.useState(!1),[p,m]=b.useState(null),[f,v]=b.useState([]),[g,x]=b.useState(!1),[,y]=b.useState(null),[w,S]=b.useState(null),[k,C]=b.useState(!1),T=b.useRef(a),E=b.useRef(new Map);b.useEffect(()=>{T.current=a},[a]);const A=b.useCallback(async()=>{d(!0),m(null);try{const $=await e.listThreads();i($??[])}catch($){const _=String($);m(_),n==null||n(_)}finally{d(!1)}},[e,n]),O=b.useCallback(async()=>{x(!0),y(null);try{const $=await e.listSharedThreads();v($??[])}catch($){const _=String($);y(_),n==null||n(_)}finally{x(!1)}},[e,n]);b.useEffect(()=>{A()},[A]),b.useEffect(()=>{O()},[O]),b.useEffect(()=>{r==null||r(a)},[a,r]);const F=b.useCallback(async $=>{try{const _=await e.createThread($);return l(_.threadId),await A(),_.threadId}catch(_){const V=String(_);return n==null||n(V),null}},[e,n,A]),U=b.useCallback(async $=>{const _=s;i(J=>J.filter(j=>j.threadId!==$));const V=new AbortController;E.current.set($,V);try{await e.deleteThread($),T.current===$&&(l(null),o==null||o())}catch(J){i(_);const j=String(J);n==null||n(j)}finally{E.current.delete($)}},[e,o,n,s]),W=b.useCallback(async($,_)=>{try{await e.updateThread($,_),await A()}catch(V){n==null||n(String(V))}},[e,n,A]),z=b.useCallback(async($,_)=>{C(!0),S("Sharing thread…");try{await e.shareThread($,_),await O(),S("Shared successfully")}catch(V){const J=bv(V);throw n==null||n(J),S(`Failed to share: ${J}`),new Error(J)}finally{C(!1)}},[e,n,O]),N=b.useCallback(async($,_)=>{try{await e.unshareThread($,_),await O()}catch(V){const J=String(V);throw n==null||n(J),V}},[e,n,O]),K=b.useMemo(()=>({createThread:F,deleteThread:U,renameThread:W,refreshThreads:A,refreshSharedThreads:O,shareThread:z,unshareThread:N}),[F,U,W,A,O,z,N]),M=b.useCallback($=>{if(!($!=null&&$.threadId))return;const _={threadId:$.threadId,title:$.title||`Thread ${$.threadId.slice(0,8)}`,createdAt:$.createdAt||new Date().toISOString(),updatedAt:$.updatedAt||new Date().toISOString(),messageCount:$.messageCount??1};i(V=>{let J=!1;const j=V.map(R=>R.threadId===_.threadId?(J=!0,console.debug("[useThreadsState] thread_info: updating existing thread",_.threadId),{...R,title:_.title??R.title,updatedAt:_.updatedAt??R.updatedAt,messageCount:_.messageCount??R.messageCount}):R);return J?j:(console.debug("[useThreadsState] thread_info: adding thread to list",_.threadId),[_,...V])})},[]),Q=b.useCallback(()=>S(null),[]);return{threads:s,currentThreadId:a,currentThreadIdRef:T,setCurrentThreadId:l,isLoadingThreads:c,threadsError:p,sharedThreads:f,isLoadingSharedThreads:g,actions:K,addThreadFromEvent:M,shareInFlight:k,shareStatus:w,clearShareStatus:Q}}function Ii(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function uu(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function Wr(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(Wr).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(uu(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=Wr(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function hr(e){if(typeof e=="string")return e;if(uu(e))return"";try{const t=Wr(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function yv(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function Sv(e){const t=hr(e);return typeof e=="string"&&yv(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Vr(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=Ii(t);if(n!==null)return Vr(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Vr(e.content):e}function Cv(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ni(e){const t=e.content.find(s=>s.type==="tool_call"),n=e.additionalKwargs??{},r=typeof(t==null?void 0:t.id)=="string"&&t.id||typeof n.toolCallId=="string"&&n.toolCallId||(e.id.startsWith("tool-")?e.id.slice(5):void 0);return{name:(typeof(t==null?void 0:t.name)=="string"&&t.name||typeof n.toolName=="string"&&n.toolName||e.name&&String(e.name))??void 0,toolCallId:r??void 0}}function Bo(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function Tv(e){const t=r=>{try{const o=Wr(r);return typeof o=="string"?o:JSON.stringify(o??"")}catch{return""}},n=e.filter(r=>r.type==="text");return n.length?t(n.map(r=>r.text).join(`
|
|
35
|
+
`+s):r.stack=s}catch{}}throw r}}_request(t,n){typeof t=="string"?(n=n||{},n.url=t):n=t||{},n=qn(this.defaults,n);const{transitional:r,paramsSerializer:o,headers:s}=n;r!==void 0&&Ro.assertOptions(r,{silentJSONParsing:hn.transitional(hn.boolean),forcedJSONParsing:hn.transitional(hn.boolean),clarifyTimeoutError:hn.transitional(hn.boolean)},!1),o!=null&&(B.isFunction(o)?n.paramsSerializer={serialize:o}:Ro.assertOptions(o,{encode:hn.function,serialize:hn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Ro.assertOptions(n,{baseUrl:hn.spelling("baseURL"),withXsrfToken:hn.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let i=s&&B.merge(s.common,s[n.method]);s&&B.forEach(["delete","get","head","post","put","patch","common"],v=>{delete s[v]}),n.headers=$t.concat(i,s);const a=[];let l=!0;this.interceptors.request.forEach(function(g){typeof g.runWhen=="function"&&g.runWhen(n)===!1||(l=l&&g.synchronous,a.unshift(g.fulfilled,g.rejected))});const c=[];this.interceptors.response.forEach(function(g){c.push(g.fulfilled,g.rejected)});let d,p=0,m;if(!l){const v=[$c.bind(this),void 0];for(v.unshift(...a),v.push(...c),m=v.length,d=Promise.resolve(n);p<m;)d=d.then(v[p++],v[p++]);return d}m=a.length;let f=n;for(;p<m;){const v=a[p++],g=a[p++];try{f=v(f)}catch(x){g.call(this,x);break}}try{d=$c.call(this,f)}catch(v){return Promise.reject(v)}for(p=0,m=c.length;p<m;)d=d.then(c[p++],c[p++]);return d}getUri(t){t=qn(this.defaults,t);const n=Ic(t.baseURL,t.url,t.allowAbsoluteUrls);return vc(n,t.params,t.paramsSerializer)}};B.forEach(["delete","get","head","options"],function(t){Gn.prototype[t]=function(n,r){return this.request(qn(r||{},{method:t,url:n,data:(r||{}).data}))}}),B.forEach(["post","put","patch"],function(t){function n(r){return function(s,i,a){return this.request(qn(a||{},{method:t,headers:r?{"Content-Type":"multipart/form-data"}:{},url:s,data:i}))}}Gn.prototype[t]=n(),Gn.prototype[t+"Form"]=n(!0)});let cv=class Mg{constructor(t){if(typeof t!="function")throw new TypeError("executor must be a function.");let n;this.promise=new Promise(function(s){n=s});const r=this;this.promise.then(o=>{if(!r._listeners)return;let s=r._listeners.length;for(;s-- >0;)r._listeners[s](o);r._listeners=null}),this.promise.then=o=>{let s;const i=new Promise(a=>{r.subscribe(a),s=a}).then(o);return i.cancel=function(){r.unsubscribe(s)},i},t(function(s,i,a){r.reason||(r.reason=new fr(s,i,a),n(r.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(t){if(this.reason){t(this.reason);return}this._listeners?this._listeners.push(t):this._listeners=[t]}unsubscribe(t){if(!this._listeners)return;const n=this._listeners.indexOf(t);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const t=new AbortController,n=r=>{t.abort(r)};return this.subscribe(n),t.signal.unsubscribe=()=>this.unsubscribe(n),t.signal}static source(){let t;return{token:new Mg(function(o){t=o}),cancel:t}}};function uv(e){return function(n){return e.apply(null,n)}}function dv(e){return B.isObject(e)&&e.isAxiosError===!0}const bi={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(bi).forEach(([e,t])=>{bi[t]=e});function zc(e){const t=new Gn(e),n=rc(Gn.prototype.request,t);return B.extend(n,Gn.prototype,t,{allOwnKeys:!0}),B.extend(n,t,null,{allOwnKeys:!0}),n.create=function(o){return zc(qn(e,o))},n}const vt=zc(Hr);vt.Axios=Gn,vt.CanceledError=fr,vt.CancelToken=cv,vt.isCancel=Cc,vt.VERSION=Fc,vt.toFormData=Ao,vt.AxiosError=Le,vt.Cancel=vt.CanceledError,vt.all=function(t){return Promise.all(t)},vt.spread=uv,vt.isAxiosError=dv,vt.mergeConfig=qn,vt.AxiosHeaders=$t,vt.formToJSON=e=>yc(B.isHTMLForm(e)?new FormData(e):e),vt.getAdapter=Lc.getAdapter,vt.HttpStatusCode=bi,vt.default=vt;const{Axios:MI,AxiosError:RI,CanceledError:OI,isCancel:DI,CancelToken:LI,VERSION:$I,all:FI,Cancel:BI,isAxiosError:zI,spread:HI,toFormData:UI,AxiosHeaders:WI,HttpStatusCode:VI,formToJSON:KI,getAdapter:qI,mergeConfig:GI}=vt,Hc=typeof window<"u"?window.__API_BASE_URL__:void 0,Uc=Hc?mn(Hc):void 0;function mn(e){const n=(e!=null&&e.trim()?e.trim():"/api/chat").replace(/\/+$/,"");return n?n.endsWith("/chat")?n:`${n}/chat`:"/api/chat"}let Oo=null;const yi=new Set;function Wc(){return Oo}function Do(e){Oo=e,yi.forEach(t=>t(e))}function Vc(e){return yi.add(e),()=>yi.delete(e)}const Kc=3e4,qc=9e4,Kt=vt.create({...Uc?{baseURL:Uc}:{},timeout:Kc,withCredentials:!0});Kt.interceptors.request.use(e=>(Oo&&(e.headers.Authorization=`Bearer ${Oo}`),e)),Kt.interceptors.response.use(e=>{if(typeof window<"u"&&(e!=null&&e.data))try{const t=e.data,n=t.data||{},r=typeof t.token=="string"&&t.token||typeof n.token=="string"&&n.token||null,o=typeof t.expires_at=="number"&&t.expires_at||typeof n.expires_at=="number"&&n.expires_at||typeof t.expiresAt=="number"&&t.expiresAt||typeof n.expiresAt=="number"&&n.expiresAt||null;r&&(localStorage.setItem("authToken",r),Do(r)),o&&localStorage.setItem("authTokenExpiresAt",o.toString()),(r||o)&&window.dispatchEvent(new CustomEvent("smartorg:chat-token-updated",{detail:{token:r,expiresAt:o}}))}catch(t){console.warn("[chat-api] Error storing token:",t)}return e},e=>Promise.reject(e));async function qt(e,t){return Kt.defaults.baseURL?(await Kt.get(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}async function Lo(e,t,n){return Kt.defaults.baseURL?(await Kt.post(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Gc(e,t,n){return Kt.defaults.baseURL?(await Kt.put(e,t,n)).data:Promise.reject(new Error("API base URL is not configured"))}async function Si(e,t){return Kt.defaults.baseURL?(await Kt.delete(e,t)).data:Promise.reject(new Error("API base URL is not configured"))}function Rt(e){return e&&typeof e=="object"&&"data"in e?e.data:e}class $o{get baseUrl(){const t=Kt.defaults.baseURL;return t?mn(String(t)):""}updateConfig(t){t.baseUrl&&(Kt.defaults.baseURL=mn(String(t.baseUrl))),t.authToken!==void 0&&Do(t.authToken)}getAuthToken(){return Wc()}setAuthToken(t){Do(t)}onTokenChange(t){return Vc(t)}async listThreads(){const t=await qt("/threads"),n=Rt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async listSharedThreads(){const t=await qt("/threads/shared"),n=Rt(t);return(n==null?void 0:n.items)??(t==null?void 0:t.items)??[]}async createThread(t){const r=await Lo("/threads",t?{title:t}:void 0);return Rt(r)}async updateThread(t,n){const r=await Gc(`/threads/${t}`,{title:n});return Rt(r)}async deleteThread(t){const n=await Si(`/threads/${t}`);return Rt(n)}async shareThread(t,n){const r=await Lo(`/threads/${t}/share`,{shared_with_user_id:n});return Rt(r)}async threadInfo(t){const n=await qt(`/threads/${t}/info`);return Rt(n)}async listAgents(){const t=await qt("/agents"),n=Rt(t);return(n==null?void 0:n.items)??[]}async getAgent(t){const n=await qt(`/agents/${t}`);return Rt(n)}async getAgentSchema(t){const n=await qt(`/agents/${t}/schema`);return Rt(n)}async getState(t){const n=await qt(`/threads/${t.threadId}/state`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs}});return Rt(n)}async getStateHistory(t){const n=await qt(`/threads/${t.threadId}/state/history`,{params:{thread_id:t.threadId,checkpoint_id:t.checkpointId,checkpoint_ns:t.checkpointNs},timeout:qc});return Rt(n)}async cancelRun(t){const n=await Lo("/runs/cancel",{threadId:t});return Rt(n)}async unshareThread(t,n){const r=await Si(`/threads/${t}/share/${n}`);return Rt(r)}}const An=new $o,fv=$o,pv=$o;async function Ci(e,t){return await qt(e,{responseType:"blob",onDownloadProgress:r=>{try{if(t&&r.lengthComputable){const o=r.loaded/r.total;t(o)}}catch{}},maxBodyLength:1/0})}async function hv(e,t){const n=await Ci(`/files/${e}/view`,t),r=URL.createObjectURL(n);window.open(r,"_blank"),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function Ti(e,t){return await(await Ci(`/files/${e}/view`,t)).text()}async function Yc(e,t){const n=await Ci(`/files/${e}/download`,t),r=URL.createObjectURL(n);let o=`file_${e}`;try{const i=await qt(`/files/${e}`);o=(i==null?void 0:i.filename)??o}catch{}const s=document.createElement("a");s.href=r,s.download=o,document.body.appendChild(s),s.click(),s.remove(),setTimeout(()=>URL.revokeObjectURL(r),6e4)}async function mv(e){return await qt(`/files/${e}`)}async function Xc(e,t=50,n=0){const r={limit:t,offset:n};return e&&(r.thread_id=e),await qt("/files",{params:r})}function ki(){const e=b.useContext(iu);if(!e)throw new Error("useApi must be used within ApiProvider");return e}async function Jc(e){return await new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{try{const o=r.result,s=new Uint8Array(o);let i="";const a=s.byteLength;for(let l=0;l<a;l++)i+=String.fromCharCode(s[l]);t(btoa(i))}catch(o){n(o)}},r.onerror=o=>n(o),r.readAsArrayBuffer(e)})}async function Zc(e=[]){const t=[],n=[];for(const r of e)try{const o=await Jc(r);n.push({filename:r.name,data:o,mime_type:r.type||"application/octet-stream"})}catch{}return{contentParts:t,filesInfo:n}}function pr(e){if(!(typeof globalThis>"u"))return globalThis[e]}function gv(e){if(typeof e!="string")return;const t=e.trim();if(t)return mn(t)}function Qc(){const e=[pr("__API_BASE_URL__"),pr("__CHAT_API_BASE_URL__"),pr("__CHAT_API_URL__")];for(const t of e){const n=gv(t);if(n)return n}}function eu(){const e=[pr("__API_AUTH_TOKEN__"),pr("__CHAT_API_KEY__"),pr("__CHAT_AUTH_TOKEN__")];for(const t of e)if(typeof t=="string"&&t.trim())return t.trim()}function tu(...e){for(const t of e)if(typeof t=="string"&&t.trim())return mn(t);return mn()}function nu(){const e={},t=Qc(),n=eu();return t&&(e.baseUrl=t),n&&(e.apiKey=n),e}function ru(){const e=nu(),t=An.getAuthToken(),n=Qc();return{apiBaseUrl:tu(e.baseUrl,An.baseUrl,n),apiKey:t||e.apiKey||eu()||"",model:"gpt-4",temperature:.7,maxTokens:4096,layoutSize:"desktop",showThreads:!0,autoScrollMessages:!0,darkMode:!1,enableSound:!1,messageHistory:100}}const Ei="chat-settings";function ou(){try{const e=localStorage.getItem(Ei);return e?JSON.parse(e):{}}catch(e){return console.error("Failed to parse stored settings:",e),{}}}function su(e){try{const t={...e,apiBaseUrl:mn(e.apiBaseUrl)};localStorage.setItem(Ei,JSON.stringify(t)),t.apiKey&&An.setAuthToken(t.apiKey)}catch(t){console.error("Failed to save settings:",t)}}function xv(){const e=ru(),t=ou(),n=An.getAuthToken(),r=typeof t.apiBaseUrl=="string"?t.apiBaseUrl:void 0;return{...e,...t,apiKey:n||t.apiKey||e.apiKey,apiBaseUrl:tu(An.baseUrl,r,e.apiBaseUrl)}}function vv(e){An.updateConfig({baseUrl:e.apiBaseUrl,authToken:e.apiKey??void 0}),su(e)}const iu=b.createContext(null);function au({children:e,apiConfig:t}){const n=An;if(t){const o=n.baseUrl,s=n.getAuthToken();t.baseUrl&&t.baseUrl!==o&&n.updateConfig({baseUrl:t.baseUrl}),t.apiKey!==void 0&&t.apiKey!==s&&n.updateConfig({authToken:t.apiKey})}const r={token:n.getAuthToken(),setToken:o=>n.setAuthToken(o),api:n,baseUrl:n.baseUrl};return u.jsx(iu.Provider,{value:r,children:e})}function lu({api:e,seed:t,prepend:n,onError:r,currentThreadId:o,initialThreadId:s=null,initialCheckpointId:i=null,initialCheckpointNs:a=null,autoLoadInitial:l=!0,isStreaming:c,getMessages:d}){const[p,m]=b.useState(null),v=b.useMemo(()=>Nn(p),[p]).checkpoints,g=Zl(v),x=g.timeline,[y,w]=b.useState(!1),[S,k]=b.useState(null),[C,T]=b.useState(!1),[E,A]=b.useState(!1),[O,F]=b.useState(!1),[U,W]=b.useState(null),z=b.useRef(o),N=b.useRef(null),K=b.useRef(null),M=b.useRef(null),Q=b.useRef(null),$=b.useRef(!1),_=b.useRef(null),V=b.useRef(new Map);b.useEffect(()=>{z.current=o},[o]);const J=b.useCallback(async L=>{var xe,de;if(!L.threadId)return;const oe=L.threadId;(xe=L.onStart)==null||xe.call(L),L.setLoading(!0);try{await L.action(oe)}catch(we){if(z.current===oe){const Me=String(we);(de=L.handleError)==null||de.call(L,Me),r==null||r(Me)}throw we}finally{L.setLoading(!1)}},[r]),j=b.useCallback(async(L,oe)=>{if(!L)return;const xe=`${L}:${oe??"latest"}`,de=V.current.get(xe);if(de)return de;const we=J({threadId:L,setLoading:T,onStart:()=>W(null),handleError:Me=>W(Me),action:async Me=>{const He=await e.getStateHistory({threadId:Me,checkpointId:oe??void 0});if(z.current!==Me){console.log(`[useThreadHistoryState] Thread changed during load (was ${Me}, now ${z.current}), discarding stale data`);return}const{checkpoints:$e}=Nn(He),Ae=$e.find(Fe=>Fe.messages&&Fe.messages.length>0)??(oe?$e.find(Fe=>Fe.checkpointId===oe):null)??$e[0];t((Ae==null?void 0:Ae.messages)??[],{checkpointId:(Ae==null?void 0:Ae.checkpointId)??null,checkpointNs:(Ae==null?void 0:Ae.checkpointNs)??null}),m(He),w(!!(Ae!=null&&Ae.nextCursor)),k((Ae==null?void 0:Ae.nextCursor)??null)}});V.current.set(xe,we);try{await we}finally{V.current.delete(xe)}return z.current===L&&(_.current=xe),we},[e,t,J]),R=b.useCallback(async(L,oe)=>{Q.current=L;try{await j(L,oe)}finally{Q.current===L&&(Q.current=null)}},[j]),G=b.useCallback(L=>{K.current=L},[]),Y=b.useCallback(L=>{M.current=L},[]),ie=b.useCallback(L=>{const oe=L.threadId??z.current;if(!oe||z.current&&z.current!==oe)return;const{checkpoints:xe}=Nn(L);if(!xe.length)return;const de=xe.find(we=>we.messages&&we.messages.length>0)??xe.find(we=>!!we.checkpointId)??xe[0];t((de==null?void 0:de.messages)??[],{checkpointId:(de==null?void 0:de.checkpointId)??null,checkpointNs:(de==null?void 0:de.checkpointNs)??null}),m(L),w(!!(de!=null&&de.nextCursor)),k((de==null?void 0:de.nextCursor)??null),_.current=`${oe}:latest`,K.current=null,M.current=null},[t]),H=b.useCallback(async(L,oe)=>{const xe=z.current;await J({threadId:xe,setLoading:F,action:async de=>{const we=await e.getStateHistory({threadId:de,checkpointId:L,checkpointNs:oe??void 0});if(z.current!==de){console.log(`[useThreadHistoryState] Thread changed during checkpoint navigation (was ${de}, now ${z.current}), discarding stale data`);return}const{checkpoints:Me}=Nn(we),He=Me.find($e=>$e.checkpointId===L&&(oe?$e.checkpointNs===oe:!0));if(!He){console.warn("[useThreadHistoryState] Requested checkpoint not found:",{checkpointId:L,checkpointNs:oe});return}m(we),t(He.messages??[],{checkpointId:He.checkpointId??null,checkpointNs:He.checkpointNs??null})}}).catch(()=>{})},[e,t,J]),D=b.useCallback((L,oe)=>{t(d(),{checkpointId:L??null,checkpointNs:oe??null})},[d,t]),X=b.useCallback(async()=>{z.current&&await R(z.current)},[R]),Z=b.useCallback(async()=>{const L=z.current;!L||!S||await J({threadId:L,setLoading:A,action:async oe=>{const xe=await e.getStateHistory({threadId:oe,checkpointId:S});if(z.current!==oe)return;const{checkpoints:de}=Nn(xe);if(de.length>0){const we=de[de.length-1];n((we==null?void 0:we.messages)??[]),w(!!(we!=null&&we.nextCursor)),k((we==null?void 0:we.nextCursor)??null)}}}).catch(()=>{})},[e,S,r,n,J]);b.useEffect(()=>{if(!l||!o||C||c)return;if(K.current===o){K.current=null,N.current=o;return}if(M.current===o){N.current=o;return}if(Q.current===o){Q.current=null,N.current=o;return}if(N.current===o)return;N.current=o;const L=!$.current&&!!i&&o===s;let oe;L&&i?(oe=i,$.current=!0,console.log("[useThreadHistoryState] Loading thread with checkpoint:",oe,a?`(ns: ${a})`:"")):console.log("[useThreadHistoryState] Loading thread with latest checkpoint");const xe=`${o}:${oe??"latest"}`;_.current!==xe&&R(o,oe)},[l,o,i,a,s,C,c,R]);const ce=b.useCallback(()=>{m(null),w(!1),k(null),T(!1),A(!1),F(!1),W(null),K.current=null,M.current=null,N.current=null,_.current=null,Q.current=null},[]);return{threadCheckpoints:v,threadTimeline:x,checkpointIndex:g,isLoadingThread:C,isHistoryLoading:E,isLoadingCheckpoint:O,threadStateError:U,hasMoreHistory:y,loadThread:R,navigateToCheckpoint:H,loadOlderMessages:Z,setCurrentCheckpointId:D,returnToLatest:X,handleStateHistoryEvent:ie,markSkipNextLoad:G,markStreamPendingThread:Y,resetHistoryState:ce}}const wv=["detail","message","error","description","title"];function Fo(e){if(!e)return null;if(typeof e=="string"){const t=e.trim();return t.length?t:null}if(Array.isArray(e)){for(const t of e){const n=Fo(t);if(n)return n}return null}if(typeof e=="object"){const t=e;for(const n of wv){const r=Fo(t[n]);if(r)return r}if("errors"in t){const n=Fo(t.errors);if(n)return n}}return null}function bv(e){if(!e)return"Request failed";const t=e.response,n=Fo(t==null?void 0:t.data);if(n)return n;if(t!=null&&t.statusText)return t.statusText;if(e instanceof Error&&e.message)return e.message;if(typeof e=="string"){const r=e.trim();if(r.length)return r}return t!=null&&t.status?`Request failed with status code ${t.status}`:"Request failed"}function cu({api:e,initialThreadId:t=null,onError:n,onThreadChange:r,onCurrentThreadDeleted:o}){const[s,i]=b.useState([]),[a,l]=b.useState(t),[c,d]=b.useState(!1),[p,m]=b.useState(null),[f,v]=b.useState([]),[g,x]=b.useState(!1),[,y]=b.useState(null),[w,S]=b.useState(null),[k,C]=b.useState(!1),T=b.useRef(a),E=b.useRef(new Map);b.useEffect(()=>{T.current=a},[a]);const A=b.useCallback(async()=>{d(!0),m(null);try{const $=await e.listThreads();i($??[])}catch($){const _=String($);m(_),n==null||n(_)}finally{d(!1)}},[e,n]),O=b.useCallback(async()=>{x(!0),y(null);try{const $=await e.listSharedThreads();v($??[])}catch($){const _=String($);y(_),n==null||n(_)}finally{x(!1)}},[e,n]);b.useEffect(()=>{A()},[A]),b.useEffect(()=>{O()},[O]),b.useEffect(()=>{r==null||r(a)},[a,r]);const F=b.useCallback(async $=>{try{const _=await e.createThread($);return l(_.threadId),await A(),_.threadId}catch(_){const V=String(_);return n==null||n(V),null}},[e,n,A]),U=b.useCallback(async $=>{const _=s;i(J=>J.filter(j=>j.threadId!==$));const V=new AbortController;E.current.set($,V);try{await e.deleteThread($),T.current===$&&(l(null),o==null||o())}catch(J){i(_);const j=String(J);n==null||n(j)}finally{E.current.delete($)}},[e,o,n,s]),W=b.useCallback(async($,_)=>{try{await e.updateThread($,_),await A()}catch(V){n==null||n(String(V))}},[e,n,A]),z=b.useCallback(async($,_)=>{C(!0),S("Sharing thread…");try{await e.shareThread($,_),await O(),S("Shared successfully")}catch(V){const J=bv(V);throw n==null||n(J),S(`Failed to share: ${J}`),new Error(J)}finally{C(!1)}},[e,n,O]),N=b.useCallback(async($,_)=>{try{await e.unshareThread($,_),await O()}catch(V){const J=String(V);throw n==null||n(J),V}},[e,n,O]),K=b.useMemo(()=>({createThread:F,deleteThread:U,renameThread:W,refreshThreads:A,refreshSharedThreads:O,shareThread:z,unshareThread:N}),[F,U,W,A,O,z,N]),M=b.useCallback($=>{if(!($!=null&&$.threadId))return;const _={threadId:$.threadId,title:$.title||`Thread ${$.threadId.slice(0,8)}`,createdAt:$.createdAt||new Date().toISOString(),updatedAt:$.updatedAt||new Date().toISOString(),messageCount:$.messageCount??1};i(V=>{let J=!1;const j=V.map(R=>R.threadId===_.threadId?(J=!0,console.debug("[useThreadsState] thread_info: updating existing thread",_.threadId),{...R,title:_.title??R.title,updatedAt:_.updatedAt??R.updatedAt,messageCount:_.messageCount??R.messageCount}):R);return J?j:(console.debug("[useThreadsState] thread_info: adding thread to list",_.threadId),[_,...V])})},[]),Q=b.useCallback(()=>S(null),[]);return{threads:s,currentThreadId:a,currentThreadIdRef:T,setCurrentThreadId:l,isLoadingThreads:c,threadsError:p,sharedThreads:f,isLoadingSharedThreads:g,actions:K,addThreadFromEvent:M,shareInFlight:k,shareStatus:w,clearShareStatus:Q}}function Ii(e){const t=e==null?void 0:e.trim();if(!t||!(t.startsWith("{")||t.startsWith("[")))return null;try{return JSON.parse(t)}catch{return null}}function uu(e){return!!(e&&typeof e=="object"&&(e.type==="file"||e.mimeType||e.filename||e.sourceType==="base64"))}function Wr(e){if(typeof e=="string")return e;if(e&&typeof e=="object"){if(Array.isArray(e)){const n=e.map(Wr).filter(r=>r!==void 0);if(!n.length){console.debug("[message-utils] sanitizeForDisplay - array emptied -> returning undefined",{originalLength:e.length});return}return n}if(uu(e)){try{console.debug("[message-utils] sanitizeForDisplay - dropping file-like object",{sampleFilename:e&&(e.filename||e.name)?e.filename||e.name:void 0,keys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - dropped file-like (unable to inspect)",{err:String(n)})}return}const t={};for(const n of Object.keys(e)){const r=e[n];if(n==="data"&&typeof r=="string"&&r.length>100)t[n]=`[base64 ${r.length} chars omitted]`;else{const o=Wr(r);o!==void 0&&(t[n]=o)}}if(Object.keys(t).length)return t;try{console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined",{originalKeys:Object.keys(e||{})})}catch(n){console.debug("[message-utils] sanitizeForDisplay - object emptied -> returning undefined (inspect failed)",{err:String(n)})}return}return e}function hr(e){if(typeof e=="string")return e;if(uu(e))return"";try{const t=Wr(e);return t===void 0?"":typeof t=="string"?t:JSON.stringify(t,null,2)}catch{return""}}function yv(e){return typeof e!="string"?!1:/^[\s\n]*[-*]\s|^[\s\n]*#+\s|```|^\s*\[.*\]\(|^>\s/.test(e)}function Sv(e){const t=hr(e);return typeof e=="string"&&yv(e)?{content:e,isMarkdown:!0}:{content:t,isMarkdown:!1}}function Vr(e){if(e==null)return e;if(typeof e=="string"){const t=e.trim();if(t.startsWith("{")||t.startsWith("[")){const n=Ii(t);if(n!==null)return Vr(n)}return e}return typeof e=="object"&&!Array.isArray(e)&&e.content!==void 0?Vr(e.content):e}function Cv(e){return e.filter(t=>t.type==="text").map(t=>t.text).join("")}function Ni(e){const t=e.content.find(s=>s.type==="tool_call"),n=e.additionalKwargs??{},r=typeof(t==null?void 0:t.id)=="string"&&t.id||typeof n.toolCallId=="string"&&n.toolCallId||(e.id.startsWith("tool-")?e.id.slice(5):void 0);return{name:(typeof(t==null?void 0:t.name)=="string"&&t.name||typeof n.toolName=="string"&&n.toolName||e.name&&String(e.name))??void 0,toolCallId:r??void 0}}function Bo(e){if(e==null)return null;const t=String(e).trim();return t.length>0?t:null}function Tv(e){const t=r=>{try{const o=Wr(r);return typeof o=="string"?o:JSON.stringify(o??"")}catch{return""}},n=e.filter(r=>r.type==="text");return n.length?t(n.map(r=>r.text).join(`
|
|
36
36
|
`)):t(e)}function kv(e){return e.name&&e.name.trim()?e.name:e.model&&e.model.includes("/")?e.model.split("/").pop()||null:e.model||null}function du(e){if("type"in e&&e.type==="default_message")return`default:${e.content.length}`;const t=e.updatedAt??e.createdAt??"",n=Array.isArray(e.content)?e.content.map(r=>{switch(r.type){case"text":return`t:${r.text.length}`;case"image_url":return"img";case"file":return"file";case"tool_call":return"call";case"interrupt":return"interrupt";default:return"unknown"}}).join("|"):"";return`${e.id}:${t}:${n}`}function Ev(e){if(!e)return"image/png";const t=e.trim();return t?t.includes("/")?t:`image/${t}`:"image/png"}function Iv(e){const t=[],n=r=>{r&&r.trim()&&t.push(r.trim())};return e&&(n(e.plotId),n(e.artifactId)),t}function Nv({base64:e,url:t,formatHint:n,extras:r}){const o=typeof e=="string"&&e.length>0,s=Ev(n),i=o?`data:${s};base64,${e}`:t,a=Iv(r),l=a.length?a.join(" / "):void 0,c=l?`${l} artifact`:"artifact image";return{src:i,alt:c,label:l}}function Av(e){var o,s;const t=((o=e.content_base64)==null?void 0:o.trim())||void 0,n=((s=e.url)==null?void 0:s.trim())||void 0,r=e.format||e.mimeType||e.mime_type;return Nv({base64:t,url:n,formatHint:r,extras:{plotId:e.plotId,artifactId:e.artifactId}})}function Ai(e){return e.filter(t=>{var i;if(t.role!=="assistant")return!0;const n=(t.content??[]).some(a=>{var l;return a&&a.type==="text"&&((l=a.text)==null?void 0:l.trim())}),r=(t.content??[]).some(a=>a&&a.type==="image_url"),o=(i=t.artifact)==null?void 0:i.plots,s=Array.isArray(o)&&o.length>0;return!!(n||r||s)})}function Kr(e,t,n){return t<0||t>=e.length?e:[...e.slice(0,t),n,...e.slice(t+1)]}function _v(e){let t=!1;const n=e.map(r=>{const o=(r.content??[]).filter(s=>s.type!=="interrupt");return o.length!==r.content.length?(t=!0,{...r,content:o}):r});return t?n:e}function fu(e){for(let t=e.length-1;t>=0;t--)if(e[t].role==="assistant")return e[t].id;return null}function pu(e){return!e||!e.length?"":e.filter(t=>t.type==="text").map(t=>t.text??"").join("")}function jv(e,t,n,r){const o={...n};if(r!==null&&typeof r=="number"){if(typeof o.lastSeq=="number"&&r<=o.lastSeq)return{newParts:e,newMeta:o,changed:!1};o.lastSeq=r}const s=t.filter(p=>p.type==="text").map(p=>p.text??"").join(""),i=t.filter(p=>p.type!=="text"),a=o.lastText??pu(e);let l="",c=e.slice();if(s){const p=Pv(a,s);if(p===""?l="":p===s?l=s:l=p,l){const m=c[c.length-1];if((m==null?void 0:m.type)==="text"){const f=m.text??"",v={...m,text:f+l};c=[...c.slice(0,c.length-1),v]}else c=[...c,{type:"text",text:l}];o.lastText=a+l}else o.lastText=a}i.length&&(c=[...c,...i]);const d=!!(l||i.length);return{newParts:c,newMeta:o,changed:d}}function hu(e){return e.replace(/\s+/g," ").trim()}function Pv(e,t){if(!t)return"";if(!e)return t;if(e===t)return"";const n=Math.min(e.length,t.length);for(let i=n;i>0;i--)if(e.slice(-i)===t.slice(0,i))return t.slice(i);const r=hu(e),o=hu(t);if(r===o)return"";const s=Math.min(r.length,o.length);for(let i=s;i>0;i--)if(r.slice(-i)===o.slice(0,i))return t;return t}function Mv(e,t,n){for(let r=e.length-1;r>=0;r--)if(e[r].role==="assistant"){const s={...e[r],checkpointId:t,checkpointNs:n??void 0};return Kr(e,r,s)}return e}function Rv(e){if(!e)return null;const t=e.split("/");return t[t.length-1]||null}const Ov={messages:[],assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,messagesStreamMeta:{},pendingInterrupt:null};function Dv(e,t){var n;switch(t.type){case"reset":return{messages:Ai(((n=t.payload)==null?void 0:n.messages)??[]),assemblingId:null,lastCheckpointId:null,lastCheckpointNs:null,pendingInterrupt:null,messagesStreamMeta:{}};case"user_message":{const{message:r,editingMessageId:o}=t.payload;if(o){const s=e.messages.findIndex(i=>i.id===o);if(s>=0){const i=e.messages.slice(0,s);return{...e,messages:[...i,r]}}}return{...e,messages:[...e.messages,r]}}case"seed":{const r=Ai(t.payload.messages),o={...e,messages:r,assemblingId:null,pendingInterrupt:t.payload.pendingInterrupt??null};return Object.prototype.hasOwnProperty.call(t.payload,"checkpointId")&&(o.lastCheckpointId=t.payload.checkpointId??null),Object.prototype.hasOwnProperty.call(t.payload,"checkpointNs")&&(o.lastCheckpointNs=t.payload.checkpointNs??null),o}case"prepend":{const r=Ai(t.payload.messages);if(!r.length)return e;const o=new Set(e.messages.map(a=>a.id)),s=r.filter(a=>!o.has(a.id));if(!s.length)return e;const i=[...s,...e.messages];return{...e,messages:i}}case"event":return mu(e,t.payload.ev);case"batch":{const{events:r}=t.payload;return r.length?r.reduce((o,s)=>mu(o,s),e):e}default:return e}}function Lv(e=[]){const[t,n]=b.useReducer(Dv,{...Ov,messages:e}),r=b.useRef([]),o=b.useRef(null),s=b.useRef(null),i=b.useCallback(()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),o.current=null,s.current=null;const d=r.current;d.length&&(r.current=[],n({type:"batch",payload:{events:d}}))},[]),a=b.useCallback(()=>{typeof window<"u"&&typeof window.requestAnimationFrame=="function"?o.current===null&&(o.current=window.requestAnimationFrame(()=>i())):s.current===null&&(s.current=setTimeout(i,8))},[i]),l=b.useCallback(d=>{r.current.push(d),a()},[a]);b.useEffect(()=>()=>{o.current!==null&&typeof window<"u"&&window.cancelAnimationFrame(o.current),s.current!==null&&clearTimeout(s.current),r.current=[]},[]);const c=b.useMemo(()=>({reset:d=>n({type:"reset",payload:{messages:d}}),seed:(d,p)=>n({type:"seed",payload:{messages:d,...p??{}}}),prepend:d=>n({type:"prepend",payload:{messages:d}}),pushUser:(d,p)=>n({type:"user_message",payload:{message:d,editingMessageId:p}}),onEvent:l}),[l]);return{state:t,dispatch:n,...c}}function mu(e,t){var n,r,o;if(t.type==="message.start"&&t.role==="assistant"){const s=t.id,i=Rv(t.model);if(e.messages.some(c=>c.id===s)){const c=e.messagesStreamMeta??{},d={...c,[s]:c[s]??{lastSeq:t.seq??null,lastText:""}};return{...e,assemblingId:s,messagesStreamMeta:d}}const l={id:s,role:"assistant",name:i||void 0,model:t.model,createdAt:new Date().toISOString(),content:[]};return{...e,assemblingId:s,messages:[...e.messages,l]}}if(t.type==="tool.start")return Fv(e,t);if(t.type==="tool.progress")return Bv(e,t);if(t.type==="tool.end")return zv(e,t);if(t.type==="message.delta"){const s=e.assemblingId??fu(e.messages);if(!s)return e;const i=e.messages,a=i.findIndex(C=>C.id===s&&C.role==="assistant");if(a===-1)return e;const l=i[a],c=e.messagesStreamMeta,d=c??{},p=d[s],m=p??{lastSeq:null,lastText:pu(l.content)},f=t.seq??null;if(f!==null&&typeof f=="number"&&typeof m.lastSeq=="number"&&f<=m.lastSeq)return console.debug("[MessageReducer] skipping delta - seq <= lastSeq",{seq:f,lastSeq:m.lastSeq}),e;const{newParts:v,newMeta:g,changed:x}=jv(l.content,t.delta,m,f);if(!x)return e;const y={...l,content:v},w=Kr(i,a,y),S=!p||p.lastSeq!==g.lastSeq||p.lastText!==g.lastText,k=S?{...d,[s]:g}:c;return S?{...e,messages:w,messagesStreamMeta:k}:{...e,messages:w}}if(t.type==="message.end"){const s=e.assemblingId??fu(e.messages);if(!s)return{...e,assemblingId:null};const i=e.messages,a=i.findIndex(l=>l.id===s&&l.role==="assistant");if(a>=0){const l=i[a];if(!((n=l.content)==null?void 0:n.some(d=>{var p;return(d==null?void 0:d.type)==="text"&&((p=d.text)==null?void 0:p.trim())}))){console.debug("[MessageReducer] pruning assistant message with no visible text",{id:l.id,contentTypes:(r=l.content)==null?void 0:r.map(p=>p==null?void 0:p.type),contentPreview:(o=l.content)==null?void 0:o.map(p=>(p==null?void 0:p.type)==="text"?String(p.text).slice(0,100):p==null?void 0:p.type)});const d=[...i.slice(0,a),...i.slice(a+1)];return{...e,assemblingId:null,messages:d}}}return e}if(t.type==="checkpoint"){const s=t.checkpointNs??e.lastCheckpointNs??null,i=Mv(e.messages,t.checkpointId,s);return{...e,lastCheckpointId:t.checkpointId,lastCheckpointNs:s,messages:i}}if(t.type==="error"){const s={id:`err-${Date.now()}`,role:"system",content:[{type:"text",text:`Error: ${t.message}`}],createdAt:new Date().toISOString()};return{...e,messages:[...e.messages,s]}}if(t.type==="state_history"){const s=Nn(t),i=s.interrupt,a=s.latest,l=i===null?_v(e.messages):e.messages;return{...e,messages:l,pendingInterrupt:i,lastCheckpointId:(a==null?void 0:a.checkpointId)??e.lastCheckpointId,lastCheckpointNs:(a==null?void 0:a.checkpointNs)??e.lastCheckpointNs}}return t.type==="thread_info",e}function _i(e){return e.call_id??e.id??null}function gu(e){return e.id??e.call_id??`tool-${Date.now()}-${Math.random().toString(16).slice(2)}`}function xu(e,t,n,r){const o=t??`call-${Date.now()}-${Math.random().toString(16).slice(2)}`;return{id:e,role:"tool",name:n??void 0,content:[{type:"tool_call",id:o,name:n??"tool",args:r??{}}],createdAt:new Date().toISOString(),additionalKwargs:{toolCallId:o,toolName:n??void 0,toolStreaming:!0,toolProgress:[]}}}function ji(e,t){if(!t)return-1;for(let n=0;n<e.length;n+=1){const r=e[n];if(r.role!=="tool")continue;const o=r.additionalKwargs??{};if(typeof o.toolCallId=="string"&&o.toolCallId===t||Ni(r).toolCallId===t)return n}return-1}function $v(e){if(e==null)return[];const t=Vr(e);if(typeof t=="string"&&t.trim())return[{type:"text",text:t}];const n=hr(t??e);return n?[{type:"text",text:n}]:[]}function vu(e,t){const n=e.additionalKwargs??{},r=Array.isArray(n.toolProgress)?[...n.toolProgress]:[],o={...n,toolProgress:[...r,t]};return{...e,additionalKwargs:o}}function Fv(e,t){const n=_i(t),r=ji(e.messages,n),o=t.name??t.tool??void 0,s=gu(t);if(r>=0){const a=e.messages[r],c={...a.additionalKwargs??{},toolStreaming:!0,toolProgress:[]},d={...a,name:o??a.name,additionalKwargs:c};return{...e,messages:Kr(e.messages,r,d)}}const i=xu(s,n,o,t.args);return{...e,messages:[...e.messages,i]}}function Bv(e,t){const n=_i(t);if(!n)return e;const r=ji(e.messages,n);if(r===-1)return e;const o={type:t.type,content:typeof t.content=="string"?t.content:void 0,seq:t.seq??null,timestamp:new Date().toISOString()},s=t.metadata;s&&(o.metadata=s);const i=t.idx;typeof i=="number"&&(o.idx=i);const a=vu(e.messages[r],o);return{...e,messages:Kr(e.messages,r,a)}}function zv(e,t){const n=_i(t),r=gu(t);let o=e.messages,s=ji(o,n);if(s===-1){const v=t.name??t.tool??void 0;o=[...o,xu(r,n,v,{})],s=o.length-1}const i=o[s],a=t.output??t.error??null,l=$v(a),c=[...i.content,...l],d={type:t.type,content:typeof t.output=="string"?t.output:void 0,seq:t.seq??null,timestamp:new Date().toISOString()};t.artifact&&(d.artifact=t.artifact);const p=vu(i,d),m=t.artifact??i.artifact,f={...p,name:t.name??t.tool??i.name,content:c,artifact:m,additionalKwargs:{...p.additionalKwargs??{},toolStreaming:!1}};return{...e,messages:Kr(o,s,f)}}function Hv(e={}){const t=b.useMemo(()=>mn(e.baseUrl),[e.baseUrl]),n=e.streamPath??"/runs/stream",[r,o]=b.useState(e.token??null),s=b.useRef(e.headers??{}),i=e.credentials??"include",[a,l]=b.useState(!1),[c,d]=b.useState(null),[p,m]=b.useState(""),[f,v]=b.useState(null),[g,x]=b.useState(0),[y,w]=b.useState(!1),S=b.useRef(null),k=b.useRef(!0),C=b.useRef(0),T=b.useRef(null),E=b.useRef(null),A=b.useRef(null),O=b.useRef(null),F=b.useCallback(N=>{o(N)},[]),U=b.useCallback(()=>{m(""),v(null),d(null),E.current=null,A.current=null,O.current=null},[]),W=b.useCallback(()=>{var N;console.debug("[use-chat] stop() invoked - aborting stream"),(N=S.current)==null||N.abort(),S.current=null,T.current=null,l(!1),w(!1),C.current=0,x(0)},[]),z=b.useCallback((N,K,M)=>{S.current&&(S.current.abort(),S.current=null),l(!0),d(null),e.autoAppendAssistant!==!1&&m(""),v(null),E.current=null,A.current=null,O.current=null;const Q=new AbortController;S.current=Q;let $=null,_=null,V=!1;return T.current={threadId:N.threadId??null,headers:{}},(async()=>{var j,R,G,Y,ie,H,D,X,Z,ce,L,oe,xe,de,we,Me,He,$e;const J=Ae=>{var Fe;try{const Ge=JSON.parse(JSON.stringify(Ae));return(Fe=Ge==null?void 0:Ge.payload)!=null&&Fe.files_info&&Array.isArray(Ge.payload.files_info)&&(Ge.payload.files_info=Ge.payload.files_info.map(Ke=>({...Ke,data:Ke!=null&&Ke.data?`<base64 ${String(Ke.data).length} chars>`:Ke==null?void 0:Ke.data}))),Ge}catch{return Ae}};try{let Ae={};try{if(r)Ae={Authorization:`Bearer ${r}`};else if(typeof window<"u"){const Be=window.__AUTH_TOKEN__,St=((j=window.localStorage)==null?void 0:j.getItem("authToken"))||null;let xt=null;try{const gt=(R=window.localStorage)==null?void 0:R.getItem("chat-settings");gt&&(xt=((G=JSON.parse(gt))==null?void 0:G.apiKey)||null)}catch{}const Ye=Be||St||xt||null;Ye&&(Ae={Authorization:`Bearer ${Ye}`})}}catch{}console.debug("[use-chat] POST",t+n,J(N));let Fe={};if(typeof window<"u")try{const De=(Y=window.localStorage)==null?void 0:Y.getItem("authSessionId");De&&(Fe={"X-Session-Id":De})}catch{}const Ge={...Ae,...Fe,...s.current},Ke={"Content-Type":"application/json",Accept:"text/event-stream",...Ge},Xe=await fetch(t+n,{method:"POST",headers:Ke,body:JSON.stringify(N),signal:Q.signal,credentials:i});if(T.current&&(T.current.headers=Ge),!Xe.ok||!Xe.body){const De=await Xe.text().catch(()=>"");console.debug("[use-chat] non-OK response",Xe.status,De==null?void 0:De.slice(0,500));const Be=`stream ${Xe.status}${De?": "+De:""}`;throw(ie=M==null?void 0:M.onConnectionError)==null||ie.call(M,Be),V=!0,$="error",_=Be,new Error(Be)}w(!0);const tt=Xe.body.getReader(),nt=new TextDecoder;let Ze="",pt=[];C.current=0,x(0);let ht=0,Se=null;const Re=()=>{if(pt.length){const De=pt.join("");pt=[],k.current&&m(Be=>Be+De)}Se=null},mt=()=>{typeof window<"u"&&Se==null&&(Se=requestAnimationFrame(Re))};let ot=Date.now();const qe=setInterval(()=>{var De;if(Date.now()-ot>18e5){const Be="Stream idle timeout";d(Be),$="error",_=Be,Q.abort(),(De=M==null?void 0:M.onError)==null||De.call(M,Be)}},5e3),yt=1024*1024;try{const De=Xe.headers.get("X-Thread-Id")||Xe.headers.get("x-thread-id"),Be=Xe.headers.get("X-Thread-Created")||Xe.headers.get("x-thread-created"),St=De??null,xt=String(Be??"").toLowerCase()==="true";for(T.current&&!T.current.threadId&&(T.current={...T.current,threadId:St}),(H=M==null?void 0:M.onOpen)==null||H.call(M,{threadId:St,created:xt});;){const{value:Ye,done:gt}=await tt.read();if(gt)break;Ze+=nt.decode(Ye,{stream:!0}),Ze.length>yt&&(Ze="",console.warn("Stream buffer reset: exceeded 1MB"));let P;for(;(P=Ze.indexOf(`
|
|
37
37
|
|
|
38
38
|
`))>=0;){const te=Ze.slice(0,P);Ze=Ze.slice(P+2);const ve=Wv(te);if(!ve)continue;let ae;try{ae=JSON.parse(ve)}catch{console.debug("[use-chat] malformed SSE:",ve.slice(0,200));continue}const Ie=Uv(ae)?ae.data:ae;if(!Ie){console.warn("[use-chat] dropped envelope event without payload",ae);continue}const Te=Ie;ot=Date.now();const st=Te.seq;if(st!==void 0){if(st<=ht){console.debug("[use-chat] drop duplicate/out-of-order event",{seq:st,lastProcessedSeq:ht,type:Te.type});continue}ht>0&&st>ht+1&&((D=M==null?void 0:M.onGap)==null||D.call(M,{from:ht,to:st})),ht=st,C.current=st,x(st)}if(Te.type==="checkpoint")E.current=Te.checkpointId??null,A.current=Te.checkpointNs??null,v(Te.checkpointId??null);else if(Te.type==="state_history"){O.current=Te;try{const lt=Nn(Te).latest;lt&&(E.current=lt.checkpointId??null,A.current=lt.checkpointNs??null,v(lt.checkpointId??null))}catch(Ue){console.warn("[use-chat] Failed to hydrate state_history payload",Ue)}}try{K==null||K(Te)}catch(Ue){console.error("[use-chat] Error in onEvent callback:",Ue,"for event:",Te.type)}if(Te.type==="message.delta"){const Ue=Te.delta.filter(lt=>lt.type==="text").map(lt=>lt.text).join("");Ue&&e.autoAppendAssistant!==!1&&(pt.push(Ue),mt())}else if(Te.type==="heartbeat"){console.debug("[use-chat] heartbeat received");try{(X=M==null?void 0:M.onHeartbeat)==null||X.call(M,Te)}catch(Ue){console.warn("[use-chat] heartbeat callback failed",Ue)}}else if(Se!==null&&cancelAnimationFrame(Se),Re(),Te.type==="checkpoint")v(Te.checkpointId);else if(Te.type==="error"){const Ue=Te;if(d(Ue.message),$="error",_=Ue.message,Ue.error_type==="auth_error"||Ue.code==="TOKEN_EXPIRED"||((Z=Ue.message)==null?void 0:Z.includes("token"))||((ce=Ue.message)==null?void 0:ce.includes("401"))||((L=Ue.message)==null?void 0:L.includes("unauthorized"))||((oe=Ue.message)==null?void 0:oe.includes("Unauthorized"))){console.error("[use-chat] Auth error detected:",Ue.message);try{(xe=M==null?void 0:M.onAuthError)==null||xe.call(M,Ue.message)}catch(Ut){console.warn("[use-chat] onAuthError handler failed",Ut)}Q.abort()}}}}Re(),$===null&&!Q.signal.aborted&&($="complete")}catch(De){if(De.name==="AbortError")$=$??"aborted";else{const Be=De.message||String(De);$="error",_=Be,d(Be),(de=M==null?void 0:M.onError)==null||de.call(M,Be)}}finally{try{await tt.cancel()}catch{}finally{(we=tt.releaseLock)==null||we.call(tt)}Se!==null&&typeof window<"u"&&window.cancelAnimationFrame(Se),clearInterval(qe)}}catch(Ae){if(Ae.name==="AbortError")$=$??"aborted";else{const Fe=Ae.message||String(Ae);$="error",_=Fe,d(Fe),(Me=M==null?void 0:M.onError)==null||Me.call(M,Fe),V||((He=M==null?void 0:M.onConnectionError)==null||He.call(M,Fe),V=!0)}}finally{const Ae=C.current,Fe=E.current,Ge=A.current,Ke=O.current,Xe=$??(Q.signal.aborted?"aborted":_?"error":"complete");try{($e=M==null?void 0:M.onClosed)==null||$e.call(M,{reason:Xe,lastSeq:Ae,lastCheckpointId:Fe,lastCheckpointNs:Ge,lastStateHistory:Ke,error:_})}catch(tt){console.warn("[use-chat] onClosed callback failed",tt)}l(!1),w(!1),S.current=null,C.current=0,x(0),T.current=null}})(),{close:()=>Q.abort()}},[t,n,r,e.autoAppendAssistant]);return b.useEffect(()=>()=>{var N;k.current=!1,(N=S.current)==null||N.abort()},[]),{isStreaming:a,error:c,assistantText:p,lastCheckpointId:f,lastSeq:g,connected:y,stream:z,stop:W,clear:U,setToken:F}}function Uv(e){return!!e&&typeof e=="object"&&e.protocolVersion==="v1"&&"data"in e}function Wv(e){const t=e.split(/\r?\n/),n=[];for(const r of t)if(r&&!r.startsWith(":")&&r.startsWith("data:")){const o=r.slice(5);n.push(o.startsWith(" ")?o.slice(1):o)}return n.length===0?null:n.join(`
|
|
39
|
-
`)}const wu=b.createContext(null),bu=b.createContext(null),yu=b.createContext(null);b.createContext(!1);function Vv({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:l,onToolEnd:c}){const{api:d,baseUrl:p}=ki(),m=b.useMemo(()=>mn(p),[p]),{state:f,seed:v,prepend:g,pushUser:x,onEvent:y}=Lv(),{threads:w,currentThreadId:S,setCurrentThreadId:k,currentThreadIdRef:C,isLoadingThreads:T,threadsError:E,sharedThreads:A,isLoadingSharedThreads:O,actions:F,addThreadFromEvent:U,shareInFlight:W,shareStatus:z,clearShareStatus:N}=cu({api:d,initialThreadId:t,onError:s,onThreadChange:a,onCurrentThreadDeleted:()=>v([],{})}),[K,M]=b.useState(!1),Q=b.useCallback(()=>f.messages,[f.messages]),{threadCheckpoints:$,threadTimeline:_,checkpointIndex:V,isLoadingThread:J,isHistoryLoading:j,isLoadingCheckpoint:R,threadStateError:G,hasMoreHistory:Y,loadThread:ie,navigateToCheckpoint:H,loadOlderMessages:D,setCurrentCheckpointId:X,returnToLatest:Z,handleStateHistoryEvent:ce,markSkipNextLoad:L,markStreamPendingThread:oe,resetHistoryState:xe}=lu({api:d,seed:v,prepend:g,onError:s,currentThreadId:S,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,isStreaming:K,getMessages:Q}),de=b.useCallback(Se=>{console.log("[StreamingProvider] 🎯 Received thread_info:",Se.threadId),U(Se),C.current!==Se.threadId&&((Se.created??!C.current)&&L(Se.threadId),oe(Se.threadId),console.log("[StreamingProvider] thread_info: marking to skip auto-load for new thread"),k(Se.threadId))},[U,L,oe]),we=b.useCallback(Se=>{Se.type==="thread_info"?de(Se):Se.type==="state_history"?ce(Se):Se.type==="tool.end"?c==null||c(Se):y(Se)},[de,ce,c,y]),{stream:Me,stop:He,isStreaming:$e,error:Ae,setToken:Fe}=Hv({baseUrl:m}),Ge=b.useCallback(Se=>{Me(Se,we,{onError:Re=>{console.error("[StreamingProvider] Stream error:",Re),s==null||s(Re)},onAuthError:Re=>{console.error("[StreamingProvider] Auth error:",Re),i==null||i(Re)},onConnectionError:Re=>{console.error("[StreamingProvider] Connection error:",Re),l==null||l(Re)}})},[Me,we,s,i,l]);b.useEffect(()=>{M($e)},[$e]);const Ke=b.useCallback(async()=>{v([],{}),k(null),He(),xe();try{await d.getAgent("default")}catch(Se){console.warn("[StreamingProvider] Failed to refetch agent after clearing thread:",Se)}},[v,He,d,xe]),Xe=b.useCallback(async(Se,Re,mt)=>{const ot=C.current;if(!ot)throw new Error("No active thread to handle interrupt");const qe=Re?mt??!0:!1;try{const yt={threadId:ot,checkpointId:f.lastCheckpointId??void 0,checkpointNs:f.lastCheckpointNs??void 0,command:{kind:"resume",value:qe}};Ge(yt)}catch(yt){throw console.error(`[StreamingProvider] Failed to handle interrupt ${Se}:`,yt),yt}},[f.lastCheckpointId,f.lastCheckpointNs,Ge]),tt=b.useCallback(async(Se,Re)=>{let mt=C.current;const ot=(Se==null?void 0:Se.text)??"",qe=(Se==null?void 0:Se.attachments)??[],yt=(ot==null?void 0:ot.trim())??"",De={...(Se==null?void 0:Se.payload)??{}},Be=Array.isArray(De.messages)?De.messages:void 0;Be&&delete De.messages;const St=!!(Be&&Be.length);if(!mt&&!yt&&qe.length===0&&!St)return;if(!mt){const Ue=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),lt=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);mt=`${Ue}${lt}`,L(mt),k(mt)}const{contentParts:xt,filesInfo:Ye}=await eu(qe),gt=[...xt];yt&>.push({type:"text",text:ot});const P=Re==null?void 0:Re.originalMessageId,te=!!(Re!=null&&Re.edit&&P),ve=!St&>.length>0;let ae=null;ve&&(ae={id:te?P:`msg-${Date.now()}`,role:"user",content:gt,createdAt:new Date().toISOString()},te?x(ae,P):x(ae));const Ie=St?Be:ae?[ae]:[],Te={...De,...Ye.length?{files_info:Ye}:{}};Ie.length?Te.messages=Ie:"messages"in Te||(Te.messages=[]);const st={threadId:mt,payload:Te,checkpointId:(Re==null?void 0:Re.checkpointId)??f.lastCheckpointId??void 0,checkpointNs:(Re==null?void 0:Re.checkpointNs)??f.lastCheckpointNs??void 0,edit:!!(Re!=null&&Re.edit),timelineCheckpoints:_};Ge(st)},[d,x,f,Ge,_]),nt=b.useMemo(()=>({threads:w,currentThreadId:S,setCurrentThreadId:k,isLoading:T,error:E,sharedThreads:A,isLoadingSharedThreads:O,actions:F,shareInFlight:W,shareStatus:z,clearShareStatus:N}),[w,S,k,T,E,A,O,F,W,z,N]),Ze=b.useMemo(()=>{const Se=f.assemblingId??null;return Se?{assemblingMessageId:Se}:null},[f.assemblingId]),pt=b.useMemo(()=>({threadId:S,messages:f.messages,interrupt:null,checkpoint:{id:f.lastCheckpointId??null,namespace:f.lastCheckpointNs??null},checkpoints:$,checkpointIndex:V,timelineCheckpoints:_,metadata:Ze,isLoading:J,isHistoryLoading:j,isLoadingCheckpoint:R,error:G,hasMore:Y,loadOlder:D,clearState:Ke,navigateToCheckpoint:H,setCurrentCheckpointId:X,returnToLatest:Z,loadThread:ie,clearThread:Ke,respondToInterrupt:Xe,messagePreviews:V.messagePreviews}),[S,f,$,_,V,J,j,R,G,Y,D,Ke,H,X,Z,ie,Xe,Ze]),ht=b.useMemo(()=>({isStreaming:$e,error:Ae,connectionState:$e?"connected":"idle",submit:tt,send:tt,stop:He,setAuthToken:Fe}),[$e,Ae,tt,He,Fe]);return u.jsx(wu.Provider,{value:nt,children:u.jsx(bu.Provider,{value:pt,children:u.jsx(yu.Provider,{value:ht,children:e})})})}function Pi(){const e=b.useContext(wu);if(!e)throw new Error("useThreads must be used within StreamingProvider");return e}function Mi(){const e=b.useContext(bu);if(!e)throw new Error("useThreadState must be used within StreamingProvider");return e}function Su(){const e=b.useContext(yu);if(!e)throw new Error("useStream must be used within StreamingProvider");return e}function zo({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:l,onThreadChange:c,onToolEnd:d}){return u.jsx(Zc,{apiConfig:t,children:u.jsx(Vv,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:l,onConnectionError:i,onThreadChange:c,onToolEnd:d,children:e})})}function re(...e){return Og.twMerge(Rg.clsx(e))}const Kv=Or.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ct=h.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Vt.Slot:"button";return u.jsx(i,{className:re(Kv({variant:t,size:n,className:e})),ref:s,...o})});ct.displayName="Button";var Cu=1,qv=.9,Gv=.8,Yv=.17,Ri=.1,Oi=.999,Xv=.9999,Jv=.99,Zv=/[\\\/_+.#"@\[\(\{&]/,Qv=/[\\\/_+.#"@\[\(\{&]/g,ew=/[\s-]/,Tu=/[\s-]/g;function Di(e,t,n,r,o,s,i){if(s===t.length)return o===e.length?Cu:Jv;var a=`${o},${s}`;if(i[a]!==void 0)return i[a];for(var l=r.charAt(s),c=n.indexOf(l,o),d=0,p,m,f,v;c>=0;)p=Di(e,t,n,r,c+1,s+1,i),p>d&&(c===o?p*=Cu:Zv.test(e.charAt(c-1))?(p*=Gv,f=e.slice(o,c-1).match(Qv),f&&o>0&&(p*=Math.pow(Oi,f.length))):ew.test(e.charAt(c-1))?(p*=qv,v=e.slice(o,c-1).match(Tu),v&&o>0&&(p*=Math.pow(Oi,v.length))):(p*=Yv,o>0&&(p*=Math.pow(Oi,c-o))),e.charAt(c)!==t.charAt(s)&&(p*=Xv)),(p<Ri&&n.charAt(c-1)===r.charAt(s+1)||r.charAt(s+1)===r.charAt(s)&&n.charAt(c-1)!==r.charAt(s))&&(m=Di(e,t,n,r,c+1,s+2,i),m*Ri>p&&(p=m*Ri)),p>d&&(d=p),c=n.indexOf(l,c+1);return i[a]=d,d}function ku(e){return e.toLowerCase().replace(Tu," ")}function tw(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Di(e,t,ku(e),ku(t),0,0,{})}function le(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function Eu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function _n(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Eu(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():Eu(e[o],null)}}}}function We(...e){return h.useCallback(_n(...e),e)}function nw(e,t){const n=h.createContext(t),r=s=>{const{children:i,...a}=s,l=h.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=h.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function sn(e,t=[]){let n=[];function r(s,i){const a=h.createContext(i),l=n.length;n=[...n,i];const c=p=>{var y;const{scope:m,children:f,...v}=p,g=((y=m==null?void 0:m[e])==null?void 0:y[l])||a,x=h.useMemo(()=>v,Object.values(v));return u.jsx(g.Provider,{value:x,children:f})};c.displayName=s+"Provider";function d(p,m){var g;const f=((g=m==null?void 0:m[e])==null?void 0:g[l])||a,v=h.useContext(f);if(v)return v;if(i!==void 0)return i;throw new Error(`\`${p}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>h.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return h.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,rw(o,...t)]}function rw(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const p=l(s)[`__scope${c}`];return{...a,...p}},{});return h.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var It=globalThis!=null&&globalThis.document?h.useLayoutEffect:()=>{},ow=h[" useId ".trim().toString()]||(()=>{}),sw=0;function At(e){const[t,n]=h.useState(ow());return It(()=>{n(r=>r??String(sw++))},[e]),t?`radix-${t}`:""}var iw=h[" useInsertionEffect ".trim().toString()]||It;function jn({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=aw({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=h.useRef(e!==void 0);h.useEffect(()=>{const p=d.current;p!==a&&console.warn(`${r} is changing from ${p?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=h.useCallback(d=>{var p;if(a){const m=lw(d)?d(e):d;m!==e&&((p=i.current)==null||p.call(i,m))}else s(d)},[a,e,s,i]);return[l,c]}function aw({defaultProp:e,onChange:t}){const[n,r]=h.useState(e),o=h.useRef(n),s=h.useRef(t);return iw(()=>{s.current=t},[t]),h.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function lw(e){return typeof e=="function"}var cw=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ye=cw.reduce((e,t)=>{const n=Vt.createSlot(`Primitive.${t}`),r=h.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Li(e,t){e&&Dr.flushSync(()=>e.dispatchEvent(t))}function wt(e){const t=h.useRef(e);return h.useEffect(()=>{t.current=e}),h.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function uw(e,t=globalThis==null?void 0:globalThis.document){const n=wt(e);h.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var dw="DismissableLayer",$i="dismissableLayer.update",fw="dismissableLayer.pointerDownOutside",pw="dismissableLayer.focusOutside",Iu,Nu=h.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),mr=h.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=h.useContext(Nu),[d,p]=h.useState(null),m=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=h.useState({}),v=We(t,E=>p(E)),g=Array.from(c.layers),[x]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),y=g.indexOf(x),w=d?g.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=w>=y,C=mw(E=>{const A=E.target,O=[...c.branches].some(F=>F.contains(A));!k||O||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},m),T=gw(E=>{const A=E.target;[...c.branches].some(F=>F.contains(A))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},m);return uw(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},m),h.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(Iu=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),_u(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Iu)}},[d,m,n,c]),h.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),_u())},[d,c]),h.useEffect(()=>{const E=()=>f({});return document.addEventListener($i,E),()=>document.removeEventListener($i,E)},[]),u.jsx(ye.div,{...l,ref:v,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:le(e.onFocusCapture,T.onFocusCapture),onBlurCapture:le(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:le(e.onPointerDownCapture,C.onPointerDownCapture)})});mr.displayName=dw;var hw="DismissableLayerBranch",Au=h.forwardRef((e,t)=>{const n=h.useContext(Nu),r=h.useRef(null),o=We(t,r);return h.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(ye.div,{...e,ref:o})});Au.displayName=hw;function mw(e,t=globalThis==null?void 0:globalThis.document){const n=wt(e),r=h.useRef(!1),o=h.useRef(()=>{});return h.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){ju(fw,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function gw(e,t=globalThis==null?void 0:globalThis.document){const n=wt(e),r=h.useRef(!1);return h.useEffect(()=>{const o=s=>{s.target&&!r.current&&ju(pw,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function _u(){const e=new CustomEvent($i);document.dispatchEvent(e)}function ju(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?Li(o,s):o.dispatchEvent(s)}var xw=mr,vw=Au,Fi="focusScope.autoFocusOnMount",Bi="focusScope.autoFocusOnUnmount",Pu={bubbles:!1,cancelable:!0},ww="FocusScope",Ho=h.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=h.useState(null),c=wt(o),d=wt(s),p=h.useRef(null),m=We(t,g=>l(g)),f=h.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;h.useEffect(()=>{if(r){let g=function(S){if(f.paused||!a)return;const k=S.target;a.contains(k)?p.current=k:Pn(p.current,{select:!0})},x=function(S){if(f.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||Pn(p.current,{select:!0}))},y=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&Pn(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",x);const w=new MutationObserver(y);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",x),w.disconnect()}}},[r,a,f.paused]),h.useEffect(()=>{if(a){Ou.add(f);const g=document.activeElement;if(!a.contains(g)){const y=new CustomEvent(Fi,Pu);a.addEventListener(Fi,c),a.dispatchEvent(y),y.defaultPrevented||(bw(kw(Mu(a)),{select:!0}),document.activeElement===g&&Pn(a))}return()=>{a.removeEventListener(Fi,c),setTimeout(()=>{const y=new CustomEvent(Bi,Pu);a.addEventListener(Bi,d),a.dispatchEvent(y),y.defaultPrevented||Pn(g??document.body,{select:!0}),a.removeEventListener(Bi,d),Ou.remove(f)},0)}}},[a,c,d,f]);const v=h.useCallback(g=>{if(!n&&!r||f.paused)return;const x=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,y=document.activeElement;if(x&&y){const w=g.currentTarget,[S,k]=yw(w);S&&k?!g.shiftKey&&y===k?(g.preventDefault(),n&&Pn(S,{select:!0})):g.shiftKey&&y===S&&(g.preventDefault(),n&&Pn(k,{select:!0})):y===w&&g.preventDefault()}},[n,r,f.paused]);return u.jsx(ye.div,{tabIndex:-1,...i,ref:m,onKeyDown:v})});Ho.displayName=ww;function bw(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Pn(r,{select:t}),document.activeElement!==n)return}function yw(e){const t=Mu(e),n=Ru(t,e),r=Ru(t.reverse(),e);return[n,r]}function Mu(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Ru(e,t){for(const n of e)if(!Sw(n,{upTo:t}))return n}function Sw(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Cw(e){return e instanceof HTMLInputElement&&"select"in e}function Pn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Cw(e)&&t&&e.select()}}var Ou=Tw();function Tw(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Du(e,t),e.unshift(t)},remove(t){var n;e=Du(e,t),(n=e[0])==null||n.resume()}}}function Du(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function kw(e){return e.filter(t=>t.tagName!=="A")}var Ew="Portal",qr=h.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=h.useState(!1);It(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?To.createPortal(u.jsx(ye.div,{...r,ref:t}),i):null});qr.displayName=Ew;function Iw(e,t){return h.useReducer((n,r)=>t[n][r]??n,e)}var Ft=e=>{const{present:t,children:n}=e,r=Nw(t),o=typeof n=="function"?n({present:r.isPresent}):h.Children.only(n),s=We(r.ref,Aw(o));return typeof n=="function"||r.isPresent?h.cloneElement(o,{ref:s}):null};Ft.displayName="Presence";function Nw(e){const[t,n]=h.useState(),r=h.useRef(null),o=h.useRef(e),s=h.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Iw(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return h.useEffect(()=>{const c=Uo(r.current);s.current=a==="mounted"?c:"none"},[a]),It(()=>{const c=r.current,d=o.current;if(d!==e){const m=s.current,f=Uo(c);e?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&m!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),It(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,p=f=>{const g=Uo(r.current).includes(CSS.escape(f.animationName));if(f.target===t&&g&&(l("ANIMATION_END"),!o.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},m=f=>{f.target===t&&(s.current=Uo(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:h.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Uo(e){return(e==null?void 0:e.animationName)||"none"}function Aw(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var zi=0;function Hi(){h.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Lu()),document.body.insertAdjacentElement("beforeend",e[1]??Lu()),zi++,()=>{zi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),zi--}},[])}function Lu(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var gn=function(){return gn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},gn.apply(this,arguments)};function $u(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function _w(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Wo="right-scroll-bar-position",Vo="width-before-scroll-bar",jw="with-scroll-bars-hidden",Pw="--removed-body-scroll-bar-size";function Ui(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Mw(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Rw=typeof window<"u"?h.useLayoutEffect:h.useEffect,Fu=new WeakMap;function Ow(e,t){var n=Mw(null,function(r){return e.forEach(function(o){return Ui(o,r)})});return Rw(function(){var r=Fu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Ui(a,null)}),s.forEach(function(a){o.has(a)||Ui(a,i)})}Fu.set(n,e)},[e]),n}function Dw(e){return e}function Lw(e,t){t===void 0&&(t=Dw);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function $w(e){e===void 0&&(e={});var t=Lw(null);return t.options=gn({async:!0,ssr:!1},e),t}var Bu=function(e){var t=e.sideCar,n=$u(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return h.createElement(r,gn({},n))};Bu.isSideCarExport=!0;function Fw(e,t){return e.useMedium(t),Bu}var zu=$w(),Wi=function(){},Ko=h.forwardRef(function(e,t){var n=h.useRef(null),r=h.useState({onScrollCapture:Wi,onWheelCapture:Wi,onTouchMoveCapture:Wi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,p=e.shards,m=e.sideCar,f=e.noRelative,v=e.noIsolation,g=e.inert,x=e.allowPinchZoom,y=e.as,w=y===void 0?"div":y,S=e.gapMode,k=$u(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=m,T=Ow([n,t]),E=gn(gn({},k),o);return h.createElement(h.Fragment,null,d&&h.createElement(C,{sideCar:zu,removeScrollBar:c,shards:p,noRelative:f,noIsolation:v,inert:g,setCallbacks:s,allowPinchZoom:!!x,lockRef:n,gapMode:S}),i?h.cloneElement(h.Children.only(a),gn(gn({},E),{ref:T})):h.createElement(w,gn({},E,{className:l,ref:T}),a))});Ko.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Ko.classNames={fullWidth:Vo,zeroRight:Wo};var Bw=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function zw(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Bw();return t&&e.setAttribute("nonce",t),e}function Hw(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Uw(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Ww=function(){var e=0,t=null;return{add:function(n){e==0&&(t=zw())&&(Hw(t,n),Uw(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Vw=function(){var e=Ww();return function(t,n){h.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Hu=function(){var e=Vw(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Kw={left:0,top:0,right:0,gap:0},Vi=function(e){return parseInt(e||"",10)||0},qw=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Vi(n),Vi(r),Vi(o)]},Gw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Kw;var t=qw(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Yw=Hu(),gr="data-scroll-locked",Xw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
|
39
|
+
`)}const wu=b.createContext(null),bu=b.createContext(null),yu=b.createContext(null);b.createContext(!1);function Vv({children:e,initialThreadId:t=null,initialCheckpointId:n=null,initialCheckpointNs:r=null,autoLoadInitial:o=!0,onError:s,onAuthError:i,onThreadChange:a,onConnectionError:l,onToolEnd:c}){const{api:d,baseUrl:p}=ki(),m=b.useMemo(()=>mn(p),[p]),{state:f,seed:v,prepend:g,pushUser:x,onEvent:y}=Lv(),{threads:w,currentThreadId:S,setCurrentThreadId:k,currentThreadIdRef:C,isLoadingThreads:T,threadsError:E,sharedThreads:A,isLoadingSharedThreads:O,actions:F,addThreadFromEvent:U,shareInFlight:W,shareStatus:z,clearShareStatus:N}=cu({api:d,initialThreadId:t,onError:s,onThreadChange:a,onCurrentThreadDeleted:()=>v([],{})}),[K,M]=b.useState(!1),Q=b.useCallback(()=>f.messages,[f.messages]),{threadCheckpoints:$,threadTimeline:_,checkpointIndex:V,isLoadingThread:J,isHistoryLoading:j,isLoadingCheckpoint:R,threadStateError:G,hasMoreHistory:Y,loadThread:ie,navigateToCheckpoint:H,loadOlderMessages:D,setCurrentCheckpointId:X,returnToLatest:Z,handleStateHistoryEvent:ce,markSkipNextLoad:L,markStreamPendingThread:oe,resetHistoryState:xe}=lu({api:d,seed:v,prepend:g,onError:s,currentThreadId:S,initialThreadId:t,initialCheckpointId:n,initialCheckpointNs:r,autoLoadInitial:o,isStreaming:K,getMessages:Q}),de=b.useCallback(Se=>{console.log("[StreamingProvider] 🎯 Received thread_info:",Se.threadId),U(Se),C.current!==Se.threadId&&((Se.created??!C.current)&&L(Se.threadId),oe(Se.threadId),console.log("[StreamingProvider] thread_info: marking to skip auto-load for new thread"),k(Se.threadId))},[U,L,oe]),we=b.useCallback(Se=>{Se.type==="thread_info"?de(Se):Se.type==="state_history"?ce(Se):Se.type==="tool.end"?c==null||c(Se):y(Se)},[de,ce,c,y]),{stream:Me,stop:He,isStreaming:$e,error:Ae,setToken:Fe}=Hv({baseUrl:m}),Ge=b.useCallback(Se=>{Me(Se,we,{onError:Re=>{console.error("[StreamingProvider] Stream error:",Re),s==null||s(Re)},onAuthError:Re=>{console.error("[StreamingProvider] Auth error:",Re),i==null||i(Re)},onConnectionError:Re=>{console.error("[StreamingProvider] Connection error:",Re),l==null||l(Re)}})},[Me,we,s,i,l]);b.useEffect(()=>{M($e)},[$e]);const Ke=b.useCallback(async()=>{v([],{}),k(null),He(),xe();try{await d.getAgent("default")}catch(Se){console.warn("[StreamingProvider] Failed to refetch agent after clearing thread:",Se)}},[v,He,d,xe]),Xe=b.useCallback(async(Se,Re,mt)=>{const ot=C.current;if(!ot)throw new Error("No active thread to handle interrupt");const qe=Re?mt??!0:!1;try{const yt={threadId:ot,checkpointId:f.lastCheckpointId??void 0,checkpointNs:f.lastCheckpointNs??void 0,command:{kind:"resume",value:qe}};Ge(yt)}catch(yt){throw console.error(`[StreamingProvider] Failed to handle interrupt ${Se}:`,yt),yt}},[f.lastCheckpointId,f.lastCheckpointNs,Ge]),tt=b.useCallback(async(Se,Re)=>{let mt=C.current;const ot=(Se==null?void 0:Se.text)??"",qe=(Se==null?void 0:Se.attachments)??[],yt=(ot==null?void 0:ot.trim())??"",De={...(Se==null?void 0:Se.payload)??{}},Be=Array.isArray(De.messages)?De.messages:void 0;Be&&delete De.messages;const St=!!(Be&&Be.length);if(!mt&&!yt&&qe.length===0&&!St)return;if(!mt){const Ue=Math.floor(Date.now()/1e3).toString(16).padStart(8,"0"),lt=Array.from({length:4},()=>Math.floor(Math.random()*4294967295).toString(16).padStart(8,"0")).join("").slice(0,16);mt=`${Ue}${lt}`,L(mt),k(mt)}const{contentParts:xt,filesInfo:Ye}=await Zc(qe),gt=[...xt];yt&>.push({type:"text",text:ot});const P=Re==null?void 0:Re.originalMessageId,te=!!(Re!=null&&Re.edit&&P),ve=!St&>.length>0;let ae=null;ve&&(ae={id:te?P:`msg-${Date.now()}`,role:"user",content:gt,createdAt:new Date().toISOString()},te?x(ae,P):x(ae));const Ie=St?Be:ae?[ae]:[],Te={...De,...Ye.length?{files_info:Ye}:{}};Ie.length?Te.messages=Ie:"messages"in Te||(Te.messages=[]);const st={threadId:mt,payload:Te,checkpointId:(Re==null?void 0:Re.checkpointId)??f.lastCheckpointId??void 0,checkpointNs:(Re==null?void 0:Re.checkpointNs)??f.lastCheckpointNs??void 0,edit:!!(Re!=null&&Re.edit),timelineCheckpoints:_};Ge(st)},[d,x,f,Ge,_]),nt=b.useMemo(()=>({threads:w,currentThreadId:S,setCurrentThreadId:k,isLoading:T,error:E,sharedThreads:A,isLoadingSharedThreads:O,actions:F,shareInFlight:W,shareStatus:z,clearShareStatus:N}),[w,S,k,T,E,A,O,F,W,z,N]),Ze=b.useMemo(()=>{const Se=f.assemblingId??null;return Se?{assemblingMessageId:Se}:null},[f.assemblingId]),pt=b.useMemo(()=>({threadId:S,messages:f.messages,interrupt:null,checkpoint:{id:f.lastCheckpointId??null,namespace:f.lastCheckpointNs??null},checkpoints:$,checkpointIndex:V,timelineCheckpoints:_,metadata:Ze,isLoading:J,isHistoryLoading:j,isLoadingCheckpoint:R,error:G,hasMore:Y,loadOlder:D,clearState:Ke,navigateToCheckpoint:H,setCurrentCheckpointId:X,returnToLatest:Z,loadThread:ie,clearThread:Ke,respondToInterrupt:Xe,messagePreviews:V.messagePreviews}),[S,f,$,_,V,J,j,R,G,Y,D,Ke,H,X,Z,ie,Xe,Ze]),ht=b.useMemo(()=>({isStreaming:$e,error:Ae,connectionState:$e?"connected":"idle",submit:tt,send:tt,stop:He,setAuthToken:Fe}),[$e,Ae,tt,He,Fe]);return u.jsx(wu.Provider,{value:nt,children:u.jsx(bu.Provider,{value:pt,children:u.jsx(yu.Provider,{value:ht,children:e})})})}function Pi(){const e=b.useContext(wu);if(!e)throw new Error("useThreads must be used within StreamingProvider");return e}function Mi(){const e=b.useContext(bu);if(!e)throw new Error("useThreadState must be used within StreamingProvider");return e}function Su(){const e=b.useContext(yu);if(!e)throw new Error("useStream must be used within StreamingProvider");return e}function zo({children:e,apiConfig:t,initialThreadId:n=null,initialCheckpointId:r=null,initialCheckpointNs:o=null,autoLoadInitial:s=!0,onConnectionError:i,onError:a,onAuthError:l,onThreadChange:c,onToolEnd:d}){return u.jsx(au,{apiConfig:t,children:u.jsx(Vv,{initialThreadId:n,initialCheckpointId:r,initialCheckpointNs:o,autoLoadInitial:s,onError:a,onAuthError:l,onConnectionError:i,onThreadChange:c,onToolEnd:d,children:e})})}function re(...e){return Og.twMerge(Rg.clsx(e))}const Kv=Or.cva("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-md px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),ct=h.forwardRef(({className:e,variant:t,size:n,asChild:r=!1,...o},s)=>{const i=r?Vt.Slot:"button";return u.jsx(i,{className:re(Kv({variant:t,size:n,className:e})),ref:s,...o})});ct.displayName="Button";var Cu=1,qv=.9,Gv=.8,Yv=.17,Ri=.1,Oi=.999,Xv=.9999,Jv=.99,Zv=/[\\\/_+.#"@\[\(\{&]/,Qv=/[\\\/_+.#"@\[\(\{&]/g,ew=/[\s-]/,Tu=/[\s-]/g;function Di(e,t,n,r,o,s,i){if(s===t.length)return o===e.length?Cu:Jv;var a=`${o},${s}`;if(i[a]!==void 0)return i[a];for(var l=r.charAt(s),c=n.indexOf(l,o),d=0,p,m,f,v;c>=0;)p=Di(e,t,n,r,c+1,s+1,i),p>d&&(c===o?p*=Cu:Zv.test(e.charAt(c-1))?(p*=Gv,f=e.slice(o,c-1).match(Qv),f&&o>0&&(p*=Math.pow(Oi,f.length))):ew.test(e.charAt(c-1))?(p*=qv,v=e.slice(o,c-1).match(Tu),v&&o>0&&(p*=Math.pow(Oi,v.length))):(p*=Yv,o>0&&(p*=Math.pow(Oi,c-o))),e.charAt(c)!==t.charAt(s)&&(p*=Xv)),(p<Ri&&n.charAt(c-1)===r.charAt(s+1)||r.charAt(s+1)===r.charAt(s)&&n.charAt(c-1)!==r.charAt(s))&&(m=Di(e,t,n,r,c+1,s+2,i),m*Ri>p&&(p=m*Ri)),p>d&&(d=p),c=n.indexOf(l,c+1);return i[a]=d,d}function ku(e){return e.toLowerCase().replace(Tu," ")}function tw(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,Di(e,t,ku(e),ku(t),0,0,{})}function le(e,t,{checkForDefaultPrevented:n=!0}={}){return function(o){if(e==null||e(o),n===!1||!o.defaultPrevented)return t==null?void 0:t(o)}}function Eu(e,t){if(typeof e=="function")return e(t);e!=null&&(e.current=t)}function _n(...e){return t=>{let n=!1;const r=e.map(o=>{const s=Eu(o,t);return!n&&typeof s=="function"&&(n=!0),s});if(n)return()=>{for(let o=0;o<r.length;o++){const s=r[o];typeof s=="function"?s():Eu(e[o],null)}}}}function We(...e){return h.useCallback(_n(...e),e)}function nw(e,t){const n=h.createContext(t),r=s=>{const{children:i,...a}=s,l=h.useMemo(()=>a,Object.values(a));return u.jsx(n.Provider,{value:l,children:i})};r.displayName=e+"Provider";function o(s){const i=h.useContext(n);if(i)return i;if(t!==void 0)return t;throw new Error(`\`${s}\` must be used within \`${e}\``)}return[r,o]}function sn(e,t=[]){let n=[];function r(s,i){const a=h.createContext(i),l=n.length;n=[...n,i];const c=p=>{var y;const{scope:m,children:f,...v}=p,g=((y=m==null?void 0:m[e])==null?void 0:y[l])||a,x=h.useMemo(()=>v,Object.values(v));return u.jsx(g.Provider,{value:x,children:f})};c.displayName=s+"Provider";function d(p,m){var g;const f=((g=m==null?void 0:m[e])==null?void 0:g[l])||a,v=h.useContext(f);if(v)return v;if(i!==void 0)return i;throw new Error(`\`${p}\` must be used within \`${s}\``)}return[c,d]}const o=()=>{const s=n.map(i=>h.createContext(i));return function(a){const l=(a==null?void 0:a[e])||s;return h.useMemo(()=>({[`__scope${e}`]:{...a,[e]:l}}),[a,l])}};return o.scopeName=e,[r,rw(o,...t)]}function rw(...e){const t=e[0];if(e.length===1)return t;const n=()=>{const r=e.map(o=>({useScope:o(),scopeName:o.scopeName}));return function(s){const i=r.reduce((a,{useScope:l,scopeName:c})=>{const p=l(s)[`__scope${c}`];return{...a,...p}},{});return h.useMemo(()=>({[`__scope${t.scopeName}`]:i}),[i])}};return n.scopeName=t.scopeName,n}var It=globalThis!=null&&globalThis.document?h.useLayoutEffect:()=>{},ow=h[" useId ".trim().toString()]||(()=>{}),sw=0;function At(e){const[t,n]=h.useState(ow());return It(()=>{n(r=>r??String(sw++))},[e]),t?`radix-${t}`:""}var iw=h[" useInsertionEffect ".trim().toString()]||It;function jn({prop:e,defaultProp:t,onChange:n=()=>{},caller:r}){const[o,s,i]=aw({defaultProp:t,onChange:n}),a=e!==void 0,l=a?e:o;{const d=h.useRef(e!==void 0);h.useEffect(()=>{const p=d.current;p!==a&&console.warn(`${r} is changing from ${p?"controlled":"uncontrolled"} to ${a?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),d.current=a},[a,r])}const c=h.useCallback(d=>{var p;if(a){const m=lw(d)?d(e):d;m!==e&&((p=i.current)==null||p.call(i,m))}else s(d)},[a,e,s,i]);return[l,c]}function aw({defaultProp:e,onChange:t}){const[n,r]=h.useState(e),o=h.useRef(n),s=h.useRef(t);return iw(()=>{s.current=t},[t]),h.useEffect(()=>{var i;o.current!==n&&((i=s.current)==null||i.call(s,n),o.current=n)},[n,o]),[n,r,s]}function lw(e){return typeof e=="function"}var cw=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],ye=cw.reduce((e,t)=>{const n=Vt.createSlot(`Primitive.${t}`),r=h.forwardRef((o,s)=>{const{asChild:i,...a}=o,l=i?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),u.jsx(l,{...a,ref:s})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{});function Li(e,t){e&&Dr.flushSync(()=>e.dispatchEvent(t))}function wt(e){const t=h.useRef(e);return h.useEffect(()=>{t.current=e}),h.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function uw(e,t=globalThis==null?void 0:globalThis.document){const n=wt(e);h.useEffect(()=>{const r=o=>{o.key==="Escape"&&n(o)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var dw="DismissableLayer",$i="dismissableLayer.update",fw="dismissableLayer.pointerDownOutside",pw="dismissableLayer.focusOutside",Iu,Nu=h.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),mr=h.forwardRef((e,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:o,onFocusOutside:s,onInteractOutside:i,onDismiss:a,...l}=e,c=h.useContext(Nu),[d,p]=h.useState(null),m=(d==null?void 0:d.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=h.useState({}),v=We(t,E=>p(E)),g=Array.from(c.layers),[x]=[...c.layersWithOutsidePointerEventsDisabled].slice(-1),y=g.indexOf(x),w=d?g.indexOf(d):-1,S=c.layersWithOutsidePointerEventsDisabled.size>0,k=w>=y,C=mw(E=>{const A=E.target,O=[...c.branches].some(F=>F.contains(A));!k||O||(o==null||o(E),i==null||i(E),E.defaultPrevented||a==null||a())},m),T=gw(E=>{const A=E.target;[...c.branches].some(F=>F.contains(A))||(s==null||s(E),i==null||i(E),E.defaultPrevented||a==null||a())},m);return uw(E=>{w===c.layers.size-1&&(r==null||r(E),!E.defaultPrevented&&a&&(E.preventDefault(),a()))},m),h.useEffect(()=>{if(d)return n&&(c.layersWithOutsidePointerEventsDisabled.size===0&&(Iu=m.body.style.pointerEvents,m.body.style.pointerEvents="none"),c.layersWithOutsidePointerEventsDisabled.add(d)),c.layers.add(d),_u(),()=>{n&&c.layersWithOutsidePointerEventsDisabled.size===1&&(m.body.style.pointerEvents=Iu)}},[d,m,n,c]),h.useEffect(()=>()=>{d&&(c.layers.delete(d),c.layersWithOutsidePointerEventsDisabled.delete(d),_u())},[d,c]),h.useEffect(()=>{const E=()=>f({});return document.addEventListener($i,E),()=>document.removeEventListener($i,E)},[]),u.jsx(ye.div,{...l,ref:v,style:{pointerEvents:S?k?"auto":"none":void 0,...e.style},onFocusCapture:le(e.onFocusCapture,T.onFocusCapture),onBlurCapture:le(e.onBlurCapture,T.onBlurCapture),onPointerDownCapture:le(e.onPointerDownCapture,C.onPointerDownCapture)})});mr.displayName=dw;var hw="DismissableLayerBranch",Au=h.forwardRef((e,t)=>{const n=h.useContext(Nu),r=h.useRef(null),o=We(t,r);return h.useEffect(()=>{const s=r.current;if(s)return n.branches.add(s),()=>{n.branches.delete(s)}},[n.branches]),u.jsx(ye.div,{...e,ref:o})});Au.displayName=hw;function mw(e,t=globalThis==null?void 0:globalThis.document){const n=wt(e),r=h.useRef(!1),o=h.useRef(()=>{});return h.useEffect(()=>{const s=a=>{if(a.target&&!r.current){let l=function(){ju(fw,n,c,{discrete:!0})};const c={originalEvent:a};a.pointerType==="touch"?(t.removeEventListener("click",o.current),o.current=l,t.addEventListener("click",o.current,{once:!0})):l()}else t.removeEventListener("click",o.current);r.current=!1},i=window.setTimeout(()=>{t.addEventListener("pointerdown",s)},0);return()=>{window.clearTimeout(i),t.removeEventListener("pointerdown",s),t.removeEventListener("click",o.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function gw(e,t=globalThis==null?void 0:globalThis.document){const n=wt(e),r=h.useRef(!1);return h.useEffect(()=>{const o=s=>{s.target&&!r.current&&ju(pw,n,{originalEvent:s},{discrete:!1})};return t.addEventListener("focusin",o),()=>t.removeEventListener("focusin",o)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function _u(){const e=new CustomEvent($i);document.dispatchEvent(e)}function ju(e,t,n,{discrete:r}){const o=n.originalEvent.target,s=new CustomEvent(e,{bubbles:!1,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?Li(o,s):o.dispatchEvent(s)}var xw=mr,vw=Au,Fi="focusScope.autoFocusOnMount",Bi="focusScope.autoFocusOnUnmount",Pu={bubbles:!1,cancelable:!0},ww="FocusScope",Ho=h.forwardRef((e,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:o,onUnmountAutoFocus:s,...i}=e,[a,l]=h.useState(null),c=wt(o),d=wt(s),p=h.useRef(null),m=We(t,g=>l(g)),f=h.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;h.useEffect(()=>{if(r){let g=function(S){if(f.paused||!a)return;const k=S.target;a.contains(k)?p.current=k:Pn(p.current,{select:!0})},x=function(S){if(f.paused||!a)return;const k=S.relatedTarget;k!==null&&(a.contains(k)||Pn(p.current,{select:!0}))},y=function(S){if(document.activeElement===document.body)for(const C of S)C.removedNodes.length>0&&Pn(a)};document.addEventListener("focusin",g),document.addEventListener("focusout",x);const w=new MutationObserver(y);return a&&w.observe(a,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",g),document.removeEventListener("focusout",x),w.disconnect()}}},[r,a,f.paused]),h.useEffect(()=>{if(a){Ou.add(f);const g=document.activeElement;if(!a.contains(g)){const y=new CustomEvent(Fi,Pu);a.addEventListener(Fi,c),a.dispatchEvent(y),y.defaultPrevented||(bw(kw(Mu(a)),{select:!0}),document.activeElement===g&&Pn(a))}return()=>{a.removeEventListener(Fi,c),setTimeout(()=>{const y=new CustomEvent(Bi,Pu);a.addEventListener(Bi,d),a.dispatchEvent(y),y.defaultPrevented||Pn(g??document.body,{select:!0}),a.removeEventListener(Bi,d),Ou.remove(f)},0)}}},[a,c,d,f]);const v=h.useCallback(g=>{if(!n&&!r||f.paused)return;const x=g.key==="Tab"&&!g.altKey&&!g.ctrlKey&&!g.metaKey,y=document.activeElement;if(x&&y){const w=g.currentTarget,[S,k]=yw(w);S&&k?!g.shiftKey&&y===k?(g.preventDefault(),n&&Pn(S,{select:!0})):g.shiftKey&&y===S&&(g.preventDefault(),n&&Pn(k,{select:!0})):y===w&&g.preventDefault()}},[n,r,f.paused]);return u.jsx(ye.div,{tabIndex:-1,...i,ref:m,onKeyDown:v})});Ho.displayName=ww;function bw(e,{select:t=!1}={}){const n=document.activeElement;for(const r of e)if(Pn(r,{select:t}),document.activeElement!==n)return}function yw(e){const t=Mu(e),n=Ru(t,e),r=Ru(t.reverse(),e);return[n,r]}function Mu(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function Ru(e,t){for(const n of e)if(!Sw(n,{upTo:t}))return n}function Sw(e,{upTo:t}){if(getComputedStyle(e).visibility==="hidden")return!0;for(;e;){if(t!==void 0&&e===t)return!1;if(getComputedStyle(e).display==="none")return!0;e=e.parentElement}return!1}function Cw(e){return e instanceof HTMLInputElement&&"select"in e}function Pn(e,{select:t=!1}={}){if(e&&e.focus){const n=document.activeElement;e.focus({preventScroll:!0}),e!==n&&Cw(e)&&t&&e.select()}}var Ou=Tw();function Tw(){let e=[];return{add(t){const n=e[0];t!==n&&(n==null||n.pause()),e=Du(e,t),e.unshift(t)},remove(t){var n;e=Du(e,t),(n=e[0])==null||n.resume()}}}function Du(e,t){const n=[...e],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function kw(e){return e.filter(t=>t.tagName!=="A")}var Ew="Portal",qr=h.forwardRef((e,t)=>{var a;const{container:n,...r}=e,[o,s]=h.useState(!1);It(()=>s(!0),[]);const i=n||o&&((a=globalThis==null?void 0:globalThis.document)==null?void 0:a.body);return i?To.createPortal(u.jsx(ye.div,{...r,ref:t}),i):null});qr.displayName=Ew;function Iw(e,t){return h.useReducer((n,r)=>t[n][r]??n,e)}var Ft=e=>{const{present:t,children:n}=e,r=Nw(t),o=typeof n=="function"?n({present:r.isPresent}):h.Children.only(n),s=We(r.ref,Aw(o));return typeof n=="function"||r.isPresent?h.cloneElement(o,{ref:s}):null};Ft.displayName="Presence";function Nw(e){const[t,n]=h.useState(),r=h.useRef(null),o=h.useRef(e),s=h.useRef("none"),i=e?"mounted":"unmounted",[a,l]=Iw(i,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return h.useEffect(()=>{const c=Uo(r.current);s.current=a==="mounted"?c:"none"},[a]),It(()=>{const c=r.current,d=o.current;if(d!==e){const m=s.current,f=Uo(c);e?l("MOUNT"):f==="none"||(c==null?void 0:c.display)==="none"?l("UNMOUNT"):l(d&&m!==f?"ANIMATION_OUT":"UNMOUNT"),o.current=e}},[e,l]),It(()=>{if(t){let c;const d=t.ownerDocument.defaultView??window,p=f=>{const g=Uo(r.current).includes(CSS.escape(f.animationName));if(f.target===t&&g&&(l("ANIMATION_END"),!o.current)){const x=t.style.animationFillMode;t.style.animationFillMode="forwards",c=d.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=x)})}},m=f=>{f.target===t&&(s.current=Uo(r.current))};return t.addEventListener("animationstart",m),t.addEventListener("animationcancel",p),t.addEventListener("animationend",p),()=>{d.clearTimeout(c),t.removeEventListener("animationstart",m),t.removeEventListener("animationcancel",p),t.removeEventListener("animationend",p)}}else l("ANIMATION_END")},[t,l]),{isPresent:["mounted","unmountSuspended"].includes(a),ref:h.useCallback(c=>{r.current=c?getComputedStyle(c):null,n(c)},[])}}function Uo(e){return(e==null?void 0:e.animationName)||"none"}function Aw(e){var r,o;let t=(r=Object.getOwnPropertyDescriptor(e.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=(o=Object.getOwnPropertyDescriptor(e,"ref"))==null?void 0:o.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var zi=0;function Hi(){h.useEffect(()=>{const e=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",e[0]??Lu()),document.body.insertAdjacentElement("beforeend",e[1]??Lu()),zi++,()=>{zi===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),zi--}},[])}function Lu(){const e=document.createElement("span");return e.setAttribute("data-radix-focus-guard",""),e.tabIndex=0,e.style.outline="none",e.style.opacity="0",e.style.position="fixed",e.style.pointerEvents="none",e}var gn=function(){return gn=Object.assign||function(t){for(var n,r=1,o=arguments.length;r<o;r++){n=arguments[r];for(var s in n)Object.prototype.hasOwnProperty.call(n,s)&&(t[s]=n[s])}return t},gn.apply(this,arguments)};function $u(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols=="function")for(var o=0,r=Object.getOwnPropertySymbols(e);o<r.length;o++)t.indexOf(r[o])<0&&Object.prototype.propertyIsEnumerable.call(e,r[o])&&(n[r[o]]=e[r[o]]);return n}function _w(e,t,n){if(n||arguments.length===2)for(var r=0,o=t.length,s;r<o;r++)(s||!(r in t))&&(s||(s=Array.prototype.slice.call(t,0,r)),s[r]=t[r]);return e.concat(s||Array.prototype.slice.call(t))}typeof SuppressedError=="function"&&SuppressedError;var Wo="right-scroll-bar-position",Vo="width-before-scroll-bar",jw="with-scroll-bars-hidden",Pw="--removed-body-scroll-bar-size";function Ui(e,t){return typeof e=="function"?e(t):e&&(e.current=t),e}function Mw(e,t){var n=b.useState(function(){return{value:e,callback:t,facade:{get current(){return n.value},set current(r){var o=n.value;o!==r&&(n.value=r,n.callback(r,o))}}}})[0];return n.callback=t,n.facade}var Rw=typeof window<"u"?h.useLayoutEffect:h.useEffect,Fu=new WeakMap;function Ow(e,t){var n=Mw(null,function(r){return e.forEach(function(o){return Ui(o,r)})});return Rw(function(){var r=Fu.get(n);if(r){var o=new Set(r),s=new Set(e),i=n.current;o.forEach(function(a){s.has(a)||Ui(a,null)}),s.forEach(function(a){o.has(a)||Ui(a,i)})}Fu.set(n,e)},[e]),n}function Dw(e){return e}function Lw(e,t){t===void 0&&(t=Dw);var n=[],r=!1,o={read:function(){if(r)throw new Error("Sidecar: could not `read` from an `assigned` medium. `read` could be used only with `useMedium`.");return n.length?n[n.length-1]:e},useMedium:function(s){var i=t(s,r);return n.push(i),function(){n=n.filter(function(a){return a!==i})}},assignSyncMedium:function(s){for(r=!0;n.length;){var i=n;n=[],i.forEach(s)}n={push:function(a){return s(a)},filter:function(){return n}}},assignMedium:function(s){r=!0;var i=[];if(n.length){var a=n;n=[],a.forEach(s),i=n}var l=function(){var d=i;i=[],d.forEach(s)},c=function(){return Promise.resolve().then(l)};c(),n={push:function(d){i.push(d),c()},filter:function(d){return i=i.filter(d),n}}}};return o}function $w(e){e===void 0&&(e={});var t=Lw(null);return t.options=gn({async:!0,ssr:!1},e),t}var Bu=function(e){var t=e.sideCar,n=$u(e,["sideCar"]);if(!t)throw new Error("Sidecar: please provide `sideCar` property to import the right car");var r=t.read();if(!r)throw new Error("Sidecar medium not found");return h.createElement(r,gn({},n))};Bu.isSideCarExport=!0;function Fw(e,t){return e.useMedium(t),Bu}var zu=$w(),Wi=function(){},Ko=h.forwardRef(function(e,t){var n=h.useRef(null),r=h.useState({onScrollCapture:Wi,onWheelCapture:Wi,onTouchMoveCapture:Wi}),o=r[0],s=r[1],i=e.forwardProps,a=e.children,l=e.className,c=e.removeScrollBar,d=e.enabled,p=e.shards,m=e.sideCar,f=e.noRelative,v=e.noIsolation,g=e.inert,x=e.allowPinchZoom,y=e.as,w=y===void 0?"div":y,S=e.gapMode,k=$u(e,["forwardProps","children","className","removeScrollBar","enabled","shards","sideCar","noRelative","noIsolation","inert","allowPinchZoom","as","gapMode"]),C=m,T=Ow([n,t]),E=gn(gn({},k),o);return h.createElement(h.Fragment,null,d&&h.createElement(C,{sideCar:zu,removeScrollBar:c,shards:p,noRelative:f,noIsolation:v,inert:g,setCallbacks:s,allowPinchZoom:!!x,lockRef:n,gapMode:S}),i?h.cloneElement(h.Children.only(a),gn(gn({},E),{ref:T})):h.createElement(w,gn({},E,{className:l,ref:T}),a))});Ko.defaultProps={enabled:!0,removeScrollBar:!0,inert:!1},Ko.classNames={fullWidth:Vo,zeroRight:Wo};var Bw=function(){if(typeof __webpack_nonce__<"u")return __webpack_nonce__};function zw(){if(!document)return null;var e=document.createElement("style");e.type="text/css";var t=Bw();return t&&e.setAttribute("nonce",t),e}function Hw(e,t){e.styleSheet?e.styleSheet.cssText=t:e.appendChild(document.createTextNode(t))}function Uw(e){var t=document.head||document.getElementsByTagName("head")[0];t.appendChild(e)}var Ww=function(){var e=0,t=null;return{add:function(n){e==0&&(t=zw())&&(Hw(t,n),Uw(t)),e++},remove:function(){e--,!e&&t&&(t.parentNode&&t.parentNode.removeChild(t),t=null)}}},Vw=function(){var e=Ww();return function(t,n){h.useEffect(function(){return e.add(t),function(){e.remove()}},[t&&n])}},Hu=function(){var e=Vw(),t=function(n){var r=n.styles,o=n.dynamic;return e(r,o),null};return t},Kw={left:0,top:0,right:0,gap:0},Vi=function(e){return parseInt(e||"",10)||0},qw=function(e){var t=window.getComputedStyle(document.body),n=t[e==="padding"?"paddingLeft":"marginLeft"],r=t[e==="padding"?"paddingTop":"marginTop"],o=t[e==="padding"?"paddingRight":"marginRight"];return[Vi(n),Vi(r),Vi(o)]},Gw=function(e){if(e===void 0&&(e="margin"),typeof window>"u")return Kw;var t=qw(e),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},Yw=Hu(),gr="data-scroll-locked",Xw=function(e,t,n,r){var o=e.left,s=e.top,i=e.right,a=e.gap;return n===void 0&&(n="margin"),`
|
|
40
40
|
.`.concat(jw,` {
|
|
41
41
|
overflow: hidden `).concat(r,`;
|
|
42
42
|
padding-right: `).concat(a,"px ").concat(r,`;
|
|
@@ -127,4 +127,4 @@ ${t}</tr>
|
|
|
127
127
|
`+(f.tokens?this.parseInline(f.tokens):f.text);r+=n?this.renderer.paragraph(m):m;continue}default:{const A='Token with "'+f.type+'" type was not found.';if(this.options.silent){console.error(A);return}else throw new Error(A)}}}return r}parseInline(t,n){n=n||this.renderer;let r="",o,s,i;const a=t.length;for(o=0;o<a;o++){if(s=t[o],this.options.extensions&&this.options.extensions.renderers&&this.options.extensions.renderers[s.type]&&(i=this.options.extensions.renderers[s.type].call({parser:this},s),i!==!1||!["escape","html","link","image","strong","em","codespan","br","del","text"].includes(s.type))){r+=i||"";continue}switch(s.type){case"escape":{r+=n.text(s.text);break}case"html":{r+=n.html(s.text);break}case"link":{r+=n.link(s.href,s.title,this.parseInline(s.tokens,n));break}case"image":{r+=n.image(s.href,s.title,s.text);break}case"strong":{r+=n.strong(this.parseInline(s.tokens,n));break}case"em":{r+=n.em(this.parseInline(s.tokens,n));break}case"codespan":{r+=n.codespan(s.text);break}case"br":{r+=n.br();break}case"del":{r+=n.del(this.parseInline(s.tokens,n));break}case"text":{r+=n.text(s.text);break}default:{const l='Token with "'+s.type+'" type was not found.';if(this.options.silent){console.error(l);return}else throw new Error(l)}}}return r}}class Ks{constructor(t){this.options=t||sr}preprocess(t){return t}postprocess(t){return t}}Pg(Ks,"passThroughHooks",new Set(["preprocess","postprocess"]));function YT(e,t,n){return r=>{if(r.message+=`
|
|
128
128
|
Please report this to https://github.com/markedjs/marked.`,e){const o="<p>An error occurred:</p><pre>"+Pt(r.message+"",!0)+"</pre>";if(t)return Promise.resolve(o);if(n){n(null,o);return}return o}if(t)return Promise.reject(r);if(n){n(r);return}throw r}}function Oh(e,t){return(n,r,o)=>{typeof r=="function"&&(o=r,r=null);const s={...r};r={...ke.defaults,...s};const i=YT(r.silent,r.async,o);if(typeof n>"u"||n===null)return i(new Error("marked(): input parameter is undefined or null"));if(typeof n!="string")return i(new Error("marked(): input parameter is of type "+Object.prototype.toString.call(n)+", string expected"));if(KT(r),r.hooks&&(r.hooks.options=r),o){const a=r.highlight;let l;try{r.hooks&&(n=r.hooks.preprocess(n)),l=e(n,r)}catch(p){return i(p)}const c=function(p){let m;if(!p)try{r.walkTokens&&ke.walkTokens(l,r.walkTokens),m=t(l,r),r.hooks&&(m=r.hooks.postprocess(m))}catch(f){p=f}return r.highlight=a,p?i(p):o(null,m)};if(!a||a.length<3||(delete r.highlight,!l.length))return c();let d=0;ke.walkTokens(l,function(p){p.type==="code"&&(d++,setTimeout(()=>{a(p.text,p.lang,function(m,f){if(m)return c(m);f!=null&&f!==p.text&&(p.text=f,p.escaped=!0),d--,d===0&&c()})},0))}),d===0&&c();return}if(r.async)return Promise.resolve(r.hooks?r.hooks.preprocess(n):n).then(a=>e(a,r)).then(a=>r.walkTokens?Promise.all(ke.walkTokens(a,r.walkTokens)).then(()=>a):a).then(a=>t(a,r)).then(a=>r.hooks?r.hooks.postprocess(a):a).catch(i);try{r.hooks&&(n=r.hooks.preprocess(n));const a=e(n,r);r.walkTokens&&ke.walkTokens(a,r.walkTokens);let l=t(a,r);return r.hooks&&(l=r.hooks.postprocess(l)),l}catch(a){return i(a)}}}function ke(e,t,n){return Oh(zn.lex,Hn.parse)(e,t,n)}ke.options=ke.setOptions=function(e){return ke.defaults={...ke.defaults,...e},MT(ke.defaults),ke},ke.getDefaults=Ch,ke.defaults=sr,ke.use=function(...e){const t=ke.defaults.extensions||{renderers:{},childTokens:{}};e.forEach(n=>{const r={...n};if(r.async=ke.defaults.async||r.async||!1,n.extensions&&(n.extensions.forEach(o=>{if(!o.name)throw new Error("extension name required");if(o.renderer){const s=t.renderers[o.name];s?t.renderers[o.name]=function(...i){let a=o.renderer.apply(this,i);return a===!1&&(a=s.apply(this,i)),a}:t.renderers[o.name]=o.renderer}if(o.tokenizer){if(!o.level||o.level!=="block"&&o.level!=="inline")throw new Error("extension level must be 'block' or 'inline'");t[o.level]?t[o.level].unshift(o.tokenizer):t[o.level]=[o.tokenizer],o.start&&(o.level==="block"?t.startBlock?t.startBlock.push(o.start):t.startBlock=[o.start]:o.level==="inline"&&(t.startInline?t.startInline.push(o.start):t.startInline=[o.start]))}o.childTokens&&(t.childTokens[o.name]=o.childTokens)}),r.extensions=t),n.renderer){const o=ke.defaults.renderer||new wl;for(const s in n.renderer){const i=o[s];o[s]=(...a)=>{let l=n.renderer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.renderer=o}if(n.tokenizer){const o=ke.defaults.tokenizer||new vl;for(const s in n.tokenizer){const i=o[s];o[s]=(...a)=>{let l=n.tokenizer[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.tokenizer=o}if(n.hooks){const o=ke.defaults.hooks||new Ks;for(const s in n.hooks){const i=o[s];Ks.passThroughHooks.has(s)?o[s]=a=>{if(ke.defaults.async)return Promise.resolve(n.hooks[s].call(o,a)).then(c=>i.call(o,c));const l=n.hooks[s].call(o,a);return i.call(o,l)}:o[s]=(...a)=>{let l=n.hooks[s].apply(o,a);return l===!1&&(l=i.apply(o,a)),l}}r.hooks=o}if(n.walkTokens){const o=ke.defaults.walkTokens;r.walkTokens=function(s){let i=[];return i.push(n.walkTokens.call(this,s)),o&&(i=i.concat(o.call(this,s))),i}}ke.setOptions(r)})},ke.walkTokens=function(e,t){let n=[];for(const r of e)switch(n=n.concat(t.call(ke,r)),r.type){case"table":{for(const o of r.header)n=n.concat(ke.walkTokens(o.tokens,t));for(const o of r.rows)for(const s of o)n=n.concat(ke.walkTokens(s.tokens,t));break}case"list":{n=n.concat(ke.walkTokens(r.items,t));break}default:ke.defaults.extensions&&ke.defaults.extensions.childTokens&&ke.defaults.extensions.childTokens[r.type]?ke.defaults.extensions.childTokens[r.type].forEach(function(o){n=n.concat(ke.walkTokens(r[o],t))}):r.tokens&&(n=n.concat(ke.walkTokens(r.tokens,t)))}return n},ke.parseInline=Oh(zn.lexInline,Hn.parseInline),ke.Parser=Hn,ke.parser=Hn.parse,ke.Renderer=wl,ke.TextRenderer=Mh,ke.Lexer=zn,ke.lexer=zn.lex,ke.Tokenizer=vl,ke.Slugger=Rh,ke.Hooks=Ks,ke.parse=ke,ke.options,ke.setOptions,ke.use,ke.walkTokens,ke.parseInline,Hn.parse,zn.lex;function jr({content:e,className:t="",allowHtml:n=!1,style:r}){const o=b.useMemo(()=>{try{if(!n){const i=e.replace(/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,"").replace(/<iframe\b[^<]*(?:(?!<\/iframe>)<[^<]*)*<\/iframe>/gi,"").replace(/javascript:/gi,"").replace(/on\w+\s*=/gi,"");return typeof ke.parse=="function"?ke.parse(i):ke(i)}return typeof ke.parse=="function"?ke.parse(e):ke(e)}catch(i){return console.error("[MarkdownContent] parse error",i),`<pre class="font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words">Error rendering markdown: ${String(i)}</pre>`}},[e,n]),s=b.useMemo(()=>{const i={color:"currentColor",...r};if(r&&r.color){const a=r.color;return{...i,"--tw-prose-body":a,"--tw-prose-headings":a,"--tw-prose-links":a,"--tw-prose-bold":a,"--tw-prose-counters":a,"--tw-prose-bullets":a,"--tw-prose-hr":a,"--tw-prose-quotes":a,"--tw-prose-quote-borders":a,"--tw-prose-captions":a,"--tw-prose-code":a,"--tw-prose-pre-code":a,"--tw-prose-pre-bg":"inherit","--tw-prose-th-borders":a,"--tw-prose-td-borders":a}}return i},[r]);return u.jsx("div",{className:re("markdown prose prose-sm max-w-none break-words","dark:prose-invert","text-current","prose-headings:text-current prose-p:text-current prose-li:text-current prose-a:text-current prose-strong:text-current","prose-em:text-current prose-blockquote:text-current prose-table:text-current prose-td:text-current prose-th:text-current","prose-pre:font-mono prose-pre:text-xs prose-pre:bg-background/50 prose-pre:border prose-pre:rounded prose-pre:p-3 prose-pre:whitespace-pre prose-pre:overflow-x-auto","prose-code:font-mono prose-code:text-sm prose-code:bg-background/50 prose-code:px-1.5 prose-code:py-0.5 prose-code:rounded prose-code:text-current",t),style:s,dangerouslySetInnerHTML:{__html:o}})}function XT({preview:e,idx:t}){return u.jsxs("div",{className:"space-y-2",children:[e.label&&u.jsxs("p",{className:"text-[0.65rem] uppercase tracking-wide text-muted-foreground",children:["Artifact: ",e.label]}),u.jsx("div",{className:"overflow-hidden rounded border border-border/60 bg-background/60 p-1 shadow-sm",children:u.jsx("img",{src:e.src,alt:e.alt,title:e.label,loading:"lazy",className:"h-auto max-h-[420px] w-full rounded object-contain",onLoad:()=>{},onError:n=>{console.error(`[MessageComponent] ❌ Image failed to load for artifact ${t}:`,{alt:e.alt,label:e.label,message:n.target.alt})}})})]})}function JT({artifact:e}){const[t,n]=b.useState("bg-yellow-500/20 text-yellow-700 dark:text-yellow-300"),[r,o]=b.useState(u.jsx(fe.Clock,{className:"w-4 h-4"})),[s,i]=b.useState("Processing");return b.useEffect(()=>{switch(e.status||"processing"){case"completed":n("bg-green-500/20 text-green-700 dark:text-green-300"),o(u.jsx(fe.CheckCircle,{className:"w-4 h-4"})),i("Completed");break;case"failed":n("bg-red-500/20 text-red-700 dark:text-red-300"),o(u.jsx(fe.ExternalLink,{className:"w-4 h-4 rotate-45"})),i("Failed");break;case"pending":n("bg-blue-500/20 text-blue-700 dark:text-blue-300"),o(u.jsx(fe.Clock,{className:"w-4 h-4"})),i("Pending");break;default:n("bg-yellow-500/20 text-yellow-700 dark:text-yellow-300"),o(u.jsx(fe.Clock,{className:"w-4 h-4"})),i("Processing")}},[e.status]),u.jsxs("div",{className:"rounded-lg border border-blue-200 dark:border-blue-900/50 bg-blue-50 dark:bg-blue-950/20 p-4 space-y-3",children:[u.jsxs("div",{className:"flex items-start gap-3",children:[u.jsx("div",{className:"mt-1 flex-shrink-0",children:u.jsx(fe.Search,{className:"w-5 h-5 text-blue-600 dark:text-blue-400"})}),u.jsxs("div",{className:"flex-1 min-w-0",children:[u.jsx("h3",{className:"font-semibold text-blue-900 dark:text-blue-100",children:"Research Task"}),u.jsxs("p",{className:"text-sm text-blue-700 dark:text-blue-300 mt-1",children:["Task ID: ",u.jsxs("code",{className:"font-mono text-xs bg-blue-100 dark:bg-blue-900/30 px-2 py-1 rounded",children:[e.task_id.slice(0,8),"..."]})]})]})]}),u.jsxs("div",{className:`inline-flex items-center gap-2 px-3 py-1 rounded-full text-sm font-medium ${t}`,children:[r,u.jsx("span",{children:s})]}),e.query&&u.jsxs("div",{className:"text-sm text-blue-800 dark:text-blue-200 bg-white dark:bg-blue-900/30 rounded px-3 py-2",children:[u.jsx("p",{className:"font-medium text-xs text-blue-600 dark:text-blue-400 mb-1",children:"Query:"}),u.jsx("p",{className:"line-clamp-2",children:e.query})]}),typeof e.results=="string"&&e.results.trim()&&u.jsxs("div",{className:"text-sm text-blue-900 dark:text-blue-100 bg-white dark:bg-blue-900/30 rounded px-3 py-2 space-y-2",children:[u.jsx("p",{className:"font-semibold text-xs text-blue-600 dark:text-blue-400",children:"Results:"}),u.jsx(jr,{content:e.results,allowHtml:!1,className:"prose text-xs !prose-sm prose-blue dark:prose-invert"})]}),e.progress_url&&u.jsx("div",{className:"pt-2",children:u.jsxs("a",{href:e.progress_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white dark:bg-blue-700 dark:hover:bg-blue-600 rounded-md text-sm font-medium transition-colors",children:[u.jsx("span",{children:"Monitor Progress"}),u.jsx(fe.ExternalLink,{className:"w-3.5 h-3.5"})]})}),e.createdAt&&u.jsxs("p",{className:"text-xs text-blue-600 dark:text-blue-400",children:["Started: ",new Date(e.createdAt).toLocaleTimeString()]})]})}function ZT({artifact:e,idx:t=0}){const n=b.useMemo(()=>e?(Array.isArray(e.plots)?e.plots:[]).map(o=>Av(o)).filter(o=>o!==null):[],[e]);return(e==null?void 0:e.type)==="research_task_info"?u.jsx(JT,{artifact:{type:"research_task_info",task_id:e.task_id,progress_url:e.progress_url,query:e.query,status:e.status,createdAt:e.createdAt}}):n.length>0?u.jsx("div",{className:"space-y-2",children:n.map((r,o)=>u.jsx(XT,{preview:r,idx:o},`${t}-plot-${o}`))}):e&&typeof e=="object"?u.jsx("div",{className:"rounded-lg border border-gray-200 dark:border-gray-800 bg-gray-50 dark:bg-gray-900/20 p-4",children:u.jsxs("p",{className:"text-sm text-gray-600 dark:text-gray-400",children:["Unknown artifact type: ",u.jsx("code",{className:"font-mono",children:e.type||"unknown"})]})}):null}const bl=h.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:re("rounded-lg border bg-card text-card-foreground shadow-sm",e),...t}));bl.displayName="Card";const yl=h.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:re("flex flex-col space-y-1.5 p-6",e),...t}));yl.displayName="CardHeader";const Sl=h.forwardRef(({className:e,...t},n)=>u.jsx("h3",{ref:n,className:re("text-2xl font-semibold leading-none tracking-tight",e),...t}));Sl.displayName="CardTitle";const Cl=h.forwardRef(({className:e,...t},n)=>u.jsx("p",{ref:n,className:re("text-sm text-muted-foreground",e),...t}));Cl.displayName="CardDescription";const Tl=h.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:re("p-6 pt-0",e),...t}));Tl.displayName="CardContent";const Dh=h.forwardRef(({className:e,...t},n)=>u.jsx("div",{ref:n,className:re("flex items-center p-6 pt-0",e),...t}));Dh.displayName="CardFooter";function QT({interruptPart:e,onApprove:t,onReject:n,disabled:r,isActive:o,payload:s}){const i=e.title??"Approve the result?";let a=null;if(s!=null)if(typeof s=="string")a=u.jsx("p",{className:"text-sm leading-relaxed text-blue-800/90 dark:text-blue-200/90 whitespace-pre-wrap",children:s});else{const c=hr(s);a=u.jsx("pre",{className:"max-h-48 overflow-auto rounded bg-blue-100/60 p-2 text-xs text-blue-900/90 dark:bg-blue-900/40 dark:text-blue-100/80",children:c})}const l=o?"Please approve or reject this action to resume the workflow.":"Waiting for approval from another participant.";return u.jsxs(bl,{className:re("border-blue-200 dark:border-blue-800 bg-blue-50/50 dark:bg-blue-950/10 transition-shadow",o?"shadow-md ring-1 ring-blue-300 dark:ring-blue-500/70":"opacity-80"),children:[u.jsxs(yl,{className:"pb-3",children:[u.jsx(Sl,{className:"text-blue-900 dark:text-blue-100 text-base",children:i}),u.jsx(Cl,{className:"text-blue-700 dark:text-blue-300 text-sm",children:l})]}),a&&u.jsx(Tl,{className:"pt-0 pb-3",children:a}),u.jsx(Dh,{className:"pt-0",children:u.jsxs("div",{className:"flex gap-2 ml-auto",children:[u.jsx(ct,{size:"sm",variant:"outline",onClick:()=>n(e),className:"border-red-300 text-red-700 hover:bg-red-50 dark:border-red-700 dark:text-red-300 dark:hover:bg-red-950/50",disabled:r||!o,children:"Reject"}),u.jsx(ct,{size:"sm",onClick:()=>t(e),className:"bg-blue-600 hover:bg-blue-700 text-white",disabled:r||!o,children:"Approve"})]})})]})}const ek="prose prose-sm max-w-none break-words dark:prose-invert prose-headings:break-words prose-p:break-words prose-li:break-words prose-td:break-words prose-th:break-words prose-a:break-all prose-code:break-words prose-blockquote:break-words";function Lh({data:e}){return Array.isArray(e)?e.every(n=>n===null||["string","number","boolean"].includes(typeof n))?u.jsx("div",{className:ek,children:u.jsx("ul",{className:"list-disc pl-5",children:e.map((n,r)=>u.jsx("li",{children:String(n)},r))})}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:hr(e)}):u.jsx("pre",{className:"font-mono text-xs bg-background/50 rounded border p-2 whitespace-pre-wrap break-words",children:hr(e)})}function tk({message:e,isStreaming:t=!1}){const n=e.name??"tool",r=b.useMemo(()=>{const a=e.additionalKwargs??{};return Array.isArray(a.toolProgress)?[...a.toolProgress]:[]},[e]),s=r.some(a=>a.type==="tool.start"||a.type==="tool.call"||a.type==="message.start")?`Running ${n}…`:void 0;return t||r.length>0?u.jsxs("div",{className:"space-y-2",children:[u.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[t&&u.jsx(fe.Loader,{className:"h-3 w-3 animate-spin"}),u.jsx("span",{children:s??`Running ${n}…`})]}),r.length>0&&u.jsx("div",{className:"space-y-2 text-xs text-muted-foreground",children:r.map((a,l)=>{var c;return u.jsxs("div",{className:"rounded border border-current/10 bg-muted/60 p-2 text-[11px] leading-snug",children:[u.jsxs("div",{className:"mb-1 flex items-center justify-between text-[8px] uppercase tracking-wide text-muted-foreground",children:[u.jsx("span",{children:((c=a.type)==null?void 0:c.replace(/\./g," "))??"progress"}),u.jsx("span",{children:a.idx??l+1})]}),a.content&&u.jsx("p",{className:"mt-1 text-[12px] text-foreground/90",children:a.content}),u.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[10px] opacity-70",children:[typeof a.factsFound=="number"&&u.jsxs("span",{children:["Facts found: ",a.factsFound]}),typeof a.isSufficient=="boolean"&&u.jsxs("span",{children:["Research ",a.isSufficient?"sufficient":"needs more data"]})]})]},`tool-progress-${n}-${l}`)})})]}):null}function nk({message:e,viewMode:t,isStreaming:n=!1}){const o=Ni(e).name||"tool",s=l=>{if(l==null)return null;const c=typeof l=="string"?Ii(l)??l:l;if(c&&typeof c=="object")return u.jsx(Lh,{data:c});const d=typeof c=="string"?c:(()=>{try{return hr(c)}catch{return String(c??"")}})();return u.jsx("pre",{className:"whitespace-pre-wrap break-words font-sans text-sm text-foreground/90",children:d})},i=l=>{if(l==null)return null;const{content:c,isMarkdown:d}=Sv(l);return d?u.jsx(jr,{content:c,className:"text-current"}):s(l)},a=()=>{const l=e.content.find(p=>p.type!=="tool_call");if(!l)return u.jsx("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:u.jsxs("span",{children:["Running ",o,"…"]})});if(l.type==="text"){const m=(l.text??"").trim();if(!m)return null;const f=Vr(m);return i(f)}const c=Wr(l),d=Vr(c);return i(d)};return u.jsxs("div",{className:"space-y-2",children:[u.jsx(tk,{message:e,isStreaming:n}),t==="expanded"&&a()]})}function rk(e){const{allowFileOpen:t,currentThreadId:n}=e,{toast:r}=xl(),[o,s]=b.useState({}),[i,a]=b.useState(null),[l,c]=b.useState(!1),d=b.useCallback(()=>{c(!1),a(null)},[]),p=b.useCallback(f=>{a(f),c(!0)},[]),m=b.useCallback(async(f,v,g)=>{var x,y;if(!t){f.preventDefault();return}if(o[g]){f.preventDefault();return}try{const w=String(v.url??""),S=w.match(/\/chat\/files\/([^/]+)(?:\/(view|download))?/);if(S){f.preventDefault();const k=S[1],C=v.name||`file_${k}`,T=v.mimeType||"application/octet-stream";p({id:k,name:C,mimeType:T});return}if(w.startsWith("data:")){f.preventDefault(),s(C=>({...C,[g]:!0}));const k=r({title:"Fetching file...",description:"",open:!0});try{const C=await Xc(n??void 0);if(!C||!Array.isArray(C))throw new Error("Invalid file list response");const T=C.find(E=>!E||typeof E!="object"||!((E.filename??"")===(v.name??""))?!1:typeof v.size=="number"&&typeof E.size=="number"?E.size===v.size:!0);if(!(T!=null&&T.id))throw new Error(`File "${v.name}" is not yet available on the server`);if(!T.id||!T.filename)throw new Error("Invalid file data received from server");p({id:T.id,name:v.name||T.filename||`file_${T.id}`,mimeType:v.mimeType||T.mime_type||"application/octet-stream"}),(x=k.update)==null||x.call(k,{id:k.id,title:"Success",description:`Opened ${v.name}`,open:!0})}catch(C){console.error("Failed to fetch server file:",C);const T=C instanceof Error?C.message:"Unknown error occurred";(y=k.update)==null||y.call(k,{id:k.id,title:"Failed",description:T}),r({title:"Failed to fetch file",description:T,open:!0})}finally{s(C=>({...C,[g]:!1}))}}}catch(w){console.error("File click error:",w),s(S=>({...S,[g]:!1}))}},[t,o,r,n,p]);return{uploadingFiles:o,handleFileClick:m,fileViewerOpen:l,currentFileInfo:i,closeFileViewer:d}}function ok({text:e,expanded:t,onExpandedChange:n,previewLength:r,isCompact:o}){const s=Math.max(e.length-r,0),i=e.substring(0,r);return u.jsxs("div",{className:"flex flex-col gap-1",children:[u.jsx("div",{className:re("text-sm text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:t?u.jsx(jr,{content:e,allowHtml:!1}):u.jsxs("pre",{className:re("font-sans whitespace-pre-wrap break-words bg-transparent p-0 m-0 text-[hsl(var(--chat-bubble-user-text))]",o&&"text-xs"),children:[i,"..."]})}),u.jsx(ct,{type:"button",variant:"ghost",size:"sm",className:"h-6 text-xs !text-[hsl(var(--chat-bubble-user-text))]",onClick:()=>n(!t),children:t?u.jsxs(u.Fragment,{children:[u.jsx(fe.ChevronUp,{className:"h-3 w-3 mr-1"})," Show less"]}):u.jsxs(u.Fragment,{children:[u.jsx(fe.ChevronDown,{className:"h-3 w-3 mr-1"})," Show more (",s," chars)"]})})]})}function sk({className:e}){const[t,n]=b.useState(0);return b.useEffect(()=>{const r=setInterval(()=>n(o=>(o+1)%4),500);return()=>clearInterval(r)},[]),u.jsxs("span",{"aria-live":"polite",className:re("inline-block text-xs opacity-70 ml-1",e),children:["Is thinking",".".repeat(t)]})}function $h(e){var n;const t=(n=e.additionalKwargs)==null?void 0:n.toolProgress;return Array.isArray(t)?t:[]}const qs=b.memo(function({message:t,messageIndex:n,isStreamingMessage:r=!1,isEditing:o=!1,showActions:s=!0,showTimestamp:i=!0,showAgentName:a=!0,layoutSize:l="desktop",truncateUserMessages:c=!0,userMessagePreviewLength:d=500,showToolMessages:p=!0,showArtifactPreviews:m=!0,customStyles:f={},onEdit:v,onRegenerate:g,onCancelEdit:x,onCopy:y,activeInterrupt:w,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,checkpointCandidates:T=[],activeCheckpointId:E=null,onSelectCheckpoint:A,defaultCheckpointId:O=null,messageParentCheckpointId:F=null}){const[U,W]=b.useState(!1),[z,N]=b.useState("preview"),[K,M]=b.useState(!1),{currentThreadId:Q}=Pi(),{respondToInterrupt:$}=Mi(),_=l==="phone"||l==="half-screen",V=t.role,J=V==="tool",j=b.useMemo(()=>"type"in t&&t.type==="default_message"?t:null,[t]),R=!!j,G=!(r&&V!=="user"),{uploadingFiles:Y,handleFileClick:ie,fileViewerOpen:H,currentFileInfo:D,closeFileViewer:X}=rk({allowFileOpen:G,currentThreadId:Q}),Z=b.useMemo(()=>{switch(V){case"user":return"text-[hsl(var(--chat-bubble-user-text))]";case"assistant":return"text-[hsl(var(--chat-bubble-ai-text))]";case"tool":return"text-secondary-foreground";case"system":return"text-muted-foreground";default:return"text-[hsl(var(--chat-bubble-ai-text))]"}},[V]),ce=b.useMemo(()=>{if(j)return"";const P=t.content;return Array.isArray(P)?Cv(P):""},[j,t]),L=b.useMemo(()=>{if(j)return{};const P=t.content;return Array.isArray(P)?Ni(t):{}},[j,t]),oe=b.useMemo(()=>J?!!(t.additionalKwargs??{}).toolStreaming:!1,[J,t]),xe=b.useMemo(()=>{if(j)return[];const P=t.content;return Array.isArray(P)?P.filter(te=>te.type==="image_url"):[]},[j,t]),de=b.useMemo(()=>{if(j)return[];const P=t.content;return Array.isArray(P)?P.filter(te=>te.type==="file"):[]},[j,t]),we=b.useMemo(()=>{if(j)return[];const P=t.content;return Array.isArray(P)?P.filter(te=>te.type==="interrupt"):[]},[j,t]),Me=(w==null?void 0:w.id)??(w==null?void 0:w.interrupt_id),He=Bo(Me),$e=w==null?void 0:w.value,Ae=b.useMemo(()=>{if(j)return"";const P=t.content;return Array.isArray(P)?Tv(P):""},[j,t]),Fe=b.useMemo(()=>j||!m?null:t.artifact||null,[j,t,m]),Ge=b.useCallback(async()=>{const P=J?Ae:ce;async function te(ve){if(navigator.clipboard&&typeof navigator.clipboard.writeText=="function"){await navigator.clipboard.writeText(ve);return}if(navigator.clipboard&&typeof navigator.clipboard.write=="function"&&typeof ClipboardItem<"u"){const ae=new Blob([ve],{type:"text/plain"});await navigator.clipboard.write([new ClipboardItem({"text/plain":ae})]);return}throw new Error("Clipboard API not supported in this context.")}try{await te(P),W(!0),setTimeout(()=>W(!1),2e3),y==null||y(P)}catch(ve){console.error("Failed to copy:",ve)}},[J,Ae,ce,y]),Ke=b.useCallback(()=>{if(!v||!t.id)return;const P=(J?Ae:ce)??"",te="type"in t&&t.type==="default_message"?void 0:{checkpointId:t.checkpointId??null,checkpointNs:t.checkpointNs??null};v(t.id,P,te)},[v,t.id,J,Ae,ce,t]),Xe=b.useCallback(()=>{g==null||g(n)},[g,n]),tt=b.useCallback(()=>{const te=re(_?"h-3 w-3":"h-4 w-4","opacity-60 flex-shrink-0",Z);switch(V){case"user":return u.jsx(fe.User,{className:te});case"assistant":return u.jsx(fe.Bot,{className:te});case"tool":return u.jsx(fe.Wrench,{className:te});default:return u.jsx(fe.Bot,{className:te})}},[_,Z,V]),nt=b.useCallback(()=>{const P="group relative mb-4 flex w-full";switch(V){case"user":return re(P,"justify-end");case"assistant":case"tool":case"system":return re(P,"justify-start");default:return P}},[V]),Ze=b.useCallback(()=>{const P=re("rounded-lg px-4 py-3 relative min-w-0 max-w-full break-words",_&&"px-3 py-2 text-sm");if(R)return re(P,"w-full","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40 shadow-sm");switch(V){case"user":return re(P,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-user))] text-[hsl(var(--chat-bubble-user-text))]","border border-transparent");case"assistant":return re(P,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40");case"tool":return re(P,"w-full md:max-w-[95%] bg-secondary/50 text-secondary-foreground border border-dashed");case"system":return re(P,"w-full md:max-w-[85%] bg-accent/40 text-muted-foreground border");default:return re(P,"w-full md:max-w-[95%]","bg-[hsl(var(--chat-bubble-ai))] text-[hsl(var(--chat-bubble-ai-text))]","border border-border/60 dark:border-border/40")}},[_,R,V]),pt=b.useCallback(async P=>{if(S)return;const te=Bo((P==null?void 0:P.id)??(P==null?void 0:P.interrupt_id));if(!te){console.warn("Interrupt part missing id",P);return}try{k==null||k(),await $(te,!0)}catch(ve){console.error("Failed to approve interrupt:",ve)}finally{C==null||C()}},[S,C,k,$]),ht=b.useCallback(async P=>{if(S)return;const te=Bo((P==null?void 0:P.id)??(P==null?void 0:P.interrupt_id));if(!te){console.warn("Interrupt part missing id",P);return}try{k==null||k(),await $(te,!1)}catch(ve){console.error("Failed to reject interrupt:",ve)}finally{C==null||C()}},[S,C,k,$]),Se=b.useCallback(({part:P,i:te})=>{if(P.type==="text"){const ve=P.text??"",ae=ve.trim(),Ie=Ii(ae);return Ie&&V!=="tool"?u.jsx(Lh,{data:Ie},te):V==="user"&&c&&ae.length>d?u.jsx(ok,{text:ae,expanded:K,onExpandedChange:M,previewLength:d,isCompact:_},te):u.jsx(jr,{content:ve,allowHtml:!1},te)}if(P.type==="image_url"){const ve=P;return u.jsx("div",{className:"my-2",children:u.jsx("img",{src:ve.url,alt:ve.alt??"",loading:"lazy",className:"border rounded max-h-[420px] w-auto object-contain"})},te)}if(P.type==="file"){const ve=P,ae=ve.name||"file";return u.jsxs("a",{href:ve.url,onClick:Ie=>ie(Ie.nativeEvent,ve,te),className:`inline-flex items-center gap-2 rounded px-2 py-1 text-xs bg-gray-100 border hover:bg-gray-200
|
|
129
129
|
dark:bg-background/10 dark:border-border/30 dark:hover:bg-background/20`,children:[Y[te]?u.jsx(fe.Loader,{className:"h-4 w-4 animate-spin"}):null,u.jsxs("span",{className:"truncate max-w-[180px]",children:[ae,Y[te]?" (processing)":""]})]},te)}if(P.type==="interrupt"){const ve=P,ae=Bo((ve==null?void 0:ve.id)??(ve==null?void 0:ve.interrupt_id)),Ie=!!(He&&ae&&ae===He),Te=Ie?$e??(ve==null?void 0:ve.value):ve==null?void 0:ve.value,st=ae?{...ve,id:ae,interrupt_id:ae}:ve;return u.jsx(QT,{interruptPart:st,onApprove:pt,onReject:ht,disabled:S,isActive:Ie,payload:Te},te)}return null},[ie,Y,pt,ht,V,c,d,K,_,He,$e,w,S,we]),Re=b.useCallback(()=>u.jsxs("div",{className:"flex items-center gap-2 p-2 bg-muted/30 rounded",children:[u.jsx(fe.Paperclip,{className:"h-4 w-4 text-muted-foreground"}),u.jsx("span",{className:"text-sm text-muted-foreground",children:"File upload"})]}),[]),mt=b.useCallback(()=>{const P=ce.trim().length>0||xe.length>0||de.length>0||we.length>0;if(!J&&de.length>0&&!r)return Re();if(!J&&!P&&!r)return null;if(J)return!p&&Fe?null:p?u.jsx(nk,{message:t,viewMode:z,isStreaming:oe},t.id):null;if(!J&&!j){const te=t,ve=u.jsx("div",{className:"space-y-2",children:te.content.map((ae,Ie)=>u.jsx(Se,{part:ae,i:Ie},Ie))});return r?u.jsxs("div",{"aria-busy":"true",role:"status",children:[ve,u.jsx(sk,{className:Z})]}):ve}},[ce,xe.length,de.length,we.length,r,J,z,p,Fe,Re,Z]),ot=b.useMemo(()=>j?"Assistant":kv(t),[j,t]),qe=b.useMemo(()=>j?[]:Array.isArray(T)?T:[],[T,j]),yt=b.useMemo(()=>{var P;return qe.length?O&&qe.some(te=>te.id===O)?O:((P=qe[0])==null?void 0:P.id)??null:null},[O,qe]),Be=b.useMemo(()=>!qe.length||!E?null:qe.some(P=>P.id===E)?E:null,[E,qe])??yt,St=V==="user"&&qe.length>0&&typeof A=="function",xt=b.useCallback((P,te=!1)=>{if(!A)return;const ve=(P==null?void 0:P.id)??null,ae=(P==null?void 0:P.parentId)??F??null;A(ve,ae,te)},[F,A]),Ye=b.useMemo(()=>Be?qe.findIndex(P=>P.id===Be):-1,[Be,qe]),gt=b.useMemo(()=>Ye<0?null:qe[Ye]??null,[Ye,qe]);return J&&!p&&!Fe?null:R&&j?u.jsx("div",{className:re(nt(),f.container),children:u.jsxs("div",{className:re(Ze(),f.content),children:[u.jsxs("div",{className:"flex items-center gap-2 mb-2 pb-2 border-b border-current/10",children:[u.jsx(fe.Bot,{className:re("h-4 w-4",Z)}),a&&u.jsx("span",{className:"font-medium text-sm",children:"Assistant"})]}),u.jsx(jr,{content:j.content,className:"text-current"})]})}):u.jsxs(u.Fragment,{children:[u.jsx("div",{className:re(nt(),f.container),children:u.jsxs("div",{className:re(Ze(),f.content),children:[(i||a||J)&&u.jsxs("div",{className:re("flex items-center justify-between mb-2 pb-2 border-b border-current/10",_&&"mb-1 pb-1",Z,f.header),children:[u.jsxs("div",{className:"flex items-center gap-2",children:[tt(),a&&ot&&u.jsx("span",{className:re("font-medium",_?"text-xs":"text-sm"),children:ot}),J&&u.jsxs(bh,{variant:"outline",className:re("text-xs flex items-center gap-1 cursor-pointer select-none",Z,"border border-current/40",_&&"text-xs h-4"),role:"button",tabIndex:0,"aria-expanded":z==="expanded",onClick:()=>N(P=>P==="expanded"?"preview":"expanded"),onKeyDown:P=>{(P.key==="Enter"||P.key===" ")&&(P.preventDefault(),N(te=>te==="expanded"?"preview":"expanded"))},children:[u.jsx("span",{children:L.name??"Tool Output"}),L.toolCallId&&u.jsx("span",{className:"opacity-70",children:L.toolCallId.slice(0,8)}),z==="expanded"?u.jsx(fe.ChevronUp,{className:"h-3 w-3"}):u.jsx(fe.ChevronDown,{className:"h-3 w-3"})]})]}),u.jsxs("div",{className:"flex items-center gap-2",children:[St&>&&Ye>=0&&u.jsx("div",{className:"flex flex-wrap items-center gap-2 text-xs",children:u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx("button",{type:"button",className:re("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ye<qe.length-1?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(Ye>=qe.length-1)return;const P=qe[Ye+1];P&&xt(P)},"aria-label":"Older checkpoint (back in time)",disabled:Ye>=qe.length-1,children:u.jsx(fe.ChevronLeft,{className:"h-3 w-3"})}),u.jsx("div",{className:"flex items-center gap-2",children:u.jsxs("span",{className:"whitespace-nowrap",children:[qe.length-Ye," / ",qe.length]})}),u.jsx("button",{type:"button",className:re("flex items-center justify-center rounded border px-1.5 py-1 transition-colors",Ye>0?"border-border text-foreground hover:bg-muted/60":"border-border text-muted-foreground cursor-not-allowed"),onClick:()=>{if(!(Ye<=0))if(Ye===1)xt(null,!0);else{const P=qe[Ye-1];P&&xt(P,!1)}},"aria-label":"Newer checkpoint (forward in time)",disabled:Ye<=0,children:u.jsx(fe.ChevronRight,{className:"h-3 w-3"})})]})}),i&&t.createdAt&&u.jsx("time",{className:re("text-xs opacity-60",Z,_&&"text-xs"),dateTime:new Date(t.createdAt).toISOString(),title:new Date(t.createdAt).toLocaleString(),children:new Intl.DateTimeFormat(void 0,{hour:"2-digit",minute:"2-digit"}).format(new Date(t.createdAt))}),s&&!o&&u.jsxs("div",{className:re("opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",f.actions),children:[u.jsx("div",{className:"relative",children:u.jsx(ct,{variant:"ghost",size:"sm",onClick:()=>Ge(),className:re("h-6 w-6 p-0 hover:bg-foreground/10",Z,_&&"h-5 w-5"),"aria-label":"Copy message",title:"Copy message",children:u.jsx(fe.Copy,{className:re(U?"text-success":Z,_?"h-3 w-3":"h-4 w-4")})})}),V==="user"&&v&&u.jsx(ct,{variant:"ghost",size:"sm",onClick:Ke,className:re("h-6 w-6 p-0 hover:bg-foreground/10",Z,_&&"h-5 w-5"),"aria-label":"Edit message",children:u.jsx(fe.Edit,{className:re(Z,_?"h-3 w-3":"h-4 w-4")})}),V==="assistant"&&g&&u.jsx(ct,{variant:"ghost",size:"sm",onClick:Xe,className:re("h-6 w-6 p-0 hover:bg-foreground/10",Z,_&&"h-5 w-5"),"aria-label":"Regenerate response",children:u.jsx(fe.RotateCcw,{className:re(Z,_?"h-3 w-3":"h-4 w-4")})})]})]})]}),u.jsxs("div",{className:"relative",children:[mt(),m&&Fe&&u.jsx("div",{className:"mt-3",children:u.jsx(ZT,{artifact:Fe,idx:0})})]}),J&&z==="expanded"&&(L.toolCallId||L.name)&&u.jsxs("div",{className:re("mt-2 pt-2 border-t border-current/10 text-xs opacity-60",_&&"text-xs"),children:[L.name&&u.jsxs("div",{children:["Function: ",L.name]}),L.toolCallId&&u.jsxs("div",{children:["Call ID: ",L.toolCallId]})]}),!(i||a||J)&&s&&!o&&u.jsxs("div",{className:re("absolute top-2 right-2 opacity-0 group-hover:opacity-100 transition-opacity","flex items-center gap-1",f.actions),children:[u.jsx(ct,{variant:"ghost",size:"sm",onClick:()=>Ge(),className:re("h-6 w-6 p-0 hover:bg-background/50 text-current",_&&"h-5 w-5"),children:u.jsx(fe.Copy,{className:re(U?"text-success":"text-current",_?"h-3 w-3":"h-4 w-4")})}),V==="user"&&v&&u.jsx(ct,{variant:"ghost",size:"sm",onClick:Ke,className:re("h-6 w-6 p-0 hover:bg-background/50 text-current",_&&"h-5 w-5"),children:u.jsx(fe.Edit,{className:re("text-current",_?"h-3 w-3":"h-4 w-4")})}),V==="assistant"&&g&&u.jsx(ct,{variant:"ghost",size:"sm",onClick:Xe,className:re("h-6 w-6 p-0 hover:bg-background/50 text-current",_&&"h-5 w-5"),children:u.jsx(fe.RotateCcw,{className:re("text-current",_?"h-3 w-3":"h-4 w-4")})})]})]})}),D&&u.jsx(Sh,{isOpen:H,onClose:X,fileId:D.id,fileName:D.name,mimeType:D.mimeType})]})},(e,t)=>{var l,c,d,p,m,f,v,g;if(t.isStreamingMessage||e.isStreamingMessage||!(e.message.id===t.message.id&&du(e.message)===du(t.message)))return!1;const o=["isEditing","showActions","layoutSize","showTimestamp","showAgentName","truncateUserMessages","userMessagePreviewLength","showToolMessages"].every(x=>e[x]===t[x]),s=((l=e.customStyles)==null?void 0:l.container)===((c=t.customStyles)==null?void 0:c.container)&&((d=e.customStyles)==null?void 0:d.content)===((p=t.customStyles)==null?void 0:p.content)&&((m=e.customStyles)==null?void 0:m.actions)===((f=t.customStyles)==null?void 0:f.actions)&&((v=e.customStyles)==null?void 0:v.header)===((g=t.customStyles)==null?void 0:g.header);if(!o||!s)return!1;const i=$h(e.message),a=$h(t.message);return i.length===a.length});qs.displayName="MessageComponent";const Fh=(e,t)=>(e==null?void 0:e.id)??`message-${t}`,Bh=b.memo(function({message:t,index:n,isStreaming:r,streamingAssistantId:o,streamingDebounceMs:s,layoutSize:i,enableMessageEditing:a,editingMessageId:l,onEdit:c,onRegenerate:d,onCancelEdit:p,activeInterrupt:m,disableInterruptActions:f,onInterruptActionStart:v,onInterruptActionEnd:g,showToolMessages:x,showArtifactPreviews:y,checkpointIndex:w,activeCheckpointId:S,onSelectCheckpoint:k}){const C=Fh(t,n),T="type"in t&&t.type==="default_message",A=!!t.__syntheticStreaming,{checkpointCandidates:O,defaultCheckpointId:F}=Gl(t,w??{checkpoints:[],checkpointMetaById:new Map,checkpointIndexByKey:new Map,attemptMetaById:new Map,userMessageIdToAttempts:new Map,timeline:[],messagePreviews:new Map,getLatest:()=>{},getCheckpoint:()=>{},getAttempts:()=>[]}),U=t&&!T?t.additionalKwargs??{}:{},W=t&&!T?t.responseMetadata??{}:{},z=(()=>{if(typeof U.parentCheckpointId=="string")return U.parentCheckpointId;if(typeof W.parentCheckpointId=="string")return W.parentCheckpointId})();return u.jsx("div",{className:"relative mb-4 last:mb-0","data-message-id":C,style:{minHeight:"60px",containIntrinsicSize:"auto 120px"},children:u.jsx(qs,{message:t,messageIndex:n,isStreamingMessage:A||r&&o===t.id,streamingDebounceMs:s,isEditing:l===t.id,showActions:a,showTimestamp:!1,showAgentName:!0,layoutSize:i,onEdit:c,onRegenerate:()=>d(n),onCancelEdit:p,activeInterrupt:m,disableInterruptActions:f,onInterruptActionStart:v,onInterruptActionEnd:g,showToolMessages:x,showArtifactPreviews:y,checkpointCandidates:O,activeCheckpointId:S??null,onSelectCheckpoint:k,defaultCheckpointId:F,messageParentCheckpointId:z})})});Bh.displayName="MessageRow";const kl=b.forwardRef(({messages:e,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onStartReached:a,onEdit:l,onRegenerate:c,onCancelEdit:d,className:p,style:m,emptyMessage:f,followNewMessages:v=!0,isNavigatingCheckpoint:g=!1,onScrollAway:x,onAtBottom:y,activeInterrupt:w,disableInterruptActions:S=!1,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T=!0,showArtifactPreviews:E=!0,checkpointIndex:A,activeCheckpointId:O,onSelectCheckpoint:F,createSyntheticThinkingMessage:U=!0},W)=>{const z=b.useRef(null),N=b.useRef(null),K=b.useRef(!1),M=b.useRef(!1),[Q,$]=b.useState(!0),_=b.useMemo(()=>w?e.some(L=>"type"in L&&L.type==="default_message"?!1:Array.isArray(L==null?void 0:L.content)&&L.content.some(oe=>oe&&oe.type==="interrupt"&&(oe.id??oe.interrupt_id)===w.id)):!1,[w,e]),V=b.useMemo(()=>{if(!w||_)return null;const L=w.id&&String(w.id).trim()?String(w.id).trim():"pending-interrupt";let oe;const xe=w.value;if(xe&&typeof xe=="object"&&!Array.isArray(xe)){const de=xe.title;typeof de=="string"&&de.trim()&&(oe=de.trim())}return{id:`interrupt-${L}`,role:"system",createdAt:new Date().toISOString(),content:[{type:"interrupt",id:L,value:xe,title:oe}]}},[w,_]),J=b.useMemo(()=>V?[...e,V]:e,[e,V]),j=b.useMemo(()=>!U||!t?J:!J.some(oe=>oe.role==="assistant")&&J.length>0?[...J,{id:"thinking-assistant",role:"assistant",content:[],createdAt:new Date().toISOString(),__syntheticStreaming:!0}]:J,[J,t,U]),R=b.useMemo(()=>T?j:j.filter(L=>(L==null?void 0:L.role)!=="tool"),[j,T]),G=b.useCallback(L=>{$(L),x&&x(!L),y&&y(L)},[x,y]),Y=b.useMemo(()=>{if(a)return async()=>{if(!K.current){K.current=!0;try{await a()}finally{K.current=!1}}}},[a]),ie=b.useMemo(()=>!v||g?!1:Q?"auto":!1,[Q,v,g]),H=b.useMemo(()=>{if(typeof f!="string")return null;const L=f.trim();return L?{id:"default-message",role:"assistant",type:"default_message",content:L,createdAt:new Date().toISOString()}:null},[f]),D=["flex h-full flex-col md:flex-row",p].filter(Boolean).join(" "),X=()=>H?u.jsx("div",{className:"p-6 h-full overflow-y-auto",children:u.jsx("div",{className:"w-full max-w-full",children:u.jsx(qs,{message:H,messageIndex:0,isStreamingMessage:!1,showActions:!1,showTimestamp:!1,showAgentName:!0,layoutSize:o,onEdit:()=>{},onRegenerate:()=>{},onCancelEdit:()=>{},showArtifactPreviews:E})})}):u.jsx("div",{className:"flex h-full items-center justify-center py-8 text-center text-muted-foreground",children:f??"No messages yet. Start a conversation!"}),Z=R.length,ce=Z>0;return b.useEffect(()=>{var L,oe;if(Z===0){M.current=!1;return}if(!M.current)if(M.current=!0,z.current&&R.length>0){const xe=R.length-1;(oe=(L=z.current).scrollToIndex)==null||oe.call(L,{index:xe,align:"end",behavior:"auto"})}else N.current&&(N.current.scrollTop=N.current.scrollHeight)},[Z,R.length]),b.useImperativeHandle(W,()=>({scrollToLatest:()=>{var L,oe;if(z.current&&R.length>0){const xe=R.length-1;(oe=(L=z.current).scrollToIndex)==null||oe.call(L,{index:xe,align:"end",behavior:"auto"})}else N.current&&(N.current.scrollTop=N.current.scrollHeight)},scrollToTop:()=>{var L,oe;z.current&&R.length>0?(oe=(L=z.current).scrollToIndex)==null||oe.call(L,{index:0,align:"start",behavior:"auto"}):N.current&&(N.current.scrollTop=0)}}),[R]),u.jsx("div",{className:D,style:m,children:u.jsx("div",{className:"relative flex-1 min-h-0",children:ce?u.jsx(fT,{ref:L=>{z.current=L},scrollerRef:L=>{N.current=L instanceof HTMLDivElement?L:null},data:R,followOutput:ie,overscan:200,increaseViewportBy:{top:100,bottom:200},defaultItemHeight:80,atBottomThreshold:50,startReached:()=>{Y&&Y()},atBottomStateChange:G,style:{height:"100%",overscrollBehavior:"contain"},computeItemKey:(L,oe)=>Fh(oe,L),itemContent:(L,oe)=>u.jsx(Bh,{message:oe,index:L,isStreaming:t,streamingAssistantId:n,streamingDebounceMs:r,layoutSize:o,enableMessageEditing:s,editingMessageId:i,onEdit:l,onRegenerate:c,onCancelEdit:d,activeInterrupt:w,disableInterruptActions:S,onInterruptActionStart:k,onInterruptActionEnd:C,showToolMessages:T,showArtifactPreviews:E,checkpointIndex:A,activeCheckpointId:O,onSelectCheckpoint:F})}):X()})})});kl.displayName="MessageList";const zh={value:""};function bo({className:e="",placeholder:t="Type your message...",autoFocus:n=!0,maxHeight:r=void 0,streamingDebounceMs:o=500,streamingThrottleMs:s,followNewMessages:i=!0,enableFileUpload:a=!0,enableExcelUpload:l=!1,enableMessageEditing:c=!0,showToolMessages:d=!0,showArtifactPreviews:p=!0,customStyles:m={},onMessageSent:f,onExcelUploadSuccess:v,onError:g}){const{api:x}=ki(),{currentThreadId:y}=Pi(),{threadId:w,messages:S,isHistoryLoading:k,isLoading:C,navigateToCheckpoint:T,returnToLatest:E,checkpoint:A,checkpoints:O,interrupt:F,metadata:U,checkpointIndex:W}=Mi(),{isStreaming:z,error:N,connectionState:K,submit:M,stop:Q}=Su(),$=w??y??null,_=(A==null?void 0:A.id)??null,V=(A==null?void 0:A.namespace)??null,J=(U==null?void 0:U.assemblingMessageId)??null,j=F,[R,G]=b.useState(!1);b.useEffect(()=>{j||G(!1)},[j]);const Y=b.useCallback(()=>{G(!0)},[]),ie=b.useCallback(()=>{G(!1)},[]),H=!!j||R,[D,X]=b.useState(null),[Z,ce]=b.useState(""),[L,oe]=b.useState(null),[xe,de]=b.useState(null),[we,Me]=b.useState([]),[He,$e]=b.useState(0),[Ae,Fe]=b.useState(0),[Ge,Ke]=b.useState(!1),[Xe,tt]=b.useState(null),[nt,Ze]=b.useState(null),[pt,ht]=b.useState(!1),[Se,Re]=b.useState(null),mt=b.useRef(!1),[ot,qe]=b.useState(()=>zh.value),yt=b.useRef(ot),De=b.useRef(null),Be=b.useCallback(ue=>{zh.value=ue,qe(ue)},[]),[St,xt]=b.useState(!1),Ye=b.useRef(null),gt=b.useRef(null),P=b.useRef(null),te=b.useCallback(()=>{gt.current&&(gt.current.value=""),P.current&&(P.current.value=""),$e(ue=>ue+1),Fe(ue=>ue+1)},[]),ve=b.useCallback(ue=>{Be(ue)},[Be]),ae=b.useRef(!1);b.useEffect(()=>{ae.current&&!z&&(Me([]),te()),ae.current=z},[z,te]);const[Ie,Te]=b.useState("desktop");b.useEffect(()=>{const ue=()=>{const be=window.innerWidth;Te(be<640?"phone":be<1024?"tablet":"desktop")};return ue(),window.addEventListener("resize",ue),()=>window.removeEventListener("resize",ue)},[]),b.useEffect(()=>{mt.current=!1},[$]),b.useEffect(()=>{yt.current=ot},[ot]),b.useEffect(()=>{if(!D){De.current=null;return}De.current===null&&(De.current=yt.current),Be(Z??"")},[Z,D,Be]),b.useEffect(()=>{(async()=>{if(!x.baseUrl){Re(null);return}try{const he=(await x.getAgent("default")).uiDefaultMessage||"";Re(he||null)}catch(be){console.warn("Failed to fetch default message:",be),Re(null)}})()},[x.baseUrl]),b.useEffect(()=>{N&&!pt&&(g==null||g(N))},[N,pt,g]);const st=async ue=>{const be=ue.trim();if(!(!be&&we.length===0))try{const he=D?(L==null?void 0:L.checkpointId)??_??void 0:_??void 0,Ee=D?(L==null?void 0:L.checkpointNs)??V??void 0:V??void 0;await M({text:be||"",attachments:we},{checkpointId:he,checkpointNs:Ee,edit:!!D,originalMessageId:D??void 0}),f==null||f(be),Be(""),de(null),Me([]),te(),X(null),ce(""),oe(null)}catch(he){const Ee=(he==null?void 0:he.message)||"Failed to send message";de(Ee),g==null||g(Ee)}},Ue=b.useCallback((ue,be,he)=>{c&&(De.current=ot,X(ue),ce(be),Be(be),de(null),oe({checkpointId:(he==null?void 0:he.checkpointId)??null,checkpointNs:(he==null?void 0:he.checkpointNs)??null}))},[ot,c,Be]),lt=b.useCallback(()=>{X(null),ce(""),oe(null),de(null),Be(De.current??ot),De.current=null},[ot,Be]),Ut=b.useCallback((ue,be,he)=>{Ue(ue,be,he)},[Ue]),Mt=b.useCallback(ue=>{let be=null;for(let et=ue-1;et>=0;et--)if(S[et].role==="user"){be=S[et];break}if(!be)return;const he=Array.isArray(be.content)?be.content:[],Tt=he.filter(et=>(et==null?void 0:et.type)==="text").map(et=>et.text).join("")||(()=>{try{return JSON.stringify(he,null,2)}catch{return String(he)}})();Tt&&M({text:Tt},{checkpointId:_??void 0,checkpointNs:V??void 0,edit:!0,originalMessageId:be.id})},[S,M,_,V]),nn=ue=>{const be=Array.from(ue.target.files||[]);Me(he=>[...he,...be]),ue.target.value=""},Ul=ue=>{Me(be=>{const he=be.filter((Ee,Tt)=>ue!==Tt);return he.length===0&&te(),he})},Wl=async ue=>{const be=(ue.target.files||[])[0];if(be){tt(null),Ze(null),Ke(!0);try{await M({attachments:[be]},{checkpointId:_??void 0,checkpointNs:V??void 0});const he=`Uploaded ${be.name} - processing through chat stream`;Ze(he)}catch(he){const Ee=he instanceof Error?he.message:"Failed to upload Excel file";console.error("Excel upload failed",he),tt(Ee),g==null||g(Ee)}finally{Ke(!1),ue.target.value="",te()}}},ii=async ue=>{if(y){xt(!0);try{if(!ue){await E(),requestAnimationFrame(()=>{var Ee;(Ee=Ye.current)==null||Ee.scrollToLatest()});return}const be=O.find(Ee=>Ee.checkpointId===ue),he=(be==null?void 0:be.checkpointNs)??null;await T(ue,he),requestAnimationFrame(()=>{var Ee;(Ee=Ye.current)==null||Ee.scrollToTop()})}finally{xt(!1)}}},I=b.useCallback(async(ue,be,he)=>{await ii(he?null:ue)},[ii]),ne=`flex flex-1 w-full flex-col min-h-0 min-w-0 max-h-full overflow-hidden bg-transparent ${e} ${m.container||""}`,pe=`flex-1 min-h-0 min-w-0 max-h-full w-full overflow-hidden overscroll-contain break-words break-anywhere p-4 bg-transparent ${m.messagesArea||""}`,je=`relative flex-shrink-0 w-full border-t p-4 bg-transparent ${m.inputArea||""}`;return u.jsxs("div",{className:ne,children:[!!N&&!pt&&u.jsxs("div",{className:"flex-shrink-0 bg-red-50 border border-red-200 text-red-800 px-4 py-2 text-sm flex items-center justify-between",children:[u.jsx("span",{children:N}),u.jsx(ct,{variant:"ghost",size:"sm",onClick:()=>ht(!0),className:"text-red-800 hover:bg-red-100","aria-label":"Dismiss error",children:u.jsx(fe.X,{size:16})})]}),u.jsxs("div",{className:`relative ${pe}`,style:r?{maxHeight:r}:void 0,children:[u.jsx(kl,{ref:Ye,className:"h-full",style:{height:"100%"},messages:S,isStreaming:z,streamingAssistantId:J,streamingDebounceMs:typeof s=="number"?s:o,followNewMessages:i,layoutSize:Ie,enableMessageEditing:c,editingMessageId:D,onEdit:Ut,onRegenerate:Mt,onCancelEdit:lt,emptyMessage:Se??void 0,isNavigatingCheckpoint:St,activeInterrupt:j,disableInterruptActions:R,onInterruptActionStart:Y,onInterruptActionEnd:ie,showToolMessages:d,showArtifactPreviews:p,checkpointIndex:W,activeCheckpointId:_,onSelectCheckpoint:I,createSyntheticThinkingMessage:!0}),(K==="reconnecting"||K==="connecting")&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-muted/80 px-3 py-1 text-xs font-medium text-foreground shadow-sm backdrop-blur-sm dark:bg-muted/60",children:u.jsxs("span",{className:"flex items-center gap-2",children:[u.jsx(fe.Loader2,{className:"h-3 w-3 animate-spin"}),K==="reconnecting"?"Reconnecting…":"Connecting…"]})}),K==="error"&&u.jsx("div",{className:"pointer-events-none absolute top-3 right-3 z-20 rounded-full bg-destructive/10 px-3 py-1 text-xs font-semibold text-destructive shadow-sm",children:"Connection lost"}),C&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(fe.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading messages…"})]}),(k||St)&&u.jsxs("div",{className:"absolute inset-0 z-10 flex flex-col items-center justify-center gap-2 bg-background/80 backdrop-blur-sm text-muted-foreground",children:[u.jsx(fe.Loader2,{className:"h-6 w-6 animate-spin"}),u.jsx("span",{className:"text-xs font-semibold uppercase tracking-wide",children:"Loading checkpoint…"})]})]}),u.jsxs("div",{className:je,children:[D&&u.jsx("div",{className:"mb-3 p-3 bg-blue-50 border border-blue-200 rounded-lg",children:u.jsxs("div",{className:"flex items-center justify-between",children:[u.jsxs("div",{className:"flex items-center gap-2",children:[u.jsx(fe.Edit3,{size:16,className:"text-blue-600"}),u.jsx("span",{className:"text-sm font-medium text-blue-800",children:"Editing message"})]}),u.jsx(ct,{variant:"ghost",size:"sm",onClick:lt,className:"text-blue-600 hover:bg-blue-100",children:u.jsx(fe.X,{size:16})})]})}),(a||l)&&u.jsxs("div",{className:"mb-3 space-y-3",children:[a&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:gt,type:"file",multiple:!0,onChange:ue=>nn(ue),className:"hidden"},He),we.length>0&&u.jsx("div",{className:"flex flex-wrap gap-2",children:we.map((ue,be)=>u.jsxs("div",{className:"flex items-center gap-2 bg-gray-100 dark:bg-gray-800 rounded-lg px-3 py-2 text-sm text-gray-900 dark:text-gray-100",children:[u.jsx(fe.Paperclip,{size:14}),u.jsx("span",{className:"truncate max-w-[150px]",children:ue.name}),u.jsx(ct,{variant:"ghost",size:"sm",onClick:()=>Ul(be),className:"h-4 w-4 p-0 text-gray-500 dark:text-gray-400 hover:text-red-500 dark:hover:text-red-400","aria-label":`Remove ${ue.name}`,children:u.jsx(fe.X,{size:12})})]},be))})]}),l&&u.jsxs(u.Fragment,{children:[u.jsx("input",{ref:P,type:"file",accept:".xls,.xlsx,.xlsm",onChange:Wl,className:"hidden"},Ae),Ge&&u.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[u.jsx(fe.Loader2,{className:"h-4 w-4 animate-spin"})," Uploading Excel file..."]}),nt&&!Ge&&u.jsx("div",{className:"text-sm rounded border border-emerald-200 bg-emerald-50 px-3 py-2 text-emerald-700",children:nt}),Xe&&!Ge&&u.jsx("div",{className:"text-sm rounded border border-red-200 bg-red-50 px-3 py-2 text-red-600",children:Xe})]})]}),xe&&u.jsx("div",{className:"mb-3 text-sm text-red-600 bg-red-50 border border-red-200 rounded px-3 py-2",children:xe}),u.jsxs("div",{className:"flex items-end gap-2",children:[(a||l)&&u.jsxs(Ss,{children:[u.jsx(Cs,{asChild:!0,children:u.jsx(ct,{type:"button",size:"icon",variant:"outline",disabled:z||H,title:"More input actions",className:m.moreButton||"",children:u.jsx(fe.Plus,{size:16})})}),u.jsxs(ao,{align:"start",sideOffset:6,className:"w-52",children:[a&&u.jsxs(Dn,{onClick:()=>{var ue;return(ue=gt.current)==null?void 0:ue.click()},className:"cursor-pointer",children:[u.jsx(fe.Paperclip,{className:"h-4 w-4 mr-2"})," Attach files or images"]}),l&&u.jsxs(Dn,{onClick:()=>{var ue;Ge||(ue=P.current)==null||ue.click()},className:`cursor-pointer ${Ge?"opacity-60 pointer-events-none":""}`,children:[u.jsx(fe.FileSpreadsheet,{className:"h-4 w-4 mr-2"})," Upload Excel file"]})]})]}),u.jsx("div",{className:"flex-1",children:u.jsx(nC,{initialValue:Z,editingMessageId:D,value:ot,onValueChange:ve,placeholder:D?"Edit your message...":t,isStreaming:z,disabled:H,onSend:st,onCancelEdit:lt,onStop:Q,allowEmptySend:we.length>0,textareaClassName:`resize-none min-h-[44px] max-h-[20rem] w-full transition-colors ${D?"border-blue-400 bg-blue-50 text-blue-900 dark:border-blue-500 dark:bg-blue-950/60 dark:text-blue-50":""} ${xe?"border-red-400":""} ${m.textarea||""}`})})]})]})]})}function Hh({layout:e="sidebar",layoutSize:t="desktop",showThreads:n=!0,className:r="",customStyles:o={},...s}){const i=c=>{const d="h-full";switch(c){case"phone":return`${d} max-w-none`;case"tablet":return`${d} max-w-4xl mx-auto`;case"half-screen":return`${d} max-w-2xl`;case"desktop":default:return`${d} max-w-7xl mx-auto`}},a=c=>({"--chat-sidebar-width":c==="phone"?"100%":c==="tablet"?"280px":c==="half-screen"?"240px":"320px","--chat-message-max-width":c==="phone"?"95%":c==="tablet"?"90%":c==="half-screen"?"85%":"80%","--chat-input-height":c==="phone"?"120px":"100px"}),l=b.useCallback(c=>{var d;(d=s.onThreadChange)==null||d.call(s,c)},[s]);return e==="fullscreen"?u.jsx(zo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsx(bo,{className:"flex-1",onError:s.onError,enableFileUpload:!0})})}):e==="tabs"?u.jsx(zo,{...s,onThreadChange:l,children:u.jsx("div",{className:`${i(t)} flex flex-col overflow-hidden ${r} ${o.container||""}`,style:a(t),children:u.jsxs("div",{className:"flex-1 flex min-h-0 overflow-hidden",children:[n&&u.jsx("div",{className:`w-80 border-r flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Wa,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(bo,{onError:s.onError,enableFileUpload:!0})})]})})}):u.jsx(zo,{...s,onThreadChange:l,children:u.jsxs("div",{className:`${i(t)} flex overflow-hidden ${r} ${o.container||""}`,style:a(t),children:[n&&u.jsx("div",{className:`w-80 border-r bg-gray-50 flex-shrink-0 overflow-hidden ${o.sidebar||""}`,children:u.jsx(Wa,{showCreateButton:!0,showDeleteButton:!0,showEditTitle:!0,className:"h-full"})}),u.jsx("div",{className:`flex-1 min-w-0 overflow-hidden ${o.chatArea||""}`,children:u.jsx(bo,{onError:s.onError,enableFileUpload:!0})})]})})}function ik({apiConfig:e,className:t="",onError:n}){return u.jsx(zo,{apiConfig:e,onError:n,children:u.jsx("div",{className:`h-full ${t}`,children:u.jsx(bo,{})})})}var ak="Label",Uh=h.forwardRef((e,t)=>u.jsx(ye.label,{...e,ref:t,onMouseDown:n=>{var o;n.target.closest("button, input, select, textarea")||((o=e.onMouseDown)==null||o.call(e,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));Uh.displayName=ak;var Wh=Uh;const lk=Or.cva("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),Vh=h.forwardRef(({className:e,...t},n)=>u.jsx(Wh,{ref:n,className:re(lk(),e),...t}));Vh.displayName=Wh.displayName;function Kh(e){const t=h.useRef({value:e,previous:e});return h.useMemo(()=>(t.current.value!==e&&(t.current.previous=t.current.value,t.current.value=e),t.current.previous),[e])}var qh=Object.freeze({position:"absolute",border:0,width:1,height:1,padding:0,margin:-1,overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",wordWrap:"normal"}),ck="VisuallyHidden",Gs=h.forwardRef((e,t)=>u.jsx(ye.span,{...e,ref:t,style:{...qh,...e.style}}));Gs.displayName=ck;var uk=Gs,dk=[" ","Enter","ArrowUp","ArrowDown"],fk=[" ","Enter"],ir="Select",[Ys,Xs,pk]=ss(ir),[Pr,t1]=sn(ir,[pk,Er]),Js=Er(),[hk,Un]=Pr(ir),[mk,gk]=Pr(ir),Gh=e=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:o,onOpenChange:s,value:i,defaultValue:a,onValueChange:l,dir:c,name:d,autoComplete:p,disabled:m,required:f,form:v}=e,g=Js(t),[x,y]=h.useState(null),[w,S]=h.useState(null),[k,C]=h.useState(!1),T=is(c),[E,A]=jn({prop:r,defaultProp:o??!1,onChange:s,caller:ir}),[O,F]=jn({prop:i,defaultProp:a,onChange:l,caller:ir}),U=h.useRef(null),W=x?v||!!x.closest("form"):!0,[z,N]=h.useState(new Set),K=Array.from(z).map(M=>M.props.value).join(";");return u.jsx(Ca,{...g,children:u.jsxs(hk,{required:f,scope:t,trigger:x,onTriggerChange:y,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:k,onValueNodeHasChildrenChange:C,contentId:At(),value:O,onValueChange:F,open:E,onOpenChange:A,dir:T,triggerPointerDownPosRef:U,disabled:m,children:[u.jsx(Ys.Provider,{scope:t,children:u.jsx(mk,{scope:e.__scopeSelect,onNativeOptionAdd:h.useCallback(M=>{N(Q=>new Set(Q).add(M))},[]),onNativeOptionRemove:h.useCallback(M=>{N(Q=>{const $=new Set(Q);return $.delete(M),$})},[]),children:n})}),W?u.jsxs(vm,{"aria-hidden":!0,required:f,tabIndex:-1,name:d,autoComplete:p,value:O,onChange:M=>F(M.target.value),disabled:m,form:v,children:[O===void 0?u.jsx("option",{value:""}):null,Array.from(z)]},K):null]})})};Gh.displayName=ir;var Yh="SelectTrigger",Xh=h.forwardRef((e,t)=>{const{__scopeSelect:n,disabled:r=!1,...o}=e,s=Js(n),i=Un(Yh,n),a=i.disabled||r,l=We(t,i.onTriggerChange),c=Xs(n),d=h.useRef("touch"),[p,m,f]=bm(g=>{const x=c().filter(S=>!S.disabled),y=x.find(S=>S.value===i.value),w=ym(x,g,y);w!==void 0&&i.onValueChange(w.value)}),v=g=>{a||(i.onOpenChange(!0),f()),g&&(i.triggerPointerDownPosRef.current={x:Math.round(g.pageX),y:Math.round(g.pageY)})};return u.jsx(Ta,{asChild:!0,...s,children:u.jsx(ye.button,{type:"button",role:"combobox","aria-controls":i.contentId,"aria-expanded":i.open,"aria-required":i.required,"aria-autocomplete":"none",dir:i.dir,"data-state":i.open?"open":"closed",disabled:a,"data-disabled":a?"":void 0,"data-placeholder":wm(i.value)?"":void 0,...o,ref:l,onClick:le(o.onClick,g=>{g.currentTarget.focus(),d.current!=="mouse"&&v(g)}),onPointerDown:le(o.onPointerDown,g=>{d.current=g.pointerType;const x=g.target;x.hasPointerCapture(g.pointerId)&&x.releasePointerCapture(g.pointerId),g.button===0&&g.ctrlKey===!1&&g.pointerType==="mouse"&&(v(g),g.preventDefault())}),onKeyDown:le(o.onKeyDown,g=>{const x=p.current!=="";!(g.ctrlKey||g.altKey||g.metaKey)&&g.key.length===1&&m(g.key),!(x&&g.key===" ")&&dk.includes(g.key)&&(v(),g.preventDefault())})})})});Xh.displayName=Yh;var Jh="SelectValue",Zh=h.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,children:s,placeholder:i="",...a}=e,l=Un(Jh,n),{onValueNodeHasChildrenChange:c}=l,d=s!==void 0,p=We(t,l.onValueNodeChange);return It(()=>{c(d)},[c,d]),u.jsx(ye.span,{...a,ref:p,style:{pointerEvents:"none"},children:wm(l.value)?u.jsx(u.Fragment,{children:i}):s})});Zh.displayName=Jh;var xk="SelectIcon",Qh=h.forwardRef((e,t)=>{const{__scopeSelect:n,children:r,...o}=e;return u.jsx(ye.span,{"aria-hidden":!0,...o,ref:t,children:r||"▼"})});Qh.displayName=xk;var vk="SelectPortal",em=e=>u.jsx(qr,{asChild:!0,...e});em.displayName=vk;var ar="SelectContent",tm=h.forwardRef((e,t)=>{const n=Un(ar,e.__scopeSelect),[r,o]=h.useState();if(It(()=>{o(new DocumentFragment)},[]),!n.open){const s=r;return s?Dr.createPortal(u.jsx(nm,{scope:e.__scopeSelect,children:u.jsx(Ys.Slot,{scope:e.__scopeSelect,children:u.jsx("div",{children:e.children})})}),s):null}return u.jsx(rm,{...e,ref:t})});tm.displayName=ar;var fn=10,[nm,Wn]=Pr(ar),wk="SelectContentImpl",bk=Vt.createSlot("SelectContent.RemoveScroll"),rm=h.forwardRef((e,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:o,onEscapeKeyDown:s,onPointerDownOutside:i,side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:v,hideWhenDetached:g,avoidCollisions:x,...y}=e,w=Un(ar,n),[S,k]=h.useState(null),[C,T]=h.useState(null),E=We(t,H=>k(H)),[A,O]=h.useState(null),[F,U]=h.useState(null),W=Xs(n),[z,N]=h.useState(!1),K=h.useRef(!1);h.useEffect(()=>{if(S)return Gi(S)},[S]),Hi();const M=h.useCallback(H=>{const[D,...X]=W().map(L=>L.ref.current),[Z]=X.slice(-1),ce=document.activeElement;for(const L of H)if(L===ce||(L==null||L.scrollIntoView({block:"nearest"}),L===D&&C&&(C.scrollTop=0),L===Z&&C&&(C.scrollTop=C.scrollHeight),L==null||L.focus(),document.activeElement!==ce))return},[W,C]),Q=h.useCallback(()=>M([A,S]),[M,A,S]);h.useEffect(()=>{z&&Q()},[z,Q]);const{onOpenChange:$,triggerPointerDownPosRef:_}=w;h.useEffect(()=>{if(S){let H={x:0,y:0};const D=Z=>{var ce,L;H={x:Math.abs(Math.round(Z.pageX)-(((ce=_.current)==null?void 0:ce.x)??0)),y:Math.abs(Math.round(Z.pageY)-(((L=_.current)==null?void 0:L.y)??0))}},X=Z=>{H.x<=10&&H.y<=10?Z.preventDefault():S.contains(Z.target)||$(!1),document.removeEventListener("pointermove",D),_.current=null};return _.current!==null&&(document.addEventListener("pointermove",D),document.addEventListener("pointerup",X,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",D),document.removeEventListener("pointerup",X,{capture:!0})}}},[S,$,_]),h.useEffect(()=>{const H=()=>$(!1);return window.addEventListener("blur",H),window.addEventListener("resize",H),()=>{window.removeEventListener("blur",H),window.removeEventListener("resize",H)}},[$]);const[V,J]=bm(H=>{const D=W().filter(ce=>!ce.disabled),X=D.find(ce=>ce.ref.current===document.activeElement),Z=ym(D,H,X);Z&&setTimeout(()=>Z.ref.current.focus())}),j=h.useCallback((H,D,X)=>{const Z=!K.current&&!X;(w.value!==void 0&&w.value===D||Z)&&(O(H),Z&&(K.current=!0))},[w.value]),R=h.useCallback(()=>S==null?void 0:S.focus(),[S]),G=h.useCallback((H,D,X)=>{const Z=!K.current&&!X;(w.value!==void 0&&w.value===D||Z)&&U(H)},[w.value]),Y=r==="popper"?El:om,ie=Y===El?{side:a,sideOffset:l,align:c,alignOffset:d,arrowPadding:p,collisionBoundary:m,collisionPadding:f,sticky:v,hideWhenDetached:g,avoidCollisions:x}:{};return u.jsx(nm,{scope:n,content:S,viewport:C,onViewportChange:T,itemRefCallback:j,selectedItem:A,onItemLeave:R,itemTextRefCallback:G,focusSelectedItem:Q,selectedItemText:F,position:r,isPositioned:z,searchRef:V,children:u.jsx(Yo,{as:bk,allowPinchZoom:!0,children:u.jsx(Ho,{asChild:!0,trapped:w.open,onMountAutoFocus:H=>{H.preventDefault()},onUnmountAutoFocus:le(o,H=>{var D;(D=w.trigger)==null||D.focus({preventScroll:!0}),H.preventDefault()}),children:u.jsx(mr,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:H=>H.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:u.jsx(Y,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:H=>H.preventDefault(),...y,...ie,onPlaced:()=>N(!0),ref:E,style:{display:"flex",flexDirection:"column",outline:"none",...y.style},onKeyDown:le(y.onKeyDown,H=>{const D=H.ctrlKey||H.altKey||H.metaKey;if(H.key==="Tab"&&H.preventDefault(),!D&&H.key.length===1&&J(H.key),["ArrowUp","ArrowDown","Home","End"].includes(H.key)){let Z=W().filter(ce=>!ce.disabled).map(ce=>ce.ref.current);if(["ArrowUp","End"].includes(H.key)&&(Z=Z.slice().reverse()),["ArrowUp","ArrowDown"].includes(H.key)){const ce=H.target,L=Z.indexOf(ce);Z=Z.slice(L+1)}setTimeout(()=>M(Z)),H.preventDefault()}})})})})})})});rm.displayName=wk;var yk="SelectItemAlignedPosition",om=h.forwardRef((e,t)=>{const{__scopeSelect:n,onPlaced:r,...o}=e,s=Un(ar,n),i=Wn(ar,n),[a,l]=h.useState(null),[c,d]=h.useState(null),p=We(t,E=>d(E)),m=Xs(n),f=h.useRef(!1),v=h.useRef(!0),{viewport:g,selectedItem:x,selectedItemText:y,focusSelectedItem:w}=i,S=h.useCallback(()=>{if(s.trigger&&s.valueNode&&a&&c&&g&&x&&y){const E=s.trigger.getBoundingClientRect(),A=c.getBoundingClientRect(),O=s.valueNode.getBoundingClientRect(),F=y.getBoundingClientRect();if(s.dir!=="rtl"){const ce=F.left-A.left,L=O.left-ce,oe=E.left-L,xe=E.width+oe,de=Math.max(xe,A.width),we=window.innerWidth-fn,Me=La(L,[fn,Math.max(fn,we-de)]);a.style.minWidth=xe+"px",a.style.left=Me+"px"}else{const ce=A.right-F.right,L=window.innerWidth-O.right-ce,oe=window.innerWidth-E.right-L,xe=E.width+oe,de=Math.max(xe,A.width),we=window.innerWidth-fn,Me=La(L,[fn,Math.max(fn,we-de)]);a.style.minWidth=xe+"px",a.style.right=Me+"px"}const U=m(),W=window.innerHeight-fn*2,z=g.scrollHeight,N=window.getComputedStyle(c),K=parseInt(N.borderTopWidth,10),M=parseInt(N.paddingTop,10),Q=parseInt(N.borderBottomWidth,10),$=parseInt(N.paddingBottom,10),_=K+M+z+$+Q,V=Math.min(x.offsetHeight*5,_),J=window.getComputedStyle(g),j=parseInt(J.paddingTop,10),R=parseInt(J.paddingBottom,10),G=E.top+E.height/2-fn,Y=W-G,ie=x.offsetHeight/2,H=x.offsetTop+ie,D=K+M+H,X=_-D;if(D<=G){const ce=U.length>0&&x===U[U.length-1].ref.current;a.style.bottom="0px";const L=c.clientHeight-g.offsetTop-g.offsetHeight,oe=Math.max(Y,ie+(ce?R:0)+L+Q),xe=D+oe;a.style.height=xe+"px"}else{const ce=U.length>0&&x===U[0].ref.current;a.style.top="0px";const oe=Math.max(G,K+g.offsetTop+(ce?j:0)+ie)+X;a.style.height=oe+"px",g.scrollTop=D-G+g.offsetTop}a.style.margin=`${fn}px 0`,a.style.minHeight=V+"px",a.style.maxHeight=W+"px",r==null||r(),requestAnimationFrame(()=>f.current=!0)}},[m,s.trigger,s.valueNode,a,c,g,x,y,s.dir,r]);It(()=>S(),[S]);const[k,C]=h.useState();It(()=>{c&&C(window.getComputedStyle(c).zIndex)},[c]);const T=h.useCallback(E=>{E&&v.current===!0&&(S(),w==null||w(),v.current=!1)},[S,w]);return u.jsx(Ck,{scope:n,contentWrapper:a,shouldExpandOnScrollRef:f,onScrollButtonChange:T,children:u.jsx("div",{ref:l,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:k},children:u.jsx(ye.div,{...o,ref:p,style:{boxSizing:"border-box",maxHeight:"100%",...o.style}})})})});om.displayName=yk;var Sk="SelectPopperPosition",El=h.forwardRef((e,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:o=fn,...s}=e,i=Js(n);return u.jsx(ka,{...i,...s,ref:t,align:r,collisionPadding:o,style:{boxSizing:"border-box",...s.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});El.displayName=Sk;var[Ck,Il]=Pr(ar,{}),Nl="SelectViewport",sm=h.forwardRef((e,t)=>{const{__scopeSelect:n,nonce:r,...o}=e,s=Wn(Nl,n),i=Il(Nl,n),a=We(t,s.onViewportChange),l=h.useRef(0);return u.jsxs(u.Fragment,{children:[u.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),u.jsx(Ys.Slot,{scope:n,children:u.jsx(ye.div,{"data-radix-select-viewport":"",role:"presentation",...o,ref:a,style:{position:"relative",flex:1,overflow:"hidden auto",...o.style},onScroll:le(o.onScroll,c=>{const d=c.currentTarget,{contentWrapper:p,shouldExpandOnScrollRef:m}=i;if(m!=null&&m.current&&p){const f=Math.abs(l.current-d.scrollTop);if(f>0){const v=window.innerHeight-fn*2,g=parseFloat(p.style.minHeight),x=parseFloat(p.style.height),y=Math.max(g,x);if(y<v){const w=y+f,S=Math.min(v,w),k=w-S;p.style.height=S+"px",p.style.bottom==="0px"&&(d.scrollTop=k>0?k:0,p.style.justifyContent="flex-end")}}}l.current=d.scrollTop})})})]})});sm.displayName=Nl;var im="SelectGroup",[Tk,kk]=Pr(im),Ek=h.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=At();return u.jsx(Tk,{scope:n,id:o,children:u.jsx(ye.div,{role:"group","aria-labelledby":o,...r,ref:t})})});Ek.displayName=im;var am="SelectLabel",lm=h.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=kk(am,n);return u.jsx(ye.div,{id:o.id,...r,ref:t})});lm.displayName=am;var Zs="SelectItem",[Ik,cm]=Pr(Zs),um=h.forwardRef((e,t)=>{const{__scopeSelect:n,value:r,disabled:o=!1,textValue:s,...i}=e,a=Un(Zs,n),l=Wn(Zs,n),c=a.value===r,[d,p]=h.useState(s??""),[m,f]=h.useState(!1),v=We(t,w=>{var S;return(S=l.itemRefCallback)==null?void 0:S.call(l,w,r,o)}),g=At(),x=h.useRef("touch"),y=()=>{o||(a.onValueChange(r),a.onOpenChange(!1))};if(r==="")throw new Error("A <Select.Item /> must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return u.jsx(Ik,{scope:n,value:r,disabled:o,textId:g,isSelected:c,onItemTextChange:h.useCallback(w=>{p(S=>S||((w==null?void 0:w.textContent)??"").trim())},[]),children:u.jsx(Ys.ItemSlot,{scope:n,value:r,disabled:o,textValue:d,children:u.jsx(ye.div,{role:"option","aria-labelledby":g,"data-highlighted":m?"":void 0,"aria-selected":c&&m,"data-state":c?"checked":"unchecked","aria-disabled":o||void 0,"data-disabled":o?"":void 0,tabIndex:o?void 0:-1,...i,ref:v,onFocus:le(i.onFocus,()=>f(!0)),onBlur:le(i.onBlur,()=>f(!1)),onClick:le(i.onClick,()=>{x.current!=="mouse"&&y()}),onPointerUp:le(i.onPointerUp,()=>{x.current==="mouse"&&y()}),onPointerDown:le(i.onPointerDown,w=>{x.current=w.pointerType}),onPointerMove:le(i.onPointerMove,w=>{var S;x.current=w.pointerType,o?(S=l.onItemLeave)==null||S.call(l):x.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:le(i.onPointerLeave,w=>{var S;w.currentTarget===document.activeElement&&((S=l.onItemLeave)==null||S.call(l))}),onKeyDown:le(i.onKeyDown,w=>{var k;((k=l.searchRef)==null?void 0:k.current)!==""&&w.key===" "||(fk.includes(w.key)&&y(),w.key===" "&&w.preventDefault())})})})})});um.displayName=Zs;var yo="SelectItemText",dm=h.forwardRef((e,t)=>{const{__scopeSelect:n,className:r,style:o,...s}=e,i=Un(yo,n),a=Wn(yo,n),l=cm(yo,n),c=gk(yo,n),[d,p]=h.useState(null),m=We(t,y=>p(y),l.onItemTextChange,y=>{var w;return(w=a.itemTextRefCallback)==null?void 0:w.call(a,y,l.value,l.disabled)}),f=d==null?void 0:d.textContent,v=h.useMemo(()=>u.jsx("option",{value:l.value,disabled:l.disabled,children:f},l.value),[l.disabled,l.value,f]),{onNativeOptionAdd:g,onNativeOptionRemove:x}=c;return It(()=>(g(v),()=>x(v)),[g,x,v]),u.jsxs(u.Fragment,{children:[u.jsx(ye.span,{id:l.textId,...s,ref:m}),l.isSelected&&i.valueNode&&!i.valueNodeHasChildren?Dr.createPortal(s.children,i.valueNode):null]})});dm.displayName=yo;var fm="SelectItemIndicator",pm=h.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return cm(fm,n).isSelected?u.jsx(ye.span,{"aria-hidden":!0,...r,ref:t}):null});pm.displayName=fm;var Al="SelectScrollUpButton",hm=h.forwardRef((e,t)=>{const n=Wn(Al,e.__scopeSelect),r=Il(Al,e.__scopeSelect),[o,s]=h.useState(!1),i=We(t,r.onScrollButtonChange);return It(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollTop>0;s(c)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(gm,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop-l.offsetHeight)}}):null});hm.displayName=Al;var _l="SelectScrollDownButton",mm=h.forwardRef((e,t)=>{const n=Wn(_l,e.__scopeSelect),r=Il(_l,e.__scopeSelect),[o,s]=h.useState(!1),i=We(t,r.onScrollButtonChange);return It(()=>{if(n.viewport&&n.isPositioned){let a=function(){const c=l.scrollHeight-l.clientHeight,d=Math.ceil(l.scrollTop)<c;s(d)};const l=n.viewport;return a(),l.addEventListener("scroll",a),()=>l.removeEventListener("scroll",a)}},[n.viewport,n.isPositioned]),o?u.jsx(gm,{...e,ref:i,onAutoScroll:()=>{const{viewport:a,selectedItem:l}=n;a&&l&&(a.scrollTop=a.scrollTop+l.offsetHeight)}}):null});mm.displayName=_l;var gm=h.forwardRef((e,t)=>{const{__scopeSelect:n,onAutoScroll:r,...o}=e,s=Wn("SelectScrollButton",n),i=h.useRef(null),a=Xs(n),l=h.useCallback(()=>{i.current!==null&&(window.clearInterval(i.current),i.current=null)},[]);return h.useEffect(()=>()=>l(),[l]),It(()=>{var d;const c=a().find(p=>p.ref.current===document.activeElement);(d=c==null?void 0:c.ref.current)==null||d.scrollIntoView({block:"nearest"})},[a]),u.jsx(ye.div,{"aria-hidden":!0,...o,ref:t,style:{flexShrink:0,...o.style},onPointerDown:le(o.onPointerDown,()=>{i.current===null&&(i.current=window.setInterval(r,50))}),onPointerMove:le(o.onPointerMove,()=>{var c;(c=s.onItemLeave)==null||c.call(s),i.current===null&&(i.current=window.setInterval(r,50))}),onPointerLeave:le(o.onPointerLeave,()=>{l()})})}),Nk="SelectSeparator",xm=h.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e;return u.jsx(ye.div,{"aria-hidden":!0,...r,ref:t})});xm.displayName=Nk;var jl="SelectArrow",Ak=h.forwardRef((e,t)=>{const{__scopeSelect:n,...r}=e,o=Js(n),s=Un(jl,n),i=Wn(jl,n);return s.open&&i.position==="popper"?u.jsx(Ea,{...o,...r,ref:t}):null});Ak.displayName=jl;var _k="SelectBubbleInput",vm=h.forwardRef(({__scopeSelect:e,value:t,...n},r)=>{const o=h.useRef(null),s=We(r,o),i=Kh(t);return h.useEffect(()=>{const a=o.current;if(!a)return;const l=window.HTMLSelectElement.prototype,d=Object.getOwnPropertyDescriptor(l,"value").set;if(i!==t&&d){const p=new Event("change",{bubbles:!0});d.call(a,t),a.dispatchEvent(p)}},[i,t]),u.jsx(ye.select,{...n,style:{...qh,...n.style},ref:s,defaultValue:t})});vm.displayName=_k;function wm(e){return e===""||e===void 0}function bm(e){const t=wt(e),n=h.useRef(""),r=h.useRef(0),o=h.useCallback(i=>{const a=n.current+i;t(a),function l(c){n.current=c,window.clearTimeout(r.current),c!==""&&(r.current=window.setTimeout(()=>l(""),1e3))}(a)},[t]),s=h.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return h.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,o,s]}function ym(e,t,n){const o=t.length>1&&Array.from(t).every(c=>c===t[0])?t[0]:t,s=n?e.indexOf(n):-1;let i=jk(e,Math.max(s,0));o.length===1&&(i=i.filter(c=>c!==n));const l=i.find(c=>c.textValue.toLowerCase().startsWith(o.toLowerCase()));return l!==n?l:void 0}function jk(e,t){return e.map((n,r)=>e[(t+r)%e.length])}var Pk=Gh,Sm=Xh,Mk=Zh,Rk=Qh,Ok=em,Cm=tm,Dk=sm,Tm=lm,km=um,Lk=dm,$k=pm,Em=hm,Im=mm,Nm=xm;const Fk=Pk,Bk=Mk,Am=h.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(Sm,{ref:r,className:re("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",e),...n,children:[t,u.jsx(Rk,{asChild:!0,children:u.jsx(fe.ChevronDown,{className:"h-4 w-4 opacity-50"})})]}));Am.displayName=Sm.displayName;const _m=h.forwardRef(({className:e,...t},n)=>u.jsx(Em,{ref:n,className:re("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(fe.ChevronUp,{className:"h-4 w-4"})}));_m.displayName=Em.displayName;const jm=h.forwardRef(({className:e,...t},n)=>u.jsx(Im,{ref:n,className:re("flex cursor-default items-center justify-center py-1",e),...t,children:u.jsx(fe.ChevronDown,{className:"h-4 w-4"})}));jm.displayName=Im.displayName;const Pm=h.forwardRef(({className:e,children:t,position:n="popper",...r},o)=>u.jsx(Ok,{children:u.jsxs(Cm,{ref:o,className:re("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",e),position:n,...r,children:[u.jsx(_m,{}),u.jsx(Dk,{className:re("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),u.jsx(jm,{})]})}));Pm.displayName=Cm.displayName;const zk=h.forwardRef(({className:e,...t},n)=>u.jsx(Tm,{ref:n,className:re("py-1.5 pl-8 pr-2 text-sm font-semibold",e),...t}));zk.displayName=Tm.displayName;const Mm=h.forwardRef(({className:e,children:t,...n},r)=>u.jsxs(km,{ref:r,className:re("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50",e),...n,children:[u.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:u.jsx($k,{children:u.jsx(fe.Check,{className:"h-4 w-4"})})}),u.jsx(Lk,{children:t})]}));Mm.displayName=km.displayName;const Hk=h.forwardRef(({className:e,...t},n)=>u.jsx(Nm,{ref:n,className:re("-mx-1 my-1 h-px bg-muted",e),...t}));Hk.displayName=Nm.displayName;var Uk="Separator",Rm="horizontal",Wk=["horizontal","vertical"],Om=h.forwardRef((e,t)=>{const{decorative:n,orientation:r=Rm,...o}=e,s=Vk(r)?r:Rm,a=n?{role:"none"}:{"aria-orientation":s==="vertical"?s:void 0,role:"separator"};return u.jsx(ye.div,{"data-orientation":s,...a,...o,ref:t})});Om.displayName=Uk;function Vk(e){return Wk.includes(e)}var Dm=Om;const Lm=h.forwardRef(({className:e,orientation:t="horizontal",decorative:n=!0,...r},o)=>u.jsx(Dm,{ref:o,decorative:n,orientation:t,className:re("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",e),...r}));Lm.displayName=Dm.displayName;var Qs="Switch",[Kk,n1]=sn(Qs),[qk,Gk]=Kk(Qs),$m=h.forwardRef((e,t)=>{const{__scopeSwitch:n,name:r,checked:o,defaultChecked:s,required:i,disabled:a,value:l="on",onCheckedChange:c,form:d,...p}=e,[m,f]=h.useState(null),v=We(t,S=>f(S)),g=h.useRef(!1),x=m?d||!!m.closest("form"):!0,[y,w]=jn({prop:o,defaultProp:s??!1,onChange:c,caller:Qs});return u.jsxs(qk,{scope:n,checked:y,disabled:a,children:[u.jsx(ye.button,{type:"button",role:"switch","aria-checked":y,"aria-required":i,"data-state":Hm(y),"data-disabled":a?"":void 0,disabled:a,value:l,...p,ref:v,onClick:le(e.onClick,S=>{w(k=>!k),x&&(g.current=S.isPropagationStopped(),g.current||S.stopPropagation())})}),x&&u.jsx(zm,{control:m,bubbles:!g.current,name:r,value:l,checked:y,required:i,disabled:a,form:d,style:{transform:"translateX(-100%)"}})]})});$m.displayName=Qs;var Fm="SwitchThumb",Bm=h.forwardRef((e,t)=>{const{__scopeSwitch:n,...r}=e,o=Gk(Fm,n);return u.jsx(ye.span,{"data-state":Hm(o.checked),"data-disabled":o.disabled?"":void 0,...r,ref:t})});Bm.displayName=Fm;var Yk="SwitchBubbleInput",zm=h.forwardRef(({__scopeSwitch:e,control:t,checked:n,bubbles:r=!0,...o},s)=>{const i=h.useRef(null),a=We(i,s),l=Kh(n),c=Kd(t);return h.useEffect(()=>{const d=i.current;if(!d)return;const p=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(p,"checked").set;if(l!==n&&f){const v=new Event("click",{bubbles:r});f.call(d,n),d.dispatchEvent(v)}},[l,n,r]),u.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...o,tabIndex:-1,ref:a,style:{...o.style,...c,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});zm.displayName=Yk;function Hm(e){return e?"checked":"unchecked"}var Um=$m,Xk=Bm;const Wm=h.forwardRef(({className:e,...t},n)=>u.jsx(Um,{className:re("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=unchecked]:bg-input",e),...t,ref:n,children:u.jsx(Xk,{className:re("pointer-events-none block h-5 w-5 rounded-full bg-background shadow-lg ring-0 transition-transform data-[state=checked]:translate-x-5 data-[state=unchecked]:translate-x-0")})}));Wm.displayName=Um.displayName;const Jk=Zi,Zk=Tb,Qk=Qi,Vm=h.forwardRef(({className:e,...t},n)=>u.jsx(Gr,{className:re("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",e),...t,ref:n}));Vm.displayName=Gr.displayName;const eE=Or.cva("fixed z-50 gap-4 bg-background p-6 shadow-lg transition ease-in-out data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:duration-300 data-[state=open]:duration-500",{variants:{side:{top:"inset-x-0 top-0 border-b data-[state=closed]:slide-out-to-top data-[state=open]:slide-in-from-top",bottom:"inset-x-0 bottom-0 border-t data-[state=closed]:slide-out-to-bottom data-[state=open]:slide-in-from-bottom",left:"inset-y-0 left-0 h-full w-3/4 border-r data-[state=closed]:slide-out-to-left data-[state=open]:slide-in-from-left sm:max-w-sm",right:"inset-y-0 right-0 h-full w-3/4 border-l data-[state=closed]:slide-out-to-right data-[state=open]:slide-in-from-right sm:max-w-sm"}},defaultVariants:{side:"right"}}),Km=h.forwardRef(({side:e="right",className:t,children:n,...r},o)=>u.jsxs(Qk,{children:[u.jsx(Vm,{}),u.jsxs(Yr,{ref:o,className:re(eE({side:e}),t),...r,children:[n,u.jsxs(pd,{className:"absolute right-4 top-4 rounded-sm opacity-70 ring-offset-background transition-opacity hover:opacity-100 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none data-[state=open]:bg-secondary",children:[u.jsx(fe.X,{className:"h-4 w-4"}),u.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Km.displayName=Yr.displayName;const qm=({className:e,...t})=>u.jsx("div",{className:re("flex flex-col space-y-2 text-center sm:text-left",e),...t});qm.displayName="SheetHeader";const Gm=h.forwardRef(({className:e,...t},n)=>u.jsx(Xn,{ref:n,className:re("text-lg font-semibold text-foreground",e),...t}));Gm.displayName=Xn.displayName;const Ym=h.forwardRef(({className:e,...t},n)=>u.jsx(es,{ref:n,className:re("text-sm text-muted-foreground",e),...t}));Ym.displayName=es.displayName;var[ei,r1]=sn("Tooltip",[Er]),ti=Er(),Xm="TooltipProvider",tE=700,Pl="tooltip.open",[nE,Ml]=ei(Xm),Jm=e=>{const{__scopeTooltip:t,delayDuration:n=tE,skipDelayDuration:r=300,disableHoverableContent:o=!1,children:s}=e,i=h.useRef(!0),a=h.useRef(!1),l=h.useRef(0);return h.useEffect(()=>{const c=l.current;return()=>window.clearTimeout(c)},[]),u.jsx(nE,{scope:t,isOpenDelayedRef:i,delayDuration:n,onOpen:h.useCallback(()=>{window.clearTimeout(l.current),i.current=!1},[]),onClose:h.useCallback(()=>{window.clearTimeout(l.current),l.current=window.setTimeout(()=>i.current=!0,r)},[r]),isPointerInTransitRef:a,onPointerInTransitChange:h.useCallback(c=>{a.current=c},[]),disableHoverableContent:o,children:s})};Jm.displayName=Xm;var So="Tooltip",[rE,ni]=ei(So),Zm=e=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:o,onOpenChange:s,disableHoverableContent:i,delayDuration:a}=e,l=Ml(So,e.__scopeTooltip),c=ti(t),[d,p]=h.useState(null),m=At(),f=h.useRef(0),v=i??l.disableHoverableContent,g=a??l.delayDuration,x=h.useRef(!1),[y,w]=jn({prop:r,defaultProp:o??!1,onChange:E=>{E?(l.onOpen(),document.dispatchEvent(new CustomEvent(Pl))):l.onClose(),s==null||s(E)},caller:So}),S=h.useMemo(()=>y?x.current?"delayed-open":"instant-open":"closed",[y]),k=h.useCallback(()=>{window.clearTimeout(f.current),f.current=0,x.current=!1,w(!0)},[w]),C=h.useCallback(()=>{window.clearTimeout(f.current),f.current=0,w(!1)},[w]),T=h.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{x.current=!0,w(!0),f.current=0},g)},[g,w]);return h.useEffect(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),u.jsx(Ca,{...c,children:u.jsx(rE,{scope:t,contentId:m,open:y,stateAttribute:S,trigger:d,onTriggerChange:p,onTriggerEnter:h.useCallback(()=>{l.isOpenDelayedRef.current?T():k()},[l.isOpenDelayedRef,T,k]),onTriggerLeave:h.useCallback(()=>{v?C():(window.clearTimeout(f.current),f.current=0)},[C,v]),onOpen:k,onClose:C,disableHoverableContent:v,children:n})})};Zm.displayName=So;var Rl="TooltipTrigger",Qm=h.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=ni(Rl,n),s=Ml(Rl,n),i=ti(n),a=h.useRef(null),l=We(t,a,o.onTriggerChange),c=h.useRef(!1),d=h.useRef(!1),p=h.useCallback(()=>c.current=!1,[]);return h.useEffect(()=>()=>document.removeEventListener("pointerup",p),[p]),u.jsx(Ta,{asChild:!0,...i,children:u.jsx(ye.button,{"aria-describedby":o.open?o.contentId:void 0,"data-state":o.stateAttribute,...r,ref:l,onPointerMove:le(e.onPointerMove,m=>{m.pointerType!=="touch"&&!d.current&&!s.isPointerInTransitRef.current&&(o.onTriggerEnter(),d.current=!0)}),onPointerLeave:le(e.onPointerLeave,()=>{o.onTriggerLeave(),d.current=!1}),onPointerDown:le(e.onPointerDown,()=>{o.open&&o.onClose(),c.current=!0,document.addEventListener("pointerup",p,{once:!0})}),onFocus:le(e.onFocus,()=>{c.current||o.onOpen()}),onBlur:le(e.onBlur,o.onClose),onClick:le(e.onClick,o.onClose)})})});Qm.displayName=Rl;var oE="TooltipPortal",[o1,sE]=ei(oE,{forceMount:void 0}),Mr="TooltipContent",eg=h.forwardRef((e,t)=>{const n=sE(Mr,e.__scopeTooltip),{forceMount:r=n.forceMount,side:o="top",...s}=e,i=ni(Mr,e.__scopeTooltip);return u.jsx(Ft,{present:r||i.open,children:i.disableHoverableContent?u.jsx(tg,{side:o,...s,ref:t}):u.jsx(iE,{side:o,...s,ref:t})})}),iE=h.forwardRef((e,t)=>{const n=ni(Mr,e.__scopeTooltip),r=Ml(Mr,e.__scopeTooltip),o=h.useRef(null),s=We(t,o),[i,a]=h.useState(null),{trigger:l,onClose:c}=n,d=o.current,{onPointerInTransitChange:p}=r,m=h.useCallback(()=>{a(null),p(!1)},[p]),f=h.useCallback((v,g)=>{const x=v.currentTarget,y={x:v.clientX,y:v.clientY},w=dE(y,x.getBoundingClientRect()),S=fE(y,w),k=pE(g.getBoundingClientRect()),C=mE([...S,...k]);a(C),p(!0)},[p]);return h.useEffect(()=>()=>m(),[m]),h.useEffect(()=>{if(l&&d){const v=x=>f(x,d),g=x=>f(x,l);return l.addEventListener("pointerleave",v),d.addEventListener("pointerleave",g),()=>{l.removeEventListener("pointerleave",v),d.removeEventListener("pointerleave",g)}}},[l,d,f,m]),h.useEffect(()=>{if(i){const v=g=>{const x=g.target,y={x:g.clientX,y:g.clientY},w=(l==null?void 0:l.contains(x))||(d==null?void 0:d.contains(x)),S=!hE(y,i);w?m():S&&(m(),c())};return document.addEventListener("pointermove",v),()=>document.removeEventListener("pointermove",v)}},[l,d,i,c,m]),u.jsx(tg,{...e,ref:s})}),[aE,lE]=ei(So,{isInside:!1}),cE=Vt.createSlottable("TooltipContent"),tg=h.forwardRef((e,t)=>{const{__scopeTooltip:n,children:r,"aria-label":o,onEscapeKeyDown:s,onPointerDownOutside:i,...a}=e,l=ni(Mr,n),c=ti(n),{onClose:d}=l;return h.useEffect(()=>(document.addEventListener(Pl,d),()=>document.removeEventListener(Pl,d)),[d]),h.useEffect(()=>{if(l.trigger){const p=m=>{const f=m.target;f!=null&&f.contains(l.trigger)&&d()};return window.addEventListener("scroll",p,{capture:!0}),()=>window.removeEventListener("scroll",p,{capture:!0})}},[l.trigger,d]),u.jsx(mr,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:s,onPointerDownOutside:i,onFocusOutside:p=>p.preventDefault(),onDismiss:d,children:u.jsxs(ka,{"data-state":l.stateAttribute,...c,...a,ref:t,style:{...a.style,"--radix-tooltip-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-tooltip-content-available-width":"var(--radix-popper-available-width)","--radix-tooltip-content-available-height":"var(--radix-popper-available-height)","--radix-tooltip-trigger-width":"var(--radix-popper-anchor-width)","--radix-tooltip-trigger-height":"var(--radix-popper-anchor-height)"},children:[u.jsx(cE,{children:r}),u.jsx(aE,{scope:n,isInside:!0,children:u.jsx(uk,{id:l.contentId,role:"tooltip",children:o||r})})]})})});eg.displayName=Mr;var ng="TooltipArrow",uE=h.forwardRef((e,t)=>{const{__scopeTooltip:n,...r}=e,o=ti(n);return lE(ng,n).isInside?null:u.jsx(Ea,{...o,...r,ref:t})});uE.displayName=ng;function dE(e,t){const n=Math.abs(t.top-e.y),r=Math.abs(t.bottom-e.y),o=Math.abs(t.right-e.x),s=Math.abs(t.left-e.x);switch(Math.min(n,r,o,s)){case s:return"left";case o:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function fE(e,t,n=5){const r=[];switch(t){case"top":r.push({x:e.x-n,y:e.y+n},{x:e.x+n,y:e.y+n});break;case"bottom":r.push({x:e.x-n,y:e.y-n},{x:e.x+n,y:e.y-n});break;case"left":r.push({x:e.x+n,y:e.y-n},{x:e.x+n,y:e.y+n});break;case"right":r.push({x:e.x-n,y:e.y-n},{x:e.x-n,y:e.y+n});break}return r}function pE(e){const{top:t,right:n,bottom:r,left:o}=e;return[{x:o,y:t},{x:n,y:t},{x:n,y:r},{x:o,y:r}]}function hE(e,t){const{x:n,y:r}=e;let o=!1;for(let s=0,i=t.length-1;s<t.length;i=s++){const a=t[s],l=t[i],c=a.x,d=a.y,p=l.x,m=l.y;d>r!=m>r&&n<(p-c)*(r-d)/(m-d)+c&&(o=!o)}return o}function mE(e){const t=e.slice();return t.sort((n,r)=>n.x<r.x?-1:n.x>r.x?1:n.y<r.y?-1:n.y>r.y?1:0),gE(t)}function gE(e){if(e.length<=1)return e.slice();const t=[];for(let r=0;r<e.length;r++){const o=e[r];for(;t.length>=2;){const s=t[t.length-1],i=t[t.length-2];if((s.x-i.x)*(o.y-i.y)>=(s.y-i.y)*(o.x-i.x))t.pop();else break}t.push(o)}t.pop();const n=[];for(let r=e.length-1;r>=0;r--){const o=e[r];for(;n.length>=2;){const s=n[n.length-1],i=n[n.length-2];if((s.x-i.x)*(o.y-i.y)>=(s.y-i.y)*(o.x-i.x))n.pop();else break}n.push(o)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var xE=Jm,vE=Zm,wE=Qm,rg=eg;const bE=xE,yE=vE,SE=wE,og=h.forwardRef(({className:e,sideOffset:t=4,...n},r)=>u.jsx(rg,{ref:r,sideOffset:t,className:re("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",e),...n}));og.displayName=rg.displayName;var Ol="ToastProvider",[Dl,CE,TE]=ss("Toast"),[sg,s1]=sn("Toast",[TE]),[kE,ri]=sg(Ol),ig=e=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:o="right",swipeThreshold:s=50,children:i}=e,[a,l]=h.useState(null),[c,d]=h.useState(0),p=h.useRef(!1),m=h.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${Ol}\`. Expected non-empty \`string\`.`),u.jsx(Dl.Provider,{scope:t,children:u.jsx(kE,{scope:t,label:n,duration:r,swipeDirection:o,swipeThreshold:s,toastCount:c,viewport:a,onViewportChange:l,onToastAdd:h.useCallback(()=>d(f=>f+1),[]),onToastRemove:h.useCallback(()=>d(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:p,isClosePausedRef:m,children:i})})};ig.displayName=Ol;var ag="ToastViewport",EE=["F8"],Ll="toast.viewportPause",$l="toast.viewportResume",lg=h.forwardRef((e,t)=>{const{__scopeToast:n,hotkey:r=EE,label:o="Notifications ({hotkey})",...s}=e,i=ri(ag,n),a=CE(n),l=h.useRef(null),c=h.useRef(null),d=h.useRef(null),p=h.useRef(null),m=We(t,p,i.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),v=i.toastCount>0;h.useEffect(()=>{const x=y=>{var S;r.length!==0&&r.every(k=>y[k]||y.code===k)&&((S=p.current)==null||S.focus())};return document.addEventListener("keydown",x),()=>document.removeEventListener("keydown",x)},[r]),h.useEffect(()=>{const x=l.current,y=p.current;if(v&&x&&y){const w=()=>{if(!i.isClosePausedRef.current){const T=new CustomEvent(Ll);y.dispatchEvent(T),i.isClosePausedRef.current=!0}},S=()=>{if(i.isClosePausedRef.current){const T=new CustomEvent($l);y.dispatchEvent(T),i.isClosePausedRef.current=!1}},k=T=>{!x.contains(T.relatedTarget)&&S()},C=()=>{x.contains(document.activeElement)||S()};return x.addEventListener("focusin",w),x.addEventListener("focusout",k),x.addEventListener("pointermove",w),x.addEventListener("pointerleave",C),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{x.removeEventListener("focusin",w),x.removeEventListener("focusout",k),x.removeEventListener("pointermove",w),x.removeEventListener("pointerleave",C),window.removeEventListener("blur",w),window.removeEventListener("focus",S)}}},[v,i.isClosePausedRef]);const g=h.useCallback(({tabbingDirection:x})=>{const w=a().map(S=>{const k=S.ref.current,C=[k,...FE(k)];return x==="forwards"?C:C.reverse()});return(x==="forwards"?w.reverse():w).flat()},[a]);return h.useEffect(()=>{const x=p.current;if(x){const y=w=>{var C,T,E;const S=w.altKey||w.ctrlKey||w.metaKey;if(w.key==="Tab"&&!S){const A=document.activeElement,O=w.shiftKey;if(w.target===x&&O){(C=c.current)==null||C.focus();return}const W=g({tabbingDirection:O?"backwards":"forwards"}),z=W.findIndex(N=>N===A);zl(W.slice(z+1))?w.preventDefault():O?(T=c.current)==null||T.focus():(E=d.current)==null||E.focus()}};return x.addEventListener("keydown",y),()=>x.removeEventListener("keydown",y)}},[a,g]),u.jsxs(vw,{ref:l,role:"region","aria-label":o.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:v?void 0:"none"},children:[v&&u.jsx(Fl,{ref:c,onFocusFromOutsideViewport:()=>{const x=g({tabbingDirection:"forwards"});zl(x)}}),u.jsx(Dl.Slot,{scope:n,children:u.jsx(ye.ol,{tabIndex:-1,...s,ref:m})}),v&&u.jsx(Fl,{ref:d,onFocusFromOutsideViewport:()=>{const x=g({tabbingDirection:"backwards"});zl(x)}})]})});lg.displayName=ag;var cg="ToastFocusProxy",Fl=h.forwardRef((e,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...o}=e,s=ri(cg,n);return u.jsx(Gs,{tabIndex:0,...o,ref:t,style:{position:"fixed"},onFocus:i=>{var c;const a=i.relatedTarget;!((c=s.viewport)!=null&&c.contains(a))&&r()}})});Fl.displayName=cg;var Co="Toast",IE="toast.swipeStart",NE="toast.swipeMove",AE="toast.swipeCancel",_E="toast.swipeEnd",ug=h.forwardRef((e,t)=>{const{forceMount:n,open:r,defaultOpen:o,onOpenChange:s,...i}=e,[a,l]=jn({prop:r,defaultProp:o??!0,onChange:s,caller:Co});return u.jsx(Ft,{present:n||a,children:u.jsx(ME,{open:a,...i,ref:t,onClose:()=>l(!1),onPause:wt(e.onPause),onResume:wt(e.onResume),onSwipeStart:le(e.onSwipeStart,c=>{c.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:le(e.onSwipeMove,c=>{const{x:d,y:p}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","move"),c.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${d}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${p}px`)}),onSwipeCancel:le(e.onSwipeCancel,c=>{c.currentTarget.setAttribute("data-swipe","cancel"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:le(e.onSwipeEnd,c=>{const{x:d,y:p}=c.detail.delta;c.currentTarget.setAttribute("data-swipe","end"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),c.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),c.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${d}px`),c.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${p}px`),l(!1)})})})});ug.displayName=Co;var[jE,PE]=sg(Co,{onClose(){}}),ME=h.forwardRef((e,t)=>{const{__scopeToast:n,type:r="foreground",duration:o,open:s,onClose:i,onEscapeKeyDown:a,onPause:l,onResume:c,onSwipeStart:d,onSwipeMove:p,onSwipeCancel:m,onSwipeEnd:f,...v}=e,g=ri(Co,n),[x,y]=h.useState(null),w=We(t,N=>y(N)),S=h.useRef(null),k=h.useRef(null),C=o||g.duration,T=h.useRef(0),E=h.useRef(C),A=h.useRef(0),{onToastAdd:O,onToastRemove:F}=g,U=wt(()=>{var K;(x==null?void 0:x.contains(document.activeElement))&&((K=g.viewport)==null||K.focus()),i()}),W=h.useCallback(N=>{!N||N===1/0||(window.clearTimeout(A.current),T.current=new Date().getTime(),A.current=window.setTimeout(U,N))},[U]);h.useEffect(()=>{const N=g.viewport;if(N){const K=()=>{W(E.current),c==null||c()},M=()=>{const Q=new Date().getTime()-T.current;E.current=E.current-Q,window.clearTimeout(A.current),l==null||l()};return N.addEventListener(Ll,M),N.addEventListener($l,K),()=>{N.removeEventListener(Ll,M),N.removeEventListener($l,K)}}},[g.viewport,C,l,c,W]),h.useEffect(()=>{s&&!g.isClosePausedRef.current&&W(C)},[s,C,g.isClosePausedRef,W]),h.useEffect(()=>(O(),()=>F()),[O,F]);const z=h.useMemo(()=>x?xg(x):null,[x]);return g.viewport?u.jsxs(u.Fragment,{children:[z&&u.jsx(RE,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite",children:z}),u.jsx(jE,{scope:n,onClose:U,children:Dr.createPortal(u.jsx(Dl.ItemSlot,{scope:n,children:u.jsx(xw,{asChild:!0,onEscapeKeyDown:le(a,()=>{g.isFocusedToastEscapeKeyDownRef.current||U(),g.isFocusedToastEscapeKeyDownRef.current=!1}),children:u.jsx(ye.li,{tabIndex:0,"data-state":s?"open":"closed","data-swipe-direction":g.swipeDirection,...v,ref:w,style:{userSelect:"none",touchAction:"none",...e.style},onKeyDown:le(e.onKeyDown,N=>{N.key==="Escape"&&(a==null||a(N.nativeEvent),N.nativeEvent.defaultPrevented||(g.isFocusedToastEscapeKeyDownRef.current=!0,U()))}),onPointerDown:le(e.onPointerDown,N=>{N.button===0&&(S.current={x:N.clientX,y:N.clientY})}),onPointerMove:le(e.onPointerMove,N=>{if(!S.current)return;const K=N.clientX-S.current.x,M=N.clientY-S.current.y,Q=!!k.current,$=["left","right"].includes(g.swipeDirection),_=["left","up"].includes(g.swipeDirection)?Math.min:Math.max,V=$?_(0,K):0,J=$?0:_(0,M),j=N.pointerType==="touch"?10:2,R={x:V,y:J},G={originalEvent:N,delta:R};Q?(k.current=R,oi(NE,p,G,{discrete:!1})):vg(R,g.swipeDirection,j)?(k.current=R,oi(IE,d,G,{discrete:!1}),N.target.setPointerCapture(N.pointerId)):(Math.abs(K)>j||Math.abs(M)>j)&&(S.current=null)}),onPointerUp:le(e.onPointerUp,N=>{const K=k.current,M=N.target;if(M.hasPointerCapture(N.pointerId)&&M.releasePointerCapture(N.pointerId),k.current=null,S.current=null,K){const Q=N.currentTarget,$={originalEvent:N,delta:K};vg(K,g.swipeDirection,g.swipeThreshold)?oi(_E,f,$,{discrete:!0}):oi(AE,m,$,{discrete:!0}),Q.addEventListener("click",_=>_.preventDefault(),{once:!0})}})})})}),g.viewport)})]}):null}),RE=e=>{const{__scopeToast:t,children:n,...r}=e,o=ri(Co,t),[s,i]=h.useState(!1),[a,l]=h.useState(!1);return LE(()=>i(!0)),h.useEffect(()=>{const c=window.setTimeout(()=>l(!0),1e3);return()=>window.clearTimeout(c)},[]),a?null:u.jsx(qr,{asChild:!0,children:u.jsx(Gs,{...r,children:s&&u.jsxs(u.Fragment,{children:[o.label," ",n]})})})},OE="ToastTitle",dg=h.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return u.jsx(ye.div,{...r,ref:t})});dg.displayName=OE;var DE="ToastDescription",fg=h.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e;return u.jsx(ye.div,{...r,ref:t})});fg.displayName=DE;var pg="ToastAction",hg=h.forwardRef((e,t)=>{const{altText:n,...r}=e;return n.trim()?u.jsx(gg,{altText:n,asChild:!0,children:u.jsx(Bl,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${pg}\`. Expected non-empty \`string\`.`),null)});hg.displayName=pg;var mg="ToastClose",Bl=h.forwardRef((e,t)=>{const{__scopeToast:n,...r}=e,o=PE(mg,n);return u.jsx(gg,{asChild:!0,children:u.jsx(ye.button,{type:"button",...r,ref:t,onClick:le(e.onClick,o.onClose)})})});Bl.displayName=mg;var gg=h.forwardRef((e,t)=>{const{__scopeToast:n,altText:r,...o}=e;return u.jsx(ye.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...o,ref:t})});function xg(e){const t=[];return Array.from(e.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),$E(r)){const o=r.ariaHidden||r.hidden||r.style.display==="none",s=r.dataset.radixToastAnnounceExclude==="";if(!o)if(s){const i=r.dataset.radixToastAnnounceAlt;i&&t.push(i)}else t.push(...xg(r))}}),t}function oi(e,t,n,{discrete:r}){const o=n.originalEvent.currentTarget,s=new CustomEvent(e,{bubbles:!0,cancelable:!0,detail:n});t&&o.addEventListener(e,t,{once:!0}),r?Li(o,s):o.dispatchEvent(s)}var vg=(e,t,n=0)=>{const r=Math.abs(e.x),o=Math.abs(e.y),s=r>o;return t==="left"||t==="right"?s&&r>n:!s&&o>n};function LE(e=()=>{}){const t=wt(e);It(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function $E(e){return e.nodeType===e.ELEMENT_NODE}function FE(e){const t=[],n=document.createTreeWalker(e,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const o=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||o?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function zl(e){const t=document.activeElement;return e.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var BE=ig,wg=lg,bg=ug,yg=dg,Sg=fg,Cg=hg,Tg=Bl;const zE=BE,kg=h.forwardRef(({className:e,...t},n)=>u.jsx(wg,{ref:n,className:re("fixed bottom-0 right-0 z-[100] flex max-h-screen w-full flex-col p-4 md:max-w-[420px]",e),...t}));kg.displayName=wg.displayName;const HE=Or.cva("group pointer-events-auto relative flex w-full items-center justify-between space-x-4 overflow-hidden rounded-md border p-6 pr-8 shadow-lg transition-all data-[swipe=cancel]:translate-x-0 data-[swipe=end]:translate-x-[var(--radix-toast-swipe-end-x)] data-[swipe=move]:translate-x-[var(--radix-toast-swipe-move-x)] data-[swipe=move]:transition-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[swipe=end]:animate-out data-[state=closed]:fade-out-80 data-[state=closed]:slide-out-to-right-full data-[state=open]:slide-in-from-top-full data-[state=open]:sm:slide-in-from-bottom-full",{variants:{variant:{default:"border bg-background text-foreground",destructive:"destructive group border-destructive bg-destructive text-destructive-foreground"}},defaultVariants:{variant:"default"}}),Eg=h.forwardRef(({className:e,variant:t,...n},r)=>u.jsx(bg,{ref:r,className:re(HE({variant:t}),e),...n}));Eg.displayName=bg.displayName;const UE=h.forwardRef(({className:e,...t},n)=>u.jsx(Cg,{ref:n,className:re("inline-flex h-8 shrink-0 items-center justify-center rounded-md border bg-transparent px-3 text-sm font-medium ring-offset-background transition-colors hover:bg-secondary focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 group-[.destructive]:border-muted/40 group-[.destructive]:hover:border-destructive/30 group-[.destructive]:hover:bg-destructive group-[.destructive]:hover:text-destructive-foreground group-[.destructive]:focus:ring-destructive",e),...t}));UE.displayName=Cg.displayName;const Ig=h.forwardRef(({className:e,...t},n)=>u.jsx(Tg,{ref:n,className:re("absolute right-2 top-2 rounded-md p-1 text-foreground/50 opacity-0 transition-opacity hover:text-foreground focus:opacity-100 focus:outline-none focus:ring-2 group-hover:opacity-100 group-[.destructive]:text-red-300 group-[.destructive]:hover:text-red-50 group-[.destructive]:focus:ring-red-400 group-[.destructive]:focus:ring-offset-red-600",e),"toast-close":"",...t,children:u.jsx(fe.X,{className:"h-4 w-4"})}));Ig.displayName=Tg.displayName;const Ng=h.forwardRef(({className:e,...t},n)=>u.jsx(yg,{ref:n,className:re("text-sm font-semibold",e),...t}));Ng.displayName=yg.displayName;const Ag=h.forwardRef(({className:e,...t},n)=>u.jsx(Sg,{ref:n,className:re("text-sm opacity-90",e),...t}));Ag.displayName=Sg.displayName;function WE(){const{toasts:e}=xl();return u.jsxs(zE,{children:[e.map(function({id:t,title:n,description:r,action:o,...s}){return u.jsxs(Eg,{...s,children:[u.jsxs("div",{className:"grid gap-1",children:[n&&u.jsx(Ng,{children:n}),r&&u.jsx(Ag,{children:r})]}),o,u.jsx(Ig,{})]},t)}),u.jsx(kg,{})]})}var VE=(e,t,n,r,o,s,i,a)=>{let l=document.documentElement,c=["light","dark"];function d(f){(Array.isArray(e)?e:[e]).forEach(v=>{let g=v==="class",x=g&&s?o.map(y=>s[y]||y):o;g?(l.classList.remove(...x),l.classList.add(s&&s[f]?s[f]:f)):l.setAttribute(v,f)}),p(f)}function p(f){a&&c.includes(f)&&(l.style.colorScheme=f)}function m(){return window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"}if(r)d(r);else try{let f=localStorage.getItem(t)||n,v=i&&f==="system"?m():f;d(v)}catch{}},KE=h.createContext(void 0),qE={setTheme:e=>{},themes:[]},GE=()=>{var e;return(e=h.useContext(KE))!=null?e:qE};h.memo(({forcedTheme:e,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:o,defaultTheme:s,value:i,themes:a,nonce:l,scriptProps:c})=>{let d=JSON.stringify([n,t,s,e,a,i,r,o]).slice(1,-1);return h.createElement("script",{...c,suppressHydrationWarning:!0,nonce:typeof window>"u"?l:"",dangerouslySetInnerHTML:{__html:`(${VE.toString()})(${d})`}})});var YE=e=>{switch(e){case"success":return ZE;case"info":return eI;case"warning":return QE;case"error":return tI;default:return null}},XE=Array(12).fill(0),JE=({visible:e,className:t})=>b.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":e},b.createElement("div",{className:"sonner-spinner"},XE.map((n,r)=>b.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),ZE=b.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},b.createElement("path",{fillRule:"evenodd",d:"M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z",clipRule:"evenodd"})),QE=b.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},b.createElement("path",{fillRule:"evenodd",d:"M9.401 3.003c1.155-2 4.043-2 5.197 0l7.355 12.748c1.154 2-.29 4.5-2.599 4.5H4.645c-2.309 0-3.752-2.5-2.598-4.5L9.4 3.003zM12 8.25a.75.75 0 01.75.75v3.75a.75.75 0 01-1.5 0V9a.75.75 0 01.75-.75zm0 8.25a.75.75 0 100-1.5.75.75 0 000 1.5z",clipRule:"evenodd"})),eI=b.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},b.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a.75.75 0 000 1.5h.253a.25.25 0 01.244.304l-.459 2.066A1.75 1.75 0 0010.747 15H11a.75.75 0 000-1.5h-.253a.25.25 0 01-.244-.304l.459-2.066A1.75 1.75 0 009.253 9H9z",clipRule:"evenodd"})),tI=b.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},b.createElement("path",{fillRule:"evenodd",d:"M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-8-5a.75.75 0 01.75.75v4.5a.75.75 0 01-1.5 0v-4.5A.75.75 0 0110 5zm0 10a1 1 0 100-2 1 1 0 000 2z",clipRule:"evenodd"})),nI=b.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",width:"12",height:"12",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"},b.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),b.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),rI=()=>{let[e,t]=b.useState(document.hidden);return b.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),e},Hl=1,oI=class{constructor(){this.subscribe=e=>(this.subscribers.push(e),()=>{let t=this.subscribers.indexOf(e);this.subscribers.splice(t,1)}),this.publish=e=>{this.subscribers.forEach(t=>t(e))},this.addToast=e=>{this.publish(e),this.toasts=[...this.toasts,e]},this.create=e=>{var t;let{message:n,...r}=e,o=typeof(e==null?void 0:e.id)=="number"||((t=e.id)==null?void 0:t.length)>0?e.id:Hl++,s=this.toasts.find(a=>a.id===o),i=e.dismissible===void 0?!0:e.dismissible;return this.dismissedToasts.has(o)&&this.dismissedToasts.delete(o),s?this.toasts=this.toasts.map(a=>a.id===o?(this.publish({...a,...e,id:o,title:n}),{...a,...e,id:o,dismissible:i,title:n}):a):this.addToast({title:n,...r,dismissible:i,id:o}),o},this.dismiss=e=>(this.dismissedToasts.add(e),e||this.toasts.forEach(t=>{this.subscribers.forEach(n=>n({id:t.id,dismiss:!0}))}),this.subscribers.forEach(t=>t({id:e,dismiss:!0})),e),this.message=(e,t)=>this.create({...t,message:e}),this.error=(e,t)=>this.create({...t,message:e,type:"error"}),this.success=(e,t)=>this.create({...t,type:"success",message:e}),this.info=(e,t)=>this.create({...t,type:"info",message:e}),this.warning=(e,t)=>this.create({...t,type:"warning",message:e}),this.loading=(e,t)=>this.create({...t,type:"loading",message:e}),this.promise=(e,t)=>{if(!t)return;let n;t.loading!==void 0&&(n=this.create({...t,promise:e,type:"loading",message:t.loading,description:typeof t.description!="function"?t.description:void 0}));let r=e instanceof Promise?e:e(),o=n!==void 0,s,i=r.then(async l=>{if(s=["resolve",l],b.isValidElement(l))o=!1,this.create({id:n,type:"default",message:l});else if(iI(l)&&!l.ok){o=!1;let c=typeof t.error=="function"?await t.error(`HTTP error! status: ${l.status}`):t.error,d=typeof t.description=="function"?await t.description(`HTTP error! status: ${l.status}`):t.description;this.create({id:n,type:"error",message:c,description:d})}else if(t.success!==void 0){o=!1;let c=typeof t.success=="function"?await t.success(l):t.success,d=typeof t.description=="function"?await t.description(l):t.description;this.create({id:n,type:"success",message:c,description:d})}}).catch(async l=>{if(s=["reject",l],t.error!==void 0){o=!1;let c=typeof t.error=="function"?await t.error(l):t.error,d=typeof t.description=="function"?await t.description(l):t.description;this.create({id:n,type:"error",message:c,description:d})}}).finally(()=>{var l;o&&(this.dismiss(n),n=void 0),(l=t.finally)==null||l.call(t)}),a=()=>new Promise((l,c)=>i.then(()=>s[0]==="reject"?c(s[1]):l(s[1])).catch(c));return typeof n!="string"&&typeof n!="number"?{unwrap:a}:Object.assign(n,{unwrap:a})},this.custom=(e,t)=>{let n=(t==null?void 0:t.id)||Hl++;return this.create({jsx:e(n),id:n,...t}),n},this.getActiveToasts=()=>this.toasts.filter(e=>!this.dismissedToasts.has(e.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Ht=new oI,sI=(e,t)=>{let n=(t==null?void 0:t.id)||Hl++;return Ht.addToast({title:e,...t,id:n}),n},iI=e=>e&&typeof e=="object"&&"ok"in e&&typeof e.ok=="boolean"&&"status"in e&&typeof e.status=="number",aI=sI,lI=()=>Ht.toasts,cI=()=>Ht.getActiveToasts();Object.assign(aI,{success:Ht.success,info:Ht.info,warning:Ht.warning,error:Ht.error,custom:Ht.custom,message:Ht.message,promise:Ht.promise,dismiss:Ht.dismiss,loading:Ht.loading},{getHistory:lI,getToasts:cI});function uI(e,{insertAt:t}={}){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t==="top"&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=e:r.appendChild(document.createTextNode(e))}uI(`:where(html[dir="ltr"]),:where([data-sonner-toaster][dir="ltr"]){--toast-icon-margin-start: -3px;--toast-icon-margin-end: 4px;--toast-svg-margin-start: -1px;--toast-svg-margin-end: 0px;--toast-button-margin-start: auto;--toast-button-margin-end: 0;--toast-close-button-start: 0;--toast-close-button-end: unset;--toast-close-button-transform: translate(-35%, -35%)}:where(html[dir="rtl"]),:where([data-sonner-toaster][dir="rtl"]){--toast-icon-margin-start: 4px;--toast-icon-margin-end: -3px;--toast-svg-margin-start: 0px;--toast-svg-margin-end: -1px;--toast-button-margin-start: 0;--toast-button-margin-end: auto;--toast-close-button-start: unset;--toast-close-button-end: 0;--toast-close-button-transform: translate(35%, -35%)}:where([data-sonner-toaster]){position:fixed;width:var(--width);font-family:ui-sans-serif,system-ui,-apple-system,BlinkMacSystemFont,Segoe UI,Roboto,Helvetica Neue,Arial,Noto Sans,sans-serif,Apple Color Emoji,Segoe UI Emoji,Segoe UI Symbol,Noto Color Emoji;--gray1: hsl(0, 0%, 99%);--gray2: hsl(0, 0%, 97.3%);--gray3: hsl(0, 0%, 95.1%);--gray4: hsl(0, 0%, 93%);--gray5: hsl(0, 0%, 90.9%);--gray6: hsl(0, 0%, 88.7%);--gray7: hsl(0, 0%, 85.8%);--gray8: hsl(0, 0%, 78%);--gray9: hsl(0, 0%, 56.1%);--gray10: hsl(0, 0%, 52.3%);--gray11: hsl(0, 0%, 43.5%);--gray12: hsl(0, 0%, 9%);--border-radius: 8px;box-sizing:border-box;padding:0;margin:0;list-style:none;outline:none;z-index:999999999;transition:transform .4s ease}:where([data-sonner-toaster][data-lifted="true"]){transform:translateY(-10px)}@media (hover: none) and (pointer: coarse){:where([data-sonner-toaster][data-lifted="true"]){transform:none}}:where([data-sonner-toaster][data-x-position="right"]){right:var(--offset-right)}:where([data-sonner-toaster][data-x-position="left"]){left:var(--offset-left)}:where([data-sonner-toaster][data-x-position="center"]){left:50%;transform:translate(-50%)}:where([data-sonner-toaster][data-y-position="top"]){top:var(--offset-top)}:where([data-sonner-toaster][data-y-position="bottom"]){bottom:var(--offset-bottom)}:where([data-sonner-toast]){--y: translateY(100%);--lift-amount: calc(var(--lift) * var(--gap));z-index:var(--z-index);position:absolute;opacity:0;transform:var(--y);filter:blur(0);touch-action:none;transition:transform .4s,opacity .4s,height .4s,box-shadow .2s;box-sizing:border-box;outline:none;overflow-wrap:anywhere}:where([data-sonner-toast][data-styled="true"]){padding:16px;background:var(--normal-bg);border:1px solid var(--normal-border);color:var(--normal-text);border-radius:var(--border-radius);box-shadow:0 4px 12px #0000001a;width:var(--width);font-size:13px;display:flex;align-items:center;gap:6px}:where([data-sonner-toast]:focus-visible){box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast][data-y-position="top"]){top:0;--y: translateY(-100%);--lift: 1;--lift-amount: calc(1 * var(--gap))}:where([data-sonner-toast][data-y-position="bottom"]){bottom:0;--y: translateY(100%);--lift: -1;--lift-amount: calc(var(--lift) * var(--gap))}:where([data-sonner-toast]) :where([data-description]){font-weight:400;line-height:1.4;color:inherit}:where([data-sonner-toast]) :where([data-title]){font-weight:500;line-height:1.5;color:inherit}:where([data-sonner-toast]) :where([data-icon]){display:flex;height:16px;width:16px;position:relative;justify-content:flex-start;align-items:center;flex-shrink:0;margin-left:var(--toast-icon-margin-start);margin-right:var(--toast-icon-margin-end)}:where([data-sonner-toast][data-promise="true"]) :where([data-icon])>svg{opacity:0;transform:scale(.8);transform-origin:center;animation:sonner-fade-in .3s ease forwards}:where([data-sonner-toast]) :where([data-icon])>*{flex-shrink:0}:where([data-sonner-toast]) :where([data-icon]) svg{margin-left:var(--toast-svg-margin-start);margin-right:var(--toast-svg-margin-end)}:where([data-sonner-toast]) :where([data-content]){display:flex;flex-direction:column;gap:2px}[data-sonner-toast][data-styled=true] [data-button]{border-radius:4px;padding-left:8px;padding-right:8px;height:24px;font-size:12px;color:var(--normal-bg);background:var(--normal-text);margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end);border:none;cursor:pointer;outline:none;display:flex;align-items:center;flex-shrink:0;transition:opacity .4s,box-shadow .2s}:where([data-sonner-toast]) :where([data-button]):focus-visible{box-shadow:0 0 0 2px #0006}:where([data-sonner-toast]) :where([data-button]):first-of-type{margin-left:var(--toast-button-margin-start);margin-right:var(--toast-button-margin-end)}:where([data-sonner-toast]) :where([data-cancel]){color:var(--normal-text);background:rgba(0,0,0,.08)}:where([data-sonner-toast][data-theme="dark"]) :where([data-cancel]){background:rgba(255,255,255,.3)}:where([data-sonner-toast]) :where([data-close-button]){position:absolute;left:var(--toast-close-button-start);right:var(--toast-close-button-end);top:0;height:20px;width:20px;display:flex;justify-content:center;align-items:center;padding:0;color:var(--gray12);border:1px solid var(--gray4);transform:var(--toast-close-button-transform);border-radius:50%;cursor:pointer;z-index:1;transition:opacity .1s,background .2s,border-color .2s}[data-sonner-toast] [data-close-button]{background:var(--gray1)}:where([data-sonner-toast]) :where([data-close-button]):focus-visible{box-shadow:0 4px 12px #0000001a,0 0 0 2px #0003}:where([data-sonner-toast]) :where([data-disabled="true"]){cursor:not-allowed}:where([data-sonner-toast]):hover :where([data-close-button]):hover{background:var(--gray2);border-color:var(--gray5)}:where([data-sonner-toast][data-swiping="true"]):before{content:"";position:absolute;left:-50%;right:-50%;height:100%;z-index:-1}:where([data-sonner-toast][data-y-position="top"][data-swiping="true"]):before{bottom:50%;transform:scaleY(3) translateY(50%)}:where([data-sonner-toast][data-y-position="bottom"][data-swiping="true"]):before{top:50%;transform:scaleY(3) translateY(-50%)}:where([data-sonner-toast][data-swiping="false"][data-removed="true"]):before{content:"";position:absolute;inset:0;transform:scaleY(2)}:where([data-sonner-toast]):after{content:"";position:absolute;left:0;height:calc(var(--gap) + 1px);bottom:100%;width:100%}:where([data-sonner-toast][data-mounted="true"]){--y: translateY(0);opacity:1}:where([data-sonner-toast][data-expanded="false"][data-front="false"]){--scale: var(--toasts-before) * .05 + 1;--y: translateY(calc(var(--lift-amount) * var(--toasts-before))) scale(calc(-1 * var(--scale)));height:var(--front-toast-height)}:where([data-sonner-toast])>*{transition:opacity .4s}:where([data-sonner-toast][data-expanded="false"][data-front="false"][data-styled="true"])>*{opacity:0}:where([data-sonner-toast][data-visible="false"]){opacity:0;pointer-events:none}:where([data-sonner-toast][data-mounted="true"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset)));height:var(--initial-height)}:where([data-sonner-toast][data-removed="true"][data-front="true"][data-swipe-out="false"]){--y: translateY(calc(var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="true"]){--y: translateY(calc(var(--lift) * var(--offset) + var(--lift) * -100%));opacity:0}:where([data-sonner-toast][data-removed="true"][data-front="false"][data-swipe-out="false"][data-expanded="false"]){--y: translateY(40%);opacity:0;transition:transform .5s,opacity .2s}:where([data-sonner-toast][data-removed="true"][data-front="false"]):before{height:calc(var(--initial-height) + 20%)}[data-sonner-toast][data-swiping=true]{transform:var(--y) translateY(var(--swipe-amount-y, 0px)) translate(var(--swipe-amount-x, 0px));transition:none}[data-sonner-toast][data-swiped=true]{user-select:none}[data-sonner-toast][data-swipe-out=true][data-y-position=bottom],[data-sonner-toast][data-swipe-out=true][data-y-position=top]{animation-duration:.2s;animation-timing-function:ease-out;animation-fill-mode:forwards}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=left]{animation-name:swipe-out-left}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=right]{animation-name:swipe-out-right}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=up]{animation-name:swipe-out-up}[data-sonner-toast][data-swipe-out=true][data-swipe-direction=down]{animation-name:swipe-out-down}@keyframes swipe-out-left{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) - 100%));opacity:0}}@keyframes swipe-out-right{0%{transform:var(--y) translate(var(--swipe-amount-x));opacity:1}to{transform:var(--y) translate(calc(var(--swipe-amount-x) + 100%));opacity:0}}@keyframes swipe-out-up{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) - 100%));opacity:0}}@keyframes swipe-out-down{0%{transform:var(--y) translateY(var(--swipe-amount-y));opacity:1}to{transform:var(--y) translateY(calc(var(--swipe-amount-y) + 100%));opacity:0}}@media (max-width: 600px){[data-sonner-toaster]{position:fixed;right:var(--mobile-offset-right);left:var(--mobile-offset-left);width:100%}[data-sonner-toaster][dir=rtl]{left:calc(var(--mobile-offset-left) * -1)}[data-sonner-toaster] [data-sonner-toast]{left:0;right:0;width:calc(100% - var(--mobile-offset-left) * 2)}[data-sonner-toaster][data-x-position=left]{left:var(--mobile-offset-left)}[data-sonner-toaster][data-y-position=bottom]{bottom:var(--mobile-offset-bottom)}[data-sonner-toaster][data-y-position=top]{top:var(--mobile-offset-top)}[data-sonner-toaster][data-x-position=center]{left:var(--mobile-offset-left);right:var(--mobile-offset-right);transform:none}}[data-sonner-toaster][data-theme=light]{--normal-bg: #fff;--normal-border: var(--gray4);--normal-text: var(--gray12);--success-bg: hsl(143, 85%, 96%);--success-border: hsl(145, 92%, 91%);--success-text: hsl(140, 100%, 27%);--info-bg: hsl(208, 100%, 97%);--info-border: hsl(221, 91%, 91%);--info-text: hsl(210, 92%, 45%);--warning-bg: hsl(49, 100%, 97%);--warning-border: hsl(49, 91%, 91%);--warning-text: hsl(31, 92%, 45%);--error-bg: hsl(359, 100%, 97%);--error-border: hsl(359, 100%, 94%);--error-text: hsl(360, 100%, 45%)}[data-sonner-toaster][data-theme=light] [data-sonner-toast][data-invert=true]{--normal-bg: #000;--normal-border: hsl(0, 0%, 20%);--normal-text: var(--gray1)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast][data-invert=true]{--normal-bg: #fff;--normal-border: var(--gray3);--normal-text: var(--gray12)}[data-sonner-toaster][data-theme=dark]{--normal-bg: #000;--normal-bg-hover: hsl(0, 0%, 12%);--normal-border: hsl(0, 0%, 20%);--normal-border-hover: hsl(0, 0%, 25%);--normal-text: var(--gray1);--success-bg: hsl(150, 100%, 6%);--success-border: hsl(147, 100%, 12%);--success-text: hsl(150, 86%, 65%);--info-bg: hsl(215, 100%, 6%);--info-border: hsl(223, 100%, 12%);--info-text: hsl(216, 87%, 65%);--warning-bg: hsl(64, 100%, 6%);--warning-border: hsl(60, 100%, 12%);--warning-text: hsl(46, 87%, 65%);--error-bg: hsl(358, 76%, 10%);--error-border: hsl(357, 89%, 16%);--error-text: hsl(358, 100%, 81%)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]{background:var(--normal-bg);border-color:var(--normal-border);color:var(--normal-text)}[data-sonner-toaster][data-theme=dark] [data-sonner-toast] [data-close-button]:hover{background:var(--normal-bg-hover);border-color:var(--normal-border-hover)}[data-rich-colors=true][data-sonner-toast][data-type=success],[data-rich-colors=true][data-sonner-toast][data-type=success] [data-close-button]{background:var(--success-bg);border-color:var(--success-border);color:var(--success-text)}[data-rich-colors=true][data-sonner-toast][data-type=info],[data-rich-colors=true][data-sonner-toast][data-type=info] [data-close-button]{background:var(--info-bg);border-color:var(--info-border);color:var(--info-text)}[data-rich-colors=true][data-sonner-toast][data-type=warning],[data-rich-colors=true][data-sonner-toast][data-type=warning] [data-close-button]{background:var(--warning-bg);border-color:var(--warning-border);color:var(--warning-text)}[data-rich-colors=true][data-sonner-toast][data-type=error],[data-rich-colors=true][data-sonner-toast][data-type=error] [data-close-button]{background:var(--error-bg);border-color:var(--error-border);color:var(--error-text)}.sonner-loading-wrapper{--size: 16px;height:var(--size);width:var(--size);position:absolute;inset:0;z-index:10}.sonner-loading-wrapper[data-visible=false]{transform-origin:center;animation:sonner-fade-out .2s ease forwards}.sonner-spinner{position:relative;top:50%;left:50%;height:var(--size);width:var(--size)}.sonner-loading-bar{animation:sonner-spin 1.2s linear infinite;background:var(--gray11);border-radius:6px;height:8%;left:-10%;position:absolute;top:-3.9%;width:24%}.sonner-loading-bar:nth-child(1){animation-delay:-1.2s;transform:rotate(.0001deg) translate(146%)}.sonner-loading-bar:nth-child(2){animation-delay:-1.1s;transform:rotate(30deg) translate(146%)}.sonner-loading-bar:nth-child(3){animation-delay:-1s;transform:rotate(60deg) translate(146%)}.sonner-loading-bar:nth-child(4){animation-delay:-.9s;transform:rotate(90deg) translate(146%)}.sonner-loading-bar:nth-child(5){animation-delay:-.8s;transform:rotate(120deg) translate(146%)}.sonner-loading-bar:nth-child(6){animation-delay:-.7s;transform:rotate(150deg) translate(146%)}.sonner-loading-bar:nth-child(7){animation-delay:-.6s;transform:rotate(180deg) translate(146%)}.sonner-loading-bar:nth-child(8){animation-delay:-.5s;transform:rotate(210deg) translate(146%)}.sonner-loading-bar:nth-child(9){animation-delay:-.4s;transform:rotate(240deg) translate(146%)}.sonner-loading-bar:nth-child(10){animation-delay:-.3s;transform:rotate(270deg) translate(146%)}.sonner-loading-bar:nth-child(11){animation-delay:-.2s;transform:rotate(300deg) translate(146%)}.sonner-loading-bar:nth-child(12){animation-delay:-.1s;transform:rotate(330deg) translate(146%)}@keyframes sonner-fade-in{0%{opacity:0;transform:scale(.8)}to{opacity:1;transform:scale(1)}}@keyframes sonner-fade-out{0%{opacity:1;transform:scale(1)}to{opacity:0;transform:scale(.8)}}@keyframes sonner-spin{0%{opacity:1}to{opacity:.15}}@media (prefers-reduced-motion){[data-sonner-toast],[data-sonner-toast]>*,.sonner-loading-bar{transition:none!important;animation:none!important}}.sonner-loader{position:absolute;top:50%;left:50%;transform:translate(-50%,-50%);transform-origin:center;transition:opacity .2s,transform .2s}.sonner-loader[data-visible=false]{opacity:0;transform:scale(.8) translate(-50%,-50%)}
|
|
130
|
-
`);function si(e){return e.label!==void 0}var dI=3,fI="32px",pI="16px",_g=4e3,hI=356,mI=14,gI=20,xI=200;function pn(...e){return e.filter(Boolean).join(" ")}function vI(e){let[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var wI=e=>{var t,n,r,o,s,i,a,l,c,d,p;let{invert:m,toast:f,unstyled:v,interacting:g,setHeights:x,visibleToasts:y,heights:w,index:S,toasts:k,expanded:C,removeToast:T,defaultRichColors:E,closeButton:A,style:O,cancelButtonStyle:F,actionButtonStyle:U,className:W="",descriptionClassName:z="",duration:N,position:K,gap:M,loadingIcon:Q,expandByDefault:$,classNames:_,icons:V,closeButtonAriaLabel:J="Close toast",pauseWhenPageIsHidden:j}=e,[R,G]=b.useState(null),[Y,ie]=b.useState(null),[H,D]=b.useState(!1),[X,Z]=b.useState(!1),[ce,L]=b.useState(!1),[oe,xe]=b.useState(!1),[de,we]=b.useState(!1),[Me,He]=b.useState(0),[$e,Ae]=b.useState(0),Fe=b.useRef(f.duration||N||_g),Ge=b.useRef(null),Ke=b.useRef(null),Xe=S===0,tt=S+1<=y,nt=f.type,Ze=f.dismissible!==!1,pt=f.className||"",ht=f.descriptionClassName||"",Se=b.useMemo(()=>w.findIndex(ae=>ae.toastId===f.id)||0,[w,f.id]),Re=b.useMemo(()=>{var ae;return(ae=f.closeButton)!=null?ae:A},[f.closeButton,A]),mt=b.useMemo(()=>f.duration||N||_g,[f.duration,N]),ot=b.useRef(0),qe=b.useRef(0),yt=b.useRef(0),De=b.useRef(null),[Be,St]=K.split("-"),xt=b.useMemo(()=>w.reduce((ae,Ie,Te)=>Te>=Se?ae:ae+Ie.height,0),[w,Se]),Ye=rI(),gt=f.invert||m,P=nt==="loading";qe.current=b.useMemo(()=>Se*M+xt,[Se,xt]),b.useEffect(()=>{Fe.current=mt},[mt]),b.useEffect(()=>{D(!0)},[]),b.useEffect(()=>{let ae=Ke.current;if(ae){let Ie=ae.getBoundingClientRect().height;return Ae(Ie),x(Te=>[{toastId:f.id,height:Ie,position:f.position},...Te]),()=>x(Te=>Te.filter(st=>st.toastId!==f.id))}},[x,f.id]),b.useLayoutEffect(()=>{if(!H)return;let ae=Ke.current,Ie=ae.style.height;ae.style.height="auto";let Te=ae.getBoundingClientRect().height;ae.style.height=Ie,Ae(Te),x(st=>st.find(Ue=>Ue.toastId===f.id)?st.map(Ue=>Ue.toastId===f.id?{...Ue,height:Te}:Ue):[{toastId:f.id,height:Te,position:f.position},...st])},[H,f.title,f.description,x,f.id]);let te=b.useCallback(()=>{Z(!0),He(qe.current),x(ae=>ae.filter(Ie=>Ie.toastId!==f.id)),setTimeout(()=>{T(f)},xI)},[f,T,x,qe]);b.useEffect(()=>{if(f.promise&&nt==="loading"||f.duration===1/0||f.type==="loading")return;let ae;return C||g||j&&Ye?(()=>{if(yt.current<ot.current){let Ie=new Date().getTime()-ot.current;Fe.current=Fe.current-Ie}yt.current=new Date().getTime()})():Fe.current!==1/0&&(ot.current=new Date().getTime(),ae=setTimeout(()=>{var Ie;(Ie=f.onAutoClose)==null||Ie.call(f,f),te()},Fe.current)),()=>clearTimeout(ae)},[C,g,f,nt,j,Ye,te]),b.useEffect(()=>{f.delete&&te()},[te,f.delete]);function ve(){var ae,Ie,Te;return V!=null&&V.loading?b.createElement("div",{className:pn(_==null?void 0:_.loader,(ae=f==null?void 0:f.classNames)==null?void 0:ae.loader,"sonner-loader"),"data-visible":nt==="loading"},V.loading):Q?b.createElement("div",{className:pn(_==null?void 0:_.loader,(Ie=f==null?void 0:f.classNames)==null?void 0:Ie.loader,"sonner-loader"),"data-visible":nt==="loading"},Q):b.createElement(JE,{className:pn(_==null?void 0:_.loader,(Te=f==null?void 0:f.classNames)==null?void 0:Te.loader),visible:nt==="loading"})}return b.createElement("li",{tabIndex:0,ref:Ke,className:pn(W,pt,_==null?void 0:_.toast,(t=f==null?void 0:f.classNames)==null?void 0:t.toast,_==null?void 0:_.default,_==null?void 0:_[nt],(n=f==null?void 0:f.classNames)==null?void 0:n[nt]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:E,"data-styled":!(f.jsx||f.unstyled||v),"data-mounted":H,"data-promise":!!f.promise,"data-swiped":de,"data-removed":X,"data-visible":tt,"data-y-position":Be,"data-x-position":St,"data-index":S,"data-front":Xe,"data-swiping":ce,"data-dismissible":Ze,"data-type":nt,"data-invert":gt,"data-swipe-out":oe,"data-swipe-direction":Y,"data-expanded":!!(C||$&&H),style:{"--index":S,"--toasts-before":S,"--z-index":k.length-S,"--offset":`${X?Me:qe.current}px`,"--initial-height":$?"auto":`${$e}px`,...O,...f.style},onDragEnd:()=>{L(!1),G(null),De.current=null},onPointerDown:ae=>{P||!Ze||(Ge.current=new Date,He(qe.current),ae.target.setPointerCapture(ae.pointerId),ae.target.tagName!=="BUTTON"&&(L(!0),De.current={x:ae.clientX,y:ae.clientY}))},onPointerUp:()=>{var ae,Ie,Te,st;if(oe||!Ze)return;De.current=null;let Ue=Number(((ae=Ke.current)==null?void 0:ae.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),lt=Number(((Ie=Ke.current)==null?void 0:Ie.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Ut=new Date().getTime()-((Te=Ge.current)==null?void 0:Te.getTime()),Mt=R==="x"?Ue:lt,nn=Math.abs(Mt)/Ut;if(Math.abs(Mt)>=gI||nn>.11){He(qe.current),(st=f.onDismiss)==null||st.call(f,f),ie(R==="x"?Ue>0?"right":"left":lt>0?"down":"up"),te(),xe(!0),we(!1);return}L(!1),G(null)},onPointerMove:ae=>{var Ie,Te,st,Ue;if(!De.current||!Ze||((Ie=window.getSelection())==null?void 0:Ie.toString().length)>0)return;let lt=ae.clientY-De.current.y,Ut=ae.clientX-De.current.x,Mt=(Te=e.swipeDirections)!=null?Te:vI(K);!R&&(Math.abs(Ut)>1||Math.abs(lt)>1)&&G(Math.abs(Ut)>Math.abs(lt)?"x":"y");let nn={x:0,y:0};R==="y"?(Mt.includes("top")||Mt.includes("bottom"))&&(Mt.includes("top")&<<0||Mt.includes("bottom")&<>0)&&(nn.y=lt):R==="x"&&(Mt.includes("left")||Mt.includes("right"))&&(Mt.includes("left")&&Ut<0||Mt.includes("right")&&Ut>0)&&(nn.x=Ut),(Math.abs(nn.x)>0||Math.abs(nn.y)>0)&&we(!0),(st=Ke.current)==null||st.style.setProperty("--swipe-amount-x",`${nn.x}px`),(Ue=Ke.current)==null||Ue.style.setProperty("--swipe-amount-y",`${nn.y}px`)}},Re&&!f.jsx?b.createElement("button",{"aria-label":J,"data-disabled":P,"data-close-button":!0,onClick:P||!Ze?()=>{}:()=>{var ae;te(),(ae=f.onDismiss)==null||ae.call(f,f)},className:pn(_==null?void 0:_.closeButton,(o=f==null?void 0:f.classNames)==null?void 0:o.closeButton)},(s=V==null?void 0:V.close)!=null?s:nI):null,f.jsx||b.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:b.createElement(b.Fragment,null,nt||f.icon||f.promise?b.createElement("div",{"data-icon":"",className:pn(_==null?void 0:_.icon,(i=f==null?void 0:f.classNames)==null?void 0:i.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||ve():null,f.type!=="loading"?f.icon||(V==null?void 0:V[nt])||YE(nt):null):null,b.createElement("div",{"data-content":"",className:pn(_==null?void 0:_.content,(a=f==null?void 0:f.classNames)==null?void 0:a.content)},b.createElement("div",{"data-title":"",className:pn(_==null?void 0:_.title,(l=f==null?void 0:f.classNames)==null?void 0:l.title)},typeof f.title=="function"?f.title():f.title),f.description?b.createElement("div",{"data-description":"",className:pn(z,ht,_==null?void 0:_.description,(c=f==null?void 0:f.classNames)==null?void 0:c.description)},typeof f.description=="function"?f.description():f.description):null),b.isValidElement(f.cancel)?f.cancel:f.cancel&&si(f.cancel)?b.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||F,onClick:ae=>{var Ie,Te;si(f.cancel)&&Ze&&((Te=(Ie=f.cancel).onClick)==null||Te.call(Ie,ae),te())},className:pn(_==null?void 0:_.cancelButton,(d=f==null?void 0:f.classNames)==null?void 0:d.cancelButton)},f.cancel.label):null,b.isValidElement(f.action)?f.action:f.action&&si(f.action)?b.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||U,onClick:ae=>{var Ie,Te;si(f.action)&&((Te=(Ie=f.action).onClick)==null||Te.call(Ie,ae),!ae.defaultPrevented&&te())},className:pn(_==null?void 0:_.actionButton,(p=f==null?void 0:f.classNames)==null?void 0:p.actionButton)},f.action.label):null))};function jg(){if(typeof window>"u"||typeof document>"u")return"ltr";let e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function bI(e,t){let n={};return[e,t].forEach((r,o)=>{let s=o===1,i=s?"--mobile-offset":"--offset",a=s?pI:fI;function l(c){["top","right","bottom","left"].forEach(d=>{n[`${i}-${d}`]=typeof c=="number"?`${c}px`:c})}typeof r=="number"||typeof r=="string"?l(r):typeof r=="object"?["top","right","bottom","left"].forEach(c=>{r[c]===void 0?n[`${i}-${c}`]=a:n[`${i}-${c}`]=typeof r[c]=="number"?`${r[c]}px`:r[c]}):l(a)}),n}var yI=b.forwardRef(function(e,t){let{invert:n,position:r="bottom-right",hotkey:o=["altKey","KeyT"],expand:s,closeButton:i,className:a,offset:l,mobileOffset:c,theme:d="light",richColors:p,duration:m,style:f,visibleToasts:v=dI,toastOptions:g,dir:x=jg(),gap:y=mI,loadingIcon:w,icons:S,containerAriaLabel:k="Notifications",pauseWhenPageIsHidden:C}=e,[T,E]=b.useState([]),A=b.useMemo(()=>Array.from(new Set([r].concat(T.filter(j=>j.position).map(j=>j.position)))),[T,r]),[O,F]=b.useState([]),[U,W]=b.useState(!1),[z,N]=b.useState(!1),[K,M]=b.useState(d!=="system"?d:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Q=b.useRef(null),$=o.join("+").replace(/Key/g,"").replace(/Digit/g,""),_=b.useRef(null),V=b.useRef(!1),J=b.useCallback(j=>{E(R=>{var G;return(G=R.find(Y=>Y.id===j.id))!=null&&G.delete||Ht.dismiss(j.id),R.filter(({id:Y})=>Y!==j.id)})},[]);return b.useEffect(()=>Ht.subscribe(j=>{if(j.dismiss){E(R=>R.map(G=>G.id===j.id?{...G,delete:!0}:G));return}setTimeout(()=>{To.flushSync(()=>{E(R=>{let G=R.findIndex(Y=>Y.id===j.id);return G!==-1?[...R.slice(0,G),{...R[G],...j},...R.slice(G+1)]:[j,...R]})})})}),[]),b.useEffect(()=>{if(d!=="system"){M(d);return}if(d==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?M("dark"):M("light")),typeof window>"u")return;let j=window.matchMedia("(prefers-color-scheme: dark)");try{j.addEventListener("change",({matches:R})=>{M(R?"dark":"light")})}catch{j.addListener(({matches:G})=>{try{M(G?"dark":"light")}catch(Y){console.error(Y)}})}},[d]),b.useEffect(()=>{T.length<=1&&W(!1)},[T]),b.useEffect(()=>{let j=R=>{var G,Y;o.every(ie=>R[ie]||R.code===ie)&&(W(!0),(G=Q.current)==null||G.focus()),R.code==="Escape"&&(document.activeElement===Q.current||(Y=Q.current)!=null&&Y.contains(document.activeElement))&&W(!1)};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[o]),b.useEffect(()=>{if(Q.current)return()=>{_.current&&(_.current.focus({preventScroll:!0}),_.current=null,V.current=!1)}},[Q.current]),b.createElement("section",{ref:t,"aria-label":`${k} ${$}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},A.map((j,R)=>{var G;let[Y,ie]=j.split("-");return T.length?b.createElement("ol",{key:j,dir:x==="auto"?jg():x,tabIndex:-1,ref:Q,className:a,"data-sonner-toaster":!0,"data-theme":K,"data-y-position":Y,"data-lifted":U&&T.length>1&&!s,"data-x-position":ie,style:{"--front-toast-height":`${((G=O[0])==null?void 0:G.height)||0}px`,"--width":`${hI}px`,"--gap":`${y}px`,...f,...bI(l,c)},onBlur:H=>{V.current&&!H.currentTarget.contains(H.relatedTarget)&&(V.current=!1,_.current&&(_.current.focus({preventScroll:!0}),_.current=null))},onFocus:H=>{H.target instanceof HTMLElement&&H.target.dataset.dismissible==="false"||V.current||(V.current=!0,_.current=H.relatedTarget)},onMouseEnter:()=>W(!0),onMouseMove:()=>W(!0),onMouseLeave:()=>{z||W(!1)},onDragEnd:()=>W(!1),onPointerDown:H=>{H.target instanceof HTMLElement&&H.target.dataset.dismissible==="false"||N(!0)},onPointerUp:()=>N(!1)},T.filter(H=>!H.position&&R===0||H.position===j).map((H,D)=>{var X,Z;return b.createElement(wI,{key:H.id,icons:S,index:D,toast:H,defaultRichColors:p,duration:(X=g==null?void 0:g.duration)!=null?X:m,className:g==null?void 0:g.className,descriptionClassName:g==null?void 0:g.descriptionClassName,invert:n,visibleToasts:v,closeButton:(Z=g==null?void 0:g.closeButton)!=null?Z:i,interacting:z,position:j,style:g==null?void 0:g.style,unstyled:g==null?void 0:g.unstyled,classNames:g==null?void 0:g.classNames,cancelButtonStyle:g==null?void 0:g.cancelButtonStyle,actionButtonStyle:g==null?void 0:g.actionButtonStyle,removeToast:J,toasts:T.filter(ce=>ce.position==H.position),heights:O.filter(ce=>ce.position==H.position),setHeights:F,expandByDefault:s,gap:y,loadingIcon:w,expanded:U,pauseWhenPageIsHidden:C,swipeDirections:e.swipeDirections})})):null}))});const SI=({...e})=>{const{theme:t="system"}=GE();return u.jsx(yI,{theme:t,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...e})};q.Api=pv,q.ApiClient=fv,q.ApiProvider=Zc,q.Badge=bh,q.Button=ct,q.Card=bl,q.CardContent=Tl,q.CardDescription=Cl,q.CardHeader=yl,q.CardTitle=Sl,q.ChatApi=$o,q.ChatApp=Hh,q.ChatInput=yp,q.ChatInterface=bo,q.Command=oa,q.CommandEmpty=aa,q.CommandGroup=la,q.CommandInput=sa,q.CommandItem=ca,q.CommandList=ia,q.DEFAULT_TIMEOUT_MS=Kc,q.Dialog=ra,q.DialogContent=ns,q.DialogHeader=rs,q.DialogTitle=os,q.DropdownMenu=Ss,q.DropdownMenuContent=ao,q.DropdownMenuItem=Dn,q.DropdownMenuTrigger=Cs,q.FileViewerModal=Sh,q.HISTORY_TIMEOUT_MS=qc,q.Input=Ua,q.Label=Vh,q.MarkdownContent=jr,q.MessageComponent=qs,q.MessageList=kl,q.SETTINGS_STORAGE_KEY=Ei,q.ScrollArea=Ha,q.Select=Fk,q.SelectContent=Pm,q.SelectItem=Mm,q.SelectTrigger=Am,q.SelectValue=Bk,q.Separator=Lm,q.Sheet=Jk,q.SheetContent=Km,q.SheetDescription=Ym,q.SheetHeader=qm,q.SheetTitle=Gm,q.SheetTrigger=Zk,q.SimpleChat=ik,q.Sonner=SI,q.Switch=Wm,q.Textarea=Va,q.ThreadManager=Wa,q.TimelineColumn=Ug,q.Toaster=WE,q.Tooltip=yE,q.TooltipContent=og,q.TooltipProvider=bE,q.TooltipTrigger=SE,q.applySettings=vv,q.buildAttemptMaps=Yl,q.buildCheckpointIndex=Jl,q.buildCheckpointPreviewMap=Lg,q.chatApiClient=An,q.default=Hh,q.del=Si,q.downloadFileById=Yc,q.extractConfigFields=li,q.fileToBase64=Qc,q.get=qt,q.getChatToken=Wc,q.getCurrentSettings=xv,q.getDefaultApiConfig=ou,q.getDefaultChatSettings=su,q.getFileContent=Ti,q.getFileInfo=mv,q.getPreviewForMessage=ai,q.httpClient=Kt,q.hydrateHistorySnapshots=Nn,q.listFiles=Xc,q.loadStoredSettings=iu,q.onChatTokenChanged=Vc,q.post=Lo,q.processAttachments=eu,q.put=Gc,q.readNumber=Ql,q.readString=Vn,q.resolveChatBaseUrl=mn,q.resolveMessageMetadata=ql,q.saveSettings=au,q.setChatToken=Do,q.toPlainObject=cr,q.unwrap=Rt,q.useApi=ki,q.useCheckpointIndex=Zl,q.useMessageMetadata=Gl,q.useStreamingHook=Su,q.useThreadHistoryState=lu,q.useThreadManagerViewState=bp,q.useThreadsState=cu,q.viewFileById=hv,Object.defineProperties(q,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
|
130
|
+
`);function si(e){return e.label!==void 0}var dI=3,fI="32px",pI="16px",_g=4e3,hI=356,mI=14,gI=20,xI=200;function pn(...e){return e.filter(Boolean).join(" ")}function vI(e){let[t,n]=e.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var wI=e=>{var t,n,r,o,s,i,a,l,c,d,p;let{invert:m,toast:f,unstyled:v,interacting:g,setHeights:x,visibleToasts:y,heights:w,index:S,toasts:k,expanded:C,removeToast:T,defaultRichColors:E,closeButton:A,style:O,cancelButtonStyle:F,actionButtonStyle:U,className:W="",descriptionClassName:z="",duration:N,position:K,gap:M,loadingIcon:Q,expandByDefault:$,classNames:_,icons:V,closeButtonAriaLabel:J="Close toast",pauseWhenPageIsHidden:j}=e,[R,G]=b.useState(null),[Y,ie]=b.useState(null),[H,D]=b.useState(!1),[X,Z]=b.useState(!1),[ce,L]=b.useState(!1),[oe,xe]=b.useState(!1),[de,we]=b.useState(!1),[Me,He]=b.useState(0),[$e,Ae]=b.useState(0),Fe=b.useRef(f.duration||N||_g),Ge=b.useRef(null),Ke=b.useRef(null),Xe=S===0,tt=S+1<=y,nt=f.type,Ze=f.dismissible!==!1,pt=f.className||"",ht=f.descriptionClassName||"",Se=b.useMemo(()=>w.findIndex(ae=>ae.toastId===f.id)||0,[w,f.id]),Re=b.useMemo(()=>{var ae;return(ae=f.closeButton)!=null?ae:A},[f.closeButton,A]),mt=b.useMemo(()=>f.duration||N||_g,[f.duration,N]),ot=b.useRef(0),qe=b.useRef(0),yt=b.useRef(0),De=b.useRef(null),[Be,St]=K.split("-"),xt=b.useMemo(()=>w.reduce((ae,Ie,Te)=>Te>=Se?ae:ae+Ie.height,0),[w,Se]),Ye=rI(),gt=f.invert||m,P=nt==="loading";qe.current=b.useMemo(()=>Se*M+xt,[Se,xt]),b.useEffect(()=>{Fe.current=mt},[mt]),b.useEffect(()=>{D(!0)},[]),b.useEffect(()=>{let ae=Ke.current;if(ae){let Ie=ae.getBoundingClientRect().height;return Ae(Ie),x(Te=>[{toastId:f.id,height:Ie,position:f.position},...Te]),()=>x(Te=>Te.filter(st=>st.toastId!==f.id))}},[x,f.id]),b.useLayoutEffect(()=>{if(!H)return;let ae=Ke.current,Ie=ae.style.height;ae.style.height="auto";let Te=ae.getBoundingClientRect().height;ae.style.height=Ie,Ae(Te),x(st=>st.find(Ue=>Ue.toastId===f.id)?st.map(Ue=>Ue.toastId===f.id?{...Ue,height:Te}:Ue):[{toastId:f.id,height:Te,position:f.position},...st])},[H,f.title,f.description,x,f.id]);let te=b.useCallback(()=>{Z(!0),He(qe.current),x(ae=>ae.filter(Ie=>Ie.toastId!==f.id)),setTimeout(()=>{T(f)},xI)},[f,T,x,qe]);b.useEffect(()=>{if(f.promise&&nt==="loading"||f.duration===1/0||f.type==="loading")return;let ae;return C||g||j&&Ye?(()=>{if(yt.current<ot.current){let Ie=new Date().getTime()-ot.current;Fe.current=Fe.current-Ie}yt.current=new Date().getTime()})():Fe.current!==1/0&&(ot.current=new Date().getTime(),ae=setTimeout(()=>{var Ie;(Ie=f.onAutoClose)==null||Ie.call(f,f),te()},Fe.current)),()=>clearTimeout(ae)},[C,g,f,nt,j,Ye,te]),b.useEffect(()=>{f.delete&&te()},[te,f.delete]);function ve(){var ae,Ie,Te;return V!=null&&V.loading?b.createElement("div",{className:pn(_==null?void 0:_.loader,(ae=f==null?void 0:f.classNames)==null?void 0:ae.loader,"sonner-loader"),"data-visible":nt==="loading"},V.loading):Q?b.createElement("div",{className:pn(_==null?void 0:_.loader,(Ie=f==null?void 0:f.classNames)==null?void 0:Ie.loader,"sonner-loader"),"data-visible":nt==="loading"},Q):b.createElement(JE,{className:pn(_==null?void 0:_.loader,(Te=f==null?void 0:f.classNames)==null?void 0:Te.loader),visible:nt==="loading"})}return b.createElement("li",{tabIndex:0,ref:Ke,className:pn(W,pt,_==null?void 0:_.toast,(t=f==null?void 0:f.classNames)==null?void 0:t.toast,_==null?void 0:_.default,_==null?void 0:_[nt],(n=f==null?void 0:f.classNames)==null?void 0:n[nt]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:E,"data-styled":!(f.jsx||f.unstyled||v),"data-mounted":H,"data-promise":!!f.promise,"data-swiped":de,"data-removed":X,"data-visible":tt,"data-y-position":Be,"data-x-position":St,"data-index":S,"data-front":Xe,"data-swiping":ce,"data-dismissible":Ze,"data-type":nt,"data-invert":gt,"data-swipe-out":oe,"data-swipe-direction":Y,"data-expanded":!!(C||$&&H),style:{"--index":S,"--toasts-before":S,"--z-index":k.length-S,"--offset":`${X?Me:qe.current}px`,"--initial-height":$?"auto":`${$e}px`,...O,...f.style},onDragEnd:()=>{L(!1),G(null),De.current=null},onPointerDown:ae=>{P||!Ze||(Ge.current=new Date,He(qe.current),ae.target.setPointerCapture(ae.pointerId),ae.target.tagName!=="BUTTON"&&(L(!0),De.current={x:ae.clientX,y:ae.clientY}))},onPointerUp:()=>{var ae,Ie,Te,st;if(oe||!Ze)return;De.current=null;let Ue=Number(((ae=Ke.current)==null?void 0:ae.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),lt=Number(((Ie=Ke.current)==null?void 0:Ie.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),Ut=new Date().getTime()-((Te=Ge.current)==null?void 0:Te.getTime()),Mt=R==="x"?Ue:lt,nn=Math.abs(Mt)/Ut;if(Math.abs(Mt)>=gI||nn>.11){He(qe.current),(st=f.onDismiss)==null||st.call(f,f),ie(R==="x"?Ue>0?"right":"left":lt>0?"down":"up"),te(),xe(!0),we(!1);return}L(!1),G(null)},onPointerMove:ae=>{var Ie,Te,st,Ue;if(!De.current||!Ze||((Ie=window.getSelection())==null?void 0:Ie.toString().length)>0)return;let lt=ae.clientY-De.current.y,Ut=ae.clientX-De.current.x,Mt=(Te=e.swipeDirections)!=null?Te:vI(K);!R&&(Math.abs(Ut)>1||Math.abs(lt)>1)&&G(Math.abs(Ut)>Math.abs(lt)?"x":"y");let nn={x:0,y:0};R==="y"?(Mt.includes("top")||Mt.includes("bottom"))&&(Mt.includes("top")&<<0||Mt.includes("bottom")&<>0)&&(nn.y=lt):R==="x"&&(Mt.includes("left")||Mt.includes("right"))&&(Mt.includes("left")&&Ut<0||Mt.includes("right")&&Ut>0)&&(nn.x=Ut),(Math.abs(nn.x)>0||Math.abs(nn.y)>0)&&we(!0),(st=Ke.current)==null||st.style.setProperty("--swipe-amount-x",`${nn.x}px`),(Ue=Ke.current)==null||Ue.style.setProperty("--swipe-amount-y",`${nn.y}px`)}},Re&&!f.jsx?b.createElement("button",{"aria-label":J,"data-disabled":P,"data-close-button":!0,onClick:P||!Ze?()=>{}:()=>{var ae;te(),(ae=f.onDismiss)==null||ae.call(f,f)},className:pn(_==null?void 0:_.closeButton,(o=f==null?void 0:f.classNames)==null?void 0:o.closeButton)},(s=V==null?void 0:V.close)!=null?s:nI):null,f.jsx||b.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:b.createElement(b.Fragment,null,nt||f.icon||f.promise?b.createElement("div",{"data-icon":"",className:pn(_==null?void 0:_.icon,(i=f==null?void 0:f.classNames)==null?void 0:i.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||ve():null,f.type!=="loading"?f.icon||(V==null?void 0:V[nt])||YE(nt):null):null,b.createElement("div",{"data-content":"",className:pn(_==null?void 0:_.content,(a=f==null?void 0:f.classNames)==null?void 0:a.content)},b.createElement("div",{"data-title":"",className:pn(_==null?void 0:_.title,(l=f==null?void 0:f.classNames)==null?void 0:l.title)},typeof f.title=="function"?f.title():f.title),f.description?b.createElement("div",{"data-description":"",className:pn(z,ht,_==null?void 0:_.description,(c=f==null?void 0:f.classNames)==null?void 0:c.description)},typeof f.description=="function"?f.description():f.description):null),b.isValidElement(f.cancel)?f.cancel:f.cancel&&si(f.cancel)?b.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||F,onClick:ae=>{var Ie,Te;si(f.cancel)&&Ze&&((Te=(Ie=f.cancel).onClick)==null||Te.call(Ie,ae),te())},className:pn(_==null?void 0:_.cancelButton,(d=f==null?void 0:f.classNames)==null?void 0:d.cancelButton)},f.cancel.label):null,b.isValidElement(f.action)?f.action:f.action&&si(f.action)?b.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||U,onClick:ae=>{var Ie,Te;si(f.action)&&((Te=(Ie=f.action).onClick)==null||Te.call(Ie,ae),!ae.defaultPrevented&&te())},className:pn(_==null?void 0:_.actionButton,(p=f==null?void 0:f.classNames)==null?void 0:p.actionButton)},f.action.label):null))};function jg(){if(typeof window>"u"||typeof document>"u")return"ltr";let e=document.documentElement.getAttribute("dir");return e==="auto"||!e?window.getComputedStyle(document.documentElement).direction:e}function bI(e,t){let n={};return[e,t].forEach((r,o)=>{let s=o===1,i=s?"--mobile-offset":"--offset",a=s?pI:fI;function l(c){["top","right","bottom","left"].forEach(d=>{n[`${i}-${d}`]=typeof c=="number"?`${c}px`:c})}typeof r=="number"||typeof r=="string"?l(r):typeof r=="object"?["top","right","bottom","left"].forEach(c=>{r[c]===void 0?n[`${i}-${c}`]=a:n[`${i}-${c}`]=typeof r[c]=="number"?`${r[c]}px`:r[c]}):l(a)}),n}var yI=b.forwardRef(function(e,t){let{invert:n,position:r="bottom-right",hotkey:o=["altKey","KeyT"],expand:s,closeButton:i,className:a,offset:l,mobileOffset:c,theme:d="light",richColors:p,duration:m,style:f,visibleToasts:v=dI,toastOptions:g,dir:x=jg(),gap:y=mI,loadingIcon:w,icons:S,containerAriaLabel:k="Notifications",pauseWhenPageIsHidden:C}=e,[T,E]=b.useState([]),A=b.useMemo(()=>Array.from(new Set([r].concat(T.filter(j=>j.position).map(j=>j.position)))),[T,r]),[O,F]=b.useState([]),[U,W]=b.useState(!1),[z,N]=b.useState(!1),[K,M]=b.useState(d!=="system"?d:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),Q=b.useRef(null),$=o.join("+").replace(/Key/g,"").replace(/Digit/g,""),_=b.useRef(null),V=b.useRef(!1),J=b.useCallback(j=>{E(R=>{var G;return(G=R.find(Y=>Y.id===j.id))!=null&&G.delete||Ht.dismiss(j.id),R.filter(({id:Y})=>Y!==j.id)})},[]);return b.useEffect(()=>Ht.subscribe(j=>{if(j.dismiss){E(R=>R.map(G=>G.id===j.id?{...G,delete:!0}:G));return}setTimeout(()=>{To.flushSync(()=>{E(R=>{let G=R.findIndex(Y=>Y.id===j.id);return G!==-1?[...R.slice(0,G),{...R[G],...j},...R.slice(G+1)]:[j,...R]})})})}),[]),b.useEffect(()=>{if(d!=="system"){M(d);return}if(d==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?M("dark"):M("light")),typeof window>"u")return;let j=window.matchMedia("(prefers-color-scheme: dark)");try{j.addEventListener("change",({matches:R})=>{M(R?"dark":"light")})}catch{j.addListener(({matches:G})=>{try{M(G?"dark":"light")}catch(Y){console.error(Y)}})}},[d]),b.useEffect(()=>{T.length<=1&&W(!1)},[T]),b.useEffect(()=>{let j=R=>{var G,Y;o.every(ie=>R[ie]||R.code===ie)&&(W(!0),(G=Q.current)==null||G.focus()),R.code==="Escape"&&(document.activeElement===Q.current||(Y=Q.current)!=null&&Y.contains(document.activeElement))&&W(!1)};return document.addEventListener("keydown",j),()=>document.removeEventListener("keydown",j)},[o]),b.useEffect(()=>{if(Q.current)return()=>{_.current&&(_.current.focus({preventScroll:!0}),_.current=null,V.current=!1)}},[Q.current]),b.createElement("section",{ref:t,"aria-label":`${k} ${$}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},A.map((j,R)=>{var G;let[Y,ie]=j.split("-");return T.length?b.createElement("ol",{key:j,dir:x==="auto"?jg():x,tabIndex:-1,ref:Q,className:a,"data-sonner-toaster":!0,"data-theme":K,"data-y-position":Y,"data-lifted":U&&T.length>1&&!s,"data-x-position":ie,style:{"--front-toast-height":`${((G=O[0])==null?void 0:G.height)||0}px`,"--width":`${hI}px`,"--gap":`${y}px`,...f,...bI(l,c)},onBlur:H=>{V.current&&!H.currentTarget.contains(H.relatedTarget)&&(V.current=!1,_.current&&(_.current.focus({preventScroll:!0}),_.current=null))},onFocus:H=>{H.target instanceof HTMLElement&&H.target.dataset.dismissible==="false"||V.current||(V.current=!0,_.current=H.relatedTarget)},onMouseEnter:()=>W(!0),onMouseMove:()=>W(!0),onMouseLeave:()=>{z||W(!1)},onDragEnd:()=>W(!1),onPointerDown:H=>{H.target instanceof HTMLElement&&H.target.dataset.dismissible==="false"||N(!0)},onPointerUp:()=>N(!1)},T.filter(H=>!H.position&&R===0||H.position===j).map((H,D)=>{var X,Z;return b.createElement(wI,{key:H.id,icons:S,index:D,toast:H,defaultRichColors:p,duration:(X=g==null?void 0:g.duration)!=null?X:m,className:g==null?void 0:g.className,descriptionClassName:g==null?void 0:g.descriptionClassName,invert:n,visibleToasts:v,closeButton:(Z=g==null?void 0:g.closeButton)!=null?Z:i,interacting:z,position:j,style:g==null?void 0:g.style,unstyled:g==null?void 0:g.unstyled,classNames:g==null?void 0:g.classNames,cancelButtonStyle:g==null?void 0:g.cancelButtonStyle,actionButtonStyle:g==null?void 0:g.actionButtonStyle,removeToast:J,toasts:T.filter(ce=>ce.position==H.position),heights:O.filter(ce=>ce.position==H.position),setHeights:F,expandByDefault:s,gap:y,loadingIcon:w,expanded:U,pauseWhenPageIsHidden:C,swipeDirections:e.swipeDirections})})):null}))});const SI=({...e})=>{const{theme:t="system"}=GE();return u.jsx(yI,{theme:t,className:"toaster group",toastOptions:{classNames:{toast:"group toast group-[.toaster]:bg-background group-[.toaster]:text-foreground group-[.toaster]:border-border group-[.toaster]:shadow-lg",description:"group-[.toast]:text-muted-foreground",actionButton:"group-[.toast]:bg-primary group-[.toast]:text-primary-foreground",cancelButton:"group-[.toast]:bg-muted group-[.toast]:text-muted-foreground"}},...e})};q.Api=pv,q.ApiClient=fv,q.ApiProvider=au,q.Badge=bh,q.Button=ct,q.Card=bl,q.CardContent=Tl,q.CardDescription=Cl,q.CardHeader=yl,q.CardTitle=Sl,q.ChatApi=$o,q.ChatApp=Hh,q.ChatInput=yp,q.ChatInterface=bo,q.Command=oa,q.CommandEmpty=aa,q.CommandGroup=la,q.CommandInput=sa,q.CommandItem=ca,q.CommandList=ia,q.DEFAULT_TIMEOUT_MS=Kc,q.Dialog=ra,q.DialogContent=ns,q.DialogHeader=rs,q.DialogTitle=os,q.DropdownMenu=Ss,q.DropdownMenuContent=ao,q.DropdownMenuItem=Dn,q.DropdownMenuTrigger=Cs,q.FileViewerModal=Sh,q.HISTORY_TIMEOUT_MS=qc,q.Input=Ua,q.Label=Vh,q.MarkdownContent=jr,q.MessageComponent=qs,q.MessageList=kl,q.SETTINGS_STORAGE_KEY=Ei,q.ScrollArea=Ha,q.Select=Fk,q.SelectContent=Pm,q.SelectItem=Mm,q.SelectTrigger=Am,q.SelectValue=Bk,q.Separator=Lm,q.Sheet=Jk,q.SheetContent=Km,q.SheetDescription=Ym,q.SheetHeader=qm,q.SheetTitle=Gm,q.SheetTrigger=Zk,q.SimpleChat=ik,q.Sonner=SI,q.Switch=Wm,q.Textarea=Va,q.ThreadManager=Wa,q.TimelineColumn=Ug,q.Toaster=WE,q.Tooltip=yE,q.TooltipContent=og,q.TooltipProvider=bE,q.TooltipTrigger=SE,q.applySettings=vv,q.buildAttemptMaps=Yl,q.buildCheckpointIndex=Jl,q.buildCheckpointPreviewMap=Lg,q.chatApiClient=An,q.default=Hh,q.del=Si,q.downloadFileById=Yc,q.extractConfigFields=li,q.fileToBase64=Jc,q.get=qt,q.getChatToken=Wc,q.getCurrentSettings=xv,q.getDefaultApiConfig=nu,q.getDefaultChatSettings=ru,q.getFileContent=Ti,q.getFileInfo=mv,q.getPreviewForMessage=ai,q.httpClient=Kt,q.hydrateHistorySnapshots=Nn,q.listFiles=Xc,q.loadStoredSettings=ou,q.onChatTokenChanged=Vc,q.post=Lo,q.processAttachments=Zc,q.put=Gc,q.readNumber=Ql,q.readString=Vn,q.resolveChatBaseUrl=mn,q.resolveMessageMetadata=ql,q.saveSettings=su,q.setChatToken=Do,q.toPlainObject=cr,q.unwrap=Rt,q.useApi=ki,q.useCheckpointIndex=Zl,q.useMessageMetadata=Gl,q.useStreamingHook=Su,q.useThreadHistoryState=lu,q.useThreadManagerViewState=bp,q.useThreadsState=cu,q.viewFileById=hv,Object.defineProperties(q,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})});
|
package/package.json
CHANGED