@leeoohoo/aichat 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,70 @@
1
+ "use strict";require('./index.css');var Yl=Object.defineProperty;var Kl=(r,e,t)=>e in r?Yl(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var D=(r,e,t)=>Kl(r,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const l=require("react/jsx-runtime"),M=require("react"),Ql={},io=r=>{let e;const t=new Set,n=(u,f)=>{const m=typeof u=="function"?u(e):u;if(!Object.is(m,e)){const b=e;e=f??(typeof m!="object"||m===null)?m:Object.assign({},e,m),t.forEach(g=>g(e,b))}},s=()=>e,d={setState:n,getState:s,getInitialState:()=>c,subscribe:u=>(t.add(u),()=>t.delete(u)),destroy:()=>{(Ql?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),t.clear()}},c=e=r(n,s,d);return d},Zl=r=>r?io(r):io;function ec(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Pn={exports:{}},dn={},or={exports:{}},un={};/**
2
+ * @license React
3
+ * use-sync-external-store-shim.production.js
4
+ *
5
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
6
+ *
7
+ * This source code is licensed under the MIT license found in the
8
+ * LICENSE file in the root directory of this source tree.
9
+ */var lo;function tc(){if(lo)return un;lo=1;var r=M;function e(f,m){return f===m&&(f!==0||1/f===1/m)||f!==f&&m!==m}var t=typeof Object.is=="function"?Object.is:e,n=r.useState,s=r.useEffect,o=r.useLayoutEffect,a=r.useDebugValue;function i(f,m){var b=m(),g=n({inst:{value:b,getSnapshot:m}}),h=g[0].inst,p=g[1];return o(function(){h.value=b,h.getSnapshot=m,d(h)&&p({inst:h})},[f,b,m]),s(function(){return d(h)&&p({inst:h}),f(function(){d(h)&&p({inst:h})})},[f]),a(b),b}function d(f){var m=f.getSnapshot;f=f.value;try{var b=m();return!t(f,b)}catch{return!0}}function c(f,m){return m()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?c:i;return un.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:u,un}var fn={};/**
10
+ * @license React
11
+ * use-sync-external-store-shim.development.js
12
+ *
13
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
14
+ *
15
+ * This source code is licensed under the MIT license found in the
16
+ * LICENSE file in the root directory of this source tree.
17
+ */var co;function rc(){return co||(co=1,process.env.NODE_ENV!=="production"&&function(){function r(b,g){return b===g&&(b!==0||1/b===1/g)||b!==b&&g!==g}function e(b,g){u||s.startTransition===void 0||(u=!0,console.error("You are using an outdated, pre-release alpha of React 18 that does not support useSyncExternalStore. The use-sync-external-store shim will not work correctly. Upgrade to a newer pre-release."));var h=g();if(!f){var p=g();o(h,p)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),f=!0)}p=a({inst:{value:h,getSnapshot:g}});var y=p[0].inst,w=p[1];return d(function(){y.value=h,y.getSnapshot=g,t(y)&&w({inst:y})},[b,h,g]),i(function(){return t(y)&&w({inst:y}),b(function(){t(y)&&w({inst:y})})},[b]),c(h),h}function t(b){var g=b.getSnapshot;b=b.value;try{var h=g();return!o(b,h)}catch{return!0}}function n(b,g){return g()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var s=M,o=typeof Object.is=="function"?Object.is:r,a=s.useState,i=s.useEffect,d=s.useLayoutEffect,c=s.useDebugValue,u=!1,f=!1,m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n:e;fn.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:m,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),fn}var uo;function va(){return uo||(uo=1,process.env.NODE_ENV==="production"?or.exports=tc():or.exports=rc()),or.exports}/**
18
+ * @license React
19
+ * use-sync-external-store-shim/with-selector.production.js
20
+ *
21
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
22
+ *
23
+ * This source code is licensed under the MIT license found in the
24
+ * LICENSE file in the root directory of this source tree.
25
+ */var fo;function nc(){if(fo)return dn;fo=1;var r=M,e=va();function t(c,u){return c===u&&(c!==0||1/c===1/u)||c!==c&&u!==u}var n=typeof Object.is=="function"?Object.is:t,s=e.useSyncExternalStore,o=r.useRef,a=r.useEffect,i=r.useMemo,d=r.useDebugValue;return dn.useSyncExternalStoreWithSelector=function(c,u,f,m,b){var g=o(null);if(g.current===null){var h={hasValue:!1,value:null};g.current=h}else h=g.current;g=i(function(){function y(A){if(!w){if(w=!0,x=A,A=m(A),b!==void 0&&h.hasValue){var k=h.value;if(b(k,A))return v=k}return v=A}if(k=v,n(x,A))return k;var $=m(A);return b!==void 0&&b(k,$)?(x=A,k):(x=A,v=$)}var w=!1,x,v,S=f===void 0?null:f;return[function(){return y(u())},S===null?void 0:function(){return y(S())}]},[u,f,m,b]);var p=s(c,g[0],g[1]);return a(function(){h.hasValue=!0,h.value=p},[p]),d(p),p},dn}var hn={};/**
26
+ * @license React
27
+ * use-sync-external-store-shim/with-selector.development.js
28
+ *
29
+ * Copyright (c) Meta Platforms, Inc. and affiliates.
30
+ *
31
+ * This source code is licensed under the MIT license found in the
32
+ * LICENSE file in the root directory of this source tree.
33
+ */var ho;function sc(){return ho||(ho=1,process.env.NODE_ENV!=="production"&&function(){function r(c,u){return c===u&&(c!==0||1/c===1/u)||c!==c&&u!==u}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=M,t=va(),n=typeof Object.is=="function"?Object.is:r,s=t.useSyncExternalStore,o=e.useRef,a=e.useEffect,i=e.useMemo,d=e.useDebugValue;hn.useSyncExternalStoreWithSelector=function(c,u,f,m,b){var g=o(null);if(g.current===null){var h={hasValue:!1,value:null};g.current=h}else h=g.current;g=i(function(){function y(A){if(!w){if(w=!0,x=A,A=m(A),b!==void 0&&h.hasValue){var k=h.value;if(b(k,A))return v=k}return v=A}if(k=v,n(x,A))return k;var $=m(A);return b!==void 0&&b(k,$)?(x=A,k):(x=A,v=$)}var w=!1,x,v,S=f===void 0?null:f;return[function(){return y(u())},S===null?void 0:function(){return y(S())}]},[u,f,m,b]);var p=s(c,g[0],g[1]);return a(function(){h.hasValue=!0,h.value=p},[p]),d(p),p},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),hn}process.env.NODE_ENV==="production"?Pn.exports=nc():Pn.exports=sc();var oc=Pn.exports;const ac=ec(oc),Sa={},{useDebugValue:ic}=M,{useSyncExternalStoreWithSelector:lc}=ac;let mo=!1;const cc=r=>r;function dc(r,e=cc,t){(Sa?"production":void 0)!=="production"&&t&&!mo&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),mo=!0);const n=lc(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return ic(n),n}const uc=r=>{(Sa?"production":void 0)!=="production"&&typeof r!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof r=="function"?Zl(r):r,t=(n,s)=>dc(e,n,s);return Object.assign(t,e),t},Ca=r=>uc,fc={},hc=r=>(e,t,n)=>{const s=n.subscribe;return n.subscribe=(a,i,d)=>{let c=a;if(i){const u=(d==null?void 0:d.equalityFn)||Object.is;let f=a(n.getState());c=m=>{const b=a(m);if(!u(f,b)){const g=f;i(f=b,g)}},d!=null&&d.fireImmediately&&i(f,f)}return s(c)},r(e,t,n)},ka=hc;function mc(r,e){let t;try{t=r()}catch{return}return{getItem:s=>{var o;const a=d=>d===null?null:JSON.parse(d,void 0),i=(o=t.getItem(s))!=null?o:null;return i instanceof Promise?i.then(a):a(i)},setItem:(s,o)=>t.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>t.removeItem(s)}}const Ft=r=>e=>{try{const t=r(e);return t instanceof Promise?t:{then(n){return Ft(n)(t)},catch(n){return this}}}catch(t){return{then(n){return this},catch(n){return Ft(n)(t)}}}},gc=(r,e)=>(t,n,s)=>{let o={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:p=>p,version:0,merge:(p,y)=>({...y,...p}),...e},a=!1;const i=new Set,d=new Set;let c;try{c=o.getStorage()}catch{}if(!c)return r((...p)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...p)},n,s);const u=Ft(o.serialize),f=()=>{const p=o.partialize({...n()});let y;const w=u({state:p,version:o.version}).then(x=>c.setItem(o.name,x)).catch(x=>{y=x});if(y)throw y;return w},m=s.setState;s.setState=(p,y)=>{m(p,y),f()};const b=r((...p)=>{t(...p),f()},n,s);let g;const h=()=>{var p;if(!c)return;a=!1,i.forEach(w=>w(n()));const y=((p=o.onRehydrateStorage)==null?void 0:p.call(o,n()))||void 0;return Ft(c.getItem.bind(c))(o.name).then(w=>{if(w)return o.deserialize(w)}).then(w=>{if(w)if(typeof w.version=="number"&&w.version!==o.version){if(o.migrate)return o.migrate(w.state,w.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return w.state}).then(w=>{var x;return g=o.merge(w,(x=n())!=null?x:b),t(g,!0),f()}).then(()=>{y==null||y(g,void 0),a=!0,d.forEach(w=>w(g))}).catch(w=>{y==null||y(void 0,w)})};return s.persist={setOptions:p=>{o={...o,...p},p.getStorage&&(c=p.getStorage())},clearStorage:()=>{c==null||c.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>h(),hasHydrated:()=>a,onHydrate:p=>(i.add(p),()=>{i.delete(p)}),onFinishHydration:p=>(d.add(p),()=>{d.delete(p)})},h(),g||b},pc=(r,e)=>(t,n,s)=>{let o={storage:mc(()=>localStorage),partialize:h=>h,version:0,merge:(h,p)=>({...p,...h}),...e},a=!1;const i=new Set,d=new Set;let c=o.storage;if(!c)return r((...h)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...h)},n,s);const u=()=>{const h=o.partialize({...n()});return c.setItem(o.name,{state:h,version:o.version})},f=s.setState;s.setState=(h,p)=>{f(h,p),u()};const m=r((...h)=>{t(...h),u()},n,s);s.getInitialState=()=>m;let b;const g=()=>{var h,p;if(!c)return;a=!1,i.forEach(w=>{var x;return w((x=n())!=null?x:m)});const y=((p=o.onRehydrateStorage)==null?void 0:p.call(o,(h=n())!=null?h:m))||void 0;return Ft(c.getItem.bind(c))(o.name).then(w=>{if(w)if(typeof w.version=="number"&&w.version!==o.version){if(o.migrate)return[!0,o.migrate(w.state,w.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,w.state];return[!1,void 0]}).then(w=>{var x;const[v,S]=w;if(b=o.merge(S,(x=n())!=null?x:m),t(b,!0),v)return u()}).then(()=>{y==null||y(b,void 0),b=n(),a=!0,d.forEach(w=>w(b))}).catch(w=>{y==null||y(void 0,w)})};return s.persist={setOptions:h=>{o={...o,...h},h.storage&&(c=h.storage)},clearStorage:()=>{c==null||c.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>g(),hasHydrated:()=>a,onHydrate:h=>(i.add(h),()=>{i.delete(h)}),onFinishHydration:h=>(d.add(h),()=>{d.delete(h)})},o.skipHydration||g(),b||m},yc=(r,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((fc?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),gc(r,e)):pc(r,e),Aa=yc;var Ea=Symbol.for("immer-nothing"),go=Symbol.for("immer-draftable"),pe=Symbol.for("immer-state"),bc=process.env.NODE_ENV!=="production"?[function(r){return`The plugin for '${r}' has not been loaded into Immer. To enable the plugin, import and call \`enable${r}()\` when initializing your application.`},function(r){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${r}'`},"This object has been frozen and should not be mutated",function(r){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+r},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(r){return`'current' expects a draft, got: ${r}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(r){return`'original' expects a draft, got: ${r}`}]:[];function ce(r,...e){if(process.env.NODE_ENV!=="production"){const t=bc[r],n=typeof t=="function"?t.apply(null,e):t;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${r}. Full error at: https://bit.ly/3cXEKWf`)}var mt=Object.getPrototypeOf;function gt(r){return!!r&&!!r[pe]}function Ke(r){var e;return r?Ma(r)||Array.isArray(r)||!!r[go]||!!((e=r.constructor)!=null&&e[go])||zt(r)||Ur(r):!1}var wc=Object.prototype.constructor.toString();function Ma(r){if(!r||typeof r!="object")return!1;const e=mt(r);if(e===null)return!0;const t=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return t===Object?!0:typeof t=="function"&&Function.toString.call(t)===wc}function jr(r,e){Br(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function Br(r){const e=r[pe];return e?e.type_:Array.isArray(r)?1:zt(r)?2:Ur(r)?3:0}function Rn(r,e){return Br(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function ja(r,e,t){const n=Br(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function xc(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function zt(r){return r instanceof Map}function Ur(r){return r instanceof Set}function ze(r){return r.copy_||r.base_}function Tn(r,e){if(zt(r))return new Map(r);if(Ur(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);const t=Ma(r);if(e===!0||e==="class_only"&&!t){const n=Object.getOwnPropertyDescriptors(r);delete n[pe];let s=Reflect.ownKeys(n);for(let o=0;o<s.length;o++){const a=s[o],i=n[a];i.writable===!1&&(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(n[a]={configurable:!0,writable:!0,enumerable:i.enumerable,value:r[a]})}return Object.create(mt(r),n)}else{const n=mt(r);if(n!==null&&t)return{...r};const s=Object.create(n);return Object.assign(s,r)}}function ls(r,e=!1){return Wr(r)||gt(r)||!Ke(r)||(Br(r)>1&&Object.defineProperties(r,{set:{value:ar},add:{value:ar},clear:{value:ar},delete:{value:ar}}),Object.freeze(r),e&&Object.values(r).forEach(t=>ls(t,!0))),r}function ar(){ce(2)}function Wr(r){return Object.isFrozen(r)}var _c={};function Qe(r){const e=_c[r];return e||ce(0,r),e}var $t;function Na(){return $t}function vc(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function po(r,e){e&&(Qe("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function In(r){Ln(r),r.drafts_.forEach(Sc),r.drafts_=null}function Ln(r){r===$t&&($t=r.parent_)}function yo(r){return $t=vc($t,r)}function Sc(r){const e=r[pe];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function bo(r,e){e.unfinalizedDrafts_=e.drafts_.length;const t=e.drafts_[0];return r!==void 0&&r!==t?(t[pe].modified_&&(In(e),ce(4)),Ke(r)&&(r=Nr(e,r),e.parent_||Or(e,r)),e.patches_&&Qe("Patches").generateReplacementPatches_(t[pe].base_,r,e.patches_,e.inversePatches_)):r=Nr(e,t,[]),In(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==Ea?r:void 0}function Nr(r,e,t){if(Wr(e))return e;const n=e[pe];if(!n)return jr(e,(s,o)=>wo(r,n,e,s,o,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return Or(r,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const s=n.copy_;let o=s,a=!1;n.type_===3&&(o=new Set(s),s.clear(),a=!0),jr(o,(i,d)=>wo(r,n,s,i,d,t,a)),Or(r,s,!1),t&&r.patches_&&Qe("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function wo(r,e,t,n,s,o,a){if(process.env.NODE_ENV!=="production"&&s===t&&ce(5),gt(s)){const i=o&&e&&e.type_!==3&&!Rn(e.assigned_,n)?o.concat(n):void 0,d=Nr(r,s,i);if(ja(t,n,d),gt(d))r.canAutoFreeze_=!1;else return}else a&&t.add(s);if(Ke(s)&&!Wr(s)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;Nr(r,s),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&(zt(t)?t.has(n):Object.prototype.propertyIsEnumerable.call(t,n))&&Or(r,s)}}function Or(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&ls(e,t)}function Cc(r,e){const t=Array.isArray(r),n={type_:t?1:0,scope_:e?e.scope_:Na(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=n,o=cs;t&&(s=[n],o=Bt);const{revoke:a,proxy:i}=Proxy.revocable(s,o);return n.draft_=i,n.revoke_=a,i}var cs={get(r,e){if(e===pe)return r;const t=ze(r);if(!Rn(t,e))return kc(r,t,e);const n=t[e];return r.finalized_||!Ke(n)?n:n===mn(r.base_,e)?(gn(r),r.copy_[e]=Fn(n,r)):n},has(r,e){return e in ze(r)},ownKeys(r){return Reflect.ownKeys(ze(r))},set(r,e,t){const n=Oa(ze(r),e);if(n!=null&&n.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){const s=mn(ze(r),e),o=s==null?void 0:s[pe];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(xc(t,s)&&(t!==void 0||Rn(r.base_,e)))return!0;gn(r),Dn(r)}return r.copy_[e]===t&&(t!==void 0||e in r.copy_)||Number.isNaN(t)&&Number.isNaN(r.copy_[e])||(r.copy_[e]=t,r.assigned_[e]=!0),!0},deleteProperty(r,e){return mn(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,gn(r),Dn(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){const t=ze(r),n=Reflect.getOwnPropertyDescriptor(t,e);return n&&{writable:!0,configurable:r.type_!==1||e!=="length",enumerable:n.enumerable,value:t[e]}},defineProperty(){ce(11)},getPrototypeOf(r){return mt(r.base_)},setPrototypeOf(){ce(12)}},Bt={};jr(cs,(r,e)=>{Bt[r]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});Bt.deleteProperty=function(r,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&ce(13),Bt.set.call(this,r,e,void 0)};Bt.set=function(r,e,t){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&ce(14),cs.set.call(this,r[0],e,t,r[0])};function mn(r,e){const t=r[pe];return(t?ze(t):r)[e]}function kc(r,e,t){var s;const n=Oa(e,t);return n?"value"in n?n.value:(s=n.get)==null?void 0:s.call(r.draft_):void 0}function Oa(r,e){if(!(e in r))return;let t=mt(r);for(;t;){const n=Object.getOwnPropertyDescriptor(t,e);if(n)return n;t=mt(t)}}function Dn(r){r.modified_||(r.modified_=!0,r.parent_&&Dn(r.parent_))}function gn(r){r.copy_||(r.copy_=Tn(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Ac=class{constructor(r){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if(typeof e=="function"&&typeof t!="function"){const o=t;t=e;const a=this;return function(d=o,...c){return a.produce(d,u=>t.call(this,u,...c))}}typeof t!="function"&&ce(6),n!==void 0&&typeof n!="function"&&ce(7);let s;if(Ke(e)){const o=yo(this),a=Fn(e,void 0);let i=!0;try{s=t(a),i=!1}finally{i?In(o):Ln(o)}return po(o,n),bo(s,o)}else if(!e||typeof e!="object"){if(s=t(e),s===void 0&&(s=e),s===Ea&&(s=void 0),this.autoFreeze_&&ls(s,!0),n){const o=[],a=[];Qe("Patches").generateReplacementPatches_(e,s,o,a),n(o,a)}return s}else ce(1,e)},this.produceWithPatches=(e,t)=>{if(typeof e=="function")return(a,...i)=>this.produceWithPatches(a,d=>e(d,...i));let n,s;return[this.produce(e,t,(a,i)=>{n=a,s=i}),n,s]},typeof(r==null?void 0:r.autoFreeze)=="boolean"&&this.setAutoFreeze(r.autoFreeze),typeof(r==null?void 0:r.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(r.useStrictShallowCopy)}createDraft(r){Ke(r)||ce(8),gt(r)&&(r=Ec(r));const e=yo(this),t=Fn(r,void 0);return t[pe].isManual_=!0,Ln(e),t}finishDraft(r,e){const t=r&&r[pe];(!t||!t.isManual_)&&ce(9);const{scope_:n}=t;return po(n,e),bo(void 0,n)}setAutoFreeze(r){this.autoFreeze_=r}setUseStrictShallowCopy(r){this.useStrictShallowCopy_=r}applyPatches(r,e){let t;for(t=e.length-1;t>=0;t--){const s=e[t];if(s.path.length===0&&s.op==="replace"){r=s.value;break}}t>-1&&(e=e.slice(t+1));const n=Qe("Patches").applyPatches_;return gt(r)?n(r,e):this.produce(r,s=>n(s,e))}};function Fn(r,e){const t=zt(r)?Qe("MapSet").proxyMap_(r,e):Ur(r)?Qe("MapSet").proxySet_(r,e):Cc(r,e);return(e?e.scope_:Na()).drafts_.push(t),t}function Ec(r){return gt(r)||ce(10,r),Pa(r)}function Pa(r){if(!Ke(r)||Wr(r))return r;const e=r[pe];let t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=Tn(r,e.scope_.immer_.useStrictShallowCopy_)}else t=Tn(r,!0);return jr(t,(n,s)=>{ja(t,n,Pa(s))}),e&&(e.finalized_=!1),t}var Mc=new Ac,jc=Mc.produce;const Nc=r=>(e,t,n)=>(n.setState=(s,o,...a)=>{const i=typeof s=="function"?jc(s):s;return e(i,o,...a)},r(n.setState,t,n)),Ra=Nc,Oc="/api";class Ta{constructor(e=Oc){D(this,"baseUrl");this.baseUrl=e}async request(e,t={}){const n=`${this.baseUrl}${e}`,s={headers:{"Content-Type":"application/json",...t.headers},...t};try{const o=await fetch(n,s);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(o){throw console.error(`API request failed: ${e}`,o),o}}async getSessions(){return this.request("/sessions")}async createSession(e){return this.request("/sessions",{method:"POST",body:JSON.stringify(e)})}async getSession(e){return this.request(`/sessions/${e}`)}async deleteSession(e){return this.request(`/sessions/${e}`,{method:"DELETE"})}async getSessionMessages(e){return this.request(`/sessions/${e}/messages`)}async createMessage(e){const t={...e,createdAt:e.createdAt?e.createdAt.toISOString():void 0};return this.request("/messages",{method:"POST",body:JSON.stringify(t)})}async getMcpConfigs(){return this.request("/mcp-configs")}async createMcpConfig(e){return this.request("/mcp-configs",{method:"POST",body:JSON.stringify(e)})}async updateMcpConfig(e,t){return this.request(`/mcp-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteMcpConfig(e){return this.request(`/mcp-configs/${e}`,{method:"DELETE"})}async getSystemContext(){return this.request("/system-context")}async updateSystemContext(e){return this.request("/system-context",{method:"POST",body:JSON.stringify({content:e})})}}const ge=new Ta;class Ia{constructor(){}async createSession(e){const t={id:crypto.randomUUID(),title:e.title},n=await ge.createSession(t);return{id:n.id,title:n.title,createdAt:new Date(n.created_at),updatedAt:new Date(n.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}}async getSession(e){try{const t=await ge.getSession(e);return t?{id:t.id,title:t.title,createdAt:new Date(t.created_at),updatedAt:new Date(t.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}:null}catch{return null}}async getAllSessions(){return(await ge.getSessions()).map(t=>({id:t.id,title:t.title,createdAt:new Date(t.created_at),updatedAt:new Date(t.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}))}async updateSession(e,t){return console.warn("updateSession not implemented yet"),null}async deleteSession(e){try{return await ge.deleteSession(e),!0}catch{return!1}}async createMessage(e){var o;const t={id:crypto.randomUUID(),session_id:e.sessionId,role:e.role,content:e.content,summary:e.rawContent,tool_calls:(o=e.metadata)!=null&&o.toolCalls?JSON.stringify(e.metadata.toolCalls):void 0,tool_call_id:e.toolCallId,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n={id:t.id,sessionId:t.session_id,role:t.role,content:t.content,metadata:t.metadata?JSON.parse(t.metadata):void 0,toolCalls:t.tool_calls?JSON.parse(t.tool_calls):void 0},s=await ge.createMessage(n);return{id:s.id,sessionId:s.session_id,role:s.role,content:s.content,rawContent:s.summary,tokensUsed:e.tokensUsed,status:e.status||"completed",createdAt:new Date(s.created_at),updatedAt:e.updatedAt,toolCallId:s.tool_call_id,metadata:s.metadata?JSON.parse(s.metadata):e.metadata}}async getSessionMessages(e){return(await ge.getSessionMessages(e)).map(n=>({id:n.id,sessionId:n.session_id,role:n.role,content:n.content,rawContent:n.summary,tokensUsed:void 0,status:"completed",createdAt:new Date(n.created_at),updatedAt:void 0,toolCallId:n.tool_call_id,metadata:n.metadata?JSON.parse(n.metadata):void 0}))}async updateMessage(e,t){return console.warn("updateMessage not implemented yet"),null}async deleteMessage(e){return console.warn("deleteMessage not implemented yet"),!1}}const q=new Ia,Je=class Je{constructor(){D(this,"pendingSaves",new Set);D(this,"savedMessages",new Map)}static getInstance(){return Je.instance||(Je.instance=new Je),Je.instance}async saveUserMessage(e){var n;const t=`${e.sessionId}-${e.role}-${e.content}-${(n=e.createdAt)==null?void 0:n.getTime()}`;if(this.pendingSaves.has(t)){for(;this.pendingSaves.has(t);)await new Promise(o=>setTimeout(o,10));const s=this.savedMessages.get(t);if(s)return s}this.pendingSaves.add(t);try{const s=await q.createMessage(e);return this.savedMessages.set(t,s),s}finally{this.pendingSaves.delete(t)}}async saveAssistantMessage(e){var n,s;const t=`${e.sessionId}-${e.role}-${JSON.stringify(((n=e.metadata)==null?void 0:n.toolCalls)||[])}-${(s=e.createdAt)==null?void 0:s.getTime()}`;if(this.pendingSaves.has(t)){for(;this.pendingSaves.has(t);)await new Promise(a=>setTimeout(a,10));const o=this.savedMessages.get(t);if(o)return o}this.pendingSaves.add(t);try{const o=await q.createMessage(e);return this.savedMessages.set(t,o),o}finally{this.pendingSaves.delete(t)}}async saveToolMessage(e){var n;const t=`${e.sessionId}-${e.role}-${e.content}-${(n=e.createdAt)==null?void 0:n.getTime()}`;if(this.pendingSaves.has(t)){for(;this.pendingSaves.has(t);)await new Promise(o=>setTimeout(o,10));const s=this.savedMessages.get(t);if(s)return s}this.pendingSaves.add(t);try{const s=await q.createMessage(e);return this.savedMessages.set(t,s),s}finally{this.pendingSaves.delete(t)}}async saveMessage(e){switch(e.role){case"user":return this.saveUserMessage(e);case"assistant":return this.saveAssistantMessage(e);case"tool":return this.saveToolMessage(e);default:return q.createMessage(e)}}clearCache(){this.savedMessages.clear()}getCacheStats(){return{pendingCount:this.pendingSaves.size,cachedCount:this.savedMessages.size}}};D(Je,"instance");let $n=Je;const Pr=$n.getInstance(),Pe=Ca()(ka(Ra(Aa((r,e)=>({sessions:[],currentSessionId:null,currentSession:null,messages:[],isLoading:!1,isStreaming:!1,streamingMessageId:null,sidebarOpen:!0,theme:"light",chatConfig:{model:"gpt-4",temperature:.7,maxTokens:2048,systemPrompt:"",enableMcp:!0},mcpConfigs:[],aiModelConfigs:[],systemContext:null,selectedModelId:null,error:null,loadSessions:async()=>{try{r(n=>{n.isLoading=!0,n.error=null});const t=await q.getAllSessions();r(n=>{n.sessions=t,n.isLoading=!1})}catch(t){r(n=>{n.error=t instanceof Error?t.message:"Failed to load sessions",n.isLoading=!1})}},createSession:async(t="New Chat")=>{try{const n=await q.createSession({title:t,createdAt:new Date,updatedAt:new Date,messageCount:0,tokenUsage:0,pinned:!1,archived:!1});return r(s=>{s.sessions.unshift(n),s.currentSessionId=n.id,s.currentSession=n,s.messages=[]}),n.id}catch(n){throw r(s=>{s.error=n instanceof Error?n.message:"Failed to create session"}),n}},selectSession:async t=>{var n;try{console.log("🔍 selectSession 被调用,sessionId:",t),r(d=>{d.isLoading=!0,d.error=null}),console.log("✅ isLoading 已设置为 true");const{conversationsApi:s}=await Promise.resolve().then(()=>To),o=await s.getDetails(t),a=await s.getMessages(t);console.log("✅ API 调用完成,获取到会话和消息数据"),console.log("📊 原始消息数据结构:",a);const i=((n=a.data)==null?void 0:n.messages)||[];console.log("📊 解析后的消息数组:",i.length,"条消息"),i.forEach((d,c)=>{var u,f;console.log(`📝 消息 ${c+1}:`,{id:d.id,role:d.role,content:d.content?d.content.substring(0,100)+"...":"(空内容)",metadata:d.metadata,hasToolCalls:!!(d.metadata&&d.metadata.toolCalls),toolCallsCount:(u=d.metadata)!=null&&u.toolCalls?d.metadata.toolCalls.length:0,toolCallsPreview:(f=d.metadata)!=null&&f.toolCalls?d.metadata.toolCalls.map(m=>m.name||m.type):[]})}),r(d=>{d.currentSessionId=t;const c=o.data.conversation;d.currentSession={id:c.id,title:c.title,createdAt:new Date(c.created_at),updatedAt:new Date(c.updated_at),messageCount:c.messageCount||0,tokenUsage:c.tokenUsage||0,tags:c.tags||null,pinned:c.pinned||!1,archived:c.archived||!1,metadata:c.metadata||null};const u=a.data.messages.map((f,m)=>{const b={...f,createdAt:new Date(f.created_at||f.createdAt),updatedAt:f.updated_at?new Date(f.updated_at):void 0,status:f.status||"completed"};return console.log(`🔄 处理消息 ${m+1} (${f.id}):`,{原始content:f.content,原始metadata:f.metadata,处理后content:b.content,处理后metadata:b.metadata}),b});d.messages=u.sort((f,m)=>{const b=f.createdAt.getTime(),g=m.createdAt.getTime();return b-g}),console.log("✅ 最终存储的messages数量:",u.length),d.isLoading=!1}),console.log("✅ selectSession 完成,currentSessionId 已设置为:",t)}catch(s){console.error("❌ selectSession 失败:",s),r(o=>{o.error=s instanceof Error?s.message:"Failed to load session",o.isLoading=!1})}},updateSession:async(t,n)=>{try{await q.updateSession(t,n),r(s=>{const o=s.sessions.findIndex(a=>a.id===t);o!==-1&&(s.sessions[o]={...s.sessions[o],...n}),s.currentSessionId===t&&s.currentSession&&(s.currentSession={...s.currentSession,...n})})}catch(s){r(o=>{o.error=s instanceof Error?s.message:"Failed to update session"})}},deleteSession:async t=>{try{await q.deleteSession(t),r(n=>{n.sessions=n.sessions.filter(s=>s.id!==t),n.currentSessionId===t&&(n.currentSessionId=null,n.currentSession=null,n.messages=[])})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to delete session"})}},loadMessages:async t=>{try{const{conversationsApi:n}=await Promise.resolve().then(()=>To),s=await n.getMessages(t);console.log("=== loadMessages Debug ==="),console.log("Session ID:",t),console.log("Raw messages from API:",s.data.messages.length),s.data.messages.forEach((o,a)=>{var i;console.log(`Message ${a+1}:`,{id:o.id,role:o.role,content:o.content?o.content.substring(0,100)+"...":"[EMPTY]",hasToolCalls:!!(o.toolCalls||(i=o.metadata)!=null&&i.toolCalls),tool_calls:o.tool_calls?"YES":"NO"})}),r(o=>{const a=s.data.messages.map(i=>{var c;const d={...i.metadata,toolCalls:i.toolCalls||((c=i.metadata)==null?void 0:c.toolCalls)||[]};return{...i,createdAt:new Date(i.created_at||i.createdAt),status:i.status||"completed",metadata:d}});o.messages=a.sort((i,d)=>{const c=i.createdAt.getTime(),u=d.createdAt.getTime();return c-u}),console.log("Final processed messages:",o.messages.length),o.messages.forEach((i,d)=>{var c,u,f,m;console.log(`Processed ${d+1}:`,{id:i.id,role:i.role,content:i.content?i.content.substring(0,50)+"...":"[EMPTY]",hasMetadataToolCalls:!!((u=(c=i.metadata)==null?void 0:c.toolCalls)!=null&&u.length),toolCallsCount:((m=(f=i.metadata)==null?void 0:f.toolCalls)==null?void 0:m.length)||0})})})}catch(n){console.error("loadMessages error:",n),r(s=>{s.error=n instanceof Error?n.message:"Failed to load messages"})}},sendMessage:async(t,n=[])=>{const{currentSessionId:s,selectedModelId:o,aiModelConfigs:a}=e();if(!s)throw new Error("No active session");if(!o)throw new Error("请先选择一个AI模型");const i=a.find(d=>d.id===o);if(!i||!i.enabled)throw new Error("选择的模型不可用");try{const d=new Date,c=await Pr.saveUserMessage({sessionId:s,role:"user",content:t,status:"completed",createdAt:d,metadata:{...n.length>0?{attachments:n}:{},model:i.model_name,modelConfig:{id:i.id,name:i.name,base_url:i.base_url,model_name:i.model_name}}});r(h=>{h.messages.push(c),h.isLoading=!0});const u=new Date(d.getTime()+1),f={id:`temp_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:s,role:"assistant",content:"",status:"streaming",createdAt:u,metadata:{model:i.model_name,modelConfig:{id:i.id,name:i.name,base_url:i.base_url,model_name:i.model_name},toolCalls:[],contentSegments:[{content:"",type:"text"}],currentSegmentIndex:0}};r(h=>{h.messages.push(f),h.isStreaming=!0,h.streamingMessageId=f.id});const{chatService:m}=await Promise.resolve().then(()=>ng),{chatConfig:b}=e(),g=i?{model_name:i.model_name,temperature:b.temperature,max_tokens:16e3,api_key:i.api_key,base_url:i.base_url}:void 0;await m.sendMessage(s,t,n,{onChunk:h=>{r(p=>{const y=p.messages.find(w=>w.id===f.id);if(y&&y.metadata){const w=typeof h.content=="string"?h.content:typeof h=="string"?h:h.content||"",x=y.metadata.currentSegmentIndex||0,v=y.metadata.contentSegments||[];v[x]&&v[x].type==="text"?v[x].content+=w:(v.push({content:w,type:"text"}),y.metadata.currentSegmentIndex=v.length-1),y.content=v.filter(S=>S.type==="text").map(S=>S.content).join("")}})},onToolCall:h=>{console.log("Tool calls:",h),r(p=>{var w,x;const y=p.messages.find(v=>v.id===f.id);if(y&&y.metadata){y.metadata.toolCalls||(y.metadata.toolCalls=[]);const v=y.metadata.contentSegments||[];if(Array.isArray(h))h.forEach(S=>{var k,$;const A={id:S.id,messageId:y.id,name:((k=S.function)==null?void 0:k.name)||S.name,arguments:(($=S.function)==null?void 0:$.arguments)||S.arguments,result:"",createdAt:new Date};y.metadata.toolCalls.push(A),v.push({content:"",type:"tool_call",toolCallId:A.id})});else{const S={id:h.id,messageId:y.id,name:((w=h.function)==null?void 0:w.name)||h.name,arguments:((x=h.function)==null?void 0:x.arguments)||h.arguments,result:"",createdAt:new Date};y.metadata.toolCalls.push(S),v.push({content:"",type:"tool_call",toolCallId:h.id})}v.push({content:"",type:"text"}),y.metadata.currentSegmentIndex=v.length-1}})},onToolResult:h=>{console.log("Tool results:",h),r(p=>{const y=p.messages.find(w=>w.id===f.id);if(y&&y.metadata&&y.metadata.toolCalls){if(Array.isArray(h))h.forEach(w=>{const x=y.metadata.toolCalls.find(v=>v.id===w.toolCallId);x&&(x.result=w.result)});else if(h.toolCallId){const w=y.metadata.toolCalls.find(x=>x.id===h.toolCallId);w&&(w.result=h.result)}}})},onToolStreamChunk:h=>{r(p=>{const y=p.messages.find(w=>w.id===f.id);if(y&&y.metadata&&y.metadata.toolCalls){const w=y.metadata.toolCalls.find(x=>x.id===h.toolCallId);w&&(w.result=(w.result||"")+h.chunk)}})},onComplete:async()=>{var h;try{const p=e().messages.find(y=>y.id===f.id);if(p){const y={sessionId:s,role:"assistant",content:p.content,status:"completed",createdAt:p.createdAt,metadata:p.metadata};(h=p.metadata)!=null&&h.toolCalls&&p.metadata.toolCalls.length>0&&(y.toolCalls=p.metadata.toolCalls.map(x=>({id:x.id,function:{name:x.name,arguments:typeof x.arguments=="string"?x.arguments:JSON.stringify(x.arguments)}})));const w=await Pr.saveAssistantMessage(y);r(x=>{const v=x.messages.findIndex(S=>S.id===f.id);v!==-1&&(x.messages[v]=w),x.isLoading=!1,x.isStreaming=!1,x.streamingMessageId=null}),s&&await e().selectSession(s)}}catch(p){console.error("Failed to save assistant message:",p),r(y=>{y.isLoading=!1,y.isStreaming=!1,y.streamingMessageId=null})}},onError:h=>{r(p=>{p.error=h.message||"AI response failed",p.isLoading=!1,p.isStreaming=!1,p.streamingMessageId=null})}},g)}catch(d){r(c=>{c.error=d instanceof Error?d.message:"Failed to send message",c.isLoading=!1,c.isStreaming=!1,c.streamingMessageId=null})}},updateMessage:async(t,n)=>{try{const s={...n,...n.role==="tool"?{role:void 0}:{}};s.role===void 0&&delete s.role,await q.updateMessage(t,s),r(o=>{const a=o.messages.findIndex(i=>i.id===t);a!==-1&&(o.messages[a]={...o.messages[a],...n})})}catch(s){r(o=>{o.error=s instanceof Error?s.message:"Failed to update message"})}},deleteMessage:async t=>{try{await q.deleteMessage(t),r(n=>{n.messages=n.messages.filter(s=>s.id!==t)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to delete message"})}},startStreaming:t=>{r(n=>{n.isStreaming=!0,n.streamingMessageId=t})},updateStreamingMessage:t=>{const{streamingMessageId:n}=e();n&&r(s=>{const o=s.messages.findIndex(a=>a.id===n);o!==-1&&(s.messages[o].content=t)})},stopStreaming:()=>{const{streamingMessageId:t}=e();if(r(n=>{n.isStreaming=!1,n.isLoading=!1,n.streamingMessageId=null}),t){const n=e().messages.find(s=>s.id===t);n&&q.updateMessage(t,{content:n.content,updatedAt:new Date})}},toggleSidebar:()=>{r(t=>{t.sidebarOpen=!t.sidebarOpen})},setTheme:t=>{r(n=>{n.theme=t})},updateChatConfig:async t=>{try{const n={...e().chatConfig,...t};r(s=>{s.chatConfig=n})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to update config"})}},loadMcpConfigs:async()=>{try{const t=await ge.getMcpConfigs();r(n=>{n.mcpConfigs=t.map(s=>({id:s.id,name:s.name,serverUrl:s.command,enabled:s.enabled,createdAt:new Date(s.created_at),updatedAt:new Date(s.created_at)}))})}catch(t){r(n=>{n.error=t instanceof Error?t.message:"Failed to load MCP configs"})}},updateMcpConfig:async t=>{try{e().mcpConfigs.findIndex(s=>s.id===t.id)!==-1?await ge.updateMcpConfig(t.id,{name:t.name,command:t.serverUrl,enabled:t.enabled,args:"[]",env:"{}"}):await ge.createMcpConfig({id:t.id,name:t.name,command:t.serverUrl,enabled:t.enabled,args:"[]",env:"{}"}),r(s=>{const o=s.mcpConfigs.findIndex(a=>a.id===t.id);o!==-1?s.mcpConfigs[o]=t:s.mcpConfigs.push(t)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to update MCP config"})}},deleteMcpConfig:async t=>{try{await ge.deleteMcpConfig(t),r(n=>{n.mcpConfigs=n.mcpConfigs.filter(s=>s.id!==t)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to delete MCP config"})}},loadAiModelConfigs:async()=>{try{const t=await fetch("/api/ai-model-configs");if(!t.ok)throw new Error("Failed to load AI model configs");const s=(await t.json()).map(o=>({id:o.id,name:o.name,base_url:o.base_url,api_key:o.api_key,model_name:o.model,enabled:o.enabled,createdAt:new Date(o.created_at),updatedAt:new Date(o.created_at)}));r(o=>{o.aiModelConfigs=s})}catch(t){r(n=>{n.error=t instanceof Error?t.message:"Failed to load AI model configs"})}},updateAiModelConfig:async t=>{try{const n=e().aiModelConfigs.find(d=>d.id===t.id),s=n?"PUT":"POST",o=n?`/api/ai-model-configs/${t.id}`:"/api/ai-model-configs",a={id:t.id,name:t.name,provider:"openai",model:t.model_name,apiKey:t.api_key,baseUrl:t.base_url,enabled:t.enabled},i=await fetch(o,{method:s,headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){const d=await i.text();throw new Error(`Failed to save AI model config: ${d}`)}r(d=>{const c=d.aiModelConfigs.findIndex(u=>u.id===t.id);c!==-1?d.aiModelConfigs[c]=t:d.aiModelConfigs.push(t)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to update AI model config"})}},deleteAiModelConfig:async t=>{try{if(!(await fetch(`/api/ai-model-configs/${t}`,{method:"DELETE"})).ok)throw new Error("Failed to delete AI model config");r(s=>{s.aiModelConfigs=s.aiModelConfigs.filter(o=>o.id!==t),s.selectedModelId===t&&(s.selectedModelId=null)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to delete AI model config"})}},setError:t=>{r(n=>{n.error=t})},clearError:()=>{r(t=>{t.error=null})},setSelectedModel:t=>{r(n=>{n.selectedModelId=t})},loadSystemContext:async()=>{try{console.log("Store: Loading system context from API");const t=await ge.getSystemContext();console.log("Store: API response:",t),r(n=>{n.systemContext=t.content||null}),console.log("Store: System context set to:",t.content||null)}catch(t){console.error("Store: Failed to load system context:",t),r(n=>{n.systemContext=null})}},updateSystemContext:async t=>{try{await ge.updateSystemContext(t),r(n=>{n.systemContext=t})}catch(n){throw console.error("Failed to update system context:",n),n}}}),{name:"chat-store",partialize:r=>({theme:r.theme,sidebarOpen:r.sidebarOpen,chatConfig:r.chatConfig,selectedModelId:r.selectedModelId})})))),Pc=()=>Pe(r=>r.currentSession),Rc=()=>Pe(r=>r.sessions);function Tc(r){const e=r||ge;return Ca()(ka(Ra(Aa((t,n)=>({sessions:[],currentSessionId:null,currentSession:null,messages:[],isLoading:!1,isStreaming:!1,streamingMessageId:null,sidebarOpen:!0,theme:"light",chatConfig:{model:"gpt-4",temperature:.7,maxTokens:2048,systemPrompt:"",enableMcp:!0},mcpConfigs:[],aiModelConfigs:[],systemContext:null,selectedModelId:null,error:null,loadSessions:async()=>{try{t(o=>{o.isLoading=!0,o.error=null});const s=await q.getAllSessions();t(o=>{o.sessions=s,o.isLoading=!1})}catch(s){console.error("Failed to load sessions:",s),t(o=>{o.error=s instanceof Error?s.message:"Failed to load sessions",o.isLoading=!1})}},createSession:async(s="New Chat")=>{try{const o=await q.createSession({title:s,messageCount:0,tokenUsage:0,pinned:!1,archived:!1,createdAt:new Date,updatedAt:new Date});return t(a=>{a.sessions.unshift(o),a.currentSessionId=o.id,a.currentSession=o,a.messages=[],a.error=null}),o.id}catch(o){throw console.error("Failed to create session:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to create session"}),o}},selectSession:async s=>{try{t(i=>{i.isLoading=!0,i.error=null});const o=await q.getSession(s),a=await q.getSessionMessages(s);t(i=>{i.currentSessionId=s,i.currentSession=o,i.messages=a,i.isLoading=!1,o||(i.error="Session not found")})}catch(o){console.error("Failed to select session:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to select session",a.isLoading=!1})}},updateSession:async(s,o)=>{try{const a=await q.updateSession(s,o);t(i=>{const d=i.sessions.findIndex(c=>c.id===s);d!==-1&&a&&(i.sessions[d]=a),i.currentSessionId===s&&(i.currentSession=a)})}catch(a){console.error("Failed to update session:",a),t(i=>{i.error=a instanceof Error?a.message:"Failed to update session"})}},deleteSession:async s=>{try{await q.deleteSession(s),t(o=>{o.sessions=o.sessions.filter(a=>a.id!==s),o.currentSessionId===s&&(o.currentSessionId=null,o.currentSession=null,o.messages=[])})}catch(o){console.error("Failed to delete session:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to delete session"})}},loadMessages:async s=>{try{t(a=>{a.isLoading=!0,a.error=null});const o=await q.getSessionMessages(s);t(a=>{a.messages=o,a.isLoading=!1})}catch(o){console.error("Failed to load messages:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to load messages",a.isLoading=!1})}},sendMessage:async(s,o=[])=>{const{currentSession:a}=n();if(!a)throw new Error("No active session");try{t(c=>{c.isLoading=!0,c.error=null});const i=await q.createMessage({sessionId:a.id,role:"user",content:s,status:"completed",createdAt:new Date,metadata:{attachments:o}});t(c=>{c.messages.push(i)});const d=await q.createMessage({sessionId:a.id,role:"assistant",content:"",status:"streaming",createdAt:new Date});t(c=>{c.messages.push(d),c.streamingMessageId=d.id,c.isStreaming=!0}),t(c=>{c.isStreaming=!1,c.streamingMessageId=null,c.isLoading=!1})}catch(i){console.error("Failed to send message:",i),t(d=>{d.error=i instanceof Error?i.message:"Failed to send message",d.isLoading=!1,d.isStreaming=!1,d.streamingMessageId=null})}},updateMessage:async(s,o)=>{try{const a=await q.updateMessage(s,o);t(i=>{const d=i.messages.findIndex(c=>c.id===s);d!==-1&&a&&(i.messages[d]=a)})}catch(a){console.error("Failed to update message:",a),t(i=>{i.error=a instanceof Error?a.message:"Failed to update message"})}},deleteMessage:async s=>{try{await q.deleteMessage(s),t(o=>{o.messages=o.messages.filter(a=>a.id!==s)})}catch(o){console.error("Failed to delete message:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to delete message"})}},startStreaming:s=>{t(o=>{o.isStreaming=!0,o.streamingMessageId=s})},updateStreamingMessage:s=>{t(o=>{if(o.streamingMessageId){const a=o.messages.findIndex(i=>i.id===o.streamingMessageId);a!==-1&&(o.messages[a].content=s)}})},stopStreaming:()=>{t(s=>{s.isStreaming=!1,s.streamingMessageId=null})},toggleSidebar:()=>{t(s=>{s.sidebarOpen=!s.sidebarOpen})},setTheme:s=>{t(o=>{o.theme=s})},updateChatConfig:async s=>{try{t(o=>{o.chatConfig={...o.chatConfig,...s}})}catch(o){console.error("Failed to update chat config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to update chat config"})}},loadMcpConfigs:async()=>{try{const s=await e.getMcpConfigs();t(o=>{o.mcpConfigs=s})}catch(s){console.error("Failed to load MCP configs:",s),t(o=>{o.error=s instanceof Error?s.message:"Failed to load MCP configs"})}},updateMcpConfig:async s=>{try{s.id?await e.updateMcpConfig(s.id,{id:s.id,name:s.name,command:s.serverUrl,enabled:s.enabled}):await e.createMcpConfig({id:crypto.randomUUID(),name:s.name,command:s.serverUrl,enabled:s.enabled});const o=await e.getMcpConfigs();t(a=>{a.mcpConfigs=o})}catch(o){console.error("Failed to update MCP config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to update MCP config"})}},deleteMcpConfig:async s=>{try{await e.deleteMcpConfig(s),t(o=>{o.mcpConfigs=o.mcpConfigs.filter(a=>a.id!==s)})}catch(o){console.error("Failed to delete MCP config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to delete MCP config"})}},loadAiModelConfigs:async()=>{try{const s=[];t(o=>{o.aiModelConfigs=s})}catch(s){console.error("Failed to load AI model configs:",s),t(o=>{o.error=s instanceof Error?s.message:"Failed to load AI model configs"})}},updateAiModelConfig:async s=>{try{t(o=>{if(s.id){const a=o.aiModelConfigs.findIndex(i=>i.id===s.id);a!==-1&&(o.aiModelConfigs[a]=s)}else{const a={...s,id:crypto.randomUUID()};o.aiModelConfigs.push(a)}})}catch(o){console.error("Failed to update AI model config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to update AI model config"})}},deleteAiModelConfig:async s=>{try{t(o=>{o.aiModelConfigs=o.aiModelConfigs.filter(a=>a.id!==s)})}catch(o){console.error("Failed to delete AI model config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to delete AI model config"})}},setSelectedModel:s=>{t(o=>{o.selectedModelId=s})},loadSystemContext:async()=>{try{const s=await e.getSystemContext();t(o=>{o.systemContext=s.content||null})}catch(s){console.error("Failed to load system context:",s),t(o=>{o.systemContext=null})}},updateSystemContext:async s=>{try{await e.updateSystemContext(s),t(o=>{o.systemContext=s})}catch(o){throw console.error("Failed to update system context:",o),o}},setError:s=>{t(o=>{o.error=s})},clearError:()=>{t(s=>{s.error=null})}}),{name:"chat-store",partialize:t=>({theme:t.theme,sidebarOpen:t.sidebarOpen,chatConfig:t.chatConfig,selectedModelId:t.selectedModelId})}))))}function La(r){var e,t,n="";if(typeof r=="string"||typeof r=="number")n+=r;else if(typeof r=="object")if(Array.isArray(r)){var s=r.length;for(e=0;e<s;e++)r[e]&&(t=La(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Ic(){for(var r,e,t=0,n="",s=arguments.length;t<s;t++)(r=arguments[t])&&(e=La(r))&&(n&&(n+=" "),n+=e);return n}const ds="-",Lc=r=>{const e=Fc(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:a=>{const i=a.split(ds);return i[0]===""&&i.length!==1&&i.shift(),Da(i,e)||Dc(a)},getConflictingClassGroupIds:(a,i)=>{const d=t[a]||[];return i&&n[a]?[...d,...n[a]]:d}}},Da=(r,e)=>{var a;if(r.length===0)return e.classGroupId;const t=r[0],n=e.nextPart.get(t),s=n?Da(r.slice(1),n):void 0;if(s)return s;if(e.validators.length===0)return;const o=r.join(ds);return(a=e.validators.find(({validator:i})=>i(o)))==null?void 0:a.classGroupId},xo=/^\[(.+)\]$/,Dc=r=>{if(xo.test(r)){const e=xo.exec(r)[1],t=e==null?void 0:e.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},Fc=r=>{const{theme:e,prefix:t}=r,n={nextPart:new Map,validators:[]};return Bc(Object.entries(r.classGroups),t).forEach(([o,a])=>{Bn(a,n,o,e)}),n},Bn=(r,e,t,n)=>{r.forEach(s=>{if(typeof s=="string"){const o=s===""?e:_o(e,s);o.classGroupId=t;return}if(typeof s=="function"){if($c(s)){Bn(s(n),e,t,n);return}e.validators.push({validator:s,classGroupId:t});return}Object.entries(s).forEach(([o,a])=>{Bn(a,_o(e,o),t,n)})})},_o=(r,e)=>{let t=r;return e.split(ds).forEach(n=>{t.nextPart.has(n)||t.nextPart.set(n,{nextPart:new Map,validators:[]}),t=t.nextPart.get(n)}),t},$c=r=>r.isThemeGetter,Bc=(r,e)=>e?r.map(([t,n])=>{const s=n.map(o=>typeof o=="string"?e+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([a,i])=>[e+a,i])):o);return[t,s]}):r,Uc=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,n=new Map;const s=(o,a)=>{t.set(o,a),e++,e>r&&(e=0,n=t,t=new Map)};return{get(o){let a=t.get(o);if(a!==void 0)return a;if((a=n.get(o))!==void 0)return s(o,a),a},set(o,a){t.has(o)?t.set(o,a):s(o,a)}}},Fa="!",Wc=r=>{const{separator:e,experimentalParseClassName:t}=r,n=e.length===1,s=e[0],o=e.length,a=i=>{const d=[];let c=0,u=0,f;for(let p=0;p<i.length;p++){let y=i[p];if(c===0){if(y===s&&(n||i.slice(p,p+o)===e)){d.push(i.slice(u,p)),u=p+o;continue}if(y==="/"){f=p;continue}}y==="["?c++:y==="]"&&c--}const m=d.length===0?i:i.substring(u),b=m.startsWith(Fa),g=b?m.substring(1):m,h=f&&f>u?f-u:void 0;return{modifiers:d,hasImportantModifier:b,baseClassName:g,maybePostfixModifierPosition:h}};return t?i=>t({className:i,parseClassName:a}):a},Hc=r=>{if(r.length<=1)return r;const e=[];let t=[];return r.forEach(n=>{n[0]==="["?(e.push(...t.sort(),n),t=[]):t.push(n)}),e.push(...t.sort()),e},zc=r=>({cache:Uc(r.cacheSize),parseClassName:Wc(r),...Lc(r)}),qc=/\s+/,Vc=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:s}=e,o=[],a=r.trim().split(qc);let i="";for(let d=a.length-1;d>=0;d-=1){const c=a[d],{modifiers:u,hasImportantModifier:f,baseClassName:m,maybePostfixModifierPosition:b}=t(c);let g=!!b,h=n(g?m.substring(0,b):m);if(!h){if(!g){i=c+(i.length>0?" "+i:i);continue}if(h=n(m),!h){i=c+(i.length>0?" "+i:i);continue}g=!1}const p=Hc(u).join(":"),y=f?p+Fa:p,w=y+h;if(o.includes(w))continue;o.push(w);const x=s(h,g);for(let v=0;v<x.length;++v){const S=x[v];o.push(y+S)}i=c+(i.length>0?" "+i:i)}return i};function Jc(){let r=0,e,t,n="";for(;r<arguments.length;)(e=arguments[r++])&&(t=$a(e))&&(n&&(n+=" "),n+=t);return n}const $a=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=$a(r[n]))&&(t&&(t+=" "),t+=e);return t};function Gc(r,...e){let t,n,s,o=a;function a(d){const c=e.reduce((u,f)=>f(u),r());return t=zc(c),n=t.cache.get,s=t.cache.set,o=i,i(d)}function i(d){const c=n(d);if(c)return c;const u=Vc(d,t);return s(d,u),u}return function(){return o(Jc.apply(null,arguments))}}const H=r=>{const e=t=>t[r]||[];return e.isThemeGetter=!0,e},Ba=/^\[(?:([a-z-]+):)?(.+)\]$/i,Xc=/^\d+\/\d+$/,Yc=new Set(["px","full","screen"]),Kc=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Qc=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Zc=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,ed=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,td=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Me=r=>ut(r)||Yc.has(r)||Xc.test(r),Te=r=>yt(r,"length",cd),ut=r=>!!r&&!Number.isNaN(Number(r)),pn=r=>yt(r,"number",ut),Ct=r=>!!r&&Number.isInteger(Number(r)),rd=r=>r.endsWith("%")&&ut(r.slice(0,-1)),L=r=>Ba.test(r),Ie=r=>Kc.test(r),nd=new Set(["length","size","percentage"]),sd=r=>yt(r,nd,Ua),od=r=>yt(r,"position",Ua),ad=new Set(["image","url"]),id=r=>yt(r,ad,ud),ld=r=>yt(r,"",dd),kt=()=>!0,yt=(r,e,t)=>{const n=Ba.exec(r);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):t(n[2]):!1},cd=r=>Qc.test(r)&&!Zc.test(r),Ua=()=>!1,dd=r=>ed.test(r),ud=r=>td.test(r),fd=()=>{const r=H("colors"),e=H("spacing"),t=H("blur"),n=H("brightness"),s=H("borderColor"),o=H("borderRadius"),a=H("borderSpacing"),i=H("borderWidth"),d=H("contrast"),c=H("grayscale"),u=H("hueRotate"),f=H("invert"),m=H("gap"),b=H("gradientColorStops"),g=H("gradientColorStopPositions"),h=H("inset"),p=H("margin"),y=H("opacity"),w=H("padding"),x=H("saturate"),v=H("scale"),S=H("sepia"),A=H("skew"),k=H("space"),$=H("translate"),j=()=>["auto","contain","none"],T=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto",L,e],C=()=>[L,e],F=()=>["",Me,Te],U=()=>["auto",ut,L],G=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],te=()=>["solid","dashed","dotted","double","none"],St=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ye=()=>["start","end","center","between","around","evenly","stretch"],Re=()=>["","0",L],nr=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Q=()=>[ut,L];return{cacheSize:500,separator:":",theme:{colors:[kt],spacing:[Me,Te],blur:["none","",Ie,L],brightness:Q(),borderColor:[r],borderRadius:["none","","full",Ie,L],borderSpacing:C(),borderWidth:F(),contrast:Q(),grayscale:Re(),hueRotate:Q(),invert:Re(),gap:C(),gradientColorStops:[r],gradientColorStopPositions:[rd,Te],inset:P(),margin:P(),opacity:Q(),padding:C(),saturate:Q(),scale:Q(),sepia:Re(),skew:Q(),space:C(),translate:C()},classGroups:{aspect:[{aspect:["auto","square","video",L]}],container:["container"],columns:[{columns:[Ie]}],"break-after":[{"break-after":nr()}],"break-before":[{"break-before":nr()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...G(),L]}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:j()}],"overscroll-x":[{"overscroll-x":j()}],"overscroll-y":[{"overscroll-y":j()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[h]}],"inset-x":[{"inset-x":[h]}],"inset-y":[{"inset-y":[h]}],start:[{start:[h]}],end:[{end:[h]}],top:[{top:[h]}],right:[{right:[h]}],bottom:[{bottom:[h]}],left:[{left:[h]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ct,L]}],basis:[{basis:P()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",L]}],grow:[{grow:Re()}],shrink:[{shrink:Re()}],order:[{order:["first","last","none",Ct,L]}],"grid-cols":[{"grid-cols":[kt]}],"col-start-end":[{col:["auto",{span:["full",Ct,L]},L]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[kt]}],"row-start-end":[{row:["auto",{span:[Ct,L]},L]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",L]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",L]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...ye()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ye(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ye(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[w]}],px:[{px:[w]}],py:[{py:[w]}],ps:[{ps:[w]}],pe:[{pe:[w]}],pt:[{pt:[w]}],pr:[{pr:[w]}],pb:[{pb:[w]}],pl:[{pl:[w]}],m:[{m:[p]}],mx:[{mx:[p]}],my:[{my:[p]}],ms:[{ms:[p]}],me:[{me:[p]}],mt:[{mt:[p]}],mr:[{mr:[p]}],mb:[{mb:[p]}],ml:[{ml:[p]}],"space-x":[{"space-x":[k]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[k]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",L,e]}],"min-w":[{"min-w":[L,e,"min","max","fit"]}],"max-w":[{"max-w":[L,e,"none","full","min","max","fit","prose",{screen:[Ie]},Ie]}],h:[{h:[L,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[L,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[L,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[L,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Ie,Te]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",pn]}],"font-family":[{font:[kt]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",L]}],"line-clamp":[{"line-clamp":["none",ut,pn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Me,L]}],"list-image":[{"list-image":["none",L]}],"list-style-type":[{list:["none","disc","decimal",L]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[r]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[r]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...te(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Me,Te]}],"underline-offset":[{"underline-offset":["auto",Me,L]}],"text-decoration-color":[{decoration:[r]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",L]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",L]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...G(),od]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",sd]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},id]}],"bg-color":[{bg:[r]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[b]}],"gradient-via":[{via:[b]}],"gradient-to":[{to:[b]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[i]}],"border-w-x":[{"border-x":[i]}],"border-w-y":[{"border-y":[i]}],"border-w-s":[{"border-s":[i]}],"border-w-e":[{"border-e":[i]}],"border-w-t":[{"border-t":[i]}],"border-w-r":[{"border-r":[i]}],"border-w-b":[{"border-b":[i]}],"border-w-l":[{"border-l":[i]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...te(),"hidden"]}],"divide-x":[{"divide-x":[i]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[i]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}],"divide-style":[{divide:te()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-s":[{"border-s":[s]}],"border-color-e":[{"border-e":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...te()]}],"outline-offset":[{"outline-offset":[Me,L]}],"outline-w":[{outline:[Me,Te]}],"outline-color":[{outline:[r]}],"ring-w":[{ring:F()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[r]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[Me,Te]}],"ring-offset-color":[{"ring-offset":[r]}],shadow:[{shadow:["","inner","none",Ie,ld]}],"shadow-color":[{shadow:[kt]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...St(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":St()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[n]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",Ie,L]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[f]}],saturate:[{saturate:[x]}],sepia:[{sepia:[S]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[t]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[d]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[f]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[x]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",L]}],duration:[{duration:Q()}],ease:[{ease:["linear","in","out","in-out",L]}],delay:[{delay:Q()}],animate:[{animate:["none","spin","ping","pulse","bounce",L]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[v]}],"scale-x":[{"scale-x":[v]}],"scale-y":[{"scale-y":[v]}],rotate:[{rotate:[Ct,L]}],"translate-x":[{"translate-x":[$]}],"translate-y":[{"translate-y":[$]}],"skew-x":[{"skew-x":[A]}],"skew-y":[{"skew-y":[A]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",L]}],accent:[{accent:["auto",r]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",L]}],"caret-color":[{caret:[r]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",L]}],fill:[{fill:[r,"none"]}],"stroke-w":[{stroke:[Me,Te,pn]}],stroke:[{stroke:[r,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},hd=Gc(fd);let ir;const md=new Uint8Array(16);function gd(){if(!ir&&(ir=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ir))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ir(md)}const re=[];for(let r=0;r<256;++r)re.push((r+256).toString(16).slice(1));function pd(r,e=0){return re[r[e+0]]+re[r[e+1]]+re[r[e+2]]+re[r[e+3]]+"-"+re[r[e+4]]+re[r[e+5]]+"-"+re[r[e+6]]+re[r[e+7]]+"-"+re[r[e+8]]+re[r[e+9]]+"-"+re[r[e+10]]+re[r[e+11]]+re[r[e+12]]+re[r[e+13]]+re[r[e+14]]+re[r[e+15]]}const yd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),vo={randomUUID:yd};function bd(r,e,t){if(vo.randomUUID&&!r)return vo.randomUUID();r=r||{};const n=r.random||(r.rng||gd)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,pd(n)}const Wa=6048e5,wd=864e5,lr=43200,So=1440,Co=Symbol.for("constructDateFrom");function Oe(r,e){return typeof r=="function"?r(e):r&&typeof r=="object"&&Co in r?r[Co](e):r instanceof Date?new r.constructor(e):new Date(e)}function ee(r,e){return Oe(e||r,r)}let xd={};function qt(){return xd}function Ut(r,e){var i,d,c,u;const t=qt(),n=(e==null?void 0:e.weekStartsOn)??((d=(i=e==null?void 0:e.locale)==null?void 0:i.options)==null?void 0:d.weekStartsOn)??t.weekStartsOn??((u=(c=t.locale)==null?void 0:c.options)==null?void 0:u.weekStartsOn)??0,s=ee(r,e==null?void 0:e.in),o=s.getDay(),a=(o<n?7:0)+o-n;return s.setDate(s.getDate()-a),s.setHours(0,0,0,0),s}function Rr(r,e){return Ut(r,{...e,weekStartsOn:1})}function Ha(r,e){const t=ee(r,e==null?void 0:e.in),n=t.getFullYear(),s=Oe(t,0);s.setFullYear(n+1,0,4),s.setHours(0,0,0,0);const o=Rr(s),a=Oe(t,0);a.setFullYear(n,0,4),a.setHours(0,0,0,0);const i=Rr(a);return t.getTime()>=o.getTime()?n+1:t.getTime()>=i.getTime()?n:n-1}function Tr(r){const e=ee(r),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+r-+t}function Hr(r,...e){const t=Oe.bind(null,r||e.find(n=>typeof n=="object"));return e.map(t)}function ko(r,e){const t=ee(r,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function _d(r,e,t){const[n,s]=Hr(t==null?void 0:t.in,r,e),o=ko(n),a=ko(s),i=+o-Tr(o),d=+a-Tr(a);return Math.round((i-d)/wd)}function vd(r,e){const t=Ha(r,e),n=Oe(r,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),Rr(n)}function wr(r,e){const t=+ee(r)-+ee(e);return t<0?-1:t>0?1:t}function Sd(r){return Oe(r,Date.now())}function Cd(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function kd(r){return!(!Cd(r)&&typeof r!="number"||isNaN(+ee(r)))}function Ad(r,e,t){const[n,s]=Hr(t==null?void 0:t.in,r,e),o=n.getFullYear()-s.getFullYear(),a=n.getMonth()-s.getMonth();return o*12+a}function Ed(r){return e=>{const n=(r?Math[r]:Math.trunc)(e);return n===0?0:n}}function Md(r,e){return+ee(r)-+ee(e)}function jd(r,e){const t=ee(r,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Nd(r,e){const t=ee(r,e==null?void 0:e.in),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function Od(r,e){const t=ee(r,e==null?void 0:e.in);return+jd(t,e)==+Nd(t,e)}function Pd(r,e,t){const[n,s,o]=Hr(t==null?void 0:t.in,r,r,e),a=wr(s,o),i=Math.abs(Ad(s,o));if(i<1)return 0;s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-a*i);let d=wr(s,o)===-a;Od(n)&&i===1&&wr(n,o)===1&&(d=!1);const c=a*(i-+d);return c===0?0:c}function Rd(r,e,t){const n=Md(r,e)/1e3;return Ed(t==null?void 0:t.roundingMethod)(n)}function Td(r,e){const t=ee(r,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}const Id={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Ld=(r,e,t)=>{let n;const s=Id[r];return typeof s=="string"?n=s:e===1?n=s.one:n=s.other.replace("{{count}}",e.toString()),t!=null&&t.addSuffix?t.comparison&&t.comparison>0?"in "+n:n+" ago":n};function yn(r){return(e={})=>{const t=e.width?String(e.width):r.defaultWidth;return r.formats[t]||r.formats[r.defaultWidth]}}const Dd={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Fd={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},$d={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Bd={date:yn({formats:Dd,defaultWidth:"full"}),time:yn({formats:Fd,defaultWidth:"full"}),dateTime:yn({formats:$d,defaultWidth:"full"})},Ud={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Wd=(r,e,t,n)=>Ud[r];function At(r){return(e,t)=>{const n=t!=null&&t.context?String(t.context):"standalone";let s;if(n==="formatting"&&r.formattingValues){const a=r.defaultFormattingWidth||r.defaultWidth,i=t!=null&&t.width?String(t.width):a;s=r.formattingValues[i]||r.formattingValues[a]}else{const a=r.defaultWidth,i=t!=null&&t.width?String(t.width):r.defaultWidth;s=r.values[i]||r.values[a]}const o=r.argumentCallback?r.argumentCallback(e):e;return s[o]}}const Hd={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},zd={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},qd={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Vd={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Jd={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Gd={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},Xd=(r,e)=>{const t=Number(r),n=t%100;if(n>20||n<10)switch(n%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},Yd={ordinalNumber:Xd,era:At({values:Hd,defaultWidth:"wide"}),quarter:At({values:zd,defaultWidth:"wide",argumentCallback:r=>r-1}),month:At({values:qd,defaultWidth:"wide"}),day:At({values:Vd,defaultWidth:"wide"}),dayPeriod:At({values:Jd,defaultWidth:"wide",formattingValues:Gd,defaultFormattingWidth:"wide"})};function Et(r){return(e,t={})=>{const n=t.width,s=n&&r.matchPatterns[n]||r.matchPatterns[r.defaultMatchWidth],o=e.match(s);if(!o)return null;const a=o[0],i=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],d=Array.isArray(i)?Qd(i,f=>f.test(a)):Kd(i,f=>f.test(a));let c;c=r.valueCallback?r.valueCallback(d):d,c=t.valueCallback?t.valueCallback(c):c;const u=e.slice(a.length);return{value:c,rest:u}}}function Kd(r,e){for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&e(r[t]))return t}function Qd(r,e){for(let t=0;t<r.length;t++)if(e(r[t]))return t}function Zd(r){return(e,t={})=>{const n=e.match(r.matchPattern);if(!n)return null;const s=n[0],o=e.match(r.parsePattern);if(!o)return null;let a=r.valueCallback?r.valueCallback(o[0]):o[0];a=t.valueCallback?t.valueCallback(a):a;const i=e.slice(s.length);return{value:a,rest:i}}}const eu=/^(\d+)(th|st|nd|rd)?/i,tu=/\d+/i,ru={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},nu={any:[/^b/i,/^(a|c)/i]},su={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},ou={any:[/1/i,/2/i,/3/i,/4/i]},au={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},iu={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},lu={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},cu={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},du={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},uu={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},fu={ordinalNumber:Zd({matchPattern:eu,parsePattern:tu,valueCallback:r=>parseInt(r,10)}),era:Et({matchPatterns:ru,defaultMatchWidth:"wide",parsePatterns:nu,defaultParseWidth:"any"}),quarter:Et({matchPatterns:su,defaultMatchWidth:"wide",parsePatterns:ou,defaultParseWidth:"any",valueCallback:r=>r+1}),month:Et({matchPatterns:au,defaultMatchWidth:"wide",parsePatterns:iu,defaultParseWidth:"any"}),day:Et({matchPatterns:lu,defaultMatchWidth:"wide",parsePatterns:cu,defaultParseWidth:"any"}),dayPeriod:Et({matchPatterns:du,defaultMatchWidth:"any",parsePatterns:uu,defaultParseWidth:"any"})},za={code:"en-US",formatDistance:Ld,formatLong:Bd,formatRelative:Wd,localize:Yd,match:fu,options:{weekStartsOn:0,firstWeekContainsDate:1}};function hu(r,e){const t=ee(r,e==null?void 0:e.in);return _d(t,Td(t))+1}function mu(r,e){const t=ee(r,e==null?void 0:e.in),n=+Rr(t)-+vd(t);return Math.round(n/Wa)+1}function qa(r,e){var u,f,m,b;const t=ee(r,e==null?void 0:e.in),n=t.getFullYear(),s=qt(),o=(e==null?void 0:e.firstWeekContainsDate)??((f=(u=e==null?void 0:e.locale)==null?void 0:u.options)==null?void 0:f.firstWeekContainsDate)??s.firstWeekContainsDate??((b=(m=s.locale)==null?void 0:m.options)==null?void 0:b.firstWeekContainsDate)??1,a=Oe((e==null?void 0:e.in)||r,0);a.setFullYear(n+1,0,o),a.setHours(0,0,0,0);const i=Ut(a,e),d=Oe((e==null?void 0:e.in)||r,0);d.setFullYear(n,0,o),d.setHours(0,0,0,0);const c=Ut(d,e);return+t>=+i?n+1:+t>=+c?n:n-1}function gu(r,e){var i,d,c,u;const t=qt(),n=(e==null?void 0:e.firstWeekContainsDate)??((d=(i=e==null?void 0:e.locale)==null?void 0:i.options)==null?void 0:d.firstWeekContainsDate)??t.firstWeekContainsDate??((u=(c=t.locale)==null?void 0:c.options)==null?void 0:u.firstWeekContainsDate)??1,s=qa(r,e),o=Oe((e==null?void 0:e.in)||r,0);return o.setFullYear(s,0,n),o.setHours(0,0,0,0),Ut(o,e)}function pu(r,e){const t=ee(r,e==null?void 0:e.in),n=+Ut(t,e)-+gu(t,e);return Math.round(n/Wa)+1}function B(r,e){const t=r<0?"-":"",n=Math.abs(r).toString().padStart(e,"0");return t+n}const Le={y(r,e){const t=r.getFullYear(),n=t>0?t:1-t;return B(e==="yy"?n%100:n,e.length)},M(r,e){const t=r.getMonth();return e==="M"?String(t+1):B(t+1,2)},d(r,e){return B(r.getDate(),e.length)},a(r,e){const t=r.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(r,e){return B(r.getHours()%12||12,e.length)},H(r,e){return B(r.getHours(),e.length)},m(r,e){return B(r.getMinutes(),e.length)},s(r,e){return B(r.getSeconds(),e.length)},S(r,e){const t=e.length,n=r.getMilliseconds(),s=Math.trunc(n*Math.pow(10,t-3));return B(s,e.length)}},rt={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ao={G:function(r,e,t){const n=r.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return t.era(n,{width:"abbreviated"});case"GGGGG":return t.era(n,{width:"narrow"});case"GGGG":default:return t.era(n,{width:"wide"})}},y:function(r,e,t){if(e==="yo"){const n=r.getFullYear(),s=n>0?n:1-n;return t.ordinalNumber(s,{unit:"year"})}return Le.y(r,e)},Y:function(r,e,t,n){const s=qa(r,n),o=s>0?s:1-s;if(e==="YY"){const a=o%100;return B(a,2)}return e==="Yo"?t.ordinalNumber(o,{unit:"year"}):B(o,e.length)},R:function(r,e){const t=Ha(r);return B(t,e.length)},u:function(r,e){const t=r.getFullYear();return B(t,e.length)},Q:function(r,e,t){const n=Math.ceil((r.getMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return B(n,2);case"Qo":return t.ordinalNumber(n,{unit:"quarter"});case"QQQ":return t.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(n,{width:"wide",context:"formatting"})}},q:function(r,e,t){const n=Math.ceil((r.getMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return B(n,2);case"qo":return t.ordinalNumber(n,{unit:"quarter"});case"qqq":return t.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(n,{width:"wide",context:"standalone"})}},M:function(r,e,t){const n=r.getMonth();switch(e){case"M":case"MM":return Le.M(r,e);case"Mo":return t.ordinalNumber(n+1,{unit:"month"});case"MMM":return t.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(n,{width:"wide",context:"formatting"})}},L:function(r,e,t){const n=r.getMonth();switch(e){case"L":return String(n+1);case"LL":return B(n+1,2);case"Lo":return t.ordinalNumber(n+1,{unit:"month"});case"LLL":return t.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(n,{width:"wide",context:"standalone"})}},w:function(r,e,t,n){const s=pu(r,n);return e==="wo"?t.ordinalNumber(s,{unit:"week"}):B(s,e.length)},I:function(r,e,t){const n=mu(r);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):B(n,e.length)},d:function(r,e,t){return e==="do"?t.ordinalNumber(r.getDate(),{unit:"date"}):Le.d(r,e)},D:function(r,e,t){const n=hu(r);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):B(n,e.length)},E:function(r,e,t){const n=r.getDay();switch(e){case"E":case"EE":case"EEE":return t.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(n,{width:"short",context:"formatting"});case"EEEE":default:return t.day(n,{width:"wide",context:"formatting"})}},e:function(r,e,t,n){const s=r.getDay(),o=(s-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(o);case"ee":return B(o,2);case"eo":return t.ordinalNumber(o,{unit:"day"});case"eee":return t.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(s,{width:"short",context:"formatting"});case"eeee":default:return t.day(s,{width:"wide",context:"formatting"})}},c:function(r,e,t,n){const s=r.getDay(),o=(s-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(o);case"cc":return B(o,e.length);case"co":return t.ordinalNumber(o,{unit:"day"});case"ccc":return t.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(s,{width:"narrow",context:"standalone"});case"cccccc":return t.day(s,{width:"short",context:"standalone"});case"cccc":default:return t.day(s,{width:"wide",context:"standalone"})}},i:function(r,e,t){const n=r.getDay(),s=n===0?7:n;switch(e){case"i":return String(s);case"ii":return B(s,e.length);case"io":return t.ordinalNumber(s,{unit:"day"});case"iii":return t.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(n,{width:"short",context:"formatting"});case"iiii":default:return t.day(n,{width:"wide",context:"formatting"})}},a:function(r,e,t){const s=r.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(s,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(r,e,t){const n=r.getHours();let s;switch(n===12?s=rt.noon:n===0?s=rt.midnight:s=n/12>=1?"pm":"am",e){case"b":case"bb":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(s,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(r,e,t){const n=r.getHours();let s;switch(n>=17?s=rt.evening:n>=12?s=rt.afternoon:n>=4?s=rt.morning:s=rt.night,e){case"B":case"BB":case"BBB":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(r,e,t){if(e==="ho"){let n=r.getHours()%12;return n===0&&(n=12),t.ordinalNumber(n,{unit:"hour"})}return Le.h(r,e)},H:function(r,e,t){return e==="Ho"?t.ordinalNumber(r.getHours(),{unit:"hour"}):Le.H(r,e)},K:function(r,e,t){const n=r.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):B(n,e.length)},k:function(r,e,t){let n=r.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):B(n,e.length)},m:function(r,e,t){return e==="mo"?t.ordinalNumber(r.getMinutes(),{unit:"minute"}):Le.m(r,e)},s:function(r,e,t){return e==="so"?t.ordinalNumber(r.getSeconds(),{unit:"second"}):Le.s(r,e)},S:function(r,e){return Le.S(r,e)},X:function(r,e,t){const n=r.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return Mo(n);case"XXXX":case"XX":return qe(n);case"XXXXX":case"XXX":default:return qe(n,":")}},x:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"x":return Mo(n);case"xxxx":case"xx":return qe(n);case"xxxxx":case"xxx":default:return qe(n,":")}},O:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Eo(n,":");case"OOOO":default:return"GMT"+qe(n,":")}},z:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Eo(n,":");case"zzzz":default:return"GMT"+qe(n,":")}},t:function(r,e,t){const n=Math.trunc(+r/1e3);return B(n,e.length)},T:function(r,e,t){return B(+r,e.length)}};function Eo(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=Math.trunc(n/60),o=n%60;return o===0?t+String(s):t+String(s)+e+B(o,2)}function Mo(r,e){return r%60===0?(r>0?"-":"+")+B(Math.abs(r)/60,2):qe(r,e)}function qe(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=B(Math.trunc(n/60),2),o=B(n%60,2);return t+s+e+o}const jo=(r,e)=>{switch(r){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},Va=(r,e)=>{switch(r){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},yu=(r,e)=>{const t=r.match(/(P+)(p+)?/)||[],n=t[1],s=t[2];if(!s)return jo(r,e);let o;switch(n){case"P":o=e.dateTime({width:"short"});break;case"PP":o=e.dateTime({width:"medium"});break;case"PPP":o=e.dateTime({width:"long"});break;case"PPPP":default:o=e.dateTime({width:"full"});break}return o.replace("{{date}}",jo(n,e)).replace("{{time}}",Va(s,e))},bu={p:Va,P:yu},wu=/^D+$/,xu=/^Y+$/,_u=["D","DD","YY","YYYY"];function vu(r){return wu.test(r)}function Su(r){return xu.test(r)}function Cu(r,e,t){const n=ku(r,e,t);if(console.warn(n),_u.includes(r))throw new RangeError(n)}function ku(r,e,t){const n=r[0]==="Y"?"years":"days of the month";return`Use \`${r.toLowerCase()}\` instead of \`${r}\` (in \`${e}\`) for formatting ${n} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const Au=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Eu=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Mu=/^'([^]*?)'?$/,ju=/''/g,Nu=/[a-zA-Z]/;function us(r,e,t){var u,f,m,b;const n=qt(),s=n.locale??za,o=n.firstWeekContainsDate??((f=(u=n.locale)==null?void 0:u.options)==null?void 0:f.firstWeekContainsDate)??1,a=n.weekStartsOn??((b=(m=n.locale)==null?void 0:m.options)==null?void 0:b.weekStartsOn)??0,i=ee(r,t==null?void 0:t.in);if(!kd(i))throw new RangeError("Invalid time value");let d=e.match(Eu).map(g=>{const h=g[0];if(h==="p"||h==="P"){const p=bu[h];return p(g,s.formatLong)}return g}).join("").match(Au).map(g=>{if(g==="''")return{isToken:!1,value:"'"};const h=g[0];if(h==="'")return{isToken:!1,value:Ou(g)};if(Ao[h])return{isToken:!0,value:g};if(h.match(Nu))throw new RangeError("Format string contains an unescaped latin alphabet character `"+h+"`");return{isToken:!1,value:g}});s.localize.preprocessor&&(d=s.localize.preprocessor(i,d));const c={firstWeekContainsDate:o,weekStartsOn:a,locale:s};return d.map(g=>{if(!g.isToken)return g.value;const h=g.value;(Su(h)||vu(h))&&Cu(h,e,String(r));const p=Ao[h[0]];return p(i,h,s.localize,c)}).join("")}function Ou(r){const e=r.match(Mu);return e?e[1].replace(ju,"'"):r}function Pu(r,e,t){const n=qt(),s=(t==null?void 0:t.locale)??n.locale??za,o=2520,a=wr(r,e);if(isNaN(a))throw new RangeError("Invalid time value");const i=Object.assign({},t,{addSuffix:t==null?void 0:t.addSuffix,comparison:a}),[d,c]=Hr(t==null?void 0:t.in,...a>0?[e,r]:[r,e]),u=Rd(c,d),f=(Tr(c)-Tr(d))/1e3,m=Math.round((u-f)/60);let b;if(m<2)return t!=null&&t.includeSeconds?u<5?s.formatDistance("lessThanXSeconds",5,i):u<10?s.formatDistance("lessThanXSeconds",10,i):u<20?s.formatDistance("lessThanXSeconds",20,i):u<40?s.formatDistance("halfAMinute",0,i):u<60?s.formatDistance("lessThanXMinutes",1,i):s.formatDistance("xMinutes",1,i):m===0?s.formatDistance("lessThanXMinutes",1,i):s.formatDistance("xMinutes",m,i);if(m<45)return s.formatDistance("xMinutes",m,i);if(m<90)return s.formatDistance("aboutXHours",1,i);if(m<So){const g=Math.round(m/60);return s.formatDistance("aboutXHours",g,i)}else{if(m<o)return s.formatDistance("xDays",1,i);if(m<lr){const g=Math.round(m/So);return s.formatDistance("xDays",g,i)}else if(m<lr*2)return b=Math.round(m/lr),s.formatDistance("aboutXMonths",b,i)}if(b=Pd(c,d),b<12){const g=Math.round(m/lr);return s.formatDistance("xMonths",g,i)}else{const g=b%12,h=Math.trunc(b/12);return g<3?s.formatDistance("aboutXYears",h,i):g<9?s.formatDistance("overXYears",h,i):s.formatDistance("almostXYears",h+1,i)}}function Ru(r,e){return Pu(r,Sd(r),e)}function se(...r){return hd(Ic(r))}function Tu(){return bd()}function Ja(r){if(!r)return"--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"--:--":us(e,"HH:mm")}function Iu(r){if(!r)return"时间未知";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"时间未知":Ru(e,{addSuffix:!0})}function Lu(r){if(!r)return"----/--/--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/--":us(e,"yyyy-MM-dd")}function Du(r){if(!r)return"----/--/-- --:--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/-- --:--:--":us(e,"yyyy-MM-dd HH:mm:ss")}function Fu(r,e){return r.length<=e?r:r.slice(0,e)+"..."}function $u(r){return r.replace(/<[^>]*>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').trim()}function Bu(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function Uu(r){try{return new URL(r),!0}catch{return!1}}function Un(r){if(r===null||typeof r!="object")return r;if(r instanceof Date)return isNaN(r.getTime())?new Date:new Date(r.getTime());if(r instanceof Array)return r.map(e=>Un(e));if(typeof r=="object"){const e={};for(const t in r)r.hasOwnProperty(t)&&(e[t]=Un(r[t]));return e}return r}function Wu(r,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function Hu(r,e){let t;return(...n)=>{t||(r(...n),t=!0,setTimeout(()=>t=!1,e))}}function Ga(r){if(r===0)return"0 Bytes";const e=1024,t=["Bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(r)/Math.log(e));return parseFloat((r/Math.pow(e,n)).toFixed(2))+" "+t[n]}function Xa(r){return r.slice((r.lastIndexOf(".")-1>>>0)+2)}function zu(r){const e=["jpg","jpeg","png","gif","bmp","webp","svg"],t=Xa(r).toLowerCase();return e.includes(t)}function qu(){const r=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6366f1"];return r[Math.floor(Math.random()*r.length)]}async function Vu(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){return console.error("Failed to copy text to clipboard:",e),!1}}function Ju(r,e,t="text/plain"){const n=new Blob([r],{type:t}),s=URL.createObjectURL(n),o=document.createElement("a");o.href=s,o.download=e,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(s)}function Gu(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Xu(){const r=navigator.userAgent;return r.indexOf("Win")!==-1?"Windows":r.indexOf("Mac")!==-1?"macOS":r.indexOf("Linux")!==-1?"Linux":r.indexOf("Android")!==-1?"Android":r.indexOf("iOS")!==-1?"iOS":"Unknown"}class Yu extends Error{constructor(t,n="UNKNOWN_ERROR",s=500){super(t);D(this,"code");D(this,"statusCode");this.name="AppError",this.code=n,this.statusCode=s}}async function Ku(r,e=3,t=1e3){let n;for(let s=1;s<=e;s++)try{return await r()}catch(o){if(n=o,s===e)break;await new Promise(a=>setTimeout(a,t*s))}throw n}const Qu={get:(r,e)=>{try{const t=localStorage.getItem(r);return t?JSON.parse(t):e||null}catch{return e||null}},set:(r,e)=>{try{localStorage.setItem(r,JSON.stringify(e))}catch(t){console.error("Failed to save to localStorage:",t)}},remove:r=>{try{localStorage.removeItem(r)}catch(e){console.error("Failed to remove from localStorage:",e)}},clear:()=>{try{localStorage.clear()}catch(r){console.error("Failed to clear localStorage:",r)}}},Wn=({content:r,isStreaming:e=!1,className:t})=>{const n=M.useMemo(()=>o=>{let a=o;const i=/\$\$([\s\S]*?)\$\$/g;a=a.replace(i,(f,m)=>`<div class="math-block bg-muted/50 p-3 rounded-md my-2 text-center font-mono text-sm border">${m.trim()}</div>`);const d=/\$([^$]+)\$/g;a=a.replace(d,(f,m)=>`<span class="math-inline bg-muted/30 px-1 py-0.5 rounded font-mono text-sm">${m}</span>`);const c=/```(\w+)?\n?([\s\S]*?)```/g;a=a.replace(c,(f,m,b)=>{const g=m||"text",h=s(b.trim(),g);return`<div class="code-block my-3"><div class="code-header bg-muted/50 px-3 py-1 text-xs text-muted-foreground border-b">${g}</div><pre class="bg-muted p-3 overflow-x-auto"><code class="text-sm">${h}</code></pre></div>`});const u=/`([^`]+)`/g;return a=a.replace(u,(f,m)=>`<code class="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">${m}</code>`),a=a.replace(/^### (.*$)/gm,'<h3 class="text-lg font-semibold mt-4 mb-2">$1</h3>'),a=a.replace(/^## (.*$)/gm,'<h2 class="text-xl font-semibold mt-4 mb-2">$1</h2>'),a=a.replace(/^# (.*$)/gm,'<h1 class="text-2xl font-bold mt-4 mb-2">$1</h1>'),a=a.replace(/^\* (.*$)/gm,'<li class="ml-4">• $1</li>'),a=a.replace(/^\d+\. (.*$)/gm,'<li class="ml-4 list-decimal">$1</li>'),a=a.replace(/\*\*(.*?)\*\*/g,'<strong class="font-semibold">$1</strong>'),a=a.replace(/\*(.*?)\*/g,'<em class="italic">$1</em>'),a=a.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" class="text-primary hover:underline" target="_blank" rel="noopener noreferrer">$1</a>'),a=a.replace(/^> (.*$)/gm,'<blockquote class="border-l-4 border-primary/30 pl-4 italic text-muted-foreground">$1</blockquote>'),a=a.replace(/\n\n/g,'</p><p class="mb-2">'),a=a.replace(/\n/g,"<br>"),a&&!a.startsWith("<")&&(a=`<p class="mb-2">${a}</p>`),a},[]),s=(o,a)=>{let i=o;return a==="javascript"||a==="js"||a==="typescript"||a==="ts"?(i=i.replace(/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|async|await)\b/g,'<span class="text-blue-600 dark:text-blue-400 font-semibold">$1</span>'),i=i.replace(/(['"`])([^'"\`]*?)\1/g,'<span class="text-green-600 dark:text-green-400">$1$2$1</span>'),i=i.replace(/(\/\/.*$)/gm,'<span class="text-gray-500 italic">$1</span>')):(a==="python"||a==="py")&&(i=i.replace(/\b(def|class|import|from|return|if|else|elif|for|while|try|except|with|as|pass|break|continue)\b/g,'<span class="text-blue-600 dark:text-blue-400 font-semibold">$1</span>'),i=i.replace(/(['"`])([^'"\`]*?)\1/g,'<span class="text-green-600 dark:text-green-400">$1$2$1</span>'),i=i.replace(/(#.*$)/gm,'<span class="text-gray-500 italic">$1</span>')),i};return l.jsxs("div",{className:se("prose prose-sm max-w-none","prose-headings:text-foreground prose-p:text-foreground","prose-strong:text-foreground prose-em:text-foreground","prose-code:text-foreground prose-pre:bg-muted","prose-a:text-primary prose-a:no-underline hover:prose-a:underline",t),children:[l.jsx("div",{dangerouslySetInnerHTML:{__html:n(r)}}),e&&l.jsx("span",{className:"inline-block w-2 h-4 bg-primary animate-pulse ml-1"})]})},Ya=({attachment:r,customRenderer:e,className:t})=>{if(e)return l.jsx("div",{children:e(r)});const n=r.type==="image",s=r.type==="audio",o=()=>n?l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}):s?l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3"})}):l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})});return l.jsxs("div",{className:se("inline-flex items-center gap-2 p-2 bg-muted rounded-lg border max-w-sm",t),children:[l.jsx("div",{className:"flex-shrink-0 text-muted-foreground",children:o()}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-sm font-medium truncate",children:r.name}),l.jsx("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:Ga(r.size)})]}),r.mimeType&&l.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:r.mimeType})]}),l.jsx("div",{className:"flex-shrink-0",children:n?l.jsx("button",{onClick:()=>window.open(r.url,"_blank"),className:"p-1 hover:bg-background rounded transition-colors",title:"View image",children:l.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]})}):l.jsx("a",{href:r.url,download:r.name,className:"p-1 hover:bg-background rounded transition-colors inline-block",title:"Download file",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})})}),n&&l.jsx("div",{className:"w-full mt-2",children:l.jsx("img",{src:r.url,alt:r.name,className:"max-w-full h-auto rounded border",style:{maxHeight:"200px"},loading:"lazy"})}),s&&l.jsx("div",{className:"w-full mt-2",children:l.jsxs("audio",{controls:!0,className:"w-full",preload:"metadata",children:[l.jsx("source",{src:r.url,type:r.mimeType}),"Your browser does not support the audio element."]})})]})},Hn=({toolCall:r,allMessages:e=[],className:t})=>{var p;const[n,s]=M.useState(!1),[o,a]=M.useState(!1),[i,d]=M.useState(!1),c=e.find(y=>y.role==="tool"&&(y.toolCallId===r.id||y.tool_call_id===r.id)),u=(c==null?void 0:c.content)||r.result,f=(c==null?void 0:c.summary)||((p=c==null?void 0:c.metadata)==null?void 0:p.summary),m=!!r.error,b=!!u,g=r.arguments&&Object.keys(r.arguments).length>0,h=y=>{try{return JSON.stringify(y,null,2)}catch{return String(y)}};return l.jsxs("div",{className:se("border rounded-lg p-3 bg-muted/50",m&&"border-destructive bg-destructive/5",t),children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsxs("svg",{className:"w-4 h-4 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]}),l.jsxs("span",{className:"text-sm font-medium",children:["Tool: ",r.name]})]}),m&&l.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-destructive bg-destructive/10 px-2 py-0.5 rounded",children:[l.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Error"]}),b&&!m&&l.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-green-600 bg-green-50 px-2 py-0.5 rounded",children:[l.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"Success"]})]}),l.jsx("button",{onClick:()=>s(!n),className:"p-1 hover:bg-muted rounded transition-colors",title:n?"Collapse":"Expand",children:l.jsx("svg",{className:se("w-4 h-4 transition-transform",n&&"rotate-180"),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),n&&l.jsxs("div",{className:"mt-3 space-y-3",children:[g&&l.jsxs("div",{children:[l.jsxs("button",{onClick:()=>a(!o),className:"flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors",children:[l.jsx("svg",{className:se("w-3 h-3 transition-transform",o&&"rotate-90"),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),"Arguments"]}),o&&l.jsx("pre",{className:"mt-2 p-2 bg-background border rounded text-xs overflow-x-auto",children:l.jsx("code",{children:h(r.arguments)})})]}),b&&l.jsx("div",{children:f?l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:"AI Summary"}),l.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-800",children:f}),l.jsxs("button",{onClick:()=>d(!i),className:"flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors",children:[l.jsx("svg",{className:se("w-3 h-3 transition-transform",i&&"rotate-90"),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),i?"Hide Full Result":"Show Full Result"]}),i&&l.jsx("pre",{className:"mt-2 p-2 bg-background border rounded text-xs overflow-x-auto",children:l.jsx("code",{children:u})})]}):l.jsxs("div",{children:[l.jsxs("button",{onClick:()=>d(!i),className:"flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors",children:[l.jsx("svg",{className:se("w-3 h-3 transition-transform",i&&"rotate-90"),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),"Result"]}),i&&l.jsx("pre",{className:"mt-2 p-2 bg-background border rounded text-xs overflow-x-auto",children:l.jsx("code",{children:u})})]})}),m&&l.jsxs("div",{children:[l.jsx("div",{className:"text-sm font-medium text-destructive mb-2",children:"Error"}),l.jsx("div",{className:"p-2 bg-destructive/5 border border-destructive/20 rounded text-sm text-destructive",children:r.error})]}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Executed at: ",(()=>{const y=new Date(r.createdAt);return isNaN(y.getTime())?"时间未知":y.toLocaleString()})()]})]})]})},Ka=({message:r,isLast:e=!1,isStreaming:t=!1,onEdit:n,onDelete:s,allMessages:o=[],customRenderer:a})=>{var A,k,$;const[i,d]=M.useState(!1),[c,u]=M.useState(r.content),[f,m]=M.useState(!1),b=r.role==="user",g=r.role==="assistant",h=r.role==="system",p=r.role==="tool";if(p)return null;if(a!=null&&a.renderMessage)return l.jsx("div",{children:a.renderMessage(r)});const y=()=>{n&&c.trim()!==r.content&&n(r.id,c.trim()),d(!1)},w=()=>{u(r.content),d(!1)},x=async()=>{try{await navigator.clipboard.writeText(r.content)}catch(j){console.error("Failed to copy message:",j)}},v=((A=r.metadata)==null?void 0:A.attachments)||[];let S=((k=r.metadata)==null?void 0:k.toolCalls)||[];if(S.length===0&&(r.toolCalls||r.tool_calls)){const j=r.toolCalls||r.tool_calls;Array.isArray(j)&&(S=j.map(T=>{var P,C;return{id:T.id,messageId:r.id,name:((P=T.function)==null?void 0:P.name)||T.name,arguments:((C=T.function)==null?void 0:C.arguments)||T.arguments,result:"",createdAt:r.createdAt}}))}return l.jsxs("div",{className:se("group relative flex gap-3 px-4 py-4 rounded-lg transition-colors",b&&"bg-user-message ml-12",g&&"bg-assistant-message mr-12",h&&"bg-muted mx-12 border-l-4 border-primary",p&&"bg-blue-50 dark:bg-blue-950/20 mx-12 border-l-4 border-blue-500","hover:bg-opacity-80"),onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),children:[l.jsx("div",{className:"flex-shrink-0",children:l.jsx("div",{className:se("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium",b&&"bg-primary text-primary-foreground",g&&"bg-secondary text-secondary-foreground",h&&"bg-muted text-muted-foreground",p&&"bg-blue-500 text-white"),children:b?"U":g?"AI":p?"T":"S"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[l.jsx("span",{className:"text-sm font-medium",children:b?"You":g?"Assistant":p?"Tool Result":"System"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:Ja(r.createdAt)}),(($=r.metadata)==null?void 0:$.model)&&l.jsx("span",{className:"text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded",children:r.metadata.model})]}),v.length>0&&l.jsx("div",{className:"mb-3 space-y-2",children:v.map(j=>l.jsx(Ya,{attachment:j,customRenderer:a==null?void 0:a.renderAttachment},j.id))}),i?l.jsxs("div",{className:"space-y-2",children:[l.jsx("textarea",{value:c,onChange:j=>u(j.target.value),className:"w-full p-2 border rounded-md resize-none focus:outline-none focus:ring-2 focus:ring-primary",rows:3,autoFocus:!0}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{onClick:y,className:"px-3 py-1 text-sm bg-primary text-primary-foreground rounded hover:bg-primary/90",children:"Save"}),l.jsx("button",{onClick:w,className:"px-3 py-1 text-sm bg-muted text-muted-foreground rounded hover:bg-muted/80",children:"Cancel"})]})]}):l.jsx("div",{className:"space-y-3",children:(()=>{var C;const j=((C=r.metadata)==null?void 0:C.contentSegments)||[],T=r.content&&r.content.trim().length>0,P=t&&e;return j.length>0?l.jsx("div",{className:"space-y-3",children:j.map((F,U)=>{if(F.type==="text")return l.jsx("div",{className:"prose prose-sm max-w-none",children:l.jsx(Wn,{content:F.content,isStreaming:P&&U===j.length-1})},`segment-${U}`);if(F.type==="tool_call"){const G=S.find(te=>te.id===F.toolCallId);if(G)return l.jsx("div",{children:l.jsx(Hn,{toolCall:G,allMessages:o})},`tool-${G.id}`)}return null})}):l.jsxs("div",{className:"space-y-3",children:[T&&l.jsx("div",{className:"prose prose-sm max-w-none",children:l.jsx(Wn,{content:r.content,isStreaming:P})}),S.length>0&&l.jsx("div",{className:"space-y-2",children:S.map(F=>l.jsx("div",{children:l.jsx(Hn,{toolCall:F,allMessages:o})},`tool-${F.id}`))})]})})()}),r.tokensUsed&&l.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Tokens used: ",r.tokensUsed]})]}),f&&!i&&l.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 bg-background border rounded-md shadow-sm opacity-0 group-hover:opacity-100 transition-opacity",children:[l.jsx("button",{onClick:x,className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Copy message",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}),b&&n&&l.jsx("button",{onClick:()=>d(!0),className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Edit message",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}),s&&l.jsx("button",{onClick:()=>s(r.id),className:"p-1.5 hover:bg-destructive/10 rounded text-muted-foreground hover:text-destructive transition-colors",title:"Delete message",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})})]})]})},Qa=({size:r="md",className:e})=>{const t={sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"};return l.jsx("div",{className:se("animate-spin rounded-full border-2 border-current border-t-transparent",t[r],e),role:"status","aria-label":"Loading",children:l.jsx("span",{className:"sr-only",children:"Loading..."})})},fs=({messages:r,isLoading:e=!1,isStreaming:t=!1,onMessageEdit:n,onMessageDelete:s,customRenderer:o})=>r.length===0&&!e?l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsxs("div",{className:"text-center space-y-4",children:[l.jsx("div",{className:"w-16 h-16 mx-auto bg-muted rounded-full flex items-center justify-center",children:l.jsx("svg",{className:"w-8 h-8 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Start a conversation"}),l.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Send a message to begin your chat with AI"})]})]})}):l.jsx("div",{className:"flex flex-col h-full",children:l.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-6 space-y-6",children:[r.map((a,i)=>l.jsx(Ka,{message:a,isLast:i===r.length-1,isStreaming:t&&i===r.length-1,onEdit:n,onDelete:s,allMessages:r,customRenderer:o},a.id)),e&&l.jsx("div",{className:"flex justify-start",children:l.jsxs("div",{className:"flex items-center space-x-2 bg-muted px-4 py-3 rounded-lg max-w-xs",children:[l.jsx(Qa,{size:"sm"}),l.jsx("span",{className:"text-sm text-muted-foreground",children:"AI is thinking..."})]})})]})}),hs=({onSend:r,disabled:e=!1,placeholder:t="Type your message...",maxLength:n=4e3,allowAttachments:s=!1,supportedFileTypes:o=["image/*","text/*","application/pdf"],showModelSelector:a=!1,selectedModelId:i=null,availableModels:d=[],onModelChange:c})=>{const[u,f]=M.useState(""),[m,b]=M.useState([]),[g,h]=M.useState(!1),p=M.useRef(null),y=M.useRef(null),w=M.useCallback(()=>{const C=p.current;if(C){C.style.height="auto";const F=C.scrollHeight,U=200;C.style.height=`${Math.min(F,U)}px`}},[]),x=C=>{const F=C.target.value;F.length<=n&&(f(F),w())},v=C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),S())},S=()=>{const C=u.trim();if(!(!C&&m.length===0)&&!e){if(a&&!i){alert("请先选择一个AI模型");return}r(C,m),f(""),b([]),p.current&&(p.current.style.height="auto")}},A=C=>{const F=Array.from(C.target.files||[]);b(U=>[...U,...F]),y.current&&(y.current.value="")},k=C=>{b(F=>F.filter((U,G)=>G!==C))},$=C=>{C.preventDefault(),s&&!e&&h(!0)},j=C=>{C.preventDefault(),h(!1)},T=C=>{if(C.preventDefault(),h(!1),!s||e)return;const F=Array.from(C.dataTransfer.files);b(U=>[...U,...F])},P=C=>{if(C===0)return"0 Bytes";const F=1024,U=["Bytes","KB","MB","GB"],G=Math.floor(Math.log(C)/Math.log(F));return parseFloat((C/Math.pow(F,G)).toFixed(2))+" "+U[G]};return l.jsxs("div",{className:"border-t bg-background p-4",children:[a&&l.jsx("div",{className:"mb-3",children:d.length>0?l.jsxs("select",{value:i||"",onChange:C=>c==null?void 0:c(C.target.value||null),disabled:e,className:se("w-80 max-w-full px-3 py-2 border border-input bg-background rounded-md","text-sm text-foreground placeholder:text-muted-foreground","focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent","disabled:opacity-50 disabled:cursor-not-allowed"),children:[l.jsx("option",{value:"",children:"请选择模型..."}),d.filter(C=>C.enabled).map(C=>l.jsxs("option",{value:C.id,children:[C.name," (",C.model_name,")"]},C.id))]}):l.jsx("div",{className:"w-80 max-w-full px-3 py-2 border border-input bg-muted rounded-md text-sm text-muted-foreground",children:"暂无可用模型,请先在右上角配置AI模型"})}),m.length>0&&l.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:m.map((C,F)=>l.jsxs("div",{className:"flex items-center gap-2 bg-muted px-3 py-2 rounded-lg text-sm",children:[l.jsx("svg",{className:"w-4 h-4 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})}),l.jsx("span",{className:"truncate max-w-32",children:C.name}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",P(C.size),")"]}),l.jsx("button",{onClick:()=>k(F),className:"text-muted-foreground hover:text-destructive transition-colors",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},F))}),l.jsxs("div",{className:se("relative flex items-end gap-2 p-3 border rounded-lg transition-colors","focus-within:border-primary",g&&"border-primary bg-primary/5",e&&"opacity-50 cursor-not-allowed"),onDragOver:$,onDragLeave:j,onDrop:T,children:[s&&l.jsx("button",{onClick:()=>{var C;return(C=y.current)==null?void 0:C.click()},disabled:e,className:"flex-shrink-0 p-2 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Attach files",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}),l.jsx("textarea",{ref:p,value:u,onChange:x,onKeyDown:v,placeholder:t,disabled:e,className:se("flex-1 resize-none bg-transparent border-none outline-none","placeholder:text-muted-foreground","disabled:cursor-not-allowed"),rows:1,style:{minHeight:"24px",maxHeight:"200px"}}),l.jsxs("div",{className:"flex-shrink-0 text-xs text-muted-foreground",children:[u.length,"/",n]}),l.jsx("button",{onClick:S,disabled:e||!u.trim()&&m.length===0,className:se("flex-shrink-0 p-2 rounded-md transition-colors","disabled:opacity-50 disabled:cursor-not-allowed",(u.trim()||m.length>0)&&!e?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground"),title:a&&!i?"请先选择AI模型":"Send message",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"})})}),s&&l.jsx("input",{ref:y,type:"file",multiple:!0,accept:o.join(","),onChange:A,className:"hidden"})]}),g&&s&&l.jsx("div",{className:"absolute inset-0 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("svg",{className:"w-8 h-8 mx-auto text-primary mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"})}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to attach"})]})})]})},Za=({className:r="w-5 h-5"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),ei=({className:r="w-5 h-5"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z"})}),ti=({className:r="w-4 h-4"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"})}),ri=({className:r="w-4 h-4"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),Zu=({className:r="w-4 h-4"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),ef=({className:r="w-4 h-4"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),ni=({className:r="w-5 h-5"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})}),tf=r=>{const e=new Date;let t;if(!r)return"时间未知";if(typeof r=="string"){const s=r.replace(" ","T")+"Z";t=new Date(s),isNaN(t.getTime())&&(t=new Date(r))}else t=r;if(!t||isNaN(t.getTime()))return"时间未知";const n=Math.floor((e.getTime()-t.getTime())/1e3);return n<60?"刚刚":n<3600?`${Math.floor(n/60)}分钟前`:n<86400?`${Math.floor(n/3600)}小时前`:n<2592e3?`${Math.floor(n/86400)}天前`:t.toLocaleDateString("zh-CN")},ms=({onClose:r})=>{const e=Rc(),t=Pc(),n=Pe(),{createSession:s,selectSession:o,deleteSession:a,updateSession:i}=n,[d,c]=M.useState(null),[u,f]=M.useState(""),m=async()=>{try{await s(),r==null||r()}catch(x){console.error("Failed to create session:",x)}},b=async x=>{try{await o(x),r==null||r()}catch(v){console.error("Failed to select session:",v)}},g=async x=>{if(window.confirm("确定要删除这个会话吗?此操作无法撤销。"))try{await a(x)}catch(v){console.error("Failed to delete session:",v)}},h=(x,v)=>{c(x),f(v)},p=async()=>{if(d&&u.trim())try{await i(d,{title:u.trim()}),c(null),f("")}catch(x){console.error("Failed to update session:",x)}},y=()=>{c(null),f("")},w=x=>{x.key==="Enter"?p():x.key==="Escape"&&y()};return l.jsxs("div",{className:"flex flex-col h-full bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[l.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:"会话列表"}),l.jsx("button",{onClick:m,className:"p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"新建会话",children:l.jsx(Za,{className:"w-5 h-5"})})]}),l.jsx("div",{className:"flex-1 overflow-y-auto",children:e.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500 dark:text-gray-400",children:[l.jsx(ni,{className:"w-12 h-12 mb-4 opacity-50"}),l.jsx("p",{className:"text-sm",children:"还没有会话"}),l.jsx("button",{onClick:m,className:"mt-2 px-4 py-2 text-sm bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors",children:"创建第一个会话"})]}):l.jsx("div",{className:"p-2 space-y-1",children:e.map(x=>l.jsxs("div",{className:`group relative flex items-center p-3 rounded-lg cursor-pointer transition-colors ${(t==null?void 0:t.id)===x.id?"bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800":"hover:bg-gray-50 dark:hover:bg-gray-800"}`,onClick:()=>b(x.id),children:[l.jsx("div",{className:"flex-1 min-w-0",children:d===x.id?l.jsx("input",{type:"text",value:u,onChange:v=>f(v.target.value),onBlur:p,onKeyDown:w,className:"w-full px-2 py-1 text-sm bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-2 focus:ring-blue-500",autoFocus:!0,onClick:v=>v.stopPropagation()}):l.jsxs(l.Fragment,{children:[l.jsx("h3",{className:"text-sm font-medium text-gray-900 dark:text-white truncate",children:x.title}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:tf(x.updatedAt)})]})}),d!==x.id&&l.jsxs("div",{className:"relative",children:[l.jsx("button",{className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 opacity-0 group-hover:opacity-100 transition-opacity",onClick:v=>{v.stopPropagation();const S=v.currentTarget.nextElementSibling;S&&S.classList.toggle("hidden")},children:l.jsx(ei,{className:"w-4 h-4"})}),l.jsx("div",{className:"hidden absolute right-0 z-10 mt-1 w-32 bg-white dark:bg-gray-800 rounded-md shadow-lg ring-1 ring-black ring-opacity-5",children:l.jsxs("div",{className:"py-1",children:[l.jsxs("button",{onClick:v=>{v.stopPropagation(),h(x.id,x.title);const S=v.currentTarget.closest(".absolute");S&&S.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700",children:[l.jsx(ti,{className:"w-4 h-4 mr-2"}),"重命名"]}),l.jsxs("button",{onClick:v=>{v.stopPropagation(),g(x.id);const S=v.currentTarget.closest(".absolute");S&&S.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20",children:[l.jsx(ri,{className:"w-4 h-4 mr-2"}),"删除"]})]})})]})]},x.id))})})]})},si=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",No=r=>r==="system"?si():r,bn=r=>{if(typeof window>"u")return;const e=window.document.documentElement;e.classList.remove("light","dark"),e.classList.add(r);const t=document.querySelector('meta[name="theme-color"]');t&&t.setAttribute("content",r==="dark"?"#0f172a":"#ffffff")},Oo=()=>typeof window>"u"?"system":localStorage.getItem("theme")||"system",rf=r=>{typeof window>"u"||localStorage.setItem("theme",r)},oi=()=>{const[r,e]=M.useState(()=>Oo()),[t,n]=M.useState(()=>No(Oo())),s=a=>{e(a),rf(a);const i=No(a);n(i),bn(i)},o=()=>{let a;switch(r){case"light":a="dark";break;case"dark":a="system";break;case"system":a="light";break;default:a="system"}s(a)};return M.useEffect(()=>{if(r!=="system")return;const a=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>{const d=si();n(d),bn(d)};return a.addEventListener("change",i),()=>a.removeEventListener("change",i)},[r]),M.useEffect(()=>{bn(t)},[t]),{theme:r,actualTheme:t,setTheme:s,toggleTheme:o}},gs=({className:r=""})=>{const{theme:e,toggleTheme:t}=oi(),n=()=>{switch(e){case"light":return l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"})});case"dark":return l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"})});case"system":return l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})});default:return null}},s=()=>{switch(e){case"light":return"Light mode";case"dark":return"Dark mode";case"system":return"System theme";default:return"Toggle theme"}};return l.jsx("button",{onClick:t,className:`p-2 hover:bg-muted rounded-lg transition-colors ${r}`,title:s(),"aria-label":s(),children:n()})},Po=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"})}),nf=()=>l.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),sf=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),of=()=>l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),af=()=>l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})}),ps=({onClose:r})=>{const{mcpConfigs:e,updateMcpConfig:t,deleteMcpConfig:n,loadMcpConfigs:s}=Pe(),[o,a]=M.useState(!1),[i,d]=M.useState(null),[c,u]=M.useState({name:"",serverUrl:"",enabled:!0});M.useEffect(()=>{s()},[s]);const f=()=>{u({name:"",serverUrl:"",enabled:!0}),d(null),a(!1)},m=async y=>{if(y.preventDefault(),!c.name.trim()||!c.serverUrl.trim())return;const w={id:Date.now().toString(),name:c.name.trim(),serverUrl:c.serverUrl.trim(),enabled:c.enabled,createdAt:new Date,updatedAt:new Date};await t(w),f()},b=async y=>{if(y.preventDefault(),!i||!c.name.trim()||!c.serverUrl.trim())return;const w={...i,name:c.name.trim(),serverUrl:c.serverUrl.trim(),enabled:c.enabled,updatedAt:new Date};await t(w),f()},g=y=>{d(y),u({name:y.name,serverUrl:y.serverUrl,enabled:y.enabled}),a(!0)},h=async y=>{confirm("确定要删除这个MCP服务器配置吗?")&&await n(y)},p=async y=>{const w={...y,enabled:!y.enabled,updatedAt:new Date};await t(w)};return l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx(Po,{}),l.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"MCP 服务器管理"})]}),l.jsx("button",{onClick:r,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:l.jsx(nf,{})})]}),l.jsxs("div",{className:"p-6 overflow-y-auto max-h-[calc(80vh-120px)]",children:[!o&&l.jsxs("button",{onClick:()=>a(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg hover:border-blue-500 dark:hover:border-blue-400 transition-colors flex items-center justify-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400",children:[l.jsx(sf,{}),l.jsx("span",{children:"添加 MCP 服务器"})]}),o&&l.jsxs("form",{onSubmit:i?b:m,className:"mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-white mb-4",children:i?"编辑服务器":"添加新服务器"}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"服务器名称"}),l.jsx("input",{type:"text",value:c.name,onChange:y=>u({...c,name:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: File System",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"服务器URL"}),l.jsx("input",{type:"url",value:c.serverUrl,onChange:y=>u({...c,serverUrl:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: http://localhost:3001",required:!0})]}),l.jsxs("div",{className:"flex items-center",children:[l.jsx("input",{type:"checkbox",id:"enabled",checked:c.enabled,onChange:y=>u({...c,enabled:y.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),l.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-gray-700 dark:text-gray-300",children:"启用此服务器"})]})]}),l.jsxs("div",{className:"flex space-x-3 mt-6",children:[l.jsx("button",{type:"submit",className:"px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500",children:i?"更新":"添加"}),l.jsx("button",{type:"button",onClick:f,className:"px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-400 dark:hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-500",children:"取消"})]})]}),l.jsx("div",{className:"space-y-3",children:e.length===0?l.jsxs("div",{className:"text-center py-8 text-gray-500 dark:text-gray-400",children:[l.jsx(Po,{}),l.jsx("p",{className:"mt-2",children:"暂无 MCP 服务器配置"}),l.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个服务器"})]}):e.map(y=>l.jsxs("div",{className:"flex items-center justify-between p-4 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx("div",{className:`w-3 h-3 rounded-full ${y.enabled?"bg-green-500":"bg-gray-400"}`}),l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium text-gray-900 dark:text-white",children:y.name}),l.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:y.serverUrl})]})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx("button",{onClick:()=>p(y),className:`px-3 py-1 text-xs rounded-full ${y.enabled?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-gray-100 text-gray-800 dark:bg-gray-600 dark:text-gray-200"}`,children:y.enabled?"已启用":"已禁用"}),l.jsx("button",{onClick:()=>g(y),className:"p-2 text-gray-500 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400 transition-colors",title:"编辑",children:l.jsx(af,{})}),l.jsx("button",{onClick:()=>h(y.id),className:"p-2 text-gray-500 hover:text-red-600 dark:text-gray-400 dark:hover:text-red-400 transition-colors",title:"删除",children:l.jsx(of,{})})]})]},y.id))})]})]})})},Ro=()=>l.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})}),lf=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),cf=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),df=()=>l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})}),uf=()=>l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),ys=({onClose:r})=>{const{aiModelConfigs:e,loadAiModelConfigs:t,updateAiModelConfig:n,deleteAiModelConfig:s}=Pe(),[o,a]=M.useState(!1),[i,d]=M.useState(null),[c,u]=M.useState({name:"",base_url:"",api_key:"",model_name:"",enabled:!0});M.useEffect(()=>{t()},[t]);const f=()=>{u({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),d(null),a(!1)},m=async y=>{if(y.preventDefault(),!c.name.trim()||!c.base_url.trim()||!c.api_key.trim()||!c.model_name.trim())return;const w={id:Math.random().toString(36).substr(2,9),name:c.name.trim(),base_url:c.base_url.trim(),api_key:c.api_key.trim(),model_name:c.model_name.trim(),enabled:c.enabled,createdAt:new Date,updatedAt:new Date};await n(w),f()},b=async y=>{if(y.preventDefault(),!i||!c.name.trim()||!c.base_url.trim()||!c.api_key.trim()||!c.model_name.trim())return;const w={...i,name:c.name.trim(),base_url:c.base_url.trim(),api_key:c.api_key.trim(),model_name:c.model_name.trim(),enabled:c.enabled,updatedAt:new Date};await n(w),f()},g=y=>{d(y),u({name:y.name,base_url:y.base_url,api_key:y.api_key,model_name:y.model_name,enabled:y.enabled}),a(!0)},h=async y=>{confirm("确定要删除这个AI模型配置吗?")&&await s(y)},p=async y=>{const w={...y,enabled:!y.enabled,updatedAt:new Date};await n(w)};return l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx(Ro,{}),l.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"AI 模型管理"})]}),l.jsx("button",{onClick:r,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:l.jsx(lf,{})})]}),l.jsxs("div",{className:"p-6 overflow-y-auto max-h-[calc(80vh-120px)]",children:[!o&&l.jsxs("button",{onClick:()=>a(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg hover:border-blue-500 dark:hover:border-blue-400 transition-colors flex items-center justify-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400",children:[l.jsx(cf,{}),l.jsx("span",{children:"添加 AI 模型"})]}),o&&l.jsxs("form",{onSubmit:i?b:m,className:"mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-white mb-4",children:i?"编辑 AI 模型":"添加 AI 模型"}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"配置名称"}),l.jsx("input",{type:"text",value:c.name,onChange:y=>u({...c,name:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: OpenAI GPT-4",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Base URL"}),l.jsx("input",{type:"url",value:c.base_url,onChange:y=>u({...c,base_url:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: https://api.openai.com/v1",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"API Key"}),l.jsx("input",{type:"password",value:c.api_key,onChange:y=>u({...c,api_key:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"输入API密钥",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"模型名称"}),l.jsx("input",{type:"text",value:c.model_name,onChange:y=>u({...c,model_name:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: gpt-4",required:!0})]}),l.jsxs("div",{className:"flex items-center",children:[l.jsx("input",{type:"checkbox",id:"enabled",checked:c.enabled,onChange:y=>u({...c,enabled:y.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),l.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-gray-700 dark:text-gray-300",children:"启用此模型"})]})]}),l.jsxs("div",{className:"flex space-x-3 mt-6",children:[l.jsx("button",{type:"submit",className:"px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500",children:i?"更新":"添加"}),l.jsx("button",{type:"button",onClick:f,className:"px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-400 dark:hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-500",children:"取消"})]})]}),l.jsx("div",{className:"space-y-3",children:e.length===0?l.jsxs("div",{className:"text-center py-8 text-gray-500 dark:text-gray-400",children:[l.jsx(Ro,{}),l.jsx("p",{className:"mt-2",children:"暂无 AI 模型配置"}),l.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个模型"})]}):e.map(y=>l.jsxs("div",{className:"flex items-center justify-between p-4 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg hover:shadow-md transition-shadow",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx("div",{className:`w-3 h-3 rounded-full ${y.enabled?"bg-green-500":"bg-gray-400"}`}),l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium text-gray-900 dark:text-white",children:y.name}),l.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:[y.base_url," - ",y.model_name]})]})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx("button",{onClick:()=>p(y),className:`px-3 py-1 text-xs rounded-full transition-colors ${y.enabled?"bg-green-100 text-green-800 hover:bg-green-200 dark:bg-green-900 dark:text-green-200":"bg-gray-100 text-gray-800 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-200"}`,children:y.enabled?"已启用":"已禁用"}),l.jsx("button",{onClick:()=>g(y),className:"p-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded transition-colors",title:"编辑",children:l.jsx(df,{})}),l.jsx("button",{onClick:()=>h(y.id),className:"p-2 text-gray-500 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded transition-colors",title:"删除",children:l.jsx(uf,{})})]})]},y.id))})]})]})})},ff=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})}),hf=()=>l.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),mf=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"})}),bs=({onClose:r})=>{const{systemContext:e,updateSystemContext:t,loadSystemContext:n}=Pe(),[s,o]=M.useState(""),[a,i]=M.useState(!1),[d,c]=M.useState(!1);M.useEffect(()=>{(async()=>{console.log("SystemContextEditor: Starting to load system context"),i(!0);try{await n(),console.log("SystemContextEditor: System context loaded successfully")}catch(b){console.error("SystemContextEditor: Failed to load system context:",b)}finally{i(!1)}})()},[]),M.useEffect(()=>{o(e||"")},[e]);const u=async()=>{c(!0);try{await t(s),r==null||r()}catch(m){console.error("Failed to save system context:",m),alert("保存失败,请重试")}finally{c(!1)}},f=m=>{m.ctrlKey&&m.key==="s"&&(m.preventDefault(),u())};return l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx(ff,{}),l.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"系统上下文设置"})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsxs("button",{onClick:u,disabled:d,className:"flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[l.jsx(mf,{}),l.jsx("span",{children:d?"保存中...":"保存"})]}),l.jsx("button",{onClick:r,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:l.jsx(hf,{})})]})]}),l.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[l.jsxs("div",{className:"mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:[l.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:[l.jsx("strong",{children:"系统上下文"}),"将作为每次对话的系统提示词,支持 Markdown 格式。 您可以在这里设置 AI 的角色、行为规范、回答风格等。"]}),l.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300 mt-2",children:"提示:使用 Ctrl+S 快速保存"})]}),l.jsxs("div",{className:"flex-1 flex flex-col",children:[l.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300",children:"Markdown 内容"}),l.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:[s.length," 字符"]})]}),a?l.jsx("div",{className:"flex-1 flex items-center justify-center bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-300 dark:border-gray-600",children:l.jsx("div",{className:"text-gray-500 dark:text-gray-400",children:"加载中..."})}):l.jsx("textarea",{value:s,onChange:m=>o(m.target.value),onKeyDown:f,className:"flex-1 w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white resize-none font-mono text-sm",placeholder:"请输入系统上下文内容,支持 Markdown 格式...\\n\\n例如:\\n# AI 助手角色设定\\n\\n你是一个专业的编程助手,具有以下特点:\\n- 提供准确、简洁的代码解决方案\\n- 遵循最佳实践和代码规范\\n- 耐心解答技术问题\\n\\n## 回答风格\\n- 使用中文回答\\n- 代码示例要完整可运行\\n- 提供必要的解释说明",spellCheck:!1})]}),l.jsxs("div",{className:"mt-4 text-xs text-gray-500 dark:text-gray-400",children:[l.jsx("p",{children:"• 支持标准 Markdown 语法:标题、列表、代码块、链接等"}),l.jsx("p",{children:"• 内容将在每次对话开始时自动发送给 AI"}),l.jsx("p",{children:"• 留空则使用默认系统提示词"})]})]})]})})},ai=({className:r,apiBaseUrl:e,port:t})=>{const n=M.useMemo(()=>{if(e)return e;if(t)return`http://localhost:${t}/api`},[e,t]),s=M.useMemo(()=>{if(n)return new Ta(n)},[n]),a=M.useMemo(()=>s?Tc(s):null,[s])||Pe,{currentSession:i,messages:d,isLoading:c,isStreaming:u,error:f,loadSessions:m,sendMessage:b,clearError:g,aiModelConfigs:h,selectedModelId:p,setSelectedModel:y,loadAiModelConfigs:w}=a(),x=M.useRef(null),[v,S]=M.useState(!1),[A,k]=M.useState(!1),[$,j]=M.useState(!1),[T,P]=M.useState(!1);M.useEffect(()=>{m(),w()},[m,w]),M.useEffect(()=>{x.current&&x.current.scrollIntoView({behavior:"smooth"})},[d,u]);const C=async(F,U)=>{try{await b(F,U)}catch(G){console.error("Failed to send message:",G)}};return l.jsxs("div",{className:se("flex flex-col h-screen bg-background text-foreground",r),children:[l.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx("button",{onClick:()=>S(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),i&&l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:i.title})})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx("button",{onClick:()=>k(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP 服务器管理",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"})})}),l.jsx("button",{onClick:()=>j(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI 模型管理",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})})}),l.jsx("button",{onClick:()=>P(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"系统上下文设置",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})}),l.jsx(gs,{})]})]}),f&&l.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("p",{className:"text-sm text-destructive",children:f}),l.jsx("button",{onClick:g,className:"text-destructive hover:text-destructive/80 transition-colors",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),l.jsxs("div",{className:"flex-1 overflow-hidden",children:[i?l.jsx(fs,{messages:d,isLoading:c,isStreaming:u}):l.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:l.jsxs("div",{className:"text-center",children:[l.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 opacity-50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})}),l.jsx("p",{className:"text-lg mb-2",children:"欢迎使用AI聊天助手"}),l.jsx("p",{className:"text-sm",children:"点击左上角按钮创建新会话开始对话"})]})}),l.jsx("div",{ref:x})]}),i&&l.jsx(hs,{onSend:C,disabled:c||u,selectedModelId:p,availableModels:h,onModelChange:y,showModelSelector:!0}),v&&l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-card border border-border rounded-lg w-full max-w-md mx-4 max-h-[80vh] overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[l.jsx("h2",{className:"text-lg font-semibold",children:"会话列表"}),l.jsx("button",{onClick:()=>S(!1),className:"p-1 text-muted-foreground hover:text-foreground hover:bg-accent rounded transition-colors",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),l.jsx("div",{className:"overflow-y-auto max-h-[60vh]",children:l.jsx(ms,{onClose:()=>S(!1)})})]})}),A&&l.jsx(ps,{onClose:()=>k(!1)}),$&&l.jsx(ys,{onClose:()=>j(!1)}),T&&l.jsx(bs,{onClose:()=>P(!1)})]})},gf=({className:r,onMessageSend:e,customRenderer:t})=>{const{currentSession:n,messages:s,isLoading:o,isStreaming:a,error:i,loadSessions:d,sendMessage:c,clearError:u,aiModelConfigs:f,selectedModelId:m,setSelectedModel:b,loadAiModelConfigs:g}=Pe(),h=M.useRef(null),[p,y]=M.useState(!1),[w,x]=M.useState(!1),[v,S]=M.useState(!1),[A,k]=M.useState(!1);M.useEffect(()=>{d(),g()},[d,g]),M.useEffect(()=>{h.current&&h.current.scrollIntoView({behavior:"smooth"})},[s,a]);const $=async(j,T)=>{try{await c(j,T),e==null||e(j,[])}catch(P){console.error("Failed to send message:",P)}};return l.jsxs("div",{className:se("flex flex-col h-screen bg-background text-foreground",r),children:[l.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx("button",{onClick:()=>y(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),n&&l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:n.title})})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx("button",{onClick:()=>x(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP 服务器管理",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"})})}),l.jsx("button",{onClick:()=>S(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI 模型管理",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})})}),l.jsx("button",{onClick:()=>k(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"系统上下文设置",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})}),l.jsx(gs,{})]})]}),i&&l.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("p",{className:"text-sm text-destructive",children:i}),l.jsx("button",{onClick:u,className:"text-destructive hover:text-destructive/80 transition-colors",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),l.jsxs("div",{className:"flex-1 overflow-hidden",children:[n?l.jsx(fs,{messages:s,isLoading:o,isStreaming:a,customRenderer:t}):l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsxs("div",{className:"text-center",children:[l.jsx("h2",{className:"text-xl font-semibold text-muted-foreground mb-2",children:"欢迎使用 AI 聊天"}),l.jsx("p",{className:"text-muted-foreground mb-4",children:"点击左上角按钮选择会话,或创建新的会话开始对话"}),l.jsx("button",{onClick:()=>y(!0),className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"打开会话列表"})]})}),l.jsx("div",{ref:h})]}),n&&l.jsx("div",{className:"border-t border-border",children:l.jsx(hs,{onSend:$,disabled:o||a,placeholder:"输入消息...",showModelSelector:!0,selectedModelId:m,availableModels:f,onModelChange:b})}),p&&l.jsxs("div",{className:"fixed inset-0 z-50 overflow-y-auto",children:[l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-25 transition-opacity",onClick:()=>y(!1)}),l.jsx("div",{className:"flex min-h-full items-center justify-center p-4",children:l.jsxs("div",{className:"w-full max-w-md transform overflow-hidden rounded-2xl bg-card shadow-xl transition-all",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[l.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"会话管理"}),l.jsx("button",{onClick:()=>y(!1),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]}),l.jsx("div",{className:"h-96",children:l.jsx(ms,{onClose:()=>y(!1)})})]})})]}),w&&l.jsx(ps,{onClose:()=>x(!1)}),v&&l.jsx(ys,{onClose:()=>S(!1)}),A&&l.jsx(bs,{onClose:()=>k(!1)})]})};class pf extends M.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("ErrorBoundary caught an error:",e,t)}render(){var e;return this.state.hasError?this.props.fallback?this.props.fallback:l.jsx("div",{className:"flex items-center justify-center h-full p-8",children:l.jsxs("div",{className:"text-center space-y-4",children:[l.jsx("div",{className:"w-16 h-16 mx-auto bg-destructive/10 rounded-full flex items-center justify-center",children:l.jsx("svg",{className:"w-8 h-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"})})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Something went wrong"}),l.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),l.jsx("button",{onClick:()=>this.setState({hasError:!1,error:void 0}),className:"mt-4 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"Try again"})]})]})}):this.props.children}}const yf="http://localhost:3001/api",Mt=async(r,e={})=>{try{const t=await fetch(`${yf}${r}`,{headers:{"Content-Type":"application/json",...e.headers},...e});if(!t.ok){let n=`HTTP error! status: ${t.status}`;try{const s=await t.json();n=s.error||s.message||n}catch{}throw new Error(n)}return t.json()}catch(t){throw t instanceof TypeError&&t.message.includes("fetch")?new Error("网络连接失败,请检查网络连接或服务器状态"):t}},ct={async getDetails(r){try{const e=await Mt(`/sessions/${r}`);return{data:{conversation:{id:e.id,title:e.title,created_at:e.created_at,updated_at:e.updated_at}}}}catch(e){return console.error("Failed to get conversation details:",e),{data:{conversation:{id:r,title:"Default Conversation",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}}}}},async getAssistant(r){try{const e=await Mt("/ai-model-configs"),t=e.find(n=>n.enabled)||e[0];if(!t)throw new Error("No AI model configuration found");return{data:{assistant:{id:t.id,name:t.name,model_config:{model_name:t.model_name,temperature:.7,max_tokens:4e3,api_key:t.api_key,base_url:t.base_url}}}}}catch(e){return console.error("Failed to get assistant:",e),{data:{assistant:{id:"default-assistant",name:"AI Assistant",model_config:{model_name:"gpt-3.5-turbo",temperature:.7,max_tokens:4e3,api_key:"",base_url:"https://api.openai.com/v1"}}}}}},async getMcpServers(r){try{return{data:{mcp_servers:(await Mt("/mcp-configs")).filter(n=>n.enabled).map(n=>({name:n.name,url:n.command}))}}}catch(e){return console.error("Failed to get MCP servers:",e),{data:{mcp_servers:[]}}}},async saveMessage(r,e){try{const t=e.id||`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{data:{message:await Mt("/messages",{method:"POST",body:JSON.stringify({id:t,sessionId:r,role:e.role,content:e.content,toolCalls:e.tool_calls||null,toolCallId:e.tool_call_id||null,reasoning:e.reasoning||null,metadata:e.metadata||null})})}}}catch(t){return console.error("Failed to save message:",t),{data:{message:{...e,id:Date.now().toString(),created_at:new Date().toISOString()}}}}},async getMessages(r,e={}){try{return{data:{messages:await Mt(`/sessions/${r}/messages`)}}}catch(t){return console.error("Failed to get messages:",t),{data:{messages:[]}}}},async addMessage(r,e){return this.saveMessage(r,e)}},To=Object.freeze(Object.defineProperty({__proto__:null,conversationsApi:ct},Symbol.toStringTag,{value:"Module"})),zn="RFC3986",qn={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},bf="RFC1738",wf=Array.isArray,Se=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),wn=1024,xf=(r,e,t,n,s)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<o.length;i+=wn){const d=o.length>=wn?o.slice(i,i+wn):o,c=[];for(let u=0;u<d.length;++u){let f=d.charCodeAt(u);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||s===bf&&(f===40||f===41)){c[c.length]=d.charAt(u);continue}if(f<128){c[c.length]=Se[f];continue}if(f<2048){c[c.length]=Se[192|f>>6]+Se[128|f&63];continue}if(f<55296||f>=57344){c[c.length]=Se[224|f>>12]+Se[128|f>>6&63]+Se[128|f&63];continue}u+=1,f=65536+((f&1023)<<10|d.charCodeAt(u)&1023),c[c.length]=Se[240|f>>18]+Se[128|f>>12&63]+Se[128|f>>6&63]+Se[128|f&63]}a+=c.join("")}return a};function _f(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Io(r,e){if(wf(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const vf=Object.prototype.hasOwnProperty,ii={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},ke=Array.isArray,Sf=Array.prototype.push,li=function(r,e){Sf.apply(r,ke(e)?e:[e])},Cf=Date.prototype.toISOString,Y={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:xf,encodeValuesOnly:!1,format:zn,formatter:qn[zn],indices:!1,serializeDate(r){return Cf.call(r)},skipNulls:!1,strictNullHandling:!1};function kf(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const xn={};function ci(r,e,t,n,s,o,a,i,d,c,u,f,m,b,g,h,p,y){let w=r,x=y,v=0,S=!1;for(;(x=x.get(xn))!==void 0&&!S;){const T=x.get(r);if(v+=1,typeof T<"u"){if(T===v)throw new RangeError("Cyclic object value");S=!0}typeof x.get(xn)>"u"&&(v=0)}if(typeof c=="function"?w=c(e,w):w instanceof Date?w=m==null?void 0:m(w):t==="comma"&&ke(w)&&(w=Io(w,function(T){return T instanceof Date?m==null?void 0:m(T):T})),w===null){if(o)return d&&!h?d(e,Y.encoder,p,"key",b):e;w=""}if(kf(w)||_f(w)){if(d){const T=h?e:d(e,Y.encoder,p,"key",b);return[(g==null?void 0:g(T))+"="+(g==null?void 0:g(d(w,Y.encoder,p,"value",b)))]}return[(g==null?void 0:g(e))+"="+(g==null?void 0:g(String(w)))]}const A=[];if(typeof w>"u")return A;let k;if(t==="comma"&&ke(w))h&&d&&(w=Io(w,d)),k=[{value:w.length>0?w.join(",")||null:void 0}];else if(ke(c))k=c;else{const T=Object.keys(w);k=u?T.sort(u):T}const $=i?String(e).replace(/\./g,"%2E"):String(e),j=n&&ke(w)&&w.length===1?$+"[]":$;if(s&&ke(w)&&w.length===0)return j+"[]";for(let T=0;T<k.length;++T){const P=k[T],C=typeof P=="object"&&typeof P.value<"u"?P.value:w[P];if(a&&C===null)continue;const F=f&&i?P.replace(/\./g,"%2E"):P,U=ke(w)?typeof t=="function"?t(j,F):j:j+(f?"."+F:"["+F+"]");y.set(r,v);const G=new WeakMap;G.set(xn,y),li(A,ci(C,U,t,n,s,o,a,i,t==="comma"&&h&&ke(w)?null:d,c,u,f,m,b,g,h,p,G))}return A}function Af(r=Y){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=r.charset||Y.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=zn;if(typeof r.format<"u"){if(!vf.call(qn,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=qn[t];let s=Y.filter;(typeof r.filter=="function"||ke(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in ii?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=Y.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Y.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Y.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Y.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Y.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Y.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Y.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Y.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Y.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Y.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Y.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Y.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Y.strictNullHandling}}function Ef(r,e={}){let t=r;const n=Af(e);let s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):ke(n.filter)&&(o=n.filter,s=o);const a=[];if(typeof t!="object"||t===null)return"";const i=ii[n.arrayFormat],d=i==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const c=new WeakMap;for(let m=0;m<s.length;++m){const b=s[m];n.skipNulls&&t[b]===null||li(a,ci(t[b],b,i,d,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}const u=a.join(n.delimiter);let f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),u.length>0?f+u:""}const it="4.104.0";let Lo=!1,Lt,di,ui,Vn,fi,hi,mi,gi,pi;function Mf(r,e={auto:!1}){if(Lo)throw new Error(`you must \`import 'openai/shims/${r.kind}'\` before importing anything else from openai`);if(Lt)throw new Error(`can't \`import 'openai/shims/${r.kind}'\` after \`import 'openai/shims/${Lt}'\``);Lo=e.auto,Lt=r.kind,di=r.fetch,ui=r.FormData,Vn=r.File,fi=r.ReadableStream,hi=r.getMultipartRequestOptions,mi=r.getDefaultAgent,gi=r.fileFromPath,pi=r.isFsReadStream}class jf{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function Nf({manuallyImported:r}={}){const e=r?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let t,n,s,o;try{t=fetch,n=Request,s=Response,o=Headers}catch(a){throw new Error(`this environment is missing the following Web Fetch API type: ${a.message}. ${e}`)}return{kind:"web",fetch:t,Request:n,Response:s,Headers:o,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(a,i)=>({...i,body:new jf(a)}),getDefaultAgent:a=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:a=>!1}}const yi=()=>{Lt||Mf(Nf(),{auto:!0})};yi();class N extends Error{}class oe extends N{constructor(e,t,n,s){super(`${oe.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s==null?void 0:s["x-request-id"],this.error=t;const o=t;this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(e,t,n){const s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new zr({message:n,cause:Gn(t)});const o=t==null?void 0:t.error;return e===400?new bi(e,o,n,s):e===401?new wi(e,o,n,s):e===403?new xi(e,o,n,s):e===404?new _i(e,o,n,s):e===409?new vi(e,o,n,s):e===422?new Si(e,o,n,s):e===429?new Ci(e,o,n,s):e>=500?new ki(e,o,n,s):new oe(e,o,n,s)}}class be extends oe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class zr extends oe{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ws extends zr{constructor({message:e}={}){super({message:e??"Request timed out."})}}class bi extends oe{}class wi extends oe{}class xi extends oe{}class _i extends oe{}class vi extends oe{}class Si extends oe{}class Ci extends oe{}class ki extends oe{}class Ai extends N{constructor(){super("Could not parse response content as the length limit was reached")}}class Ei extends N{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var cr=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},He=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},he;class qr{constructor(){he.set(this,void 0),this.buffer=new Uint8Array,cr(this,he,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e;let n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;const s=[];let o;for(;(o=Of(this.buffer,He(this,he,"f")))!=null;){if(o.carriage&&He(this,he,"f")==null){cr(this,he,o.index,"f");continue}if(He(this,he,"f")!=null&&(o.index!==He(this,he,"f")+1||o.carriage)){s.push(this.decodeText(this.buffer.slice(0,He(this,he,"f")-1))),this.buffer=this.buffer.slice(He(this,he,"f")),cr(this,he,null,"f");continue}const a=He(this,he,"f")!==null?o.preceding-1:o.preceding,i=this.decodeText(this.buffer.slice(0,a));s.push(i),this.buffer=this.buffer.slice(o.index),cr(this,he,null,"f")}return s}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new N(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new N(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new N("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
34
+ `):[]}}he=new WeakMap;qr.NEWLINE_CHARS=new Set([`
35
+ `,"\r"]);qr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Of(r,e){for(let s=e??0;s<r.length;s++){if(r[s]===10)return{preceding:s,index:s+1,carriage:!1};if(r[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Pf(r){for(let n=0;n<r.length-1;n++){if(r[n]===10&&r[n+1]===10||r[n]===13&&r[n+1]===13)return n+2;if(r[n]===13&&r[n+1]===10&&n+3<r.length&&r[n+2]===13&&r[n+3]===10)return n+4}return-1}function Mi(r){if(r[Symbol.asyncIterator])return r;const e=r.getReader();return{async next(){try{const t=await e.read();return t!=null&&t.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}class Ee{constructor(e,t){this.iterator=e,this.controller=t}static fromSSEResponse(e,t){let n=!1;async function*s(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(const a of Rf(e,t))if(!o){if(a.data.startsWith("[DONE]")){o=!0;continue}if(a.event===null||a.event.startsWith("response.")||a.event.startsWith("transcript.")){let i;try{i=JSON.parse(a.data)}catch(d){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),d}if(i&&i.error)throw new oe(void 0,i.error,void 0,Ii(e.headers));yield i}else{let i;try{i=JSON.parse(a.data)}catch(d){throw console.error("Could not parse message into JSON:",a.data),console.error("From chunk:",a.raw),d}if(a.event=="error")throw new oe(void 0,i.error,i.message,void 0);yield{event:a.event,data:i}}}o=!0}catch(a){if(a instanceof Error&&a.name==="AbortError")return;throw a}finally{o||t.abort()}}return new Ee(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){const a=new qr,i=Mi(e);for await(const d of i)for(const c of a.decode(d))yield c;for(const d of a.flush())yield d}async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let a=!1;try{for await(const i of s())a||i&&(yield JSON.parse(i));a=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{a||t.abort()}}return new Ee(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){const a=n.next();e.push(a),t.push(a)}return o.shift()}});return[new Ee(()=>s(e),this.controller),new Ee(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new fi({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:o,done:a}=await t.next();if(a)return s.close();const i=n.encode(JSON.stringify(o)+`
36
+ `);s.enqueue(i)}catch(o){s.error(o)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}}async function*Rf(r,e){if(!r.body)throw e.abort(),new N("Attempted to iterate over a response with no body");const t=new If,n=new qr,s=Mi(r.body);for await(const o of Tf(s))for(const a of n.decode(o)){const i=t.decode(a);i&&(yield i)}for(const o of n.flush()){const a=t.decode(o);a&&(yield a)}}async function*Tf(r){let e=new Uint8Array;for await(const t of r){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t;let s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=Pf(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}class If{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
37
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=Lf(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function Lf(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}const ji=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Ni=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Vr(r),Vr=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Df=r=>Ni(r)||ji(r)||pi(r);async function Oi(r,e,t){var s;if(r=await r,Ni(r))return r;if(ji(r)){const o=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");const a=Vr(o)?[await o.arrayBuffer()]:[o];return new Vn(a,e,t)}const n=await Ff(r);if(e||(e=Bf(r)??"unknown_file"),!(t!=null&&t.type)){const o=(s=n[0])==null?void 0:s.type;typeof o=="string"&&(t={...t,type:o})}return new Vn(n,e,t)}async function Ff(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Vr(r))e.push(await r.arrayBuffer());else if(Uf(r))for await(const n of r)e.push(n);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${(t=r==null?void 0:r.constructor)==null?void 0:t.name}; props: ${$f(r)}`);return e}function $f(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Bf(r){var e;return _n(r.name)||_n(r.filename)||((e=_n(r.path))==null?void 0:e.split(/[\\/]/).pop())}const _n=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Uf=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Do=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody",Ze=async r=>{const e=await Wf(r.body);return hi(e,r)},Wf=async r=>{const e=new ui;return await Promise.all(Object.entries(r||{}).map(([t,n])=>Jn(e,t,n))),e},Jn=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(Df(t)){const n=await Oi(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>Jn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>Jn(r,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Hf=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},zf=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},dr;yi();async function Pi(r){var a;const{response:e}=r;if(r.options.stream)return Be("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):Ee.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;const t=e.headers.get("content-type"),n=(a=t==null?void 0:t.split(";")[0])==null?void 0:a.trim();if((n==null?void 0:n.includes("application/json"))||(n==null?void 0:n.endsWith("+json"))){const i=await e.json();return Be("response",e.status,e.url,e.headers,i),Ri(i,e)}const o=await e.text();return Be("response",e.status,e.url,e.headers,o),o}function Ri(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}class Jr extends Promise{constructor(e,t=Pi){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new Jr(this.responsePromise,async t=>Ri(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class qf{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:o}){this.baseURL=e,this.maxRetries=vn("maxRetries",t),this.timeout=vn("timeout",n),this.httpAgent=s,this.fetch=o??di}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Yf(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${eh()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async s=>{const o=s&&Vr(s==null?void 0:s.body)?new DataView(await s.body.arrayBuffer()):(s==null?void 0:s.body)instanceof DataView?s.body:(s==null?void 0:s.body)instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s==null?void 0:s.body)?new DataView(s.body.buffer):s==null?void 0:s.body;return{method:e,path:t,...s,body:o}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){var h;const n={...e},{method:s,path:o,query:a,headers:i={}}=n,d=ArrayBuffer.isView(n.body)||n.__binaryRequest&&typeof n.body=="string"?n.body:Do(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,c=this.calculateContentLength(d),u=this.buildURL(o,a);"timeout"in n&&vn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const f=n.httpAgent??this.httpAgent??mi(u),m=n.timeout+1e3;typeof((h=f==null?void 0:f.options)==null?void 0:h.timeout)=="number"&&m>(f.options.timeout??0)&&(f.options.timeout=m),this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const b=this.buildHeaders({options:n,headers:i,contentLength:c,retryCount:t});return{req:{method:s,...d&&{body:d},headers:b,...f&&{agent:f},signal:n.signal??null},url:u,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const o={};n&&(o["content-length"]=n);const a=this.defaultHeaders(e);return Uo(o,a),Uo(o,t),Do(e.body)&&Lt!=="node"&&delete o["content-type"],fr(a,"x-stainless-retry-count")===void 0&&fr(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(s)),fr(a,"x-stainless-timeout")===void 0&&fr(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(o,t),o}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,s){return oe.generate(e,t,n,s)}request(e,t=null){return new Jr(this.makeRequest(e,t))}async makeRequest(e,t){var f,m;const n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);const{req:o,url:a,timeout:i}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(o,{url:a,options:n}),Be("request",a,n,o.headers),(f=n.signal)!=null&&f.aborted)throw new be;const d=new AbortController,c=await this.fetchWithTimeout(a,o,i,d).catch(Gn);if(c instanceof Error){if((m=n.signal)!=null&&m.aborted)throw new be;if(t)return this.retryRequest(n,t);throw c.name==="AbortError"?new ws:new zr({cause:c})}const u=Ii(c.headers);if(!c.ok){if(t&&this.shouldRetry(c)){const w=`retrying, ${t} attempts remaining`;return Be(`response (error; ${w})`,c.status,a,u),this.retryRequest(n,t,u)}const b=await c.text().catch(w=>Gn(w).message),g=Kf(b),h=g?void 0:b;throw Be(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,c.status,a,u,h),this.makeStatusError(c.status,g,h,u)}return{response:c,options:n,controller:d}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new Vf(this,n,e)}buildURL(e,t){const n=Zf(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Li(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new N(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){const{signal:o,...a}=t||{};o&&o.addEventListener("abort",()=>s.abort());const i=setTimeout(()=>s.abort(),n),d={signal:s.signal,...a};return d.method&&(d.method=d.method.toUpperCase()),this.fetch.call(void 0,e,d).finally(()=>{clearTimeout(i)})}shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n){let s;const o=n==null?void 0:n["retry-after-ms"];if(o){const i=parseFloat(o);Number.isNaN(i)||(s=i)}const a=n==null?void 0:n["retry-after"];if(a&&!s){const i=parseFloat(a);Number.isNaN(i)?s=Date.parse(a)-Date.now():s=i*1e3}if(!(s&&0<=s&&s<60*1e3)){const i=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,i)}return await Vt(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const o=t-e,a=Math.min(.5*Math.pow(2,o),8),i=1-Math.random()*.25;return a*i*1e3}getUserAgent(){return`${this.constructor.name}/JS ${it}`}}class Ti{constructor(e,t,n,s){dr.set(this,void 0),Hf(this,dr,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new N("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[s,o]of n)e.url.searchParams.set(s,o);t.query=void 0,t.path=e.url.toString()}return await zf(this,dr,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(dr=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Vf extends Jr{constructor(e,t,n){super(t,async s=>new n(e,s.response,await Pi(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const Ii=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),Jf={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},V=r=>typeof r=="object"&&r!==null&&!Li(r)&&Object.keys(r).every(e=>Di(Jf,e)),Gf=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":$o(Deno.build.os),"X-Stainless-Arch":Fo(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((e=Deno.version)==null?void 0:e.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":$o(process.platform),"X-Stainless-Arch":Fo(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const r=Xf();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Xf(){if(typeof navigator>"u"||!navigator)return null;const r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of r){const n=t.exec(navigator.userAgent);if(n){const s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:e,version:`${s}.${o}.${a}`}}}return null}const Fo=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",$o=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown");let Bo;const Yf=()=>Bo??(Bo=Gf()),Kf=r=>{try{return JSON.parse(r)}catch{return}},Qf=/^[a-z][a-z0-9+.-]*:/i,Zf=r=>Qf.test(r),Vt=r=>new Promise(e=>setTimeout(e,r)),vn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new N(`${r} must be an integer`);if(e<0)throw new N(`${r} must be a positive integer`);return e},Gn=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(r)},ur=r=>{var e,t,n,s,o;if(typeof process<"u")return((t=(e=process.env)==null?void 0:e[r])==null?void 0:t.trim())??void 0;if(typeof Deno<"u")return(o=(s=(n=Deno.env)==null?void 0:n.get)==null?void 0:s.call(n,r))==null?void 0:o.trim()};function Li(r){if(!r)return!0;for(const e in r)return!1;return!0}function Di(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Uo(r,e){for(const t in e){if(!Di(e,t))continue;const n=t.toLowerCase();if(!n)continue;const s=e[t];s===null?delete r[n]:s!==void 0&&(r[n]=s)}}const Wo=new Set(["authorization","api-key"]);function Be(r,...e){var t;if(typeof process<"u"&&((t=process==null?void 0:process.env)==null?void 0:t.DEBUG)==="true"){const n=e.map(s=>{if(!s)return s;if(s.headers){const a={...s,headers:{...s.headers}};for(const i in s.headers)Wo.has(i.toLowerCase())&&(a.headers[i]="REDACTED");return a}let o=null;for(const a in s)Wo.has(a.toLowerCase())&&(o??(o={...s}),o[a]="REDACTED");return o??s});console.log(`OpenAI:DEBUG:${r}`,...n)}}const eh=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),th=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",rh=r=>typeof(r==null?void 0:r.get)=="function",fr=(r,e)=>{var n;const t=e.toLowerCase();if(rh(r)){const s=((n=e[0])==null?void 0:n.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(o,a,i)=>a+i.toUpperCase());for(const o of[e,t,e.toUpperCase(),s]){const a=r.get(o);if(a)return a}}for(const[s,o]of Object.entries(r))if(s.toLowerCase()===t)return Array.isArray(o)?(o.length<=1||console.warn(`Received ${o.length} entries for the ${e} header, using the first entry.`),o[0]):o},nh=r=>{if(typeof Buffer<"u"){const e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};function Sn(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}class Gr extends Ti{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class K extends Ti{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){var n;const e=this.getPaginatedItems();if(!e.length)return null;const t=(n=e[e.length-1])==null?void 0:n.id;return t?{params:{after:t}}:null}}class O{constructor(e){this._client=e}}let Fi=class extends O{list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,sh,{query:t,...n})}},Xr=class extends O{constructor(){super(...arguments),this.messages=new Fi(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/chat/completions",Yr,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class Yr extends K{}class sh extends K{}Xr.ChatCompletionsPage=Yr;Xr.Messages=Fi;let Kr=class extends O{constructor(){super(...arguments),this.completions=new Xr(this._client)}};Kr.Completions=Xr;Kr.ChatCompletionsPage=Yr;class $i extends O{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t==null?void 0:t.headers},__binaryResponse:!0})}}class Bi extends O{create(e,t){return this._client.post("/audio/transcriptions",Ze({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Ui extends O{create(e,t){return this._client.post("/audio/translations",Ze({body:e,...t,__metadata:{model:e.model}}))}}class Jt extends O{constructor(){super(...arguments),this.transcriptions=new Bi(this._client),this.translations=new Ui(this._client),this.speech=new $i(this._client)}}Jt.Transcriptions=Bi;Jt.Translations=Ui;Jt.Speech=$i;class xs extends O{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/batches",_s,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class _s extends K{}xs.BatchesPage=_s;var we=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},z=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Xn,xr,_r,Nt,Ot,vr,Pt,Ne,Rt,Ir,Lr,lt,Wi;class vs{constructor(){Xn.add(this),this.controller=new AbortController,xr.set(this,void 0),_r.set(this,()=>{}),Nt.set(this,()=>{}),Ot.set(this,void 0),vr.set(this,()=>{}),Pt.set(this,()=>{}),Ne.set(this,{}),Rt.set(this,!1),Ir.set(this,!1),Lr.set(this,!1),lt.set(this,!1),we(this,xr,new Promise((e,t)=>{we(this,_r,e,"f"),we(this,Nt,t,"f")}),"f"),we(this,Ot,new Promise((e,t)=>{we(this,vr,e,"f"),we(this,Pt,t,"f")}),"f"),z(this,xr,"f").catch(()=>{}),z(this,Ot,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},z(this,Xn,"m",Wi).bind(this))},0)}_connected(){this.ended||(z(this,_r,"f").call(this),this._emit("connect"))}get ended(){return z(this,Rt,"f")}get errored(){return z(this,Ir,"f")}get aborted(){return z(this,Lr,"f")}abort(){this.controller.abort()}on(e,t){return(z(this,Ne,"f")[e]||(z(this,Ne,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=z(this,Ne,"f")[e];if(!n)return this;const s=n.findIndex(o=>o.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(z(this,Ne,"f")[e]||(z(this,Ne,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{we(this,lt,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){we(this,lt,!0,"f"),await z(this,Ot,"f")}_emit(e,...t){if(z(this,Rt,"f"))return;e==="end"&&(we(this,Rt,!0,"f"),z(this,vr,"f").call(this));const n=z(this,Ne,"f")[e];if(n&&(z(this,Ne,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!z(this,lt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),z(this,Nt,"f").call(this,s),z(this,Pt,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!z(this,lt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),z(this,Nt,"f").call(this,s),z(this,Pt,"f").call(this,s),this._emit("end")}}_emitFinal(){}}xr=new WeakMap,_r=new WeakMap,Nt=new WeakMap,Ot=new WeakMap,vr=new WeakMap,Pt=new WeakMap,Ne=new WeakMap,Rt=new WeakMap,Ir=new WeakMap,Lr=new WeakMap,lt=new WeakMap,Xn=new WeakSet,Wi=function(e){if(we(this,Ir,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new be),e instanceof be)return we(this,Lr,!0,"f"),this._emit("abort",e);if(e instanceof N)return this._emit("error",e);if(e instanceof Error){const t=new N(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new N(String(e)))};var E=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},fe=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},ne,Yn,Ae,Sr,xe,Ge,dt,Ve,Dr,me,Cr,kr,Dt,Tt,It,Ho,zo,qo,Vo,Jo,Go,Xo;class _e extends vs{constructor(){super(...arguments),ne.add(this),Yn.set(this,[]),Ae.set(this,{}),Sr.set(this,{}),xe.set(this,void 0),Ge.set(this,void 0),dt.set(this,void 0),Ve.set(this,void 0),Dr.set(this,void 0),me.set(this,void 0),Cr.set(this,void 0),kr.set(this,void 0),Dt.set(this,void 0)}[(Yn=new WeakMap,Ae=new WeakMap,Sr=new WeakMap,xe=new WeakMap,Ge=new WeakMap,dt=new WeakMap,Ve=new WeakMap,Dr=new WeakMap,me=new WeakMap,Cr=new WeakMap,kr=new WeakMap,Dt=new WeakMap,ne=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new _e;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var o;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Ee.fromReadableStream(e,this.controller);for await(const a of s)E(this,ne,"m",Tt).call(this,a);if((o=s.controller.signal)!=null&&o.aborted)throw new be;return this._addRun(E(this,ne,"m",It).call(this))}toReadableStream(){return new Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,o){const a=new _e;return a._run(()=>a._runToolAssistantStream(e,t,n,s,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,s,o){var c;const a=o==null?void 0:o.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},d=await e.submitToolOutputs(t,n,i,{...o,signal:this.controller.signal});this._connected();for await(const u of d)E(this,ne,"m",Tt).call(this,u);if((c=d.controller.signal)!=null&&c.aborted)throw new be;return this._addRun(E(this,ne,"m",It).call(this))}static createThreadAssistantStream(e,t,n){const s=new _e;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){const o=new _e;return o._run(()=>o._runAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return E(this,Cr,"f")}currentRun(){return E(this,kr,"f")}currentMessageSnapshot(){return E(this,xe,"f")}currentRunStepSnapshot(){return E(this,Dt,"f")}async finalRunSteps(){return await this.done(),Object.values(E(this,Ae,"f"))}async finalMessages(){return await this.done(),Object.values(E(this,Sr,"f"))}async finalRun(){if(await this.done(),!E(this,Ge,"f"))throw Error("Final run was not received.");return E(this,Ge,"f")}async _createThreadAssistantStream(e,t,n){var i;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const o={...t,stream:!0},a=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(const d of a)E(this,ne,"m",Tt).call(this,d);if((i=a.controller.signal)!=null&&i.aborted)throw new be;return this._addRun(E(this,ne,"m",It).call(this))}async _createAssistantStream(e,t,n,s){var d;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await e.create(t,a,{...s,signal:this.controller.signal});this._connected();for await(const c of i)E(this,ne,"m",Tt).call(this,c);if((d=i.controller.signal)!=null&&d.aborted)throw new be;return this._addRun(E(this,ne,"m",It).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let o=e[n];if(o==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Sn(o)&&Sn(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...s);continue}for(const a of s){if(!Sn(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const i=a.index;if(i==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof i!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${i}`);const d=o[i];d==null?o.push(a):o[i]=this.accumulateDelta(d,a)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,o){return await this._createToolAssistantStream(n,e,t,s,o)}}Tt=function(e){if(!this.ended)switch(fe(this,Cr,e,"f"),E(this,ne,"m",qo).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":E(this,ne,"m",Xo).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":E(this,ne,"m",zo).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":E(this,ne,"m",Ho).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},It=function(){if(this.ended)throw new N("stream has ended, this shouldn't happen");if(!E(this,Ge,"f"))throw Error("Final run has not been received");return E(this,Ge,"f")},Ho=function(e){const[t,n]=E(this,ne,"m",Jo).call(this,e,E(this,xe,"f"));fe(this,xe,t,"f"),E(this,Sr,"f")[t.id]=t;for(const s of n){const o=t.content[s.index];(o==null?void 0:o.type)=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,a=t.content[s.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=E(this,dt,"f")){if(E(this,Ve,"f"))switch(E(this,Ve,"f").type){case"text":this._emit("textDone",E(this,Ve,"f").text,E(this,xe,"f"));break;case"image_file":this._emit("imageFileDone",E(this,Ve,"f").image_file,E(this,xe,"f"));break}fe(this,dt,s.index,"f")}fe(this,Ve,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(E(this,dt,"f")!==void 0){const s=e.data.content[E(this,dt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,E(this,xe,"f"));break;case"text":this._emit("textDone",s.text,E(this,xe,"f"));break}}E(this,xe,"f")&&this._emit("messageDone",e.data),fe(this,xe,void 0,"f")}},zo=function(e){const t=E(this,ne,"m",Vo).call(this,e);switch(fe(this,Dt,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const o of n.step_details.tool_calls)o.index==E(this,Dr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(E(this,me,"f")&&this._emit("toolCallDone",E(this,me,"f")),fe(this,Dr,o.index,"f"),fe(this,me,t.step_details.tool_calls[o.index],"f"),E(this,me,"f")&&this._emit("toolCallCreated",E(this,me,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":fe(this,Dt,void 0,"f"),e.data.step_details.type=="tool_calls"&&E(this,me,"f")&&(this._emit("toolCallDone",E(this,me,"f")),fe(this,me,void 0,"f")),this._emit("runStepDone",e.data,t);break}},qo=function(e){E(this,Yn,"f").push(e),this._emit("event",e)},Vo=function(e){switch(e.event){case"thread.run.step.created":return E(this,Ae,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=E(this,Ae,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=_e.accumulateDelta(t,n.delta);E(this,Ae,"f")[e.data.id]=s}return E(this,Ae,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":E(this,Ae,"f")[e.data.id]=e.data;break}if(E(this,Ae,"f")[e.data.id])return E(this,Ae,"f")[e.data.id];throw new Error("No snapshot available")},Jo=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const o of s.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=E(this,ne,"m",Go).call(this,o,a)}else t.content[o.index]=o,n.push(o);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Go=function(e,t){return _e.accumulateDelta(t,e)},Xo=function(e){switch(fe(this,kr,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":fe(this,Ge,e.data,"f"),E(this,me,"f")&&(this._emit("toolCallDone",E(this,me,"f")),fe(this,me,void 0,"f"));break}};class Ss extends O{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/assistants",Cs,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Cs extends K{}Ss.AssistantsPage=Cs;function Yo(r){return typeof r.parse=="function"}const ft=r=>(r==null?void 0:r.role)==="assistant",Hi=r=>(r==null?void 0:r.role)==="function",zi=r=>(r==null?void 0:r.role)==="tool";function ks(r){return(r==null?void 0:r.$brand)==="auto-parseable-response-format"}function Gt(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function oh(r,e){return!e||!qi(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:As(r,e)}function As(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new Ai;if(n.finish_reason==="content_filter")throw new Ei;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(o=>ih(e,o)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?ah(e,n.message.content):null}}});return{...r,choices:t}}function ah(r,e){var t,n;return((t=r.response_format)==null?void 0:t.type)!=="json_schema"?null:((n=r.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function ih(r,e){var n;const t=(n=r.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Gt(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function lh(r,e){var n;if(!r)return!1;const t=(n=r.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return Gt(t)||(t==null?void 0:t.function.strict)||!1}function qi(r){var e;return ks(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>Gt(t)||t.type==="function"&&t.function.strict===!0))??!1}function ch(r){for(const e of r??[]){if(e.type!=="function")throw new N(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new N(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var le=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},ae,Kn,Fr,Qn,Zn,es,Vi,ts;const Ko=10;class Ji extends vs{constructor(){super(...arguments),ae.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(n=e.choices[0])==null?void 0:n.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(Hi(e)||zi(e))&&e.content)this._emit("functionCallResult",e.content);else if(ft(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(ft(e)&&e.tool_calls)for(const n of e.tool_calls)n.type==="function"&&this._emit("functionCall",n.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new N("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),le(this,ae,"m",Kn).call(this)}async finalMessage(){return await this.done(),le(this,ae,"m",Fr).call(this)}async finalFunctionCall(){return await this.done(),le(this,ae,"m",Qn).call(this)}async finalFunctionCallResult(){return await this.done(),le(this,ae,"m",Zn).call(this)}async totalUsage(){return await this.done(),le(this,ae,"m",es).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=le(this,ae,"m",Fr).call(this);t&&this._emit("finalMessage",t);const n=le(this,ae,"m",Kn).call(this);n&&this._emit("finalContent",n);const s=le(this,ae,"m",Qn).call(this);s&&this._emit("finalFunctionCall",s);const o=le(this,ae,"m",Zn).call(this);o!=null&&this._emit("finalFunctionCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",le(this,ae,"m",es).call(this))}async _createChatCompletion(e,t,n){const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),le(this,ae,"m",Vi).call(this,t);const o=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(As(o,t))}async _runChatCompletion(e,t,n){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){var m;const s="function",{function_call:o="auto",stream:a,...i}=t,d=typeof o!="string"&&(o==null?void 0:o.name),{maxChatCompletions:c=Ko}=n||{},u={};for(const b of t.functions)u[b.name||b.function.name]=b;const f=t.functions.map(b=>({name:b.name||b.function.name,parameters:b.parameters,description:b.description}));for(const b of t.messages)this._addMessage(b,!1);for(let b=0;b<c;++b){const h=(m=(await this._createChatCompletion(e,{...i,function_call:o,functions:f,messages:[...this.messages]},n)).choices[0])==null?void 0:m.message;if(!h)throw new N("missing message in ChatCompletion response");if(!h.function_call)return;const{name:p,arguments:y}=h.function_call,w=u[p];if(w){if(d&&d!==p){const A=`Invalid function_call: ${JSON.stringify(p)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,name:p,content:A});continue}}else{const A=`Invalid function_call: ${JSON.stringify(p)}. Available options are: ${f.map(k=>JSON.stringify(k.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:p,content:A});continue}let x;try{x=Yo(w)?await w.parse(y):y}catch(A){this._addMessage({role:s,name:p,content:A instanceof Error?A.message:String(A)});continue}const v=await w.function(x,this),S=le(this,ae,"m",ts).call(this,v);if(this._addMessage({role:s,name:p,content:S}),d)return}}async _runTools(e,t,n){var b,g,h;const s="tool",{tool_choice:o="auto",stream:a,...i}=t,d=typeof o!="string"&&((b=o==null?void 0:o.function)==null?void 0:b.name),{maxChatCompletions:c=Ko}=n||{},u=t.tools.map(p=>{if(Gt(p)){if(!p.$callback)throw new N("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:p.$callback,name:p.function.name,description:p.function.description||"",parameters:p.function.parameters,parse:p.$parseRaw,strict:!0}}}return p}),f={};for(const p of u)p.type==="function"&&(f[p.function.name||p.function.function.name]=p.function);const m="tools"in t?u.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description,strict:p.function.strict}}:p):void 0;for(const p of t.messages)this._addMessage(p,!1);for(let p=0;p<c;++p){const w=(g=(await this._createChatCompletion(e,{...i,tool_choice:o,tools:m,messages:[...this.messages]},n)).choices[0])==null?void 0:g.message;if(!w)throw new N("missing message in ChatCompletion response");if(!((h=w.tool_calls)!=null&&h.length))return;for(const x of w.tool_calls){if(x.type!=="function")continue;const v=x.id,{name:S,arguments:A}=x.function,k=f[S];if(k){if(d&&d!==S){const P=`Invalid tool_call: ${JSON.stringify(S)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,tool_call_id:v,content:P});continue}}else{const P=`Invalid tool_call: ${JSON.stringify(S)}. Available options are: ${Object.keys(f).map(C=>JSON.stringify(C)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:v,content:P});continue}let $;try{$=Yo(k)?await k.parse(A):A}catch(P){const C=P instanceof Error?P.message:String(P);this._addMessage({role:s,tool_call_id:v,content:C});continue}const j=await k.function($,this),T=le(this,ae,"m",ts).call(this,j);if(this._addMessage({role:s,tool_call_id:v,content:T}),d)return}}}}ae=new WeakSet,Kn=function(){return le(this,ae,"m",Fr).call(this).content??null},Fr=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(ft(t)){const{function_call:n,...s}=t,o={...s,content:t.content??null,refusal:t.refusal??null};return n&&(o.function_call=n),o}}throw new N("stream ended without producing a ChatCompletionMessage with role=assistant")},Qn=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const s=this.messages[n];if(ft(s)&&(s!=null&&s.function_call))return s.function_call;if(ft(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},Zn=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Hi(t)&&t.content!=null||zi(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>{var s;return n.role==="assistant"&&((s=n.tool_calls)==null?void 0:s.some(o=>o.type==="function"&&o.id===t.tool_call_id))}))return t.content}},es=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Vi=function(e){if(e.n!=null&&e.n>1)throw new N("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ts=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Wt extends Ji{static runFunctions(e,t,n){const s=new Wt,o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,o)),s}static runTools(e,t,n){const s=new Wt,o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),ft(e)&&e.content&&this._emit("content",e.content)}}const Gi=1,Xi=2,Yi=4,Ki=8,Qi=16,Zi=32,el=64,tl=128,rl=256,nl=tl|rl,sl=Qi|Zi|nl|el,ol=Gi|Xi|sl,al=Yi|Ki,dh=ol|al,Z={STR:Gi,NUM:Xi,ARR:Yi,OBJ:Ki,NULL:Qi,BOOL:Zi,NAN:el,INFINITY:tl,MINUS_INFINITY:rl,INF:nl,SPECIAL:sl,ATOM:ol,COLLECTION:al,ALL:dh};class uh extends Error{}class fh extends Error{}function hh(r,e=Z.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return mh(r.trim(),e)}const mh=(r,e)=>{const t=r.length;let n=0;const s=m=>{throw new uh(`${m} at position ${n}`)},o=m=>{throw new fh(`${m} at position ${n}`)},a=()=>(f(),n>=t&&s("Unexpected end of input"),r[n]==='"'?i():r[n]==="{"?d():r[n]==="["?c():r.substring(n,n+4)==="null"||Z.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||Z.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||Z.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||Z.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||Z.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||Z.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):u()),i=()=>{const m=n;let b=!1;for(n++;n<t&&(r[n]!=='"'||b&&r[n-1]==="\\");)b=r[n]==="\\"?!b:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(m,++n-Number(b)))}catch(g){o(String(g))}else if(Z.STR&e)try{return JSON.parse(r.substring(m,n-Number(b))+'"')}catch{return JSON.parse(r.substring(m,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},d=()=>{n++,f();const m={};try{for(;r[n]!=="}";){if(f(),n>=t&&Z.OBJ&e)return m;const b=i();f(),n++;try{const g=a();Object.defineProperty(m,b,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(Z.OBJ&e)return m;throw g}f(),r[n]===","&&n++}}catch{if(Z.OBJ&e)return m;s("Expected '}' at end of object")}return n++,m},c=()=>{n++;const m=[];try{for(;r[n]!=="]";)m.push(a()),f(),r[n]===","&&n++}catch{if(Z.ARR&e)return m;s("Expected ']' at end of array")}return n++,m},u=()=>{if(n===0){r==="-"&&Z.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(b){if(Z.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(b))}}const m=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(Z.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(m,n))}catch{r.substring(m,n)==="-"&&Z.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(m,r.lastIndexOf("e")))}catch(g){o(String(g))}}},f=()=>{for(;n<t&&`
38
+ \r `.includes(r[n]);)n++};return a()},Qo=r=>hh(r,Z.ALL^Z.NUM);var nt=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},W=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},X,je,st,De,Cn,hr,kn,An,En,mr,Mn,Zo;class Ht extends Ji{constructor(e){super(),X.add(this),je.set(this,void 0),st.set(this,void 0),De.set(this,void 0),nt(this,je,e,"f"),nt(this,st,[],"f")}get currentChatCompletionSnapshot(){return W(this,De,"f")}static fromReadableStream(e){const t=new Ht(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new Ht(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){var a;super._createChatCompletion;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),W(this,X,"m",Cn).call(this);const o=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const i of o)W(this,X,"m",kn).call(this,i);if((a=o.controller.signal)!=null&&a.aborted)throw new be;return this._addChatCompletion(W(this,X,"m",mr).call(this))}async _fromReadableStream(e,t){var a;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),W(this,X,"m",Cn).call(this),this._connected();const s=Ee.fromReadableStream(e,this.controller);let o;for await(const i of s)o&&o!==i.id&&this._addChatCompletion(W(this,X,"m",mr).call(this)),W(this,X,"m",kn).call(this,i),o=i.id;if((a=s.controller.signal)!=null&&a.aborted)throw new be;return this._addChatCompletion(W(this,X,"m",mr).call(this))}[(je=new WeakMap,st=new WeakMap,De=new WeakMap,X=new WeakSet,Cn=function(){this.ended||nt(this,De,void 0,"f")},hr=function(t){let n=W(this,st,"f")[t.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},W(this,st,"f")[t.index]=n,n)},kn=function(t){var s,o,a,i,d,c,u,f,m,b,g,h,p,y,w;if(this.ended)return;const n=W(this,X,"m",Zo).call(this,t);this._emit("chunk",t,n);for(const x of t.choices){const v=n.choices[x.index];x.delta.content!=null&&((s=v.message)==null?void 0:s.role)==="assistant"&&((o=v.message)!=null&&o.content)&&(this._emit("content",x.delta.content,v.message.content),this._emit("content.delta",{delta:x.delta.content,snapshot:v.message.content,parsed:v.message.parsed})),x.delta.refusal!=null&&((a=v.message)==null?void 0:a.role)==="assistant"&&((i=v.message)!=null&&i.refusal)&&this._emit("refusal.delta",{delta:x.delta.refusal,snapshot:v.message.refusal}),((d=x.logprobs)==null?void 0:d.content)!=null&&((c=v.message)==null?void 0:c.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(u=x.logprobs)==null?void 0:u.content,snapshot:((f=v.logprobs)==null?void 0:f.content)??[]}),((m=x.logprobs)==null?void 0:m.refusal)!=null&&((b=v.message)==null?void 0:b.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(g=x.logprobs)==null?void 0:g.refusal,snapshot:((h=v.logprobs)==null?void 0:h.refusal)??[]});const S=W(this,X,"m",hr).call(this,v);v.finish_reason&&(W(this,X,"m",En).call(this,v),S.current_tool_call_index!=null&&W(this,X,"m",An).call(this,v,S.current_tool_call_index));for(const A of x.delta.tool_calls??[])S.current_tool_call_index!==A.index&&(W(this,X,"m",En).call(this,v),S.current_tool_call_index!=null&&W(this,X,"m",An).call(this,v,S.current_tool_call_index)),S.current_tool_call_index=A.index;for(const A of x.delta.tool_calls??[]){const k=(p=v.message.tool_calls)==null?void 0:p[A.index];k!=null&&k.type&&((k==null?void 0:k.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(y=k.function)==null?void 0:y.name,index:A.index,arguments:k.function.arguments,parsed_arguments:k.function.parsed_arguments,arguments_delta:((w=A.function)==null?void 0:w.arguments)??""}):(k==null||k.type,void 0))}}},An=function(t,n){var a,i,d;if(W(this,X,"m",hr).call(this,t).done_tool_calls.has(n))return;const o=(a=t.message.tool_calls)==null?void 0:a[n];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){const c=(d=(i=W(this,je,"f"))==null?void 0:i.tools)==null?void 0:d.find(u=>u.type==="function"&&u.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:Gt(c)?c.$parseRaw(o.function.arguments):c!=null&&c.function.strict?JSON.parse(o.function.arguments):null})}else o.type},En=function(t){var s,o;const n=W(this,X,"m",hr).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const a=W(this,X,"m",Mn).call(this);this._emit("content.done",{content:t.message.content,parsed:a?a.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(s=t.logprobs)!=null&&s.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(o=t.logprobs)!=null&&o.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},mr=function(){if(this.ended)throw new N("stream has ended, this shouldn't happen");const t=W(this,De,"f");if(!t)throw new N("request ended without sending any chunks");return nt(this,De,void 0,"f"),nt(this,st,[],"f"),gh(t,W(this,je,"f"))},Mn=function(){var n;const t=(n=W(this,je,"f"))==null?void 0:n.response_format;return ks(t)?t:null},Zo=function(t){var n,s,o,a;let i=W(this,De,"f");const{choices:d,...c}=t;i?Object.assign(i,c):i=nt(this,De,{...c,choices:[]},"f");for(const{delta:u,finish_reason:f,index:m,logprobs:b=null,...g}of t.choices){let h=i.choices[m];if(h||(h=i.choices[m]={finish_reason:f,index:m,message:{},logprobs:b,...g}),b)if(!h.logprobs)h.logprobs=Object.assign({},b);else{const{content:A,refusal:k,...$}=b;Object.assign(h.logprobs,$),A&&((n=h.logprobs).content??(n.content=[]),h.logprobs.content.push(...A)),k&&((s=h.logprobs).refusal??(s.refusal=[]),h.logprobs.refusal.push(...k))}if(f&&(h.finish_reason=f,W(this,je,"f")&&qi(W(this,je,"f")))){if(f==="length")throw new Ai;if(f==="content_filter")throw new Ei}if(Object.assign(h,g),!u)continue;const{content:p,refusal:y,function_call:w,role:x,tool_calls:v,...S}=u;if(Object.assign(h.message,S),y&&(h.message.refusal=(h.message.refusal||"")+y),x&&(h.message.role=x),w&&(h.message.function_call?(w.name&&(h.message.function_call.name=w.name),w.arguments&&((o=h.message.function_call).arguments??(o.arguments=""),h.message.function_call.arguments+=w.arguments)):h.message.function_call=w),p&&(h.message.content=(h.message.content||"")+p,!h.message.refusal&&W(this,X,"m",Mn).call(this)&&(h.message.parsed=Qo(h.message.content))),v){h.message.tool_calls||(h.message.tool_calls=[]);for(const{index:A,id:k,type:$,function:j,...T}of v){const P=(a=h.message.tool_calls)[A]??(a[A]={});Object.assign(P,T),k&&(P.id=k),$&&(P.type=$),j&&(P.function??(P.function={name:j.name??"",arguments:""})),j!=null&&j.name&&(P.function.name=j.name),j!=null&&j.arguments&&(P.function.arguments+=j.arguments,lh(W(this,je,"f"),P)&&(P.function.parsed_arguments=Qo(P.function.arguments)))}}}return i},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",s=>{const o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function gh(r,e){const{id:t,choices:n,created:s,model:o,system_fingerprint:a,...i}=r,d={...i,id:t,choices:n.map(({message:c,finish_reason:u,index:f,logprobs:m,...b})=>{if(!u)throw new N(`missing finish_reason for choice ${f}`);const{content:g=null,function_call:h,tool_calls:p,...y}=c,w=c.role;if(!w)throw new N(`missing role for choice ${f}`);if(h){const{arguments:x,name:v}=h;if(x==null)throw new N(`missing function_call.arguments for choice ${f}`);if(!v)throw new N(`missing function_call.name for choice ${f}`);return{...b,message:{content:g,function_call:{arguments:x,name:v},role:w,refusal:c.refusal??null},finish_reason:u,index:f,logprobs:m}}return p?{...b,index:f,finish_reason:u,logprobs:m,message:{...y,role:w,content:g,refusal:c.refusal??null,tool_calls:p.map((x,v)=>{const{function:S,type:A,id:k,...$}=x,{arguments:j,name:T,...P}=S||{};if(k==null)throw new N(`missing choices[${f}].tool_calls[${v}].id
39
+ ${gr(r)}`);if(A==null)throw new N(`missing choices[${f}].tool_calls[${v}].type
40
+ ${gr(r)}`);if(T==null)throw new N(`missing choices[${f}].tool_calls[${v}].function.name
41
+ ${gr(r)}`);if(j==null)throw new N(`missing choices[${f}].tool_calls[${v}].function.arguments
42
+ ${gr(r)}`);return{...$,id:k,type:A,function:{...P,name:T,arguments:j}}})}}:{...b,message:{...y,content:g,role:w,refusal:c.refusal??null},finish_reason:u,index:f,logprobs:m}}),created:s,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return oh(d,e)}function gr(r){return JSON.stringify(r)}class ht extends Ht{static fromReadableStream(e){const t=new ht(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new ht(null),o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,o)),s}static runTools(e,t,n){const s=new ht(t),o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}}let il=class extends O{parse(e,t){return ch(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(n=>As(n,e))}runFunctions(e,t){return e.stream?ht.runFunctions(this._client,e,t):Wt.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?ht.runTools(this._client,e,t):Wt.runTools(this._client,e,t)}stream(e,t){return Ht.createChatCompletion(this._client,e,t)}};class rs extends O{constructor(){super(...arguments),this.completions=new il(this._client)}}(function(r){r.Completions=il})(rs||(rs={}));class ll extends O{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class cl extends O{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Qr extends O{constructor(){super(...arguments),this.sessions=new ll(this._client),this.transcriptionSessions=new cl(this._client)}}Qr.Sessions=ll;Qr.TranscriptionSessions=cl;class Es extends O{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Ms,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class Ms extends K{}Es.MessagesPage=Ms;class js extends O{retrieve(e,t,n,s={},o){return V(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...o,headers:{"OpenAI-Beta":"assistants=v2",...o==null?void 0:o.headers}})}list(e,t,n={},s){return V(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Ns,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}}class Ns extends K{}js.RunStepsPage=Ns;let Xt=class extends O{constructor(){super(...arguments),this.steps=new js(this._client)}create(e,t,n){const{include:s,...o}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Os,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}createAndStream(e,t,n){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:o,response:a}=await this.retrieve(e,t,{...n,headers:{...n==null?void 0:n.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(n!=null&&n.pollIntervalMs)i=n.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const c=parseInt(d);isNaN(c)||(i=c)}}await Vt(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,n){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const o=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,o.id,s)}submitToolOutputsStream(e,t,n,s){return _e.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class Os extends K{}Xt.RunsPage=Os;Xt.Steps=js;Xt.RunStepsPage=Ns;class bt extends O{constructor(){super(...arguments),this.runs=new Xt(this._client),this.messages=new Es(this._client)}create(e={},t){return V(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return _e.createThreadAssistantStream(e,this._client.beta.threads,t)}}bt.Runs=Xt;bt.RunsPage=Os;bt.Messages=Es;bt.MessagesPage=Ms;class wt extends O{constructor(){super(...arguments),this.realtime=new Qr(this._client),this.chat=new rs(this._client),this.assistants=new Ss(this._client),this.threads=new bt(this._client)}}wt.Realtime=Qr;wt.Assistants=Ss;wt.AssistantsPage=Cs;wt.Threads=bt;class dl extends O{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class ul extends O{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n==null?void 0:n.headers},__binaryResponse:!0})}}let Zr=class extends O{constructor(){super(...arguments),this.content=new ul(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,Ze({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Ps,{query:t,...n})}del(e,t,n){return this._client.delete(`/containers/${e}/files/${t}`,{...n,headers:{Accept:"*/*",...n==null?void 0:n.headers}})}};class Ps extends K{}Zr.FileListResponsesPage=Ps;Zr.Content=ul;class Yt extends O{constructor(){super(...arguments),this.files=new Zr(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/containers",Rs,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}}class Rs extends K{}Yt.ContainerListResponsesPage=Rs;Yt.Files=Zr;Yt.FileListResponsesPage=Ps;class fl extends O{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&Be("Request","User defined encoding_format:",e.encoding_format);const o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?o:(Be("response","Decoding base64 embeddings to float32 array"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{const d=i.embedding;i.embedding=nh(d)}),a)))}}class Ts extends O{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return V(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Is,{query:n,...s})}}class Is extends K{}Ts.OutputItemListResponsesPage=Is;class Kt extends O{constructor(){super(...arguments),this.outputItems=new Ts(this._client)}create(e,t,n){return this._client.post(`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){return this._client.get(`/evals/${e}/runs/${t}`,n)}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Ls,{query:t,...n})}del(e,t,n){return this._client.delete(`/evals/${e}/runs/${t}`,n)}cancel(e,t,n){return this._client.post(`/evals/${e}/runs/${t}`,n)}}class Ls extends K{}Kt.RunListResponsesPage=Ls;Kt.OutputItems=Ts;Kt.OutputItemListResponsesPage=Is;class Qt extends O{constructor(){super(...arguments),this.runs=new Kt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,n){return this._client.post(`/evals/${e}`,{body:t,...n})}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/evals",Ds,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class Ds extends K{}Qt.EvalListResponsesPage=Ds;Qt.Runs=Kt;Qt.RunListResponsesPage=Ls;let Fs=class extends O{create(e,t){return this._client.post("/files",Ze({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/files",$s,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t==null?void 0:t.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),o=Date.now();let a=await this.retrieve(e);for(;!a.status||!s.has(a.status);)if(await Vt(t),a=await this.retrieve(e),Date.now()-o>n)throw new ws({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};class $s extends K{}Fs.FileObjectsPage=$s;class hl extends O{}let ml=class extends O{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Bs extends O{constructor(){super(...arguments),this.graders=new ml(this._client)}}Bs.Graders=ml;class Us extends O{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Ws,{body:t,method:"post",...n})}retrieve(e,t={},n){return V(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}del(e,t,n){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,n)}}class Ws extends Gr{}Us.PermissionCreateResponsesPage=Ws;let en=class extends O{constructor(){super(...arguments),this.permissions=new Us(this._client)}};en.Permissions=Us;en.PermissionCreateResponsesPage=Ws;class Hs extends O{list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,zs,{query:t,...n})}}class zs extends K{}Hs.FineTuningJobCheckpointsPage=zs;class xt extends O{constructor(){super(...arguments),this.checkpoints=new Hs(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",qs,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return V(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Vs,{query:t,...n})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}}class qs extends K{}class Vs extends K{}xt.FineTuningJobsPage=qs;xt.FineTuningJobEventsPage=Vs;xt.Checkpoints=Hs;xt.FineTuningJobCheckpointsPage=zs;class Ue extends O{constructor(){super(...arguments),this.methods=new hl(this._client),this.jobs=new xt(this._client),this.checkpoints=new en(this._client),this.alpha=new Bs(this._client)}}Ue.Methods=hl;Ue.Jobs=xt;Ue.FineTuningJobsPage=qs;Ue.FineTuningJobEventsPage=Vs;Ue.Checkpoints=en;Ue.Alpha=Bs;class gl extends O{}class Js extends O{constructor(){super(...arguments),this.graderModels=new gl(this._client)}}Js.GraderModels=gl;class pl extends O{createVariation(e,t){return this._client.post("/images/variations",Ze({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",Ze({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Gs extends O{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Xs,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Xs extends Gr{}Gs.ModelsPage=Xs;class yl extends O{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function ph(r,e){return!e||!bh(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:bl(r,e)}function bl(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:_h(e,s)};if(s.type==="message"){const o=s.content.map(a=>a.type==="output_text"?{...a,parsed:yh(e,a.text)}:a);return{...s,content:o}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||wl(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const s of n.output)if(s.type==="message"){for(const o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function yh(r,e){var t,n,s,o;return((n=(t=r.text)==null?void 0:t.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((s=r.text)==null?void 0:s.format)?((o=r.text)==null?void 0:o.format).$parseRaw(e):JSON.parse(e)}function bh(r){var e;return!!ks((e=r.text)==null?void 0:e.format)}function wh(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function xh(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function _h(r,e){const t=xh(r.tools??[],e.name);return{...e,...e,parsed_arguments:wh(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function wl(r){const e=[];for(const t of r.output)if(t.type==="message")for(const n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}class xl extends O{list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Sh,{query:t,...n})}}var ot=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},Fe=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},at,pr,$e,yr,ea,ta,ra,na;class Ys extends vs{constructor(e){super(),at.add(this),pr.set(this,void 0),$e.set(this,void 0),yr.set(this,void 0),ot(this,pr,e,"f")}static createResponse(e,t,n){const s=new Ys(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){var i;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Fe(this,at,"m",ea).call(this);let o,a=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const d of o)Fe(this,at,"m",ta).call(this,d,a);if((i=o.controller.signal)!=null&&i.aborted)throw new be;return Fe(this,at,"m",ra).call(this)}[(pr=new WeakMap,$e=new WeakMap,yr=new WeakMap,at=new WeakSet,ea=function(){this.ended||ot(this,$e,void 0,"f")},ta=function(t,n){if(this.ended)return;const s=(a,i)=>{(n==null||i.sequence_number>n)&&this._emit(a,i)},o=Fe(this,at,"m",na).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const a=o.output[t.output_index];if(!a)throw new N(`missing output at index ${t.output_index}`);if(a.type==="message"){const i=a.content[t.content_index];if(!i)throw new N(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new N(`expected content to be 'output_text', got ${i.type}`);s("response.output_text.delta",{...t,snapshot:i.text})}break}case"response.function_call_arguments.delta":{const a=o.output[t.output_index];if(!a)throw new N(`missing output at index ${t.output_index}`);a.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:s(t.type,t);break}},ra=function(){if(this.ended)throw new N("stream has ended, this shouldn't happen");const t=Fe(this,$e,"f");if(!t)throw new N("request ended without sending any events");ot(this,$e,void 0,"f");const n=vh(t,Fe(this,pr,"f"));return ot(this,yr,n,"f"),n},na=function(t){let n=Fe(this,$e,"f");if(!n){if(t.type!=="response.created")throw new N(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=ot(this,$e,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{const s=n.output[t.output_index];if(!s)throw new N(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{const s=n.output[t.output_index];if(!s)throw new N(`missing output at index ${t.output_index}`);if(s.type==="message"){const o=s.content[t.content_index];if(!o)throw new N(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new N(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{const s=n.output[t.output_index];if(!s)throw new N(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{ot(this,$e,t.response,"f");break}}return n},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=Fe(this,yr,"f");if(!e)throw new N("stream ended without producing a ChatCompletion");return e}}function vh(r,e){return ph(r,e)}class Ks extends O{constructor(){super(...arguments),this.inputItems=new xl(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&wl(n),n))}retrieve(e,t={},n){return this._client.get(`/responses/${e}`,{query:t,...n,stream:(t==null?void 0:t.stream)??!1})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>bl(n,e))}stream(e,t){return Ys.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}}class Sh extends K{}Ks.InputItems=xl;class _l extends O{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,Ze({body:t,...n}))}}class Qs extends O{constructor(){super(...arguments),this.parts=new _l(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}Qs.Parts=_l;const Ch=async r=>{const e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length){for(const s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const n=[];for(const s of e)s.status==="fulfilled"&&n.push(s.value);return n};class tn extends O{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,rn,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const o=await this.retrieve(e,t,{...n,headers:s}).withResponse(),a=o.data;switch(a.status){case"in_progress":let i=5e3;if(n!=null&&n.pollIntervalMs)i=n.pollIntervalMs;else{const d=o.response.headers.get("openai-poll-after-ms");if(d){const c=parseInt(d);isNaN(c)||(i=c)}}await Vt(i);break;case"failed":case"completed":return a}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Zs,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class rn extends K{}class Zs extends Gr{}tn.VectorStoreFilesPage=rn;tn.FileContentResponsesPage=Zs;class vl extends O{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return V(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,rn,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:o,response:a}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(o.status){case"in_progress":let i=5e3;if(n!=null&&n.pollIntervalMs)i=n.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const c=parseInt(d);isNaN(c)||(i=c)}}await Vt(i);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const o=(s==null?void 0:s.maxConcurrency)??5,a=Math.min(o,t.length),i=this._client,d=t.values(),c=[...n];async function u(m){for(let b of m){const g=await i.files.create({file:b,purpose:"assistants"},s);c.push(g.id)}}const f=Array(a).fill(d).map(u);return await Ch(f),await this.createAndPoll(e,{file_ids:c})}}class We extends O{constructor(){super(...arguments),this.files=new tn(this._client),this.fileBatches=new vl(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/vector_stores",eo,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,to,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class eo extends K{}class to extends Gr{}We.VectorStoresPage=eo;We.VectorStoreSearchResponsesPage=to;We.Files=tn;We.VectorStoreFilesPage=rn;We.FileContentResponsesPage=Zs;We.FileBatches=vl;var Sl;class R extends qf{constructor({baseURL:e=ur("OPENAI_BASE_URL"),apiKey:t=ur("OPENAI_API_KEY"),organization:n=ur("OPENAI_ORG_ID")??null,project:s=ur("OPENAI_PROJECT_ID")??null,...o}={}){if(t===void 0)throw new N("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const a={apiKey:t,organization:n,project:s,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&th())throw new N(`It looks like you're running in a browser-like environment.
43
+
44
+ This is disabled by default, as it risks exposing your secret API credentials to attackers.
45
+ If you understand the risks and have appropriate mitigations in place,
46
+ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
47
+
48
+ new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
49
+
50
+ https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
51
+ `);super({baseURL:a.baseURL,timeout:a.timeout??6e5,httpAgent:a.httpAgent,maxRetries:a.maxRetries,fetch:a.fetch}),this.completions=new dl(this),this.chat=new Kr(this),this.embeddings=new fl(this),this.files=new Fs(this),this.images=new pl(this),this.audio=new Jt(this),this.moderations=new yl(this),this.models=new Gs(this),this.fineTuning=new Ue(this),this.graders=new Js(this),this.vectorStores=new We(this),this.beta=new wt(this),this.batches=new xs(this),this.uploads=new Qs(this),this.responses=new Ks(this),this.evals=new Qt(this),this.containers=new Yt(this),this._options=a,this.apiKey=t,this.organization=n,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Ef(e,{arrayFormat:"brackets"})}}Sl=R;R.OpenAI=Sl;R.DEFAULT_TIMEOUT=6e5;R.OpenAIError=N;R.APIError=oe;R.APIConnectionError=zr;R.APIConnectionTimeoutError=ws;R.APIUserAbortError=be;R.NotFoundError=_i;R.ConflictError=vi;R.RateLimitError=Ci;R.BadRequestError=bi;R.AuthenticationError=wi;R.InternalServerError=ki;R.PermissionDeniedError=xi;R.UnprocessableEntityError=Si;R.toFile=Oi;R.fileFromPath=gi;R.Completions=dl;R.Chat=Kr;R.ChatCompletionsPage=Yr;R.Embeddings=fl;R.Files=Fs;R.FileObjectsPage=$s;R.Images=pl;R.Audio=Jt;R.Moderations=yl;R.Models=Gs;R.ModelsPage=Xs;R.FineTuning=Ue;R.Graders=Js;R.VectorStores=We;R.VectorStoresPage=eo;R.VectorStoreSearchResponsesPage=to;R.Beta=wt;R.Batches=xs;R.BatchesPage=_s;R.Uploads=Qs;R.Responses=Ks;R.Evals=Qt;R.EvalListResponsesPage=Ds;R.Containers=Yt;R.ContainerListResponsesPage=Rs;class Cl{constructor(e,t,n,s,o){D(this,"messages");D(this,"tools");D(this,"callback");D(this,"modelConfig");D(this,"abortController");D(this,"isAborted");this.messages=e,this.tools=t,this.callback=s,this.modelConfig=o,this.abortController=new AbortController,this.isAborted=!1}async chatCompletion(){try{if(this.isAborted)throw new Error("Request was aborted");console.log("Using OpenAI package with base URL:",this.modelConfig.base_url),console.log("API Key:",this.modelConfig.api_key?"Present":"Missing");const e=new R({apiKey:this.modelConfig.api_key,baseURL:this.modelConfig.base_url,dangerouslyAllowBrowser:!0}),t=this.buildPayLoad(),n=await e.chat.completions.create({...t,stream:!0});return await this.handleOpenAIStreamResponse(n,this.callback),this.messages}catch(e){throw console.error("Chat completion failed:",e),console.error("Error type:",e.constructor.name),console.error("Error message:",e.message),console.error("Error stack:",e.stack),(e.message.includes("CORS")||e.message.includes("fetch"))&&console.error("This appears to be a CORS or network error. Check your base_url and API configuration."),this.callback&&this.callback("error",e),e}}async handleOpenAIStreamResponse(e,t){const n={role:"assistant",content:"",reasoning_content:"",tool_calls:[],model_info:{model:this.modelConfig.model_name,temperature:this.modelConfig.temperature,max_tokens:this.modelConfig.max_tokens},function_calls:[]};try{console.log("Starting to process OpenAI stream...");let s=0,o=null;for await(const a of e){if(this.isAborted){console.log("Stream processing aborted");break}if(s++,a.choices&&a.choices.length>0){const d=a.choices[0].delta;if(d&&(d.content&&(n.content+=d.content,t&&t("chunk",{type:"text",content:d.content})),d.reasoning_content&&(n.reasoning_content+=d.reasoning_content,t&&t("chunk",{type:"reasoning_content",content:d.reasoning_content,accumulated:n.reasoning_content})),d.tool_calls))for(const c of d.tool_calls){if(!c){console.warn("Invalid tool call:",c);continue}let u=c.index;for((u==null||typeof u!="number")&&(u=n.tool_calls.length,console.log(`Tool call index was ${c.index}, using ${u} instead`));n.tool_calls.length<=u;)n.tool_calls.push({id:"",type:"function",function:{name:"",arguments:""}});o=n.tool_calls[u],o.function||(o.function={name:"",arguments:""}),c.id&&c.id!==""?o.id=c.id:(!o.id||o.id==="")&&(o.id=`call_${Date.now()}_${u}`),c.function&&(c.function.name&&(o.function.name=c.function.name),c.function.arguments&&(o.function.arguments+=c.function.arguments))}}}console.log(`OpenAI stream completed. Processed ${s} chunks.`),n.tool_calls.length>0&&(n.function_calls=n.tool_calls.map(a=>({id:a.id,name:a.function.name,arguments:a.function.arguments}))),this.messages.push(n)}catch(s){throw console.error("Stream processing error:",s),t&&t("error",s),s}}buildPayLoad(){const e=this.convertToOpenAIFormat(this.messages),t={model:this.modelConfig.model_name||"gpt-3.5-turbo",messages:e,max_tokens:this.modelConfig.max_tokens||4e3};return this.tools&&this.tools.length>0&&(t.tools=this.tools),t}cleanHtmlContent(e){if(!e||typeof e!="string")return"";let t=e.replace(/<[^>]*>/g,"");return t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," ").replace(/\n[ \t]*/g,`
52
+ `).replace(/\n{3,}/g,`
53
+
54
+ `).trim(),t}convertToOpenAIFormat(e){return e.map(t=>{let n=t.content||t.message||"";t.role==="assistant"&&(n=this.cleanHtmlContent(n));const s={role:t.role,content:n};if(t.role==="assistant"&&(t.tool_calls||t.function_calls)){const o=t.tool_calls||t.function_calls||[];o.length>0&&(console.log("Converting tool calls for assistant message:",o),s.tool_calls=o.map(a=>{var f,m;const i=((f=a.function)==null?void 0:f.name)||a.name,d=((m=a.function)==null?void 0:m.arguments)||a.arguments;if(!i)return console.warn("Tool call missing function name:",a),null;let c;typeof d=="string"?c=d:d&&typeof d=="object"?c=JSON.stringify(d):c="{}";try{JSON.parse(c)}catch(b){console.warn("Invalid JSON in tool call arguments, using empty object:",c,b),c="{}"}const u={id:a.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:a.type||"function",function:{name:i,arguments:c}};return console.log("Converted tool call:",u),u}).filter(a=>a!==null))}return t.role==="tool"&&(s.tool_call_id=t.tool_call_id),s}).filter(t=>t.role&&(t.content||t.tool_calls))}abort(){console.log("AiRequestHandler: Aborting request"),this.isAborted=!0,this.abortController&&this.abortController.abort()}isRequestAborted(){return this.isAborted}}class kh{constructor(e,t,n,s){D(this,"messageManager");D(this,"modelConfig");D(this,"conversationId");D(this,"callback");this.messageManager=e,this.modelConfig=t,this.conversationId=n,this.callback=s}async processToolResult(e,t){const n=e;debugger;const s=(n.content||"").length,o=s>1e3;let a=n.content||"";if(o)try{const i=await this.generateContentSummary(n.content,n.tool_name);a=i,console.log(`[Tool Result Summary] 为工具 ${n.tool_name} 生成总结,原长度: ${s}, 总结长度: ${i.length}`)}catch(i){console.error("[Tool Result Summary] 生成总结失败:",i)}return await this.messageManager.saveToolMessage({sessionId:t,role:"tool",content:n.content||"",summary:o?a:void 0,status:"completed",createdAt:new Date,metadata:{tool_call_id:n.tool_call_id,tool_name:n.tool_name,is_summarized:o,original_length:s}}),{role:"tool",tool_call_id:n.tool_call_id,content:a,metadata:{tool_name:n.tool_name,timestamp:new Date().toISOString(),content_length:s,is_summarized:o}}}async generateContentSummary(e,t){try{const n=[{id:Date.now().toString()+"_system",sessionId:this.conversationId,role:"system",content:"请帮我总结一下这个内容,对其内容进行精简,将主要信息提取出来。请用简洁明了的语言概括核心要点。",rawContent:"请帮我总结一下这个内容,对其内容进行精简,将主要信息提取出来。请用简洁明了的语言概括核心要点。",status:"completed",createdAt:new Date},{id:Date.now().toString()+"_user",sessionId:this.conversationId,role:"user",content:`请帮我对以下内容进行总结:
55
+
56
+ ${e}`,rawContent:`请帮我对以下内容进行总结:
57
+
58
+ ${e}`,status:"completed",createdAt:new Date}];let s="";return await new Cl(n,[],this.conversationId,(a,i)=>{a==="chunk"&&(i!=null&&i.content)&&(s+=i.content,this.callback("summary_chunk",{content:i.content,accumulated:s}))},this.modelConfig).chatCompletion(),s.trim()||`工具 ${t} 执行完成,内容长度: ${e.length} 字符`}catch(n){return console.error("生成总结时出错:",n),`工具 ${t} 执行完成,内容长度: ${e.length} 字符`}}}class sa{constructor(e,t,n,s,o,a){D(this,"messages");D(this,"conversationId");D(this,"tools");D(this,"modelConfig");D(this,"callBack");D(this,"mcpToolExecute");D(this,"isAborted");D(this,"currentAiRequestHandler");D(this,"toolResultProcessor");this.messages=e,this.conversationId=t,this.tools=n,this.modelConfig=s,this.callBack=o,this.mcpToolExecute=a,this.isAborted=!1,this.currentAiRequestHandler=null,this.toolResultProcessor=new kh(Pr,this.modelConfig,this.conversationId,this.callBack)}async start(){await this.handleToolCallRecursively(25,0)}async handleToolCallRecursively(e,t){var s;if(t>=e){this.callBack("error","Maximum rounds reached");return}if(this.isAborted){console.log("AiClient: Request aborted");return}let n=this.messages[this.messages.length-1];if(n&&n.role==="assistant")if(n.tool_calls&&n.tool_calls.length>0){if(this.isAborted){console.log("AiClient: Tool call execution aborted");return}this.callBack("tool_call",n.tool_calls);let o=[];for(const i of n.tool_calls){if(this.isAborted){console.log("AiClient: Aborted during tool execution");return}const d=((s=i.function)==null?void 0:s.name)||i.name;if(this.mcpToolExecute.toolSupportsStreaming(d)){console.log(`Using streaming execution for tool: ${d}`);const u={tool_call_id:i.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:d,content:""};try{await this.mcpToolExecute.executeStream(i,f=>{if(this.isAborted)return;console.log("chunk",f);const m=this.processChunk(f);u.content+=m,this.callBack("tool_stream_chunk",{toolCallId:i.id,chunk:m})},()=>{this.isAborted||console.log(`Stream completed for tool: ${d}`)},f=>{this.isAborted||(console.error(`Stream error for tool ${d}:`,f),u.content=JSON.stringify({error:f.message||"Tool execution failed"}))}),u.content||(u.content=JSON.stringify({result:"Tool execution completed"}))}catch(f){console.error(`Failed to execute stream tool ${d}:`,f),u.content=JSON.stringify({error:f.message||"Tool execution failed"})}o.push(u)}else{console.log(`Using regular execution for tool: ${d}`);const u=await this.mcpToolExecute.execute([i]);o.push(...u)}}if(this.isAborted){console.log("AiClient: Aborted after tool execution");return}const a=await this.toolResultProcessor.processToolResult(o[0],this.conversationId);debugger;if(this.messages.push(a),this.callBack("tool_result",o),this.isAborted){console.log("AiClient: Aborted before chatCompletion after tool execution");return}if(await this.chatCompletion(),this.isAborted){console.log("AiClient: Aborted after chatCompletion after tool execution");return}await this.handleToolCallRecursively(e,t+1)}else{this.callBack("conversation_complete",n);return}else{if(this.isAborted){console.log("AiClient: Aborted before chatCompletion");return}if(await this.chatCompletion(),this.isAborted){console.log("AiClient: Aborted after chatCompletion");return}await this.handleToolCallRecursively(e,t+1)}}async chatCompletion(){if(this.isAborted){console.log("AiClient: chatCompletion aborted");return}const e=new Cl(this.messages,this.tools,this.conversationId,this.callBack,this.modelConfig);this.currentAiRequestHandler=e;try{this.messages=await e.chatCompletion()}catch(t){if(this.isAborted){console.log("AiClient: chatCompletion was aborted");return}throw t}finally{this.currentAiRequestHandler=null}}abort(){console.log("AiClient: Aborting request"),this.isAborted=!0,this.currentAiRequestHandler&&this.currentAiRequestHandler.abort()}isRequestAborted(){return this.isAborted}processChunk(e,t=!1){if(!e||typeof e!="string")return e||"";try{let n=e;n.startsWith("data: ")&&(n=n.substring(6));const s=JSON.parse(n);if(s&&typeof s=="object"){if(s.content)return typeof s.content=="string"&&s.content.startsWith("data: ")?this.processChunk(s.content,!1):t?`
59
+ `+s.content:s.content;if(s.data)return typeof s.data=="string"&&s.data.startsWith("data: ")?this.processChunk(s.data,!0):s.data;if(s.ai_stream_chunk)return typeof s.ai_stream_chunk=="string"&&s.ai_stream_chunk.startsWith("data: ")?this.processChunk(s.ai_stream_chunk,!1):s.ai_stream_chunk}}catch{return e}return""}}function kl(r,e){return function(){return r.apply(e,arguments)}}const{toString:Ah}=Object.prototype,{getPrototypeOf:ro}=Object,{iterator:nn,toStringTag:Al}=Symbol,sn=(r=>e=>{const t=Ah.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),ve=r=>(r=r.toLowerCase(),e=>sn(e)===r),on=r=>e=>typeof e===r,{isArray:_t}=Array,pt=on("undefined");function Zt(r){return r!==null&&!pt(r)&&r.constructor!==null&&!pt(r.constructor)&&de(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const El=ve("ArrayBuffer");function Eh(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&El(r.buffer),e}const Mh=on("string"),de=on("function"),Ml=on("number"),er=r=>r!==null&&typeof r=="object",jh=r=>r===!0||r===!1,Ar=r=>{if(sn(r)!=="object")return!1;const e=ro(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Al in r)&&!(nn in r)},Nh=r=>{if(!er(r)||Zt(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},Oh=ve("Date"),Ph=ve("File"),Rh=ve("Blob"),Th=ve("FileList"),Ih=r=>er(r)&&de(r.pipe),Lh=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||de(r.append)&&((e=sn(r))==="formdata"||e==="object"&&de(r.toString)&&r.toString()==="[object FormData]"))},Dh=ve("URLSearchParams"),[Fh,$h,Bh,Uh]=["ReadableStream","Request","Response","Headers"].map(ve),Wh=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tr(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let n,s;if(typeof r!="object"&&(r=[r]),_t(r))for(n=0,s=r.length;n<s;n++)e.call(null,r[n],n,r);else{if(Zt(r))return;const o=t?Object.getOwnPropertyNames(r):Object.keys(r),a=o.length;let i;for(n=0;n<a;n++)i=o[n],e.call(null,r[i],i,r)}}function jl(r,e){if(Zt(r))return null;e=e.toLowerCase();const t=Object.keys(r);let n=t.length,s;for(;n-- >0;)if(s=t[n],e===s.toLowerCase())return s;return null}const Xe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nl=r=>!pt(r)&&r!==Xe;function ns(){const{caseless:r,skipUndefined:e}=Nl(this)&&this||{},t={},n=(s,o)=>{const a=r&&jl(t,o)||o;Ar(t[a])&&Ar(s)?t[a]=ns(t[a],s):Ar(s)?t[a]=ns({},s):_t(s)?t[a]=s.slice():(!e||!pt(s))&&(t[a]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&tr(arguments[s],n);return t}const Hh=(r,e,t,{allOwnKeys:n}={})=>(tr(e,(s,o)=>{t&&de(s)?r[o]=kl(s,t):r[o]=s},{allOwnKeys:n}),r),zh=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),qh=(r,e,t,n)=>{r.prototype=Object.create(e.prototype,n),r.prototype.constructor=r,Object.defineProperty(r,"super",{value:e.prototype}),t&&Object.assign(r.prototype,t)},Vh=(r,e,t,n)=>{let s,o,a;const i={};if(e=e||{},r==null)return e;do{for(s=Object.getOwnPropertyNames(r),o=s.length;o-- >0;)a=s[o],(!n||n(a,r,e))&&!i[a]&&(e[a]=r[a],i[a]=!0);r=t!==!1&&ro(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},Jh=(r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const n=r.indexOf(e,t);return n!==-1&&n===t},Gh=r=>{if(!r)return null;if(_t(r))return r;let e=r.length;if(!Ml(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},Xh=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&ro(Uint8Array)),Yh=(r,e)=>{const n=(r&&r[nn]).call(r);let s;for(;(s=n.next())&&!s.done;){const o=s.value;e.call(r,o[0],o[1])}},Kh=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},Qh=ve("HTMLFormElement"),Zh=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,s){return n.toUpperCase()+s}),oa=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),em=ve("RegExp"),Ol=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};tr(t,(s,o)=>{let a;(a=e(s,o,r))!==!1&&(n[o]=a||s)}),Object.defineProperties(r,n)},tm=r=>{Ol(r,(e,t)=>{if(de(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=r[t];if(de(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},rm=(r,e)=>{const t={},n=s=>{s.forEach(o=>{t[o]=!0})};return _t(r)?n(r):n(String(r).split(e)),t},nm=()=>{},sm=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function om(r){return!!(r&&de(r.append)&&r[Al]==="FormData"&&r[nn])}const am=r=>{const e=new Array(10),t=(n,s)=>{if(er(n)){if(e.indexOf(n)>=0)return;if(Zt(n))return n;if(!("toJSON"in n)){e[s]=n;const o=_t(n)?[]:{};return tr(n,(a,i)=>{const d=t(a,s+1);!pt(d)&&(o[i]=d)}),e[s]=void 0,o}}return n};return t(r,0)},im=ve("AsyncFunction"),lm=r=>r&&(er(r)||de(r))&&de(r.then)&&de(r.catch),Pl=((r,e)=>r?setImmediate:e?((t,n)=>(Xe.addEventListener("message",({source:s,data:o})=>{s===Xe&&o===t&&n.length&&n.shift()()},!1),s=>{n.push(s),Xe.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",de(Xe.postMessage)),cm=typeof queueMicrotask<"u"?queueMicrotask.bind(Xe):typeof process<"u"&&process.nextTick||Pl,dm=r=>r!=null&&de(r[nn]),_={isArray:_t,isArrayBuffer:El,isBuffer:Zt,isFormData:Lh,isArrayBufferView:Eh,isString:Mh,isNumber:Ml,isBoolean:jh,isObject:er,isPlainObject:Ar,isEmptyObject:Nh,isReadableStream:Fh,isRequest:$h,isResponse:Bh,isHeaders:Uh,isUndefined:pt,isDate:Oh,isFile:Ph,isBlob:Rh,isRegExp:em,isFunction:de,isStream:Ih,isURLSearchParams:Dh,isTypedArray:Xh,isFileList:Th,forEach:tr,merge:ns,extend:Hh,trim:Wh,stripBOM:zh,inherits:qh,toFlatObject:Vh,kindOf:sn,kindOfTest:ve,endsWith:Jh,toArray:Gh,forEachEntry:Yh,matchAll:Kh,isHTMLForm:Qh,hasOwnProperty:oa,hasOwnProp:oa,reduceDescriptors:Ol,freezeMethods:tm,toObjectSet:rm,toCamelCase:Zh,noop:nm,toFiniteNumber:sm,findKey:jl,global:Xe,isContextDefined:Nl,isSpecCompliantForm:om,toJSONObject:am,isAsyncFn:im,isThenable:lm,setImmediate:Pl,asap:cm,isIterable:dm};function I(r,e,t,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=r,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}_.inherits(I,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_.toJSONObject(this.config),code:this.code,status:this.status}}});const Rl=I.prototype,Tl={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(r=>{Tl[r]={value:r}});Object.defineProperties(I,Tl);Object.defineProperty(Rl,"isAxiosError",{value:!0});I.from=(r,e,t,n,s,o)=>{const a=Object.create(Rl);_.toFlatObject(r,a,function(u){return u!==Error.prototype},c=>c!=="isAxiosError");const i=r&&r.message?r.message:"Error",d=e==null&&r?r.code:e;return I.call(a,i,d,t,n,s),r&&a.cause==null&&Object.defineProperty(a,"cause",{value:r,configurable:!0}),a.name=r&&r.name||"Error",o&&Object.assign(a,o),a};const um=null;function ss(r){return _.isPlainObject(r)||_.isArray(r)}function Il(r){return _.endsWith(r,"[]")?r.slice(0,-2):r}function aa(r,e,t){return r?r.concat(e).map(function(s,o){return s=Il(s),!t&&o?"["+s+"]":s}).join(t?".":""):e}function fm(r){return _.isArray(r)&&!r.some(ss)}const hm=_.toFlatObject(_,{},null,function(e){return/^is[A-Z]/.test(e)});function an(r,e,t){if(!_.isObject(r))throw new TypeError("target must be an object");e=e||new FormData,t=_.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,p){return!_.isUndefined(p[h])});const n=t.metaTokens,s=t.visitor||u,o=t.dots,a=t.indexes,d=(t.Blob||typeof Blob<"u"&&Blob)&&_.isSpecCompliantForm(e);if(!_.isFunction(s))throw new TypeError("visitor must be a function");function c(g){if(g===null)return"";if(_.isDate(g))return g.toISOString();if(_.isBoolean(g))return g.toString();if(!d&&_.isBlob(g))throw new I("Blob is not supported. Use a Buffer instead.");return _.isArrayBuffer(g)||_.isTypedArray(g)?d&&typeof Blob=="function"?new Blob([g]):Buffer.from(g):g}function u(g,h,p){let y=g;if(g&&!p&&typeof g=="object"){if(_.endsWith(h,"{}"))h=n?h:h.slice(0,-2),g=JSON.stringify(g);else if(_.isArray(g)&&fm(g)||(_.isFileList(g)||_.endsWith(h,"[]"))&&(y=_.toArray(g)))return h=Il(h),y.forEach(function(x,v){!(_.isUndefined(x)||x===null)&&e.append(a===!0?aa([h],v,o):a===null?h:h+"[]",c(x))}),!1}return ss(g)?!0:(e.append(aa(p,h,o),c(g)),!1)}const f=[],m=Object.assign(hm,{defaultVisitor:u,convertValue:c,isVisitable:ss});function b(g,h){if(!_.isUndefined(g)){if(f.indexOf(g)!==-1)throw Error("Circular reference detected in "+h.join("."));f.push(g),_.forEach(g,function(y,w){(!(_.isUndefined(y)||y===null)&&s.call(e,y,_.isString(w)?w.trim():w,h,m))===!0&&b(y,h?h.concat(w):[w])}),f.pop()}}if(!_.isObject(r))throw new TypeError("data must be an object");return b(r),e}function ia(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function no(r,e){this._pairs=[],r&&an(r,this,e)}const Ll=no.prototype;Ll.append=function(e,t){this._pairs.push([e,t])};Ll.toString=function(e){const t=e?function(n){return e.call(this,n,ia)}:ia;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function mm(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Dl(r,e,t){if(!e)return r;const n=t&&t.encode||mm;_.isFunction(t)&&(t={serialize:t});const s=t&&t.serialize;let o;if(s?o=s(e,t):o=_.isURLSearchParams(e)?e.toString():new no(e,t).toString(n),o){const a=r.indexOf("#");a!==-1&&(r=r.slice(0,a)),r+=(r.indexOf("?")===-1?"?":"&")+o}return r}class la{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){_.forEach(this.handlers,function(n){n!==null&&e(n)})}}const Fl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},gm=typeof URLSearchParams<"u"?URLSearchParams:no,pm=typeof FormData<"u"?FormData:null,ym=typeof Blob<"u"?Blob:null,bm={isBrowser:!0,classes:{URLSearchParams:gm,FormData:pm,Blob:ym},protocols:["http","https","file","blob","url","data"]},so=typeof window<"u"&&typeof document<"u",os=typeof navigator=="object"&&navigator||void 0,wm=so&&(!os||["ReactNative","NativeScript","NS"].indexOf(os.product)<0),xm=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",_m=so&&window.location.href||"http://localhost",vm=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:so,hasStandardBrowserEnv:wm,hasStandardBrowserWebWorkerEnv:xm,navigator:os,origin:_m},Symbol.toStringTag,{value:"Module"})),ie={...vm,...bm};function Sm(r,e){return an(r,new ie.classes.URLSearchParams,{visitor:function(t,n,s,o){return ie.isNode&&_.isBuffer(t)?(this.append(n,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function Cm(r){return _.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function km(r){const e={},t=Object.keys(r);let n;const s=t.length;let o;for(n=0;n<s;n++)o=t[n],e[o]=r[o];return e}function $l(r){function e(t,n,s,o){let a=t[o++];if(a==="__proto__")return!0;const i=Number.isFinite(+a),d=o>=t.length;return a=!a&&_.isArray(s)?s.length:a,d?(_.hasOwnProp(s,a)?s[a]=[s[a],n]:s[a]=n,!i):((!s[a]||!_.isObject(s[a]))&&(s[a]=[]),e(t,n,s[a],o)&&_.isArray(s[a])&&(s[a]=km(s[a])),!i)}if(_.isFormData(r)&&_.isFunction(r.entries)){const t={};return _.forEachEntry(r,(n,s)=>{e(Cm(n),s,t,0)}),t}return null}function Am(r,e,t){if(_.isString(r))try{return(e||JSON.parse)(r),_.trim(r)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(r)}const rr={transitional:Fl,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",s=n.indexOf("application/json")>-1,o=_.isObject(e);if(o&&_.isHTMLForm(e)&&(e=new FormData(e)),_.isFormData(e))return s?JSON.stringify($l(e)):e;if(_.isArrayBuffer(e)||_.isBuffer(e)||_.isStream(e)||_.isFile(e)||_.isBlob(e)||_.isReadableStream(e))return e;if(_.isArrayBufferView(e))return e.buffer;if(_.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Sm(e,this.formSerializer).toString();if((i=_.isFileList(e))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return an(i?{"files[]":e}:e,d&&new d,this.formSerializer)}}return o||s?(t.setContentType("application/json",!1),Am(e)):e}],transformResponse:[function(e){const t=this.transitional||rr.transitional,n=t&&t.forcedJSONParsing,s=this.responseType==="json";if(_.isResponse(e)||_.isReadableStream(e))return e;if(e&&_.isString(e)&&(n&&!this.responseType||s)){const a=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e,this.parseReviver)}catch(i){if(a)throw i.name==="SyntaxError"?I.from(i,I.ERR_BAD_RESPONSE,this,null,this.response):i}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ie.classes.FormData,Blob:ie.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_.forEach(["delete","get","head","post","put","patch"],r=>{rr.headers[r]={}});const Em=_.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Mm=r=>{const e={};let t,n,s;return r&&r.split(`
60
+ `).forEach(function(a){s=a.indexOf(":"),t=a.substring(0,s).trim().toLowerCase(),n=a.substring(s+1).trim(),!(!t||e[t]&&Em[t])&&(t==="set-cookie"?e[t]?e[t].push(n):e[t]=[n]:e[t]=e[t]?e[t]+", "+n:n)}),e},ca=Symbol("internals");function jt(r){return r&&String(r).trim().toLowerCase()}function Er(r){return r===!1||r==null?r:_.isArray(r)?r.map(Er):String(r)}function jm(r){const e=Object.create(null),t=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let n;for(;n=t.exec(r);)e[n[1]]=n[2];return e}const Nm=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function jn(r,e,t,n,s){if(_.isFunction(n))return n.call(this,e,t);if(s&&(e=t),!!_.isString(e)){if(_.isString(n))return e.indexOf(n)!==-1;if(_.isRegExp(n))return n.test(e)}}function Om(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function Pm(r,e){const t=_.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(r,n+t,{value:function(s,o,a){return this[n].call(this,e,s,o,a)},configurable:!0})})}let ue=class{constructor(e){e&&this.set(e)}set(e,t,n){const s=this;function o(i,d,c){const u=jt(d);if(!u)throw new Error("header name must be a non-empty string");const f=_.findKey(s,u);(!f||s[f]===void 0||c===!0||c===void 0&&s[f]!==!1)&&(s[f||d]=Er(i))}const a=(i,d)=>_.forEach(i,(c,u)=>o(c,u,d));if(_.isPlainObject(e)||e instanceof this.constructor)a(e,t);else if(_.isString(e)&&(e=e.trim())&&!Nm(e))a(Mm(e),t);else if(_.isObject(e)&&_.isIterable(e)){let i={},d,c;for(const u of e){if(!_.isArray(u))throw TypeError("Object iterator must return a key-value pair");i[c=u[0]]=(d=i[c])?_.isArray(d)?[...d,u[1]]:[d,u[1]]:u[1]}a(i,t)}else e!=null&&o(t,e,n);return this}get(e,t){if(e=jt(e),e){const n=_.findKey(this,e);if(n){const s=this[n];if(!t)return s;if(t===!0)return jm(s);if(_.isFunction(t))return t.call(this,s,n);if(_.isRegExp(t))return t.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=jt(e),e){const n=_.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||jn(this,this[n],n,t)))}return!1}delete(e,t){const n=this;let s=!1;function o(a){if(a=jt(a),a){const i=_.findKey(n,a);i&&(!t||jn(n,n[i],i,t))&&(delete n[i],s=!0)}}return _.isArray(e)?e.forEach(o):o(e),s}clear(e){const t=Object.keys(this);let n=t.length,s=!1;for(;n--;){const o=t[n];(!e||jn(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const t=this,n={};return _.forEach(this,(s,o)=>{const a=_.findKey(n,o);if(a){t[a]=Er(s),delete t[o];return}const i=e?Om(o):String(o).trim();i!==o&&delete t[o],t[i]=Er(s),n[i]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return _.forEach(this,(n,s)=>{n!=null&&n!==!1&&(t[s]=e&&_.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(`
61
+ `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(s=>n.set(s)),n}static accessor(e){const n=(this[ca]=this[ca]={accessors:{}}).accessors,s=this.prototype;function o(a){const i=jt(a);n[i]||(Pm(s,a),n[i]=!0)}return _.isArray(e)?e.forEach(o):o(e),this}};ue.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);_.reduceDescriptors(ue.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(n){this[t]=n}}});_.freezeMethods(ue);function Nn(r,e){const t=this||rr,n=e||t,s=ue.from(n.headers);let o=n.data;return _.forEach(r,function(i){o=i.call(t,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function Bl(r){return!!(r&&r.__CANCEL__)}function vt(r,e,t){I.call(this,r??"canceled",I.ERR_CANCELED,e,t),this.name="CanceledError"}_.inherits(vt,I,{__CANCEL__:!0});function Ul(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new I("Request failed with status code "+t.status,[I.ERR_BAD_REQUEST,I.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function Rm(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function Tm(r,e){r=r||10;const t=new Array(r),n=new Array(r);let s=0,o=0,a;return e=e!==void 0?e:1e3,function(d){const c=Date.now(),u=n[o];a||(a=c),t[s]=d,n[s]=c;let f=o,m=0;for(;f!==s;)m+=t[f++],f=f%r;if(s=(s+1)%r,s===o&&(o=(o+1)%r),c-a<e)return;const b=u&&c-u;return b?Math.round(m*1e3/b):void 0}}function Im(r,e){let t=0,n=1e3/e,s,o;const a=(c,u=Date.now())=>{t=u,s=null,o&&(clearTimeout(o),o=null),r(...c)};return[(...c)=>{const u=Date.now(),f=u-t;f>=n?a(c,u):(s=c,o||(o=setTimeout(()=>{o=null,a(s)},n-f)))},()=>s&&a(s)]}const $r=(r,e,t=3)=>{let n=0;const s=Tm(50,250);return Im(o=>{const a=o.loaded,i=o.lengthComputable?o.total:void 0,d=a-n,c=s(d),u=a<=i;n=a;const f={loaded:a,total:i,progress:i?a/i:void 0,bytes:d,rate:c||void 0,estimated:c&&i&&u?(i-a)/c:void 0,event:o,lengthComputable:i!=null,[e?"download":"upload"]:!0};r(f)},t)},da=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},ua=r=>(...e)=>_.asap(()=>r(...e)),Lm=ie.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,ie.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(ie.origin),ie.navigator&&/(msie|trident)/i.test(ie.navigator.userAgent)):()=>!0,Dm=ie.hasStandardBrowserEnv?{write(r,e,t,n,s,o){const a=[r+"="+encodeURIComponent(e)];_.isNumber(t)&&a.push("expires="+new Date(t).toGMTString()),_.isString(n)&&a.push("path="+n),_.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read(r){const e=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(r){this.write(r,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Fm(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function $m(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function Wl(r,e,t){let n=!Fm(e);return r&&(n||t==!1)?$m(r,e):e}const fa=r=>r instanceof ue?{...r}:r;function et(r,e){e=e||{};const t={};function n(c,u,f,m){return _.isPlainObject(c)&&_.isPlainObject(u)?_.merge.call({caseless:m},c,u):_.isPlainObject(u)?_.merge({},u):_.isArray(u)?u.slice():u}function s(c,u,f,m){if(_.isUndefined(u)){if(!_.isUndefined(c))return n(void 0,c,f,m)}else return n(c,u,f,m)}function o(c,u){if(!_.isUndefined(u))return n(void 0,u)}function a(c,u){if(_.isUndefined(u)){if(!_.isUndefined(c))return n(void 0,c)}else return n(void 0,u)}function i(c,u,f){if(f in e)return n(c,u);if(f in r)return n(void 0,c)}const d={url:o,method:o,data:o,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(c,u,f)=>s(fa(c),fa(u),f,!0)};return _.forEach(Object.keys({...r,...e}),function(u){const f=d[u]||s,m=f(r[u],e[u],u);_.isUndefined(m)&&f!==i||(t[u]=m)}),t}const Hl=r=>{const e=et({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:i}=e;if(e.headers=a=ue.from(a),e.url=Dl(Wl(e.baseURL,e.url,e.allowAbsoluteUrls),r.params,r.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):""))),_.isFormData(t)){if(ie.hasStandardBrowserEnv||ie.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(_.isFunction(t.getHeaders)){const d=t.getHeaders(),c=["content-type","content-length"];Object.entries(d).forEach(([u,f])=>{c.includes(u.toLowerCase())&&a.set(u,f)})}}if(ie.hasStandardBrowserEnv&&(n&&_.isFunction(n)&&(n=n(e)),n||n!==!1&&Lm(e.url))){const d=s&&o&&Dm.read(o);d&&a.set(s,d)}return e},Bm=typeof XMLHttpRequest<"u",Um=Bm&&function(r){return new Promise(function(t,n){const s=Hl(r);let o=s.data;const a=ue.from(s.headers).normalize();let{responseType:i,onUploadProgress:d,onDownloadProgress:c}=s,u,f,m,b,g;function h(){b&&b(),g&&g(),s.cancelToken&&s.cancelToken.unsubscribe(u),s.signal&&s.signal.removeEventListener("abort",u)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function y(){if(!p)return;const x=ue.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),S={data:!i||i==="text"||i==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:x,config:r,request:p};Ul(function(k){t(k),h()},function(k){n(k),h()},S),p=null}"onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(n(new I("Request aborted",I.ECONNABORTED,r,p)),p=null)},p.onerror=function(v){const S=v&&v.message?v.message:"Network Error",A=new I(S,I.ERR_NETWORK,r,p);A.event=v||null,n(A),p=null},p.ontimeout=function(){let v=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const S=s.transitional||Fl;s.timeoutErrorMessage&&(v=s.timeoutErrorMessage),n(new I(v,S.clarifyTimeoutError?I.ETIMEDOUT:I.ECONNABORTED,r,p)),p=null},o===void 0&&a.setContentType(null),"setRequestHeader"in p&&_.forEach(a.toJSON(),function(v,S){p.setRequestHeader(S,v)}),_.isUndefined(s.withCredentials)||(p.withCredentials=!!s.withCredentials),i&&i!=="json"&&(p.responseType=s.responseType),c&&([m,g]=$r(c,!0),p.addEventListener("progress",m)),d&&p.upload&&([f,b]=$r(d),p.upload.addEventListener("progress",f),p.upload.addEventListener("loadend",b)),(s.cancelToken||s.signal)&&(u=x=>{p&&(n(!x||x.type?new vt(null,r,p):x),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));const w=Rm(s.url);if(w&&ie.protocols.indexOf(w)===-1){n(new I("Unsupported protocol "+w+":",I.ERR_BAD_REQUEST,r));return}p.send(o||null)})},Wm=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let n=new AbortController,s;const o=function(c){if(!s){s=!0,i();const u=c instanceof Error?c:this.reason;n.abort(u instanceof I?u:new vt(u instanceof Error?u.message:u))}};let a=e&&setTimeout(()=>{a=null,o(new I(`timeout ${e} of ms exceeded`,I.ETIMEDOUT))},e);const i=()=>{r&&(a&&clearTimeout(a),a=null,r.forEach(c=>{c.unsubscribe?c.unsubscribe(o):c.removeEventListener("abort",o)}),r=null)};r.forEach(c=>c.addEventListener("abort",o));const{signal:d}=n;return d.unsubscribe=()=>_.asap(i),d}},Hm=function*(r,e){let t=r.byteLength;if(t<e){yield r;return}let n=0,s;for(;n<t;)s=n+e,yield r.slice(n,s),n=s},zm=async function*(r,e){for await(const t of qm(r))yield*Hm(t,e)},qm=async function*(r){if(r[Symbol.asyncIterator]){yield*r;return}const e=r.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{await e.cancel()}},ha=(r,e,t,n)=>{const s=zm(r,e);let o=0,a,i=d=>{a||(a=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:c,value:u}=await s.next();if(c){i(),d.close();return}let f=u.byteLength;if(t){let m=o+=f;t(m)}d.enqueue(new Uint8Array(u))}catch(c){throw i(c),c}},cancel(d){return i(d),s.return()}},{highWaterMark:2})},ma=64*1024,{isFunction:br}=_,Vm=(({Request:r,Response:e})=>({Request:r,Response:e}))(_.global),{ReadableStream:ga,TextEncoder:pa}=_.global,ya=(r,...e)=>{try{return!!r(...e)}catch{return!1}},Jm=r=>{r=_.merge.call({skipUndefined:!0},Vm,r);const{fetch:e,Request:t,Response:n}=r,s=e?br(e):typeof fetch=="function",o=br(t),a=br(n);if(!s)return!1;const i=s&&br(ga),d=s&&(typeof pa=="function"?(g=>h=>g.encode(h))(new pa):async g=>new Uint8Array(await new t(g).arrayBuffer())),c=o&&i&&ya(()=>{let g=!1;const h=new t(ie.origin,{body:new ga,method:"POST",get duplex(){return g=!0,"half"}}).headers.has("Content-Type");return g&&!h}),u=a&&i&&ya(()=>_.isReadableStream(new n("").body)),f={stream:u&&(g=>g.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!f[g]&&(f[g]=(h,p)=>{let y=h&&h[g];if(y)return y.call(h);throw new I(`Response type '${g}' is not supported`,I.ERR_NOT_SUPPORT,p)})});const m=async g=>{if(g==null)return 0;if(_.isBlob(g))return g.size;if(_.isSpecCompliantForm(g))return(await new t(ie.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(_.isArrayBufferView(g)||_.isArrayBuffer(g))return g.byteLength;if(_.isURLSearchParams(g)&&(g=g+""),_.isString(g))return(await d(g)).byteLength},b=async(g,h)=>{const p=_.toFiniteNumber(g.getContentLength());return p??m(h)};return async g=>{let{url:h,method:p,data:y,signal:w,cancelToken:x,timeout:v,onDownloadProgress:S,onUploadProgress:A,responseType:k,headers:$,withCredentials:j="same-origin",fetchOptions:T}=Hl(g),P=e||fetch;k=k?(k+"").toLowerCase():"text";let C=Wm([w,x&&x.toAbortSignal()],v),F=null;const U=C&&C.unsubscribe&&(()=>{C.unsubscribe()});let G;try{if(A&&c&&p!=="get"&&p!=="head"&&(G=await b($,y))!==0){let Q=new t(h,{method:"POST",body:y,duplex:"half"}),tt;if(_.isFormData(y)&&(tt=Q.headers.get("content-type"))&&$.setContentType(tt),Q.body){const[cn,sr]=da(G,$r(ua(A)));y=ha(Q.body,ma,cn,sr)}}_.isString(j)||(j=j?"include":"omit");const te=o&&"credentials"in t.prototype,St={...T,signal:C,method:p.toUpperCase(),headers:$.normalize().toJSON(),body:y,duplex:"half",credentials:te?j:void 0};F=o&&new t(h,St);let ye=await(o?P(F,T):P(h,St));const Re=u&&(k==="stream"||k==="response");if(u&&(S||Re&&U)){const Q={};["status","statusText","headers"].forEach(ao=>{Q[ao]=ye[ao]});const tt=_.toFiniteNumber(ye.headers.get("content-length")),[cn,sr]=S&&da(tt,$r(ua(S),!0))||[];ye=new n(ha(ye.body,ma,cn,()=>{sr&&sr(),U&&U()}),Q)}k=k||"text";let nr=await f[_.findKey(f,k)||"text"](ye,g);return!Re&&U&&U(),await new Promise((Q,tt)=>{Ul(Q,tt,{data:nr,headers:ue.from(ye.headers),status:ye.status,statusText:ye.statusText,config:g,request:F})})}catch(te){throw U&&U(),te&&te.name==="TypeError"&&/Load failed|fetch/i.test(te.message)?Object.assign(new I("Network Error",I.ERR_NETWORK,g,F),{cause:te.cause||te}):I.from(te,te&&te.code,g,F)}}},Gm=new Map,zl=r=>{let e=r?r.env:{};const{fetch:t,Request:n,Response:s}=e,o=[n,s,t];let a=o.length,i=a,d,c,u=Gm;for(;i--;)d=o[i],c=u.get(d),c===void 0&&u.set(d,c=i?new Map:Jm(e)),u=c;return c};zl();const as={http:um,xhr:Um,fetch:{get:zl}};_.forEach(as,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const ba=r=>`- ${r}`,Xm=r=>_.isFunction(r)||r===null||r===!1,ql={getAdapter:(r,e)=>{r=_.isArray(r)?r:[r];const{length:t}=r;let n,s;const o={};for(let a=0;a<t;a++){n=r[a];let i;if(s=n,!Xm(n)&&(s=as[(i=String(n)).toLowerCase()],s===void 0))throw new I(`Unknown adapter '${i}'`);if(s&&(_.isFunction(s)||(s=s.get(e))))break;o[i||"#"+a]=s}if(!s){const a=Object.entries(o).map(([d,c])=>`adapter ${d} `+(c===!1?"is not supported by the environment":"is not available in the build"));let i=t?a.length>1?`since :
62
+ `+a.map(ba).join(`
63
+ `):" "+ba(a[0]):"as no adapter specified";throw new I("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return s},adapters:as};function On(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new vt(null,r)}function wa(r){return On(r),r.headers=ue.from(r.headers),r.data=Nn.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),ql.getAdapter(r.adapter||rr.adapter,r)(r).then(function(n){return On(r),n.data=Nn.call(r,r.transformResponse,n),n.headers=ue.from(n.headers),n},function(n){return Bl(n)||(On(r),n&&n.response&&(n.response.data=Nn.call(r,r.transformResponse,n.response),n.response.headers=ue.from(n.response.headers))),Promise.reject(n)})}const Vl="1.12.2",ln={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{ln[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});const xa={};ln.transitional=function(e,t,n){function s(o,a){return"[Axios v"+Vl+"] Transitional option '"+o+"'"+a+(n?". "+n:"")}return(o,a,i)=>{if(e===!1)throw new I(s(a," has been removed"+(t?" in "+t:"")),I.ERR_DEPRECATED);return t&&!xa[a]&&(xa[a]=!0,console.warn(s(a," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(o,a,i):!0}};ln.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Ym(r,e,t){if(typeof r!="object")throw new I("options must be an object",I.ERR_BAD_OPTION_VALUE);const n=Object.keys(r);let s=n.length;for(;s-- >0;){const o=n[s],a=e[o];if(a){const i=r[o],d=i===void 0||a(i,o,r);if(d!==!0)throw new I("option "+o+" must be "+d,I.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new I("Unknown option "+o,I.ERR_BAD_OPTION)}}const Mr={assertOptions:Ym,validators:ln},Ce=Mr.validators;let Ye=class{constructor(e){this.defaults=e||{},this.interceptors={request:new la,response:new la}}async request(e,t){try{return await this._request(e,t)}catch(n){if(n instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;const o=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=`
64
+ `+o):n.stack=o}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=et(this.defaults,t);const{transitional:n,paramsSerializer:s,headers:o}=t;n!==void 0&&Mr.assertOptions(n,{silentJSONParsing:Ce.transitional(Ce.boolean),forcedJSONParsing:Ce.transitional(Ce.boolean),clarifyTimeoutError:Ce.transitional(Ce.boolean)},!1),s!=null&&(_.isFunction(s)?t.paramsSerializer={serialize:s}:Mr.assertOptions(s,{encode:Ce.function,serialize:Ce.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Mr.assertOptions(t,{baseUrl:Ce.spelling("baseURL"),withXsrfToken:Ce.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let a=o&&_.merge(o.common,o[t.method]);o&&_.forEach(["delete","get","head","post","put","patch","common"],g=>{delete o[g]}),t.headers=ue.concat(a,o);const i=[];let d=!0;this.interceptors.request.forEach(function(h){typeof h.runWhen=="function"&&h.runWhen(t)===!1||(d=d&&h.synchronous,i.unshift(h.fulfilled,h.rejected))});const c=[];this.interceptors.response.forEach(function(h){c.push(h.fulfilled,h.rejected)});let u,f=0,m;if(!d){const g=[wa.bind(this),void 0];for(g.unshift(...i),g.push(...c),m=g.length,u=Promise.resolve(t);f<m;)u=u.then(g[f++],g[f++]);return u}m=i.length;let b=t;for(;f<m;){const g=i[f++],h=i[f++];try{b=g(b)}catch(p){h.call(this,p);break}}try{u=wa.call(this,b)}catch(g){return Promise.reject(g)}for(f=0,m=c.length;f<m;)u=u.then(c[f++],c[f++]);return u}getUri(e){e=et(this.defaults,e);const t=Wl(e.baseURL,e.url,e.allowAbsoluteUrls);return Dl(t,e.params,e.paramsSerializer)}};_.forEach(["delete","get","head","options"],function(e){Ye.prototype[e]=function(t,n){return this.request(et(n||{},{method:e,url:t,data:(n||{}).data}))}});_.forEach(["post","put","patch"],function(e){function t(n){return function(o,a,i){return this.request(et(i||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:a}))}}Ye.prototype[e]=t(),Ye.prototype[e+"Form"]=t(!0)});let Km=class Jl{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(o){t=o});const n=this;this.promise.then(s=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](s);n._listeners=null}),this.promise.then=s=>{let o;const a=new Promise(i=>{n.subscribe(i),o=i}).then(s);return a.cancel=function(){n.unsubscribe(o)},a},e(function(o,a,i){n.reason||(n.reason=new vt(o,a,i),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=n=>{e.abort(n)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new Jl(function(s){e=s}),cancel:e}}};function Qm(r){return function(t){return r.apply(null,t)}}function Zm(r){return _.isObject(r)&&r.isAxiosError===!0}const is={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(is).forEach(([r,e])=>{is[e]=r});function Gl(r){const e=new Ye(r),t=kl(Ye.prototype.request,e);return _.extend(t,Ye.prototype,e,{allOwnKeys:!0}),_.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return Gl(et(r,s))},t}const J=Gl(rr);J.Axios=Ye;J.CanceledError=vt;J.CancelToken=Km;J.isCancel=Bl;J.VERSION=Vl;J.toFormData=an;J.AxiosError=I;J.Cancel=J.CanceledError;J.all=function(e){return Promise.all(e)};J.spread=Qm;J.isAxiosError=Zm;J.mergeConfig=et;J.AxiosHeaders=ue;J.formToJSON=r=>$l(_.isHTMLForm(r)?new FormData(r):r);J.getAdapter=ql.getAdapter;J.HttpStatusCode=is;J.default=J;const{Axios:_g,AxiosError:vg,CanceledError:Sg,isCancel:Cg,CancelToken:kg,VERSION:Ag,all:Eg,Cancel:Mg,isAxiosError:jg,spread:Ng,toFormData:Og,AxiosHeaders:Pg,HttpStatusCode:Rg,formToJSON:Tg,getAdapter:Ig,mergeConfig:Lg}=J,_a=J.create({timeout:3e4,headers:{"Content-Type":"application/json"}});class eg{constructor(e){D(this,"mcpServers");D(this,"tools");D(this,"toolMetadata");this.mcpServers=e,this.tools=[],this.toolMetadata=new Map}async init(){await this.buildTools()}async executeStream(e,t,n,s){return new Promise(async(o,a)=>{var i,d,c;try{const u=((i=e.function)==null?void 0:i.name)||e.name,f=((d=e.function)==null?void 0:d.arguments)||e.arguments||{};let m=f;if(typeof f=="string")try{m=JSON.parse(f)}catch(h){console.warn("Failed to parse tool arguments:",h),m={}}const b=this.findToolInfo(u);if(!b)throw new Error(`Tool not found: ${u}`);const g=this.toolSupportsStreaming(u);if(console.log("开始调用工具:",g),g)await this.callMcpToolStream(b.serverUrl,b.originalName,m,t,()=>{n(),o()},h=>{s(new Error(h.message||"Tool execution failed")),a(h)});else{const h=await this.callMcpTool(b.serverUrl,b.originalName,m);t(JSON.stringify(h)),n(),o()}}catch(u){console.error(`Failed to execute stream tool ${((c=e.function)==null?void 0:c.name)||e.name}:`,u),s(new Error(u.message||"Tool execution failed")),a(u)}})}async execute(e){var n,s,o,a;console.log("开始调用工具,但是没有用流式的方式");const t=[];for(const i of e)try{const d=((n=i.function)==null?void 0:n.name)||i.name,c=((s=i.function)==null?void 0:s.arguments)||i.arguments||{};if(!d)throw new Error("Tool name is required");let u=c;if(typeof c=="string")try{u=JSON.parse(c)}catch(b){console.warn("Failed to parse tool arguments:",b),u={}}const f=this.findToolInfo(d);if(!f)throw new Error(`Tool not found: ${d}`);const m=await this.callMcpTool(f.serverUrl,f.originalName,u||{});t.push({tool_call_id:i.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:d,content:JSON.stringify(m),createdAt:new Date})}catch(d){console.error(`Failed to execute tool ${((o=i.function)==null?void 0:o.name)||i.name}:`,d),t.push({tool_call_id:i.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:((a=i.function)==null?void 0:a.name)||i.name,content:JSON.stringify({error:d.message||"Tool execution failed"})})}return t}findToolInfo(e){if(this.toolMetadata&&this.toolMetadata.has(e))return this.toolMetadata.get(e)??null;const t=this.tools.find(n=>{var s;return((s=n.function)==null?void 0:s.name)===e});return t&&t.originalName?{originalName:t.originalName,serverName:t.serverName,serverUrl:t.serverUrl}:null}toolSupportsStreaming(e){return!0}async callMcpToolStream(e,t,n,s,o,a){try{const i=`${e}/sse/openai/tool/call`;console.log("MCP Stream Tool Call URL:",i);const d=new AbortController,c=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream","Cache-Control":"no-cache"},body:JSON.stringify({tool_name:t,arguments:n}),signal:d.signal});if(!c.ok)throw new Error(`HTTP error! status: ${c.status}`);const u=c.body.getReader(),f=new TextDecoder;let m="",b=Date.now();const g=setInterval(()=>{if(Date.now()-b>12e4){clearInterval(g),u.cancel(),a(new Error("Stream read timeout: no data received for 2 minutes"));return}},1e4);try{for(;;){const{done:h,value:p}=await u.read();if(h)break;b=Date.now(),m+=f.decode(p,{stream:!0});const y=this.parseSSEEvents(m);m=y.remaining;for(const w of y.parsed)if(await this.handleSSEEvent(w,s,o,a)){clearInterval(g),u.cancel();return}}}finally{clearInterval(g),u.releaseLock()}}catch(i){console.error(`Failed to call MCP stream tool ${t}:`,i),i.name==="AbortError"?a(new Error("Stream request was aborted")):i.message&&i.message.includes("Stream read timeout")?a(i):i.message&&i.message.includes("fetch")?a(new Error(`Network error during stream request: ${i.message}`)):a(new Error(i.message||"Stream error"))}}parseSSEEvents(e){const t=[],n=e.split(`
65
+ `);let s={},o=0;for(;o<n.length;){const d=n[o].trim();if(d==="")s.data&&(s.event||(s.event="data"),t.push(s)),s={};else if(d.startsWith("event:"))s.event=d.substring(6).trim();else if(d.startsWith("data:")){const c=d.substring(5).trim();c==="[DONE]"?t.push({event:"end",data:"{}"}):s.data=c}o++}const a=e.lastIndexOf(`
66
+
67
+ `),i=a>=0?e.substring(a+2):e;return{parsed:t,remaining:i}}async handleSSEEvent(e,t,n,s){try{const o=JSON.parse(e.data);switch(e.event){case"start":return console.log("Stream started:",o),!1;case"data":if(console.log("Stream data:",o),o.choices&&o.choices.length>0){const a=o.choices[0];if(a.delta){const i=a.delta;i.content&&i.content?t(i.content):i.function_call&&i.function_call.arguments&&t(i.function_call.arguments)}}else o.chunk&&t(o.chunk);return!1;case"end":return console.log("Stream completed:",o),n(),!0;case"error":return console.error("Stream error:",o),s(new Error(o.error||"Stream error")),!0;default:return console.warn("Unknown SSE event:",e.event,o),!1}}catch(o){return console.error("Failed to parse SSE event:",o),s(new Error(o.message||"SSE parse error")),!0}}async callMcpTool(e,t,n){try{const s={jsonrpc:"2.0",id:`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,method:"tools/call",params:{name:t,arguments:n||{}}},o=`${e}`;console.log("MCP Tool Call URL:",o);const a=await _a.post(o,s);if(a.data.error)throw new Error(`MCP tool call failed: ${a.data.error.message}`);return a.data.result}catch(s){throw console.error(`Failed to call MCP tool ${t}:`,s),s}}async buildTools(){var e;try{this.tools=[];for(const t of this.mcpServers)try{const n={jsonrpc:"2.0",id:`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,method:"tools/list",params:{}},s=`${t.url}`;console.log("MCP Tools List URL:",s);const o=await _a.post(s,n);if(o.data.error)throw new Error(`MCP tools/list failed: ${o.data.error.message}`);const i=(((e=o.data.result)==null?void 0:e.tools)||[]).map(d=>{const c={type:"function",function:{name:`${t.name}_${d.name}`,description:d.description,parameters:d.input_schema||d.inputSchema||d.parameters||{}}};return this.toolMetadata=this.toolMetadata||new Map,this.toolMetadata.set(`${t.name}_${d.name}`,{originalName:d.name,serverName:t.name,serverUrl:t.url,supportsStreaming:!0}),c});this.tools.push(...i)}catch(n){console.error(`Failed to get tools from MCP server ${t.name}:`,n)}}catch(t){throw console.error("buildTools failed:",t),t}}getTools(){return this.tools}}class tg{constructor(e,t=null){D(this,"conversationId");D(this,"conversation");D(this,"mcpServers");D(this,"messages");D(this,"tools");D(this,"mcpToolsExecute");D(this,"modelConfig");D(this,"currentAiClient");D(this,"isAborted");this.conversationId=e,this.conversation=null,this.mcpServers=[],this.messages=[],this.tools=[],this.mcpToolsExecute=null,this.modelConfig=t,this.currentAiClient=null,this.isAborted=!1}async init(){var e;try{const t=await ct.getDetails(this.conversationId);this.conversation=t.data.conversation,console.log("AiServer - Conversation:",this.conversation),console.log("AiServer - API Key:",(e=this.modelConfig)!=null&&e.api_key?"Present":"Missing");const n=await ct.getMcpServers();console.log("mcpResponse",n),this.mcpServers=n.data.mcp_servers||[],this.mcpToolsExecute=new eg(this.mcpServers),await this.mcpToolsExecute.init(),this.tools=this.mcpToolsExecute.getTools()}catch(t){throw console.error("AiServer init failed:",t),t}}callback(e,t){switch(e){case"chunk":console.log("Received chunk:",t);break;case"tool_call":console.log("Tool call:",t);break;case"error":console.error("AI Client error:",t);break;case"complete":console.log("AI response complete:",t);break;default:console.log("Unknown callback type:",e,t)}}async sendMessage(e){var t;try{if(console.log("AiServer sendMessage called with:",e),console.log("Message type:",typeof e),console.log("Message length:",e==null?void 0:e.length),!this.conversation)return this.sendMessageDirect(e);console.log("Processing user message:",e);const o=((await ct.getMessages(this.conversationId)).data.messages||[]).sort((c,u)=>{const f=new Date(c.created_at||c.timestamp||0),m=new Date(u.created_at||u.timestamp||0),b=isNaN(f.getTime())?0:f.getTime(),g=isNaN(m.getTime())?0:m.getTime();return b-g});this.messages=[];let a="";try{const c=await fetch("/api/system-context");c.ok&&(a=(await c.json()).content||"")}catch(c){console.log("Failed to load system context:",c)}this.conversation&&this.conversation.global_prompt&&(a?a=this.conversation.global_prompt+`
68
+
69
+ `+a:a=this.conversation.global_prompt,console.log("Added global prompt to system prompt:",this.conversation.global_prompt.substring(0,100)+"...")),a&&(this.messages.push({role:"system",content:a}),console.log("Final system prompt added to messages:",a.substring(0,100)+"..."));const i=o.slice(-2);this.messages.push(...i),console.log("Messages prepared for AI:",this.messages.map(c=>({role:c.role,content:(c.content||c.message||"").substring(0,50)+"...",created_at:c.created_at})));const d=new sa(this.messages,this.conversationId,this.tools,this.modelConfig,(c,u)=>this.callback(c,u),this.mcpToolsExecute);this.currentAiClient=d;try{await d.start()}catch(c){if(this.isAborted){console.log("AiServer: Request was aborted");return}throw c}finally{this.currentAiClient=null}}catch(n){throw console.error("sendMessage failed:",n),console.error("Error details:",(t=n.response)==null?void 0:t.data),this.callback("error",n),n}}async sendMessageDirect(e){try{console.log("AiServer sendMessageDirect called with:",e),this.messages=[{role:"user",content:e}],console.log("Messages prepared for AI:",this.messages);const t=new sa(this.messages,this.conversationId,[],this.modelConfig,(n,s)=>this.callback(n,s),null);this.currentAiClient=t;try{await t.start()}catch(n){if(this.isAborted){console.log("AiServer: Request was aborted");return}throw n}finally{this.currentAiClient=null}}catch(t){throw console.error("sendMessageDirect failed:",t),this.callback("error",t),t}}async getMessages(e={}){try{const t=await ct.getMessages(this.conversationId,e);return this.messages=t.data.messages||[],t.data}catch(t){throw console.error("getMessages failed:",t),t}}async addMessage(e,t="user"){try{return{message:await Pr.saveMessage({content:e,role:t,sessionId:this.conversationId,createdAt:new Date})}}catch(n){throw console.error("addMessage failed:",n),n}}abort(){console.log("AiServer: Aborting request"),this.isAborted=!0,this.currentAiClient&&this.currentAiClient.abort()}isRequestAborted(){return this.isAborted}resetAbortState(){this.isAborted=!1,this.currentAiClient=null}}class rg extends Ia{async getAllMcpConfigs(){return[]}async createMcpConfig(e){return{...e,id:Math.random().toString(36).substr(2,9),createdAt:new Date,updatedAt:new Date}}async getUserConfig(e){return null}}class oo{constructor(){D(this,"currentAiClient",null);D(this,"dbService");this.dbService=new rg}async sendMessage(e,t,n=[],s={},o){var a;try{if(!await this.dbService.getSession(e))throw new Error("Session not found");let d;if(o)d=o;else{const f=await this.getChatConfig();d={model_name:f.model,temperature:f.temperature,max_tokens:16e3,api_key:f.apiKey,base_url:f.baseUrl}}const c=new tg(e,d);let u=3;for(;u>0;)try{await c.init();break}catch(f){if(u--,u===0)throw new Error(`AI服务初始化失败: ${f instanceof Error?f.message:"未知错误"}`);await new Promise(m=>setTimeout(m,1e3))}c.callback=(f,m)=>{var b,g,h,p,y,w,x,v;try{switch(f){case"chunk":const S=typeof m=="string"?m:m.content||m.accumulated||"";(b=s.onChunk)==null||b.call(s,{type:"text",content:S,accumulated:S});break;case"summary_chunk":const A=typeof m=="string"?m:m.content||m.accumulated||"";(g=s.onChunk)==null||g.call(s,{type:"text",content:A,accumulated:A});break;case"tool_call":(h=s.onToolCall)==null||h.call(s,m);break;case"tool_result":(p=s.onToolResult)==null||p.call(s,m);break;case"tool_stream_chunk":(y=s.onToolStreamChunk)==null||y.call(s,m);break;case"complete":debugger;break;case"conversation_complete":(w=s.onComplete)==null||w.call(s,m);break;case"error":const k=m instanceof Error?m.message:typeof m=="string"?m:"AI响应出错";(x=s.onError)==null||x.call(s,new Error(k));break;default:console.warn("Unknown AI response type:",f)}}catch(S){console.error("Callback error:",S),(v=s.onError)==null||v.call(s,new Error(`处理AI响应时出错: ${S instanceof Error?S.message:"未知错误"}`))}},await c.sendMessage(t),this.currentAiClient=c}catch(i){throw console.error("Failed to send message:",i),(a=s.onError)==null||a.call(s,i instanceof Error?i:new Error(String(i))),i}}abortCurrentConversation(){this.currentAiClient&&(this.currentAiClient.abort(),this.currentAiClient=null)}async getChatConfig(){return await this.dbService.getUserConfig("chatConfig")||{model:"gpt-3.5-turbo",temperature:.7,maxTokens:4e3,apiKey:"",baseUrl:"https://api.openai.com/v1"}}}const Xl=new oo,ng=Object.freeze(Object.defineProperty({__proto__:null,ChatService:oo,chatService:Xl},Symbol.toStringTag,{value:"Module"})),sg="1.0.0";exports.AiModelManager=ys;exports.AppError=Yu;exports.AttachmentRenderer=Ya;exports.ChatIcon=ni;exports.ChatInterface=gf;exports.ChatService=oo;exports.CheckIcon=Zu;exports.DotsVerticalIcon=ei;exports.ErrorBoundary=pf;exports.InputArea=hs;exports.LoadingSpinner=Qa;exports.MarkdownRenderer=Wn;exports.McpManager=ps;exports.MessageItem=Ka;exports.MessageList=fs;exports.PencilIcon=ti;exports.PlusIcon=Za;exports.SessionList=ms;exports.StandaloneChatInterface=ai;exports.SystemContextEditor=bs;exports.ThemeToggle=gs;exports.ToolCallRenderer=Hn;exports.TrashIcon=ri;exports.XIcon=ef;exports.chatService=Xl;exports.cleanHtmlContent=$u;exports.cn=se;exports.conversationsApi=ct;exports.copyToClipboard=Vu;exports.databaseService=q;exports.debounce=Wu;exports.deepClone=Un;exports.default=ai;exports.downloadFile=Ju;exports.formatDate=Lu;exports.formatDateTime=Du;exports.formatFileSize=Ga;exports.formatRelativeTime=Iu;exports.formatTime=Ja;exports.generateId=Tu;exports.generateRandomColor=qu;exports.getFileExtension=Xa;exports.getOS=Xu;exports.isImageFile=zu;exports.isMobile=Gu;exports.isValidEmail=Bu;exports.isValidUrl=Uu;exports.retry=Ku;exports.storage=Qu;exports.throttle=Hu;exports.truncateText=Fu;exports.useChatStore=Pe;exports.useTheme=oi;exports.version=sg;
70
+ //# sourceMappingURL=index.cjs.js.map