@leeoohoo/aichat 1.0.8 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs.js CHANGED
@@ -1,4 +1,4 @@
1
- "use strict";require('./index.css');var ac=Object.defineProperty;var ic=(r,e,t)=>e in r?ac(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var J=(r,e,t)=>ic(r,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const a=require("react/jsx-runtime"),T=require("react"),lc={},xo=r=>{let e;const t=new Set,n=(p,f)=>{const x=typeof p=="function"?p(e):p;if(!Object.is(x,e)){const w=e;e=f??(typeof x!="object"||x===null)?x:Object.assign({},e,x),t.forEach(m=>m(e,w))}},s=()=>e,d={setState:n,getState:s,getInitialState:()=>u,subscribe:p=>(t.add(p),()=>t.delete(p)),destroy:()=>{(lc?"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()}},u=e=r(n,s,d);return d},cc=r=>r?xo(r):xo;function dc(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Hn={exports:{}},vn={},fr={exports:{}},_n={};/**
1
+ "use strict";require('./index.css');var sc=Object.defineProperty;var oc=(r,e,t)=>e in r?sc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var W=(r,e,t)=>oc(r,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const a=require("react/jsx-runtime"),O=require("react"),ac={},mo=r=>{let e;const t=new Set,n=(g,h)=>{const p=typeof g=="function"?g(e):g;if(!Object.is(p,e)){const w=e;e=h??(typeof p!="object"||p===null)?p:Object.assign({},e,p),t.forEach(m=>m(e,w))}},s=()=>e,d={setState:n,getState:s,getInitialState:()=>f,subscribe:g=>(t.add(g),()=>t.delete(g)),destroy:()=>{(ac?"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()}},f=e=r(n,s,d);return d},ic=r=>r?mo(r):mo;function lc(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Un={exports:{}},bn={},fr={exports:{}},yn={};/**
2
2
  * @license React
3
3
  * use-sync-external-store-shim.production.js
4
4
  *
@@ -6,7 +6,7 @@
6
6
  *
7
7
  * This source code is licensed under the MIT license found in the
8
8
  * LICENSE file in the root directory of this source tree.
9
- */var yo;function uc(){if(yo)return _n;yo=1;var r=T;function e(f,x){return f===x&&(f!==0||1/f===1/x)||f!==f&&x!==x}var t=typeof Object.is=="function"?Object.is:e,n=r.useState,s=r.useEffect,o=r.useLayoutEffect,i=r.useDebugValue;function l(f,x){var w=x(),m=n({inst:{value:w,getSnapshot:x}}),h=m[0].inst,c=m[1];return o(function(){h.value=w,h.getSnapshot=x,d(h)&&c({inst:h})},[f,w,x]),s(function(){return d(h)&&c({inst:h}),f(function(){d(h)&&c({inst:h})})},[f]),i(w),w}function d(f){var x=f.getSnapshot;f=f.value;try{var w=x();return!t(f,w)}catch{return!0}}function u(f,x){return x()}var p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?u:l;return _n.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:p,_n}var Sn={};/**
9
+ */var go;function cc(){if(go)return yn;go=1;var r=O;function e(h,p){return h===p&&(h!==0||1/h===1/p)||h!==h&&p!==p}var t=typeof Object.is=="function"?Object.is:e,n=r.useState,s=r.useEffect,o=r.useLayoutEffect,i=r.useDebugValue;function l(h,p){var w=p(),m=n({inst:{value:w,getSnapshot:p}}),u=m[0].inst,c=m[1];return o(function(){u.value=w,u.getSnapshot=p,d(u)&&c({inst:u})},[h,w,p]),s(function(){return d(u)&&c({inst:u}),h(function(){d(u)&&c({inst:u})})},[h]),i(w),w}function d(h){var p=h.getSnapshot;h=h.value;try{var w=p();return!t(h,w)}catch{return!0}}function f(h,p){return p()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?f:l;return yn.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:g,yn}var wn={};/**
10
10
  * @license React
11
11
  * use-sync-external-store-shim.development.js
12
12
  *
@@ -14,7 +14,7 @@
14
14
  *
15
15
  * This source code is licensed under the MIT license found in the
16
16
  * LICENSE file in the root directory of this source tree.
17
- */var bo;function fc(){return bo||(bo=1,process.env.NODE_ENV!=="production"&&function(){function r(w,m){return w===m&&(w!==0||1/w===1/m)||w!==w&&m!==m}function e(w,m){p||s.startTransition===void 0||(p=!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=m();if(!f){var c=m();o(h,c)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),f=!0)}c=i({inst:{value:h,getSnapshot:m}});var g=c[0].inst,y=c[1];return d(function(){g.value=h,g.getSnapshot=m,t(g)&&y({inst:g})},[w,h,m]),l(function(){return t(g)&&y({inst:g}),w(function(){t(g)&&y({inst:g})})},[w]),u(h),h}function t(w){var m=w.getSnapshot;w=w.value;try{var h=m();return!o(w,h)}catch{return!0}}function n(w,m){return m()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var s=T,o=typeof Object.is=="function"?Object.is:r,i=s.useState,l=s.useEffect,d=s.useLayoutEffect,u=s.useDebugValue,p=!1,f=!1,x=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n:e;Sn.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:x,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Sn}var wo;function Oa(){return wo||(wo=1,process.env.NODE_ENV==="production"?fr.exports=uc():fr.exports=fc()),fr.exports}/**
17
+ */var po;function dc(){return po||(po=1,process.env.NODE_ENV!=="production"&&function(){function r(w,m){return w===m&&(w!==0||1/w===1/m)||w!==w&&m!==m}function e(w,m){g||s.startTransition===void 0||(g=!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 u=m();if(!h){var c=m();o(u,c)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),h=!0)}c=i({inst:{value:u,getSnapshot:m}});var b=c[0].inst,x=c[1];return d(function(){b.value=u,b.getSnapshot=m,t(b)&&x({inst:b})},[w,u,m]),l(function(){return t(b)&&x({inst:b}),w(function(){t(b)&&x({inst:b})})},[w]),f(u),u}function t(w){var m=w.getSnapshot;w=w.value;try{var u=m();return!o(w,u)}catch{return!0}}function n(w,m){return m()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var s=O,o=typeof Object.is=="function"?Object.is:r,i=s.useState,l=s.useEffect,d=s.useLayoutEffect,f=s.useDebugValue,g=!1,h=!1,p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n:e;wn.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:p,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),wn}var xo;function Ia(){return xo||(xo=1,process.env.NODE_ENV==="production"?fr.exports=cc():fr.exports=dc()),fr.exports}/**
18
18
  * @license React
19
19
  * use-sync-external-store-shim/with-selector.production.js
20
20
  *
@@ -22,7 +22,7 @@
22
22
  *
23
23
  * This source code is licensed under the MIT license found in the
24
24
  * LICENSE file in the root directory of this source tree.
25
- */var vo;function hc(){if(vo)return vn;vo=1;var r=T,e=Oa();function t(u,p){return u===p&&(u!==0||1/u===1/p)||u!==u&&p!==p}var n=typeof Object.is=="function"?Object.is:t,s=e.useSyncExternalStore,o=r.useRef,i=r.useEffect,l=r.useMemo,d=r.useDebugValue;return vn.useSyncExternalStoreWithSelector=function(u,p,f,x,w){var m=o(null);if(m.current===null){var h={hasValue:!1,value:null};m.current=h}else h=m.current;m=l(function(){function g(C){if(!y){if(y=!0,b=C,C=x(C),w!==void 0&&h.hasValue){var S=h.value;if(w(S,C))return _=S}return _=C}if(S=_,n(b,C))return S;var I=x(C);return w!==void 0&&w(S,I)?(b=C,S):(b=C,_=I)}var y=!1,b,_,v=f===void 0?null:f;return[function(){return g(p())},v===null?void 0:function(){return g(v())}]},[p,f,x,w]);var c=s(u,m[0],m[1]);return i(function(){h.hasValue=!0,h.value=c},[c]),d(c),c},vn}var Cn={};/**
25
+ */var bo;function uc(){if(bo)return bn;bo=1;var r=O,e=Ia();function t(f,g){return f===g&&(f!==0||1/f===1/g)||f!==f&&g!==g}var n=typeof Object.is=="function"?Object.is:t,s=e.useSyncExternalStore,o=r.useRef,i=r.useEffect,l=r.useMemo,d=r.useDebugValue;return bn.useSyncExternalStoreWithSelector=function(f,g,h,p,w){var m=o(null);if(m.current===null){var u={hasValue:!1,value:null};m.current=u}else u=m.current;m=l(function(){function b(C){if(!x){if(x=!0,y=C,C=p(C),w!==void 0&&u.hasValue){var _=u.value;if(w(_,C))return v=_}return v=C}if(_=v,n(y,C))return _;var I=p(C);return w!==void 0&&w(_,I)?(y=C,_):(y=C,v=I)}var x=!1,y,v,S=h===void 0?null:h;return[function(){return b(g())},S===null?void 0:function(){return b(S())}]},[g,h,p,w]);var c=s(f,m[0],m[1]);return i(function(){u.hasValue=!0,u.value=c},[c]),d(c),c},bn}var vn={};/**
26
26
  * @license React
27
27
  * use-sync-external-store-shim/with-selector.development.js
28
28
  *
@@ -30,17 +30,17 @@
30
30
  *
31
31
  * This source code is licensed under the MIT license found in the
32
32
  * LICENSE file in the root directory of this source tree.
33
- */var _o;function mc(){return _o||(_o=1,process.env.NODE_ENV!=="production"&&function(){function r(u,p){return u===p&&(u!==0||1/u===1/p)||u!==u&&p!==p}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=T,t=Oa(),n=typeof Object.is=="function"?Object.is:r,s=t.useSyncExternalStore,o=e.useRef,i=e.useEffect,l=e.useMemo,d=e.useDebugValue;Cn.useSyncExternalStoreWithSelector=function(u,p,f,x,w){var m=o(null);if(m.current===null){var h={hasValue:!1,value:null};m.current=h}else h=m.current;m=l(function(){function g(C){if(!y){if(y=!0,b=C,C=x(C),w!==void 0&&h.hasValue){var S=h.value;if(w(S,C))return _=S}return _=C}if(S=_,n(b,C))return S;var I=x(C);return w!==void 0&&w(S,I)?(b=C,S):(b=C,_=I)}var y=!1,b,_,v=f===void 0?null:f;return[function(){return g(p())},v===null?void 0:function(){return g(v())}]},[p,f,x,w]);var c=s(u,m[0],m[1]);return i(function(){h.hasValue=!0,h.value=c},[c]),d(c),c},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Cn}process.env.NODE_ENV==="production"?Hn.exports=hc():Hn.exports=mc();var gc=Hn.exports;const pc=dc(gc),Ra={},{useDebugValue:xc}=T,{useSyncExternalStoreWithSelector:yc}=pc;let So=!1;const bc=r=>r;function wc(r,e=bc,t){(Ra?"production":void 0)!=="production"&&t&&!So&&(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"),So=!0);const n=yc(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return xc(n),n}const vc=r=>{(Ra?"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"?cc(r):r,t=(n,s)=>wc(e,n,s);return Object.assign(t,e),t},_c=r=>vc;var $a=Symbol.for("immer-nothing"),Co=Symbol.for("immer-draftable"),Ne=Symbol.for("immer-state"),Sc=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 _e(r,...e){if(process.env.NODE_ENV!=="production"){const t=Sc[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 Ct=Object.getPrototypeOf;function jt(r){return!!r&&!!r[Ne]}function it(r){var e;return r?La(r)||Array.isArray(r)||!!r[Co]||!!((e=r.constructor)!=null&&e[Co])||Zt(r)||Xr(r):!1}var Cc=Object.prototype.constructor.toString();function La(r){if(!r||typeof r!="object")return!1;const e=Ct(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)===Cc}function Lr(r,e){Gr(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function Gr(r){const e=r[Ne];return e?e.type_:Array.isArray(r)?1:Zt(r)?2:Xr(r)?3:0}function qn(r,e){return Gr(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function Da(r,e,t){const n=Gr(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function jc(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function Zt(r){return r instanceof Map}function Xr(r){return r instanceof Set}function et(r){return r.copy_||r.base_}function zn(r,e){if(Zt(r))return new Map(r);if(Xr(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);const t=La(r);if(e===!0||e==="class_only"&&!t){const n=Object.getOwnPropertyDescriptors(r);delete n[Ne];let s=Reflect.ownKeys(n);for(let o=0;o<s.length;o++){const i=s[o],l=n[i];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[i]={configurable:!0,writable:!0,enumerable:l.enumerable,value:r[i]})}return Object.create(Ct(r),n)}else{const n=Ct(r);if(n!==null&&t)return{...r};const s=Object.create(n);return Object.assign(s,r)}}function xs(r,e=!1){return Kr(r)||jt(r)||!it(r)||(Gr(r)>1&&Object.defineProperties(r,{set:{value:hr},add:{value:hr},clear:{value:hr},delete:{value:hr}}),Object.freeze(r),e&&Object.values(r).forEach(t=>xs(t,!0))),r}function hr(){_e(2)}function Kr(r){return Object.isFrozen(r)}var Ac={};function lt(r){const e=Ac[r];return e||_e(0,r),e}var Jt;function Fa(){return Jt}function kc(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function jo(r,e){e&&(lt("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function Jn(r){Vn(r),r.drafts_.forEach(Nc),r.drafts_=null}function Vn(r){r===Jt&&(Jt=r.parent_)}function Ao(r){return Jt=kc(Jt,r)}function Nc(r){const e=r[Ne];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function ko(r,e){e.unfinalizedDrafts_=e.drafts_.length;const t=e.drafts_[0];return r!==void 0&&r!==t?(t[Ne].modified_&&(Jn(e),_e(4)),it(r)&&(r=Dr(e,r),e.parent_||Fr(e,r)),e.patches_&&lt("Patches").generateReplacementPatches_(t[Ne].base_,r,e.patches_,e.inversePatches_)):r=Dr(e,t,[]),Jn(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==$a?r:void 0}function Dr(r,e,t){if(Kr(e))return e;const n=e[Ne];if(!n)return Lr(e,(s,o)=>No(r,n,e,s,o,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return Fr(r,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const s=n.copy_;let o=s,i=!1;n.type_===3&&(o=new Set(s),s.clear(),i=!0),Lr(o,(l,d)=>No(r,n,s,l,d,t,i)),Fr(r,s,!1),t&&r.patches_&&lt("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function No(r,e,t,n,s,o,i){if(process.env.NODE_ENV!=="production"&&s===t&&_e(5),jt(s)){const l=o&&e&&e.type_!==3&&!qn(e.assigned_,n)?o.concat(n):void 0,d=Dr(r,s,l);if(Da(t,n,d),jt(d))r.canAutoFreeze_=!1;else return}else i&&t.add(s);if(it(s)&&!Kr(s)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;Dr(r,s),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&(Zt(t)?t.has(n):Object.prototype.propertyIsEnumerable.call(t,n))&&Fr(r,s)}}function Fr(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&xs(e,t)}function Mc(r,e){const t=Array.isArray(r),n={type_:t?1:0,scope_:e?e.scope_:Fa(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=n,o=ys;t&&(s=[n],o=Vt);const{revoke:i,proxy:l}=Proxy.revocable(s,o);return n.draft_=l,n.revoke_=i,l}var ys={get(r,e){if(e===Ne)return r;const t=et(r);if(!qn(t,e))return Ec(r,t,e);const n=t[e];return r.finalized_||!it(n)?n:n===jn(r.base_,e)?(An(r),r.copy_[e]=Xn(n,r)):n},has(r,e){return e in et(r)},ownKeys(r){return Reflect.ownKeys(et(r))},set(r,e,t){const n=Ua(et(r),e);if(n!=null&&n.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){const s=jn(et(r),e),o=s==null?void 0:s[Ne];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(jc(t,s)&&(t!==void 0||qn(r.base_,e)))return!0;An(r),Gn(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 jn(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,An(r),Gn(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){const t=et(r),n=Reflect.getOwnPropertyDescriptor(t,e);return n&&{writable:!0,configurable:r.type_!==1||e!=="length",enumerable:n.enumerable,value:t[e]}},defineProperty(){_e(11)},getPrototypeOf(r){return Ct(r.base_)},setPrototypeOf(){_e(12)}},Vt={};Lr(ys,(r,e)=>{Vt[r]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});Vt.deleteProperty=function(r,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&_e(13),Vt.set.call(this,r,e,void 0)};Vt.set=function(r,e,t){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&_e(14),ys.set.call(this,r[0],e,t,r[0])};function jn(r,e){const t=r[Ne];return(t?et(t):r)[e]}function Ec(r,e,t){var s;const n=Ua(e,t);return n?"value"in n?n.value:(s=n.get)==null?void 0:s.call(r.draft_):void 0}function Ua(r,e){if(!(e in r))return;let t=Ct(r);for(;t;){const n=Object.getOwnPropertyDescriptor(t,e);if(n)return n;t=Ct(t)}}function Gn(r){r.modified_||(r.modified_=!0,r.parent_&&Gn(r.parent_))}function An(r){r.copy_||(r.copy_=zn(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Ic=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 i=this;return function(d=o,...u){return i.produce(d,p=>t.call(this,p,...u))}}typeof t!="function"&&_e(6),n!==void 0&&typeof n!="function"&&_e(7);let s;if(it(e)){const o=Ao(this),i=Xn(e,void 0);let l=!0;try{s=t(i),l=!1}finally{l?Jn(o):Vn(o)}return jo(o,n),ko(s,o)}else if(!e||typeof e!="object"){if(s=t(e),s===void 0&&(s=e),s===$a&&(s=void 0),this.autoFreeze_&&xs(s,!0),n){const o=[],i=[];lt("Patches").generateReplacementPatches_(e,s,o,i),n(o,i)}return s}else _e(1,e)},this.produceWithPatches=(e,t)=>{if(typeof e=="function")return(i,...l)=>this.produceWithPatches(i,d=>e(d,...l));let n,s;return[this.produce(e,t,(i,l)=>{n=i,s=l}),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){it(r)||_e(8),jt(r)&&(r=Tc(r));const e=Ao(this),t=Xn(r,void 0);return t[Ne].isManual_=!0,Vn(e),t}finishDraft(r,e){const t=r&&r[Ne];(!t||!t.isManual_)&&_e(9);const{scope_:n}=t;return jo(n,e),ko(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=lt("Patches").applyPatches_;return jt(r)?n(r,e):this.produce(r,s=>n(s,e))}};function Xn(r,e){const t=Zt(r)?lt("MapSet").proxyMap_(r,e):Xr(r)?lt("MapSet").proxySet_(r,e):Mc(r,e);return(e?e.scope_:Fa()).drafts_.push(t),t}function Tc(r){return jt(r)||_e(10,r),Ba(r)}function Ba(r){if(!it(r)||Kr(r))return r;const e=r[Ne];let t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=zn(r,e.scope_.immer_.useStrictShallowCopy_)}else t=zn(r,!0);return Lr(t,(n,s)=>{Da(t,n,Ba(s))}),e&&(e.finalized_=!1),t}var Pc=new Ic,Oc=Pc.produce;const Rc=r=>(e,t,n)=>(n.setState=(s,o,...i)=>{const l=typeof s=="function"?Oc(s):s;return e(l,o,...i)},r(n.setState,t,n)),$c=Rc,Lc={};function Dc(r,e){let t;try{t=r()}catch{return}return{getItem:s=>{var o;const i=d=>d===null?null:JSON.parse(d,void 0),l=(o=t.getItem(s))!=null?o:null;return l instanceof Promise?l.then(i):i(l)},setItem:(s,o)=>t.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>t.removeItem(s)}}const Gt=r=>e=>{try{const t=r(e);return t instanceof Promise?t:{then(n){return Gt(n)(t)},catch(n){return this}}}catch(t){return{then(n){return this},catch(n){return Gt(n)(t)}}}},Fc=(r,e)=>(t,n,s)=>{let o={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:c=>c,version:0,merge:(c,g)=>({...g,...c}),...e},i=!1;const l=new Set,d=new Set;let u;try{u=o.getStorage()}catch{}if(!u)return r((...c)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...c)},n,s);const p=Gt(o.serialize),f=()=>{const c=o.partialize({...n()});let g;const y=p({state:c,version:o.version}).then(b=>u.setItem(o.name,b)).catch(b=>{g=b});if(g)throw g;return y},x=s.setState;s.setState=(c,g)=>{x(c,g),f()};const w=r((...c)=>{t(...c),f()},n,s);let m;const h=()=>{var c;if(!u)return;i=!1,l.forEach(y=>y(n()));const g=((c=o.onRehydrateStorage)==null?void 0:c.call(o,n()))||void 0;return Gt(u.getItem.bind(u))(o.name).then(y=>{if(y)return o.deserialize(y)}).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==o.version){if(o.migrate)return o.migrate(y.state,y.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return y.state}).then(y=>{var b;return m=o.merge(y,(b=n())!=null?b:w),t(m,!0),f()}).then(()=>{g==null||g(m,void 0),i=!0,d.forEach(y=>y(m))}).catch(y=>{g==null||g(void 0,y)})};return s.persist={setOptions:c=>{o={...o,...c},c.getStorage&&(u=c.getStorage())},clearStorage:()=>{u==null||u.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>h(),hasHydrated:()=>i,onHydrate:c=>(l.add(c),()=>{l.delete(c)}),onFinishHydration:c=>(d.add(c),()=>{d.delete(c)})},h(),m||w},Uc=(r,e)=>(t,n,s)=>{let o={storage:Dc(()=>localStorage),partialize:h=>h,version:0,merge:(h,c)=>({...c,...h}),...e},i=!1;const l=new Set,d=new Set;let u=o.storage;if(!u)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 p=()=>{const h=o.partialize({...n()});return u.setItem(o.name,{state:h,version:o.version})},f=s.setState;s.setState=(h,c)=>{f(h,c),p()};const x=r((...h)=>{t(...h),p()},n,s);s.getInitialState=()=>x;let w;const m=()=>{var h,c;if(!u)return;i=!1,l.forEach(y=>{var b;return y((b=n())!=null?b:x)});const g=((c=o.onRehydrateStorage)==null?void 0:c.call(o,(h=n())!=null?h:x))||void 0;return Gt(u.getItem.bind(u))(o.name).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==o.version){if(o.migrate)return[!0,o.migrate(y.state,y.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,y.state];return[!1,void 0]}).then(y=>{var b;const[_,v]=y;if(w=o.merge(v,(b=n())!=null?b:x),t(w,!0),_)return p()}).then(()=>{g==null||g(w,void 0),w=n(),i=!0,d.forEach(y=>y(w))}).catch(y=>{g==null||g(void 0,y)})};return s.persist={setOptions:h=>{o={...o,...h},h.storage&&(u=h.storage)},clearStorage:()=>{u==null||u.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>m(),hasHydrated:()=>i,onHydrate:h=>(l.add(h),()=>{l.delete(h)}),onFinishHydration:h=>(d.add(h),()=>{d.delete(h)})},o.skipHydration||m(),w||x},Bc=(r,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((Lc?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),Fc(r,e)):Uc(r,e),Wc=Bc,Hc="/api";class Xt{constructor(e=Hc){J(this,"baseUrl");this.baseUrl=e}getBaseUrl(){return this.baseUrl}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}`);const i=await o.text();if(!i)return{};try{return JSON.parse(i)}catch(l){throw console.error(`JSON parse error for ${e}:`,l,"Response text:",i),new Error(`Invalid JSON response: ${i}`)}}catch(o){throw console.error(`API request failed: ${e}`,o),o}}async getSessions(e,t){const n=new URLSearchParams;e&&n.append("user_id",e),t&&n.append("project_id",t);const s=n.toString();return console.log("🔍 getSessions API调用:",{userId:e,projectId:t,queryString:s}),this.request(`/sessions${s?`?${s}`:""}`)}async createSession(e){return console.log("🔍 createSession API调用:",e),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,t){const n=[];(t==null?void 0:t.limit)!==void 0&&n.push(`limit=${encodeURIComponent(String(t.limit))}`),(t==null?void 0:t.offset)!==void 0&&n.push(`offset=${encodeURIComponent(String(t.offset))}`);const s=n.length?`?${n.join("&")}`:"";return this.request(`/sessions/${e}/messages${s}`)}async createMessage(e){const t={...e,createdAt:e.createdAt?e.createdAt.toISOString():void 0};return this.request(`/sessions/${e.sessionId}/messages`,{method:"POST",body:JSON.stringify(t)})}async getMcpConfigs(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return console.log("🔍 getMcpConfigs API调用:",{userId:e,params:t}),this.request(`/mcp-configs${t}`)}async createMcpConfig(e){return console.log("🔍 API client createMcpConfig 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),this.request("/mcp-configs",{method:"POST",body:JSON.stringify(e)})}async updateMcpConfig(e,t){return console.log("🔍 API client updateMcpConfig 调用:",{id:e,data:t}),console.log("🔍 [关键] app_ids 字段:",t.app_ids,"类型:",typeof t.app_ids,"是否为数组:",Array.isArray(t.app_ids)),this.request(`/mcp-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteMcpConfig(e){return this.request(`/mcp-configs/${e}`,{method:"DELETE"})}async getAiModelConfigs(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return console.log("🔍 getAiModelConfigs API调用:",{userId:e,params:t}),this.request(`/ai-model-configs${t}`)}async createAiModelConfig(e){return this.request("/ai-model-configs",{method:"POST",body:JSON.stringify(e)})}async updateAiModelConfig(e,t){return this.request(`/ai-model-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteAiModelConfig(e){return this.request(`/ai-model-configs/${e}`,{method:"DELETE"})}async getSystemContexts(e){return this.request(`/system-contexts?user_id=${e}`)}async getActiveSystemContext(e){return this.request(`/system-context/active?user_id=${e}`)}async createSystemContext(e){return console.log("🔍 API client createSystemContext 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),this.request("/system-contexts",{method:"POST",body:JSON.stringify(e)})}async updateSystemContext(e,t){return console.log("🔍 API client updateSystemContext 调用:",{id:e,data:t}),console.log("🔍 [关键] app_ids 字段:",t.app_ids,"类型:",typeof t.app_ids,"是否为数组:",Array.isArray(t.app_ids)),this.request(`/system-contexts/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteSystemContext(e){return this.request(`/system-contexts/${e}`,{method:"DELETE"})}async activateSystemContext(e,t){return this.request(`/system-contexts/${e}/activate`,{method:"POST",body:JSON.stringify({user_id:t,is_active:!0})})}async getApplications(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return this.request(`/applications${t}`)}async getApplication(e){return this.request(`/applications/${e}`)}async createApplication(e){return this.request("/applications",{method:"POST",body:JSON.stringify(e)})}async updateApplication(e,t){return this.request(`/applications/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteApplication(e){return this.request(`/applications/${e}`,{method:"DELETE"})}async getAgents(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return this.request(`/agents${t}`)}async createAgent(e){return console.log("🔍 API client createAgent 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),this.request("/agents",{method:"POST",body:JSON.stringify(e)})}async updateAgent(e,t){return console.log("🔍 API client updateAgent 调用:",{agentId:e,data:t}),console.log("🔍 [关键] app_ids 字段:",t.app_ids,"类型:",typeof t.app_ids,"是否为数组:",Array.isArray(t.app_ids)),this.request(`/agents/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteAgent(e){return this.request(`/agents/${e}`,{method:"DELETE"})}async getConversationDetails(e){try{const t=await this.request(`/sessions/${e}`);return{data:{conversation:{id:t.id,title:t.title,created_at:t.created_at,updated_at:t.updated_at}}}}catch(t){return console.error("Failed to get conversation details:",t),{data:{conversation:{id:e,title:"Default Conversation",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}}}}}async getAssistant(e){try{const t=await this.request("/ai-model-configs"),n=t.find(s=>s.enabled)||t[0];if(!n)throw new Error("No AI model configuration found");return{data:{assistant:{id:n.id,name:n.name,model_config:{model_name:n.model_name,temperature:.7,max_tokens:4e3,api_key:n.api_key,base_url:n.base_url}}}}}catch(t){return console.error("Failed to get assistant:",t),{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(e){try{return{data:{mcp_servers:(await this.request("/mcp-configs")).filter(s=>s.enabled).map(s=>({name:s.name,url:s.command}))}}}catch(t){return console.error("Failed to get MCP servers:",t),{data:{mcp_servers:[]}}}}async getMcpConfigResource(e){try{return await this.request(`/mcp-configs/${e}/resource/config`)}catch(t){return console.error("Failed to get MCP config resource:",t),{success:!1,config:null}}}async getMcpConfigResourceByCommand(e){try{return await this.request("/mcp-configs/resource/config",{method:"POST",body:JSON.stringify(e)})}catch(t){return console.error("Failed to get MCP config resource by command:",t),{success:!1,config:null}}}async getMcpConfigProfiles(e){const t=await this.request(`/mcp-configs/${e}/profiles`);return Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.items)?t.items:[]}async createMcpConfigProfile(e,t){return this.request(`/mcp-configs/${e}/profiles`,{method:"POST",body:JSON.stringify(t)})}async updateMcpConfigProfile(e,t,n){return this.request(`/mcp-configs/${e}/profiles/${t}`,{method:"PUT",body:JSON.stringify(n)})}async deleteMcpConfigProfile(e,t){return this.request(`/mcp-configs/${e}/profiles/${t}`,{method:"DELETE"})}async activateMcpConfigProfile(e,t){return this.request(`/mcp-configs/${e}/profiles/${t}/activate`,{method:"POST",body:JSON.stringify({is_active:!0})})}async saveMessage(e,t){try{const n=t.id||`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{data:{message:await this.request("/messages",{method:"POST",body:JSON.stringify({id:n,sessionId:e,role:t.role,content:t.content,toolCalls:t.tool_calls||null,toolCallId:t.tool_call_id||null,reasoning:t.reasoning||null,metadata:t.metadata||null})})}}}catch(n){return console.error("Failed to save message:",n),{data:{message:{...t,id:Date.now().toString(),created_at:new Date().toISOString()}}}}}async getMessages(e,t={}){try{const n=[];t.limit!==void 0&&n.push(`limit=${encodeURIComponent(String(t.limit))}`),t.offset!==void 0&&n.push(`offset=${encodeURIComponent(String(t.offset))}`);const s=n.length?`?${n.join("&")}`:"";return{data:{messages:await this.request(`/sessions/${e}/messages${s}`)}}}catch(n){return console.error("Failed to get messages:",n),{data:{messages:[]}}}}async addMessage(e,t){return this.saveMessage(e,t)}async streamChat(e,t,n,s){const o=`${this.baseUrl}/agent_v2/chat/stream`,i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:e,content:t,user_id:s,ai_model_config:{model_name:n.model_name,temperature:n.temperature||.7,max_tokens:n.max_tokens||1e3,api_key:n.api_key,base_url:n.base_url}})});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);if(!i.body)throw new Error("Response body is null");return i.body}async streamAgentChat(e,t,n,s){const o=`${this.baseUrl}/agents/chat/stream`,i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({session_id:e,content:t,agent_id:n,user_id:s})});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);if(!i.body)throw new Error("Response body is null");return i.body}async stopChat(e){return this.request("/chat/stop",{method:"POST",body:JSON.stringify({session_id:e})})}}const ne=new Xt,Ar={getDetails:r=>ne.getConversationDetails(r),getAssistant:r=>ne.getAssistant(r),getMcpServers:r=>ne.getMcpServers(r),saveMessage:(r,e)=>ne.saveMessage(r,e),getMessages:(r,e)=>ne.getMessages(r,e),addMessage:(r,e)=>ne.addMessage(r,e)};class bs{constructor(e,t,n=ne){J(this,"userId");J(this,"projectId");J(this,"client");this.userId=e,this.projectId=t,this.client=n}async createSession(e){const t={id:crypto.randomUUID(),title:e.title,user_id:this.userId,project_id:this.projectId},n=await this.client.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 this.client.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(){console.log("🔍 DatabaseService.getAllSessions 调用:",{userId:this.userId,projectId:this.projectId});const e=await this.client.getSessions(this.userId,this.projectId);console.log("🔍 API返回的会话数据:",e);const t=e.map(n=>({id:n.id,title:n.title,createdAt:new Date(n.created_at||n.createdAt),updatedAt:new Date(n.updated_at||n.updatedAt),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}));return console.log("🔍 格式化后的会话数据:",t),t}async updateSession(e,t){return console.warn("updateSession not implemented yet"),null}async deleteSession(e){try{return await this.client.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?typeof t.metadata=="string"?JSON.parse(t.metadata):t.metadata:void 0,toolCalls:t.tool_calls?typeof t.tool_calls=="string"?JSON.parse(t.tool_calls):t.tool_calls:void 0},s=await this.client.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?typeof s.metadata=="string"?JSON.parse(s.metadata):s.metadata:e.metadata}}async getSessionMessages(e,t={limit:10,offset:0}){var p,f,x,w,m;const n=t.limit??10,s=t.offset??0,i=(await this.client.getSessionMessages(e,{limit:n,offset:s})).map(h=>{let c;if(h.metadata)try{c=typeof h.metadata=="string"?JSON.parse(h.metadata):h.metadata}catch(y){console.warn("Failed to parse message metadata:",y),c={}}let g;if(h.toolCalls)try{g=typeof h.toolCalls=="string"?JSON.parse(h.toolCalls):h.toolCalls}catch(y){console.warn("Failed to parse top-level toolCalls:",y)}return{id:h.id,sessionId:h.session_id,role:h.role,content:h.content,summary:h.summary,toolCallId:h.tool_call_id,reasoning:h.reasoning,metadata:c,topLevelToolCalls:g,createdAt:new Date(h.created_at),originalMessage:h}}),l=new Map;i.forEach(h=>{var c;if(h.role==="tool"&&h.toolCallId){const g=((c=h.metadata)==null?void 0:c.isError)||!1;l.set(h.toolCallId,{content:h.content,error:g?h.content:void 0})}});const d=i.map(h=>{var _,v;let c;const g=h.topLevelToolCalls||((_=h.metadata)==null?void 0:_.toolCalls);h.role==="assistant"&&g&&Array.isArray(g)&&(console.log("[Database] 处理工具调用:",{messageId:h.id,sourceToolCalls:g}),c=g.map(C=>{if(C.function){let S={};try{S=typeof C.function.arguments=="string"?JSON.parse(C.function.arguments):C.function.arguments}catch(E){console.warn("Failed to parse tool call arguments:",E),S={}}const I=l.get(C.id);return{id:C.id||`tool_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,messageId:h.id,name:C.function.name,arguments:S,result:(I==null?void 0:I.content)||void 0,error:(I==null?void 0:I.error)||void 0,createdAt:h.createdAt}}return null}).filter(Boolean));const y=[],b=typeof h.reasoning=="string"&&h.reasoning.trim().length>0;return h.role==="assistant"&&b&&y.push({type:"thinking",content:h.reasoning}),typeof h.content=="string"&&h.content.trim().length>0&&y.push({type:"text",content:h.content}),c&&Array.isArray(c)&&c.length>0&&c.forEach(C=>{y.push({type:"tool_call",toolCallId:C.id})}),{id:h.id,sessionId:h.sessionId,role:h.role,content:h.content,rawContent:h.summary,tokensUsed:void 0,status:"completed",createdAt:h.createdAt,updatedAt:void 0,toolCallId:h.toolCallId,metadata:{...h.metadata,toolCalls:c,contentSegments:y.length>0?y:(v=h.metadata)==null?void 0:v.contentSegments}}}),u=new Set;for(let h=0;h<d.length;h++){const c=d[h];if(((p=c==null?void 0:c.metadata)==null?void 0:p.type)==="session_summary"){const g=typeof c.rawContent=="string"&&c.rawContent.length>0?c.rawContent:typeof((f=c.metadata)==null?void 0:f.summary)=="string"&&c.metadata.summary.length>0?c.metadata.summary:typeof c.content=="string"?c.content:"";let y=-1;for(let b=h+1;b<d.length;b++)if(((x=d[b])==null?void 0:x.role)==="assistant"){y=b;break}if(y===-1){for(let b=h-1;b>=0;b--)if(((w=d[b])==null?void 0:w.role)==="assistant"){y=b;break}}if(y!==-1){const b=d[y],_=`【上下文摘要】
34
- `,v=(((m=b.metadata)==null?void 0:m.contentSegments)||[]).slice(),C=v.length-1;C>=0&&v[C].type==="thinking"&&String(v[C].content||"").startsWith(_)?v[C].content=_+String(g||""):v.push({type:"thinking",content:_+String(g||"")}),b.metadata=b.metadata||{},b.metadata.contentSegments=v,c.metadata=c.metadata||{},c.metadata.hidden=!0,u.add(c.id)}}}return d}async updateMessage(e,t){return console.warn("updateMessage not implemented yet"),null}async deleteMessage(e){return console.warn("deleteMessage not implemented yet"),!1}}const Kn="RFC3986",Yn={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},qc="RFC1738",zc=Array.isArray,Re=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),kn=1024,Jc=(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(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=kn){const d=o.length>=kn?o.slice(l,l+kn):o,u=[];for(let p=0;p<d.length;++p){let f=d.charCodeAt(p);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||s===qc&&(f===40||f===41)){u[u.length]=d.charAt(p);continue}if(f<128){u[u.length]=Re[f];continue}if(f<2048){u[u.length]=Re[192|f>>6]+Re[128|f&63];continue}if(f<55296||f>=57344){u[u.length]=Re[224|f>>12]+Re[128|f>>6&63]+Re[128|f&63];continue}p+=1,f=65536+((f&1023)<<10|d.charCodeAt(p)&1023),u[u.length]=Re[240|f>>18]+Re[128|f>>12&63]+Re[128|f>>6&63]+Re[128|f&63]}i+=u.join("")}return i};function Vc(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Mo(r,e){if(zc(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const Gc=Object.prototype.hasOwnProperty,Wa={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Le=Array.isArray,Xc=Array.prototype.push,Ha=function(r,e){Xc.apply(r,Le(e)?e:[e])},Kc=Date.prototype.toISOString,fe={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Jc,encodeValuesOnly:!1,format:Kn,formatter:Yn[Kn],indices:!1,serializeDate(r){return Kc.call(r)},skipNulls:!1,strictNullHandling:!1};function Yc(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const Nn={};function qa(r,e,t,n,s,o,i,l,d,u,p,f,x,w,m,h,c,g){let y=r,b=g,_=0,v=!1;for(;(b=b.get(Nn))!==void 0&&!v;){const P=b.get(r);if(_+=1,typeof P<"u"){if(P===_)throw new RangeError("Cyclic object value");v=!0}typeof b.get(Nn)>"u"&&(_=0)}if(typeof u=="function"?y=u(e,y):y instanceof Date?y=x==null?void 0:x(y):t==="comma"&&Le(y)&&(y=Mo(y,function(P){return P instanceof Date?x==null?void 0:x(P):P})),y===null){if(o)return d&&!h?d(e,fe.encoder,c,"key",w):e;y=""}if(Yc(y)||Vc(y)){if(d){const P=h?e:d(e,fe.encoder,c,"key",w);return[(m==null?void 0:m(P))+"="+(m==null?void 0:m(d(y,fe.encoder,c,"value",w)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(y)))]}const C=[];if(typeof y>"u")return C;let S;if(t==="comma"&&Le(y))h&&d&&(y=Mo(y,d)),S=[{value:y.length>0?y.join(",")||null:void 0}];else if(Le(u))S=u;else{const P=Object.keys(y);S=p?P.sort(p):P}const I=l?String(e).replace(/\./g,"%2E"):String(e),E=n&&Le(y)&&y.length===1?I+"[]":I;if(s&&Le(y)&&y.length===0)return E+"[]";for(let P=0;P<S.length;++P){const R=S[P],j=typeof R=="object"&&typeof R.value<"u"?R.value:y[R];if(i&&j===null)continue;const W=f&&l?R.replace(/\./g,"%2E"):R,D=Le(y)?typeof t=="function"?t(E,W):E:E+(f?"."+W:"["+W+"]");g.set(r,_);const X=new WeakMap;X.set(Nn,g),Ha(C,qa(j,D,t,n,s,o,i,l,t==="comma"&&h&&Le(y)?null:d,u,p,f,x,w,m,h,c,X))}return C}function Qc(r=fe){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||fe.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=Kn;if(typeof r.format<"u"){if(!Gc.call(Yn,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=Yn[t];let s=fe.filter;(typeof r.filter=="function"||Le(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in Wa?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=fe.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:fe.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:fe.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:fe.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:fe.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?fe.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:fe.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:fe.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:fe.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:fe.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:fe.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:fe.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:fe.strictNullHandling}}function Zc(r,e={}){let t=r;const n=Qc(e);let s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):Le(n.filter)&&(o=n.filter,s=o);const i=[];if(typeof t!="object"||t===null)return"";const l=Wa[n.arrayFormat],d=l==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const u=new WeakMap;for(let x=0;x<s.length;++x){const w=s[x];n.skipNulls&&t[w]===null||Ha(i,qa(t[w],w,l,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,u))}const p=i.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&"),p.length>0?f+p:""}const yt="4.104.0";let Eo=!1,qt,za,Ja,Qn,Va,Ga,Xa,Ka,Ya;function ed(r,e={auto:!1}){if(Eo)throw new Error(`you must \`import 'openai/shims/${r.kind}'\` before importing anything else from openai`);if(qt)throw new Error(`can't \`import 'openai/shims/${r.kind}'\` after \`import 'openai/shims/${qt}'\``);Eo=e.auto,qt=r.kind,za=r.fetch,Ja=r.FormData,Qn=r.File,Va=r.ReadableStream,Ga=r.getMultipartRequestOptions,Xa=r.getDefaultAgent,Ka=r.fileFromPath,Ya=r.isFsReadStream}class td{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function rd({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(i){throw new Error(`this environment is missing the following Web Fetch API type: ${i.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(i,l)=>({...l,body:new td(i)}),getDefaultAgent:i=>{},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:i=>!1}}const Qa=()=>{qt||ed(rd(),{auto:!0})};Qa();class Y extends Error{}class ye extends Y{constructor(e,t,n,s){super(`${ye.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 Yr({message:n,cause:es(t)});const o=t==null?void 0:t.error;return e===400?new Za(e,o,n,s):e===401?new ei(e,o,n,s):e===403?new ti(e,o,n,s):e===404?new ri(e,o,n,s):e===409?new ni(e,o,n,s):e===422?new si(e,o,n,s):e===429?new oi(e,o,n,s):e>=500?new ai(e,o,n,s):new ye(e,o,n,s)}}class Ee extends ye{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Yr extends ye{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ws extends Yr{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Za extends ye{}class ei extends ye{}class ti extends ye{}class ri extends ye{}class ni extends ye{}class si extends ye{}class oi extends ye{}class ai extends ye{}class ii extends Y{constructor(){super("Could not parse response content as the length limit was reached")}}class li extends Y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var mr=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},Ze=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;class Qr{constructor(){Ae.set(this,void 0),this.buffer=new Uint8Array,mr(this,Ae,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=nd(this.buffer,Ze(this,Ae,"f")))!=null;){if(o.carriage&&Ze(this,Ae,"f")==null){mr(this,Ae,o.index,"f");continue}if(Ze(this,Ae,"f")!=null&&(o.index!==Ze(this,Ae,"f")+1||o.carriage)){s.push(this.decodeText(this.buffer.slice(0,Ze(this,Ae,"f")-1))),this.buffer=this.buffer.slice(Ze(this,Ae,"f")),mr(this,Ae,null,"f");continue}const i=Ze(this,Ae,"f")!==null?o.preceding-1:o.preceding,l=this.decodeText(this.buffer.slice(0,i));s.push(l),this.buffer=this.buffer.slice(o.index),mr(this,Ae,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 Y(`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 Y(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Y("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
35
- `):[]}}Ae=new WeakMap;Qr.NEWLINE_CHARS=new Set([`
36
- `,"\r"]);Qr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function nd(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 sd(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 ci(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 Fe{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 i of od(e,t))if(!o){if(i.data.startsWith("[DONE]")){o=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let l;try{l=JSON.parse(i.data)}catch(d){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),d}if(l&&l.error)throw new ye(void 0,l.error,void 0,pi(e.headers));yield l}else{let l;try{l=JSON.parse(i.data)}catch(d){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),d}if(i.event=="error")throw new ye(void 0,l.error,l.message,void 0);yield{event:i.event,data:l}}}o=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{o||t.abort()}}return new Fe(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){const i=new Qr,l=ci(e);for await(const d of l)for(const u of i.decode(d))yield u;for(const d of i.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 i=!1;try{for await(const l of s())i||l&&(yield JSON.parse(l));i=!0}catch(l){if(l instanceof Error&&l.name==="AbortError")return;throw l}finally{i||t.abort()}}return new Fe(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){const i=n.next();e.push(i),t.push(i)}return o.shift()}});return[new Fe(()=>s(e),this.controller),new Fe(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new Va({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:o,done:i}=await t.next();if(i)return s.close();const l=n.encode(JSON.stringify(o)+`
37
- `);s.enqueue(l)}catch(o){s.error(o)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}}async function*od(r,e){if(!r.body)throw e.abort(),new Y("Attempted to iterate over a response with no body");const t=new id,n=new Qr,s=ci(r.body);for await(const o of ad(s))for(const i of n.decode(o)){const l=t.decode(i);l&&(yield l)}for(const o of n.flush()){const i=t.decode(o);i&&(yield i)}}async function*ad(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=sd(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}class id{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(`
38
- `),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]=ld(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function ld(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}const di=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",ui=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Zr(r),Zr=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",cd=r=>ui(r)||di(r)||Ya(r);async function fi(r,e,t){var s;if(r=await r,ui(r))return r;if(di(r)){const o=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");const i=Zr(o)?[await o.arrayBuffer()]:[o];return new Qn(i,e,t)}const n=await dd(r);if(e||(e=fd(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 Qn(n,e,t)}async function dd(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Zr(r))e.push(await r.arrayBuffer());else if(hd(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: ${ud(r)}`);return e}function ud(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function fd(r){var e;return Mn(r.name)||Mn(r.filename)||((e=Mn(r.path))==null?void 0:e.split(/[\\/]/).pop())}const Mn=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},hd=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Io=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody",ct=async r=>{const e=await md(r.body);return Ga(e,r)},md=async r=>{const e=new Ja;return await Promise.all(Object.entries(r||{}).map(([t,n])=>Zn(e,t,n))),e},Zn=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(cd(t)){const n=await fi(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>Zn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>Zn(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 gd=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},pd=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)},gr;Qa();async function hi(r){var i;const{response:e}=r;if(r.options.stream)return Ke("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):Fe.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;const t=e.headers.get("content-type"),n=(i=t==null?void 0:t.split(";")[0])==null?void 0:i.trim();if((n==null?void 0:n.includes("application/json"))||(n==null?void 0:n.endsWith("+json"))){const l=await e.json();return Ke("response",e.status,e.url,e.headers,l),mi(l,e)}const o=await e.text();return Ke("response",e.status,e.url,e.headers,o),o}function mi(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 en extends Promise{constructor(e,t=hi){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new en(this.responsePromise,async t=>mi(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 xd{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:o}){this.baseURL=e,this.maxRetries=En("maxRetries",t),this.timeout=En("timeout",n),this.httpAgent=s,this.fetch=o??za}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),..._d(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Ad()}`}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&&Zr(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:i,headers:l={}}=n,d=ArrayBuffer.isView(n.body)||n.__binaryRequest&&typeof n.body=="string"?n.body:Io(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,u=this.calculateContentLength(d),p=this.buildURL(o,i);"timeout"in n&&En("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const f=n.httpAgent??this.httpAgent??Xa(p),x=n.timeout+1e3;typeof((h=f==null?void 0:f.options)==null?void 0:h.timeout)=="number"&&x>(f.options.timeout??0)&&(f.options.timeout=x),this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),l[this.idempotencyHeader]=e.idempotencyKey);const w=this.buildHeaders({options:n,headers:l,contentLength:u,retryCount:t});return{req:{method:s,...d&&{body:d},headers:w,...f&&{agent:f},signal:n.signal??null},url:p,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const o={};n&&(o["content-length"]=n);const i=this.defaultHeaders(e);return Ro(o,i),Ro(o,t),Io(e.body)&&qt!=="node"&&delete o["content-type"],xr(i,"x-stainless-retry-count")===void 0&&xr(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(s)),xr(i,"x-stainless-timeout")===void 0&&xr(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 ye.generate(e,t,n,s)}request(e,t=null){return new en(this.makeRequest(e,t))}async makeRequest(e,t){var f,x;const n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);const{req:o,url:i,timeout:l}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(o,{url:i,options:n}),Ke("request",i,n,o.headers),(f=n.signal)!=null&&f.aborted)throw new Ee;const d=new AbortController,u=await this.fetchWithTimeout(i,o,l,d).catch(es);if(u instanceof Error){if((x=n.signal)!=null&&x.aborted)throw new Ee;if(t)return this.retryRequest(n,t);throw u.name==="AbortError"?new ws:new Yr({cause:u})}const p=pi(u.headers);if(!u.ok){if(t&&this.shouldRetry(u)){const y=`retrying, ${t} attempts remaining`;return Ke(`response (error; ${y})`,u.status,i,p),this.retryRequest(n,t,p)}const w=await u.text().catch(y=>es(y).message),m=Sd(w),h=m?void 0:w;throw Ke(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,u.status,i,p,h),this.makeStatusError(u.status,m,h,p)}return{response:u,options:n,controller:d}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new yd(this,n,e)}buildURL(e,t){const n=jd(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return xi(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 Y(`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,...i}=t||{};o&&o.addEventListener("abort",()=>s.abort());const l=setTimeout(()=>s.abort(),n),d={signal:s.signal,...i};return d.method&&(d.method=d.method.toUpperCase()),this.fetch.call(void 0,e,d).finally(()=>{clearTimeout(l)})}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 l=parseFloat(o);Number.isNaN(l)||(s=l)}const i=n==null?void 0:n["retry-after"];if(i&&!s){const l=parseFloat(i);Number.isNaN(l)?s=Date.parse(i)-Date.now():s=l*1e3}if(!(s&&0<=s&&s<60*1e3)){const l=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,l)}return await er(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}getUserAgent(){return`${this.constructor.name}/JS ${yt}`}}class gi{constructor(e,t,n,s){gr.set(this,void 0),gd(this,gr,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 Y("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 pd(this,gr,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(gr=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class yd extends en{constructor(e,t,n){super(t,async s=>new n(e,s.response,await hi(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const pi=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),bd={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},le=r=>typeof r=="object"&&r!==null&&!xi(r)&&Object.keys(r).every(e=>yi(bd,e)),wd=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"X-Stainless-OS":Po(Deno.build.os),"X-Stainless-Arch":To(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":yt,"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":yt,"X-Stainless-OS":Po(process.platform),"X-Stainless-Arch":To(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const r=vd();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":yt,"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":yt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function vd(){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,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}const To=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Po=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 Oo;const _d=()=>Oo??(Oo=wd()),Sd=r=>{try{return JSON.parse(r)}catch{return}},Cd=/^[a-z][a-z0-9+.-]*:/i,jd=r=>Cd.test(r),er=r=>new Promise(e=>setTimeout(e,r)),En=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Y(`${r} must be an integer`);if(e<0)throw new Y(`${r} must be a positive integer`);return e},es=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)},pr=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 xi(r){if(!r)return!0;for(const e in r)return!1;return!0}function yi(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Ro(r,e){for(const t in e){if(!yi(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 $o=new Set(["authorization","api-key"]);function Ke(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 i={...s,headers:{...s.headers}};for(const l in s.headers)$o.has(l.toLowerCase())&&(i.headers[l]="REDACTED");return i}let o=null;for(const i in s)$o.has(i.toLowerCase())&&(o??(o={...s}),o[i]="REDACTED");return o??s});console.log(`OpenAI:DEBUG:${r}`,...n)}}const Ad=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),kd=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Nd=r=>typeof(r==null?void 0:r.get)=="function",xr=(r,e)=>{var n;const t=e.toLowerCase();if(Nd(r)){const s=((n=e[0])==null?void 0:n.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(o,i,l)=>i+l.toUpperCase());for(const o of[e,t,e.toUpperCase(),s]){const i=r.get(o);if(i)return i}}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},Md=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 In(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}class tn extends gi{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 he extends gi{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 Q{constructor(e){this._client=e}}let bi=class extends Q{list(e,t={},n){return le(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Ed,{query:t,...n})}},rn=class extends Q{constructor(){super(...arguments),this.messages=new bi(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 le(e)?this.list({},e):this._client.getAPIList("/chat/completions",nn,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class nn extends he{}class Ed extends he{}rn.ChatCompletionsPage=nn;rn.Messages=bi;let sn=class extends Q{constructor(){super(...arguments),this.completions=new rn(this._client)}};sn.Completions=rn;sn.ChatCompletionsPage=nn;class wi extends Q{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 vi extends Q{create(e,t){return this._client.post("/audio/transcriptions",ct({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class _i extends Q{create(e,t){return this._client.post("/audio/translations",ct({body:e,...t,__metadata:{model:e.model}}))}}class tr extends Q{constructor(){super(...arguments),this.transcriptions=new vi(this._client),this.translations=new _i(this._client),this.speech=new wi(this._client)}}tr.Transcriptions=vi;tr.Translations=_i;tr.Speech=wi;class vs extends Q{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 le(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 he{}vs.BatchesPage=_s;var Ie=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},ie=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)},ts,kr,Nr,Dt,Ft,Mr,Ut,We,Bt,Ur,Br,bt,Si;class Ss{constructor(){ts.add(this),this.controller=new AbortController,kr.set(this,void 0),Nr.set(this,()=>{}),Dt.set(this,()=>{}),Ft.set(this,void 0),Mr.set(this,()=>{}),Ut.set(this,()=>{}),We.set(this,{}),Bt.set(this,!1),Ur.set(this,!1),Br.set(this,!1),bt.set(this,!1),Ie(this,kr,new Promise((e,t)=>{Ie(this,Nr,e,"f"),Ie(this,Dt,t,"f")}),"f"),Ie(this,Ft,new Promise((e,t)=>{Ie(this,Mr,e,"f"),Ie(this,Ut,t,"f")}),"f"),ie(this,kr,"f").catch(()=>{}),ie(this,Ft,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},ie(this,ts,"m",Si).bind(this))},0)}_connected(){this.ended||(ie(this,Nr,"f").call(this),this._emit("connect"))}get ended(){return ie(this,Bt,"f")}get errored(){return ie(this,Ur,"f")}get aborted(){return ie(this,Br,"f")}abort(){this.controller.abort()}on(e,t){return(ie(this,We,"f")[e]||(ie(this,We,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=ie(this,We,"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(ie(this,We,"f")[e]||(ie(this,We,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Ie(this,bt,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){Ie(this,bt,!0,"f"),await ie(this,Ft,"f")}_emit(e,...t){if(ie(this,Bt,"f"))return;e==="end"&&(Ie(this,Bt,!0,"f"),ie(this,Mr,"f").call(this));const n=ie(this,We,"f")[e];if(n&&(ie(this,We,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!ie(this,bt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),ie(this,Dt,"f").call(this,s),ie(this,Ut,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!ie(this,bt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),ie(this,Dt,"f").call(this,s),ie(this,Ut,"f").call(this,s),this._emit("end")}}_emitFinal(){}}kr=new WeakMap,Nr=new WeakMap,Dt=new WeakMap,Ft=new WeakMap,Mr=new WeakMap,Ut=new WeakMap,We=new WeakMap,Bt=new WeakMap,Ur=new WeakMap,Br=new WeakMap,bt=new WeakMap,ts=new WeakSet,Si=function(e){if(Ie(this,Ur,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Ee),e instanceof Ee)return Ie(this,Br,!0,"f"),this._emit("abort",e);if(e instanceof Y)return this._emit("error",e);if(e instanceof Error){const t=new Y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Y(String(e)))};var K=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)},je=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},xe,rs,De,Er,Te,nt,wt,rt,Wr,ke,Ir,Tr,zt,Wt,Ht,Lo,Do,Fo,Uo,Bo,Wo,Ho;class Pe extends Ss{constructor(){super(...arguments),xe.add(this),rs.set(this,[]),De.set(this,{}),Er.set(this,{}),Te.set(this,void 0),nt.set(this,void 0),wt.set(this,void 0),rt.set(this,void 0),Wr.set(this,void 0),ke.set(this,void 0),Ir.set(this,void 0),Tr.set(this,void 0),zt.set(this,void 0)}[(rs=new WeakMap,De=new WeakMap,Er=new WeakMap,Te=new WeakMap,nt=new WeakMap,wt=new WeakMap,rt=new WeakMap,Wr=new WeakMap,ke=new WeakMap,Ir=new WeakMap,Tr=new WeakMap,zt=new WeakMap,xe=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,i)=>t.push({resolve:o,reject:i})).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 Pe;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=Fe.fromReadableStream(e,this.controller);for await(const i of s)K(this,xe,"m",Wt).call(this,i);if((o=s.controller.signal)!=null&&o.aborted)throw new Ee;return this._addRun(K(this,xe,"m",Ht).call(this))}toReadableStream(){return new Fe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,o){const i=new Pe;return i._run(()=>i._runToolAssistantStream(e,t,n,s,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,n,s,o){var u;const i=o==null?void 0:o.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const l={...s,stream:!0},d=await e.submitToolOutputs(t,n,l,{...o,signal:this.controller.signal});this._connected();for await(const p of d)K(this,xe,"m",Wt).call(this,p);if((u=d.controller.signal)!=null&&u.aborted)throw new Ee;return this._addRun(K(this,xe,"m",Ht).call(this))}static createThreadAssistantStream(e,t,n){const s=new Pe;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 Pe;return o._run(()=>o._runAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return K(this,Ir,"f")}currentRun(){return K(this,Tr,"f")}currentMessageSnapshot(){return K(this,Te,"f")}currentRunStepSnapshot(){return K(this,zt,"f")}async finalRunSteps(){return await this.done(),Object.values(K(this,De,"f"))}async finalMessages(){return await this.done(),Object.values(K(this,Er,"f"))}async finalRun(){if(await this.done(),!K(this,nt,"f"))throw Error("Final run was not received.");return K(this,nt,"f")}async _createThreadAssistantStream(e,t,n){var l;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},i=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(const d of i)K(this,xe,"m",Wt).call(this,d);if((l=i.controller.signal)!=null&&l.aborted)throw new Ee;return this._addRun(K(this,xe,"m",Ht).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 i={...n,stream:!0},l=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const u of l)K(this,xe,"m",Wt).call(this,u);if((d=l.controller.signal)!=null&&d.aborted)throw new Ee;return this._addRun(K(this,xe,"m",Ht).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(In(o)&&In(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(const i of s){if(!In(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const d=o[l];d==null?o.push(i):o[l]=this.accumulateDelta(d,i)}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)}}Wt=function(e){if(!this.ended)switch(je(this,Ir,e,"f"),K(this,xe,"m",Fo).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":K(this,xe,"m",Ho).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":K(this,xe,"m",Do).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":K(this,xe,"m",Lo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ht=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");if(!K(this,nt,"f"))throw Error("Final run has not been received");return K(this,nt,"f")},Lo=function(e){const[t,n]=K(this,xe,"m",Bo).call(this,e,K(this,Te,"f"));je(this,Te,t,"f"),K(this,Er,"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,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=K(this,wt,"f")){if(K(this,rt,"f"))switch(K(this,rt,"f").type){case"text":this._emit("textDone",K(this,rt,"f").text,K(this,Te,"f"));break;case"image_file":this._emit("imageFileDone",K(this,rt,"f").image_file,K(this,Te,"f"));break}je(this,wt,s.index,"f")}je(this,rt,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(K(this,wt,"f")!==void 0){const s=e.data.content[K(this,wt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,K(this,Te,"f"));break;case"text":this._emit("textDone",s.text,K(this,Te,"f"));break}}K(this,Te,"f")&&this._emit("messageDone",e.data),je(this,Te,void 0,"f")}},Do=function(e){const t=K(this,xe,"m",Uo).call(this,e);switch(je(this,zt,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==K(this,Wr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(K(this,ke,"f")&&this._emit("toolCallDone",K(this,ke,"f")),je(this,Wr,o.index,"f"),je(this,ke,t.step_details.tool_calls[o.index],"f"),K(this,ke,"f")&&this._emit("toolCallCreated",K(this,ke,"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":je(this,zt,void 0,"f"),e.data.step_details.type=="tool_calls"&&K(this,ke,"f")&&(this._emit("toolCallDone",K(this,ke,"f")),je(this,ke,void 0,"f")),this._emit("runStepDone",e.data,t);break}},Fo=function(e){K(this,rs,"f").push(e),this._emit("event",e)},Uo=function(e){switch(e.event){case"thread.run.step.created":return K(this,De,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=K(this,De,"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=Pe.accumulateDelta(t,n.delta);K(this,De,"f")[e.data.id]=s}return K(this,De,"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":K(this,De,"f")[e.data.id]=e.data;break}if(K(this,De,"f")[e.data.id])return K(this,De,"f")[e.data.id];throw new Error("No snapshot available")},Bo=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 i=t.content[o.index];t.content[o.index]=K(this,xe,"m",Wo).call(this,o,i)}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")},Wo=function(e,t){return Pe.accumulateDelta(t,e)},Ho=function(e){switch(je(this,Tr,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":je(this,nt,e.data,"f"),K(this,ke,"f")&&(this._emit("toolCallDone",K(this,ke,"f")),je(this,ke,void 0,"f"));break}};class Cs extends Q{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 le(e)?this.list({},e):this._client.getAPIList("/assistants",js,{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 js extends he{}Cs.AssistantsPage=js;function qo(r){return typeof r.parse=="function"}const vt=r=>(r==null?void 0:r.role)==="assistant",Ci=r=>(r==null?void 0:r.role)==="function",ji=r=>(r==null?void 0:r.role)==="tool";function As(r){return(r==null?void 0:r.$brand)==="auto-parseable-response-format"}function rr(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function Id(r,e){return!e||!Ai(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}}))}:ks(r,e)}function ks(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new ii;if(n.finish_reason==="content_filter")throw new li;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(o=>Pd(e,o)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Td(e,n.message.content):null}}});return{...r,choices:t}}function Td(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 Pd(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:rr(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function Od(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 rr(t)||(t==null?void 0:t.function.strict)||!1}function Ai(r){var e;return As(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>rr(t)||t.type==="function"&&t.function.strict===!0))??!1}function Rd(r){for(const e of r??[]){if(e.type!=="function")throw new Y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var ve=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)},be,ns,Hr,ss,os,as,ki,is;const zo=10;class Ni extends Ss{constructor(){super(...arguments),be.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),(Ci(e)||ji(e))&&e.content)this._emit("functionCallResult",e.content);else if(vt(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(vt(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 Y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),ve(this,be,"m",ns).call(this)}async finalMessage(){return await this.done(),ve(this,be,"m",Hr).call(this)}async finalFunctionCall(){return await this.done(),ve(this,be,"m",ss).call(this)}async finalFunctionCallResult(){return await this.done(),ve(this,be,"m",os).call(this)}async totalUsage(){return await this.done(),ve(this,be,"m",as).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=ve(this,be,"m",Hr).call(this);t&&this._emit("finalMessage",t);const n=ve(this,be,"m",ns).call(this);n&&this._emit("finalContent",n);const s=ve(this,be,"m",ss).call(this);s&&this._emit("finalFunctionCall",s);const o=ve(this,be,"m",os).call(this);o!=null&&this._emit("finalFunctionCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",ve(this,be,"m",as).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())),ve(this,be,"m",ki).call(this,t);const o=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ks(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 x;const s="function",{function_call:o="auto",stream:i,...l}=t,d=typeof o!="string"&&(o==null?void 0:o.name),{maxChatCompletions:u=zo}=n||{},p={};for(const w of t.functions)p[w.name||w.function.name]=w;const f=t.functions.map(w=>({name:w.name||w.function.name,parameters:w.parameters,description:w.description}));for(const w of t.messages)this._addMessage(w,!1);for(let w=0;w<u;++w){const h=(x=(await this._createChatCompletion(e,{...l,function_call:o,functions:f,messages:[...this.messages]},n)).choices[0])==null?void 0:x.message;if(!h)throw new Y("missing message in ChatCompletion response");if(!h.function_call)return;const{name:c,arguments:g}=h.function_call,y=p[c];if(y){if(d&&d!==c){const C=`Invalid function_call: ${JSON.stringify(c)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,name:c,content:C});continue}}else{const C=`Invalid function_call: ${JSON.stringify(c)}. Available options are: ${f.map(S=>JSON.stringify(S.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:c,content:C});continue}let b;try{b=qo(y)?await y.parse(g):g}catch(C){this._addMessage({role:s,name:c,content:C instanceof Error?C.message:String(C)});continue}const _=await y.function(b,this),v=ve(this,be,"m",is).call(this,_);if(this._addMessage({role:s,name:c,content:v}),d)return}}async _runTools(e,t,n){var w,m,h;const s="tool",{tool_choice:o="auto",stream:i,...l}=t,d=typeof o!="string"&&((w=o==null?void 0:o.function)==null?void 0:w.name),{maxChatCompletions:u=zo}=n||{},p=t.tools.map(c=>{if(rr(c)){if(!c.$callback)throw new Y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:c.$callback,name:c.function.name,description:c.function.description||"",parameters:c.function.parameters,parse:c.$parseRaw,strict:!0}}}return c}),f={};for(const c of p)c.type==="function"&&(f[c.function.name||c.function.function.name]=c.function);const x="tools"in t?p.map(c=>c.type==="function"?{type:"function",function:{name:c.function.name||c.function.function.name,parameters:c.function.parameters,description:c.function.description,strict:c.function.strict}}:c):void 0;for(const c of t.messages)this._addMessage(c,!1);for(let c=0;c<u;++c){const y=(m=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:x,messages:[...this.messages]},n)).choices[0])==null?void 0:m.message;if(!y)throw new Y("missing message in ChatCompletion response");if(!((h=y.tool_calls)!=null&&h.length))return;for(const b of y.tool_calls){if(b.type!=="function")continue;const _=b.id,{name:v,arguments:C}=b.function,S=f[v];if(S){if(d&&d!==v){const R=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,tool_call_id:_,content:R});continue}}else{const R=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(f).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:_,content:R});continue}let I;try{I=qo(S)?await S.parse(C):C}catch(R){const j=R instanceof Error?R.message:String(R);this._addMessage({role:s,tool_call_id:_,content:j});continue}const E=await S.function(I,this),P=ve(this,be,"m",is).call(this,E);if(this._addMessage({role:s,tool_call_id:_,content:P}),d)return}}}}be=new WeakSet,ns=function(){return ve(this,be,"m",Hr).call(this).content??null},Hr=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(vt(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 Y("stream ended without producing a ChatCompletionMessage with role=assistant")},ss=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const s=this.messages[n];if(vt(s)&&(s!=null&&s.function_call))return s.function_call;if(vt(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},os=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ci(t)&&t.content!=null||ji(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}},as=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},ki=function(e){if(e.n!=null&&e.n>1)throw new Y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},is=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Kt extends Ni{static runFunctions(e,t,n){const s=new Kt,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 Kt,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),vt(e)&&e.content&&this._emit("content",e.content)}}const Mi=1,Ei=2,Ii=4,Ti=8,Pi=16,Oi=32,Ri=64,$i=128,Li=256,Di=$i|Li,Fi=Pi|Oi|Di|Ri,Ui=Mi|Ei|Fi,Bi=Ii|Ti,$d=Ui|Bi,me={STR:Mi,NUM:Ei,ARR:Ii,OBJ:Ti,NULL:Pi,BOOL:Oi,NAN:Ri,INFINITY:$i,MINUS_INFINITY:Li,INF:Di,SPECIAL:Fi,ATOM:Ui,COLLECTION:Bi,ALL:$d};class Ld extends Error{}class Dd extends Error{}function Fd(r,e=me.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Ud(r.trim(),e)}const Ud=(r,e)=>{const t=r.length;let n=0;const s=x=>{throw new Ld(`${x} at position ${n}`)},o=x=>{throw new Dd(`${x} at position ${n}`)},i=()=>(f(),n>=t&&s("Unexpected end of input"),r[n]==='"'?l():r[n]==="{"?d():r[n]==="["?u():r.substring(n,n+4)==="null"||me.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||me.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||me.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||me.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||me.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||me.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):p()),l=()=>{const x=n;let w=!1;for(n++;n<t&&(r[n]!=='"'||w&&r[n-1]==="\\");)w=r[n]==="\\"?!w:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(x,++n-Number(w)))}catch(m){o(String(m))}else if(me.STR&e)try{return JSON.parse(r.substring(x,n-Number(w))+'"')}catch{return JSON.parse(r.substring(x,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},d=()=>{n++,f();const x={};try{for(;r[n]!=="}";){if(f(),n>=t&&me.OBJ&e)return x;const w=l();f(),n++;try{const m=i();Object.defineProperty(x,w,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(me.OBJ&e)return x;throw m}f(),r[n]===","&&n++}}catch{if(me.OBJ&e)return x;s("Expected '}' at end of object")}return n++,x},u=()=>{n++;const x=[];try{for(;r[n]!=="]";)x.push(i()),f(),r[n]===","&&n++}catch{if(me.ARR&e)return x;s("Expected ']' at end of array")}return n++,x},p=()=>{if(n===0){r==="-"&&me.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(w){if(me.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(w))}}const x=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(me.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(x,n))}catch{r.substring(x,n)==="-"&&me.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(x,r.lastIndexOf("e")))}catch(m){o(String(m))}}},f=()=>{for(;n<t&&`
39
- \r `.includes(r[n]);)n++};return i()},Jo=r=>Fd(r,me.ALL^me.NUM);var ht=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},oe=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)},ue,Ue,mt,qe,Tn,yr,Pn,On,Rn,br,$n,Vo;class Yt extends Ni{constructor(e){super(),ue.add(this),Ue.set(this,void 0),mt.set(this,void 0),qe.set(this,void 0),ht(this,Ue,e,"f"),ht(this,mt,[],"f")}get currentChatCompletionSnapshot(){return oe(this,qe,"f")}static fromReadableStream(e){const t=new Yt(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new Yt(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 i;super._createChatCompletion;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),oe(this,ue,"m",Tn).call(this);const o=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of o)oe(this,ue,"m",Pn).call(this,l);if((i=o.controller.signal)!=null&&i.aborted)throw new Ee;return this._addChatCompletion(oe(this,ue,"m",br).call(this))}async _fromReadableStream(e,t){var i;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),oe(this,ue,"m",Tn).call(this),this._connected();const s=Fe.fromReadableStream(e,this.controller);let o;for await(const l of s)o&&o!==l.id&&this._addChatCompletion(oe(this,ue,"m",br).call(this)),oe(this,ue,"m",Pn).call(this,l),o=l.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Ee;return this._addChatCompletion(oe(this,ue,"m",br).call(this))}[(Ue=new WeakMap,mt=new WeakMap,qe=new WeakMap,ue=new WeakSet,Tn=function(){this.ended||ht(this,qe,void 0,"f")},yr=function(t){let n=oe(this,mt,"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},oe(this,mt,"f")[t.index]=n,n)},Pn=function(t){var s,o,i,l,d,u,p,f,x,w,m,h,c,g,y;if(this.ended)return;const n=oe(this,ue,"m",Vo).call(this,t);this._emit("chunk",t,n);for(const b of t.choices){const _=n.choices[b.index];b.delta.content!=null&&((s=_.message)==null?void 0:s.role)==="assistant"&&((o=_.message)!=null&&o.content)&&(this._emit("content",b.delta.content,_.message.content),this._emit("content.delta",{delta:b.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),b.delta.refusal!=null&&((i=_.message)==null?void 0:i.role)==="assistant"&&((l=_.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:b.delta.refusal,snapshot:_.message.refusal}),((d=b.logprobs)==null?void 0:d.content)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(p=b.logprobs)==null?void 0:p.content,snapshot:((f=_.logprobs)==null?void 0:f.content)??[]}),((x=b.logprobs)==null?void 0:x.refusal)!=null&&((w=_.message)==null?void 0:w.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(m=b.logprobs)==null?void 0:m.refusal,snapshot:((h=_.logprobs)==null?void 0:h.refusal)??[]});const v=oe(this,ue,"m",yr).call(this,_);_.finish_reason&&(oe(this,ue,"m",Rn).call(this,_),v.current_tool_call_index!=null&&oe(this,ue,"m",On).call(this,_,v.current_tool_call_index));for(const C of b.delta.tool_calls??[])v.current_tool_call_index!==C.index&&(oe(this,ue,"m",Rn).call(this,_),v.current_tool_call_index!=null&&oe(this,ue,"m",On).call(this,_,v.current_tool_call_index)),v.current_tool_call_index=C.index;for(const C of b.delta.tool_calls??[]){const S=(c=_.message.tool_calls)==null?void 0:c[C.index];S!=null&&S.type&&((S==null?void 0:S.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(g=S.function)==null?void 0:g.name,index:C.index,arguments:S.function.arguments,parsed_arguments:S.function.parsed_arguments,arguments_delta:((y=C.function)==null?void 0:y.arguments)??""}):(S==null||S.type,void 0))}}},On=function(t,n){var i,l,d;if(oe(this,ue,"m",yr).call(this,t).done_tool_calls.has(n))return;const o=(i=t.message.tool_calls)==null?void 0:i[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 u=(d=(l=oe(this,Ue,"f"))==null?void 0:l.tools)==null?void 0:d.find(p=>p.type==="function"&&p.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:rr(u)?u.$parseRaw(o.function.arguments):u!=null&&u.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Rn=function(t){var s,o;const n=oe(this,ue,"m",yr).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=oe(this,ue,"m",$n).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$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}))},br=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");const t=oe(this,qe,"f");if(!t)throw new Y("request ended without sending any chunks");return ht(this,qe,void 0,"f"),ht(this,mt,[],"f"),Bd(t,oe(this,Ue,"f"))},$n=function(){var n;const t=(n=oe(this,Ue,"f"))==null?void 0:n.response_format;return As(t)?t:null},Vo=function(t){var n,s,o,i;let l=oe(this,qe,"f");const{choices:d,...u}=t;l?Object.assign(l,u):l=ht(this,qe,{...u,choices:[]},"f");for(const{delta:p,finish_reason:f,index:x,logprobs:w=null,...m}of t.choices){let h=l.choices[x];if(h||(h=l.choices[x]={finish_reason:f,index:x,message:{},logprobs:w,...m}),w)if(!h.logprobs)h.logprobs=Object.assign({},w);else{const{content:C,refusal:S,...I}=w;Object.assign(h.logprobs,I),C&&((n=h.logprobs).content??(n.content=[]),h.logprobs.content.push(...C)),S&&((s=h.logprobs).refusal??(s.refusal=[]),h.logprobs.refusal.push(...S))}if(f&&(h.finish_reason=f,oe(this,Ue,"f")&&Ai(oe(this,Ue,"f")))){if(f==="length")throw new ii;if(f==="content_filter")throw new li}if(Object.assign(h,m),!p)continue;const{content:c,refusal:g,function_call:y,role:b,tool_calls:_,...v}=p;if(Object.assign(h.message,v),g&&(h.message.refusal=(h.message.refusal||"")+g),b&&(h.message.role=b),y&&(h.message.function_call?(y.name&&(h.message.function_call.name=y.name),y.arguments&&((o=h.message.function_call).arguments??(o.arguments=""),h.message.function_call.arguments+=y.arguments)):h.message.function_call=y),c&&(h.message.content=(h.message.content||"")+c,!h.message.refusal&&oe(this,ue,"m",$n).call(this)&&(h.message.parsed=Jo(h.message.content))),_){h.message.tool_calls||(h.message.tool_calls=[]);for(const{index:C,id:S,type:I,function:E,...P}of _){const R=(i=h.message.tool_calls)[C]??(i[C]={});Object.assign(R,P),S&&(R.id=S),I&&(R.type=I),E&&(R.function??(R.function={name:E.name??"",arguments:""})),E!=null&&E.name&&(R.function.name=E.name),E!=null&&E.arguments&&(R.function.arguments+=E.arguments,Od(oe(this,Ue,"f"),R)&&(R.function.parsed_arguments=Jo(R.function.arguments)))}}}return l},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,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Fe(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Bd(r,e){const{id:t,choices:n,created:s,model:o,system_fingerprint:i,...l}=r,d={...l,id:t,choices:n.map(({message:u,finish_reason:p,index:f,logprobs:x,...w})=>{if(!p)throw new Y(`missing finish_reason for choice ${f}`);const{content:m=null,function_call:h,tool_calls:c,...g}=u,y=u.role;if(!y)throw new Y(`missing role for choice ${f}`);if(h){const{arguments:b,name:_}=h;if(b==null)throw new Y(`missing function_call.arguments for choice ${f}`);if(!_)throw new Y(`missing function_call.name for choice ${f}`);return{...w,message:{content:m,function_call:{arguments:b,name:_},role:y,refusal:u.refusal??null},finish_reason:p,index:f,logprobs:x}}return c?{...w,index:f,finish_reason:p,logprobs:x,message:{...g,role:y,content:m,refusal:u.refusal??null,tool_calls:c.map((b,_)=>{const{function:v,type:C,id:S,...I}=b,{arguments:E,name:P,...R}=v||{};if(S==null)throw new Y(`missing choices[${f}].tool_calls[${_}].id
40
- ${wr(r)}`);if(C==null)throw new Y(`missing choices[${f}].tool_calls[${_}].type
41
- ${wr(r)}`);if(P==null)throw new Y(`missing choices[${f}].tool_calls[${_}].function.name
42
- ${wr(r)}`);if(E==null)throw new Y(`missing choices[${f}].tool_calls[${_}].function.arguments
43
- ${wr(r)}`);return{...I,id:S,type:C,function:{...R,name:P,arguments:E}}})}}:{...w,message:{...g,content:m,role:y,refusal:u.refusal??null},finish_reason:p,index:f,logprobs:x}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Id(d,e)}function wr(r){return JSON.stringify(r)}class _t extends Yt{static fromReadableStream(e){const t=new _t(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new _t(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 _t(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 Wi=class extends Q{parse(e,t){return Rd(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=>ks(n,e))}runFunctions(e,t){return e.stream?_t.runFunctions(this._client,e,t):Kt.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?_t.runTools(this._client,e,t):Kt.runTools(this._client,e,t)}stream(e,t){return Yt.createChatCompletion(this._client,e,t)}};class ls extends Q{constructor(){super(...arguments),this.completions=new Wi(this._client)}}(function(r){r.Completions=Wi})(ls||(ls={}));class Hi extends Q{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class qi extends Q{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 on extends Q{constructor(){super(...arguments),this.sessions=new Hi(this._client),this.transcriptionSessions=new qi(this._client)}}on.Sessions=Hi;on.TranscriptionSessions=qi;class Ns extends Q{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 le(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 he{}Ns.MessagesPage=Ms;class Es extends Q{retrieve(e,t,n,s={},o){return le(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 le(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Is,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}}class Is extends he{}Es.RunStepsPage=Is;let nr=class extends Q{constructor(){super(...arguments),this.steps=new Es(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 le(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Ts,{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 Pe.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:i}=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 l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const d=i.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(l=u)}}await er(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,n){return Pe.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 Pe.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class Ts extends he{}nr.RunsPage=Ts;nr.Steps=Es;nr.RunStepsPage=Is;class kt extends Q{constructor(){super(...arguments),this.runs=new nr(this._client),this.messages=new Ns(this._client)}create(e={},t){return le(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 Pe.createThreadAssistantStream(e,this._client.beta.threads,t)}}kt.Runs=nr;kt.RunsPage=Ts;kt.Messages=Ns;kt.MessagesPage=Ms;class Nt extends Q{constructor(){super(...arguments),this.realtime=new on(this._client),this.chat=new ls(this._client),this.assistants=new Cs(this._client),this.threads=new kt(this._client)}}Nt.Realtime=on;Nt.Assistants=Cs;Nt.AssistantsPage=js;Nt.Threads=kt;class zi extends Q{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Ji extends Q{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 an=class extends Q{constructor(){super(...arguments),this.content=new Ji(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,ct({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return le(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 he{}an.FileListResponsesPage=Ps;an.Content=Ji;class sr extends Q{constructor(){super(...arguments),this.files=new an(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 le(e)?this.list({},e):this._client.getAPIList("/containers",Os,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}}class Os extends he{}sr.ContainerListResponsesPage=Os;sr.Files=an;sr.FileListResponsesPage=Ps;class Vi extends Q{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&Ke("Request","User defined encoding_format:",e.encoding_format);const o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?o:(Ke("response","Decoding base64 embeddings to float32 array"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const d=l.embedding;l.embedding=Md(d)}),i)))}}class Rs extends Q{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return le(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,$s,{query:n,...s})}}class $s extends he{}Rs.OutputItemListResponsesPage=$s;class or extends Q{constructor(){super(...arguments),this.outputItems=new Rs(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 le(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 he{}or.RunListResponsesPage=Ls;or.OutputItems=Rs;or.OutputItemListResponsesPage=$s;class ar extends Q{constructor(){super(...arguments),this.runs=new or(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 le(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 he{}ar.EvalListResponsesPage=Ds;ar.Runs=or;ar.RunListResponsesPage=Ls;let Fs=class extends Q{create(e,t){return this._client.post("/files",ct({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return le(e)?this.list({},e):this._client.getAPIList("/files",Us,{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 i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await er(t),i=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 i}};class Us extends he{}Fs.FileObjectsPage=Us;class Gi extends Q{}let Xi=class extends Q{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 Q{constructor(){super(...arguments),this.graders=new Xi(this._client)}}Bs.Graders=Xi;class Ws extends Q{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Hs,{body:t,method:"post",...n})}retrieve(e,t={},n){return le(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 Hs extends tn{}Ws.PermissionCreateResponsesPage=Hs;let ln=class extends Q{constructor(){super(...arguments),this.permissions=new Ws(this._client)}};ln.Permissions=Ws;ln.PermissionCreateResponsesPage=Hs;class qs extends Q{list(e,t={},n){return le(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,zs,{query:t,...n})}}class zs extends he{}qs.FineTuningJobCheckpointsPage=zs;class Mt extends Q{constructor(){super(...arguments),this.checkpoints=new qs(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 le(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Js,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return le(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 Js extends he{}class Vs extends he{}Mt.FineTuningJobsPage=Js;Mt.FineTuningJobEventsPage=Vs;Mt.Checkpoints=qs;Mt.FineTuningJobCheckpointsPage=zs;class Ye extends Q{constructor(){super(...arguments),this.methods=new Gi(this._client),this.jobs=new Mt(this._client),this.checkpoints=new ln(this._client),this.alpha=new Bs(this._client)}}Ye.Methods=Gi;Ye.Jobs=Mt;Ye.FineTuningJobsPage=Js;Ye.FineTuningJobEventsPage=Vs;Ye.Checkpoints=ln;Ye.Alpha=Bs;class Ki extends Q{}class Gs extends Q{constructor(){super(...arguments),this.graderModels=new Ki(this._client)}}Gs.GraderModels=Ki;class Yi extends Q{createVariation(e,t){return this._client.post("/images/variations",ct({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",ct({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Xs extends Q{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Ks,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Ks extends tn{}Xs.ModelsPage=Ks;class Qi extends Q{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Wd(r,e){return!e||!qd(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)}:Zi(r,e)}function Zi(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Vd(e,s)};if(s.type==="message"){const o=s.content.map(i=>i.type==="output_text"?{...i,parsed:Hd(e,i.text)}:i);return{...s,content:o}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||el(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 Hd(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 qd(r){var e;return!!As((e=r.text)==null?void 0:e.format)}function zd(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function Jd(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function Vd(r,e){const t=Jd(r.tools??[],e.name);return{...e,...e,parsed_arguments:zd(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function el(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 tl extends Q{list(e,t={},n){return le(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Xd,{query:t,...n})}}var gt=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},ze=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)},pt,vr,Je,_r,Go,Xo,Ko,Yo;class Ys extends Ss{constructor(e){super(),pt.add(this),vr.set(this,void 0),Je.set(this,void 0),_r.set(this,void 0),gt(this,vr,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 l;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),ze(this,pt,"m",Go).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=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)ze(this,pt,"m",Xo).call(this,d,i);if((l=o.controller.signal)!=null&&l.aborted)throw new Ee;return ze(this,pt,"m",Ko).call(this)}[(vr=new WeakMap,Je=new WeakMap,_r=new WeakMap,pt=new WeakSet,Go=function(){this.ended||gt(this,Je,void 0,"f")},Xo=function(t,n){if(this.ended)return;const s=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},o=ze(this,pt,"m",Yo).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const i=o.output[t.output_index];if(!i)throw new Y(`missing output at index ${t.output_index}`);if(i.type==="message"){const l=i.content[t.content_index];if(!l)throw new Y(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new Y(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const i=o.output[t.output_index];if(!i)throw new Y(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},Ko=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");const t=ze(this,Je,"f");if(!t)throw new Y("request ended without sending any events");gt(this,Je,void 0,"f");const n=Gd(t,ze(this,vr,"f"));return gt(this,_r,n,"f"),n},Yo=function(t){let n=ze(this,Je,"f");if(!n){if(t.type!=="response.created")throw new Y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=gt(this,Je,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 Y(`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 Y(`missing output at index ${t.output_index}`);if(s.type==="message"){const o=s.content[t.content_index];if(!o)throw new Y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new Y(`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 Y(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{gt(this,Je,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,i)=>t.push({resolve:o,reject:i})).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=ze(this,_r,"f");if(!e)throw new Y("stream ended without producing a ChatCompletion");return e}}function Gd(r,e){return Wd(r,e)}class Qs extends Q{constructor(){super(...arguments),this.inputItems=new tl(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"&&el(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=>Zi(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 Xd extends he{}Qs.InputItems=tl;class rl extends Q{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,ct({body:t,...n}))}}class Zs extends Q{constructor(){super(...arguments),this.parts=new rl(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})}}Zs.Parts=rl;const Kd=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 cn extends Q{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 le(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,dn,{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(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const d=o.response.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(l=u)}}await er(l);break;case"failed":case"completed":return i}}}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`,eo,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class dn extends he{}class eo extends tn{}cn.VectorStoreFilesPage=dn;cn.FileContentResponsesPage=eo;class nl extends Q{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 le(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,dn,{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:i}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const d=i.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(l=u)}}await er(l);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,i=Math.min(o,t.length),l=this._client,d=t.values(),u=[...n];async function p(x){for(let w of x){const m=await l.files.create({file:w,purpose:"assistants"},s);u.push(m.id)}}const f=Array(i).fill(d).map(p);return await Kd(f),await this.createAndPoll(e,{file_ids:u})}}class Qe extends Q{constructor(){super(...arguments),this.files=new cn(this._client),this.fileBatches=new nl(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 le(e)?this.list({},e):this._client.getAPIList("/vector_stores",to,{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`,ro,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class to extends he{}class ro extends tn{}Qe.VectorStoresPage=to;Qe.VectorStoreSearchResponsesPage=ro;Qe.Files=cn;Qe.VectorStoreFilesPage=dn;Qe.FileContentResponsesPage=eo;Qe.FileBatches=nl;var sl;class Z extends xd{constructor({baseURL:e=pr("OPENAI_BASE_URL"),apiKey:t=pr("OPENAI_API_KEY"),organization:n=pr("OPENAI_ORG_ID")??null,project:s=pr("OPENAI_PROJECT_ID")??null,...o}={}){if(t===void 0)throw new Y("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 i={apiKey:t,organization:n,project:s,...o,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&kd())throw new Y(`It looks like you're running in a browser-like environment.
33
+ */var yo;function fc(){return yo||(yo=1,process.env.NODE_ENV!=="production"&&function(){function r(f,g){return f===g&&(f!==0||1/f===1/g)||f!==f&&g!==g}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=O,t=Ia(),n=typeof Object.is=="function"?Object.is:r,s=t.useSyncExternalStore,o=e.useRef,i=e.useEffect,l=e.useMemo,d=e.useDebugValue;vn.useSyncExternalStoreWithSelector=function(f,g,h,p,w){var m=o(null);if(m.current===null){var u={hasValue:!1,value:null};m.current=u}else u=m.current;m=l(function(){function b(C){if(!x){if(x=!0,y=C,C=p(C),w!==void 0&&u.hasValue){var _=u.value;if(w(_,C))return v=_}return v=C}if(_=v,n(y,C))return _;var I=p(C);return w!==void 0&&w(_,I)?(y=C,_):(y=C,v=I)}var x=!1,y,v,S=h===void 0?null:h;return[function(){return b(g())},S===null?void 0:function(){return b(S())}]},[g,h,p,w]);var c=s(f,m[0],m[1]);return i(function(){u.hasValue=!0,u.value=c},[c]),d(c),c},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),vn}process.env.NODE_ENV==="production"?Un.exports=uc():Un.exports=fc();var hc=Un.exports;const mc=lc(hc),Pa={},{useDebugValue:gc}=O,{useSyncExternalStoreWithSelector:pc}=mc;let wo=!1;const xc=r=>r;function bc(r,e=xc,t){(Pa?"production":void 0)!=="production"&&t&&!wo&&(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"),wo=!0);const n=pc(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return gc(n),n}const yc=r=>{(Pa?"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"?ic(r):r,t=(n,s)=>bc(e,n,s);return Object.assign(t,e),t},wc=r=>yc;var Ta=Symbol.for("immer-nothing"),vo=Symbol.for("immer-draftable"),Ae=Symbol.for("immer-state"),vc=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 we(r,...e){if(process.env.NODE_ENV!=="production"){const t=vc[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 _t=Object.getPrototypeOf;function St(r){return!!r&&!!r[Ae]}function ot(r){var e;return r?Oa(r)||Array.isArray(r)||!!r[vo]||!!((e=r.constructor)!=null&&e[vo])||Yt(r)||Xr(r):!1}var _c=Object.prototype.constructor.toString();function Oa(r){if(!r||typeof r!="object")return!1;const e=_t(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)===_c}function Lr(r,e){Gr(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function Gr(r){const e=r[Ae];return e?e.type_:Array.isArray(r)?1:Yt(r)?2:Xr(r)?3:0}function Bn(r,e){return Gr(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function Ra(r,e,t){const n=Gr(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function Sc(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function Yt(r){return r instanceof Map}function Xr(r){return r instanceof Set}function Qe(r){return r.copy_||r.base_}function Wn(r,e){if(Yt(r))return new Map(r);if(Xr(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);const t=Oa(r);if(e===!0||e==="class_only"&&!t){const n=Object.getOwnPropertyDescriptors(r);delete n[Ae];let s=Reflect.ownKeys(n);for(let o=0;o<s.length;o++){const i=s[o],l=n[i];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[i]={configurable:!0,writable:!0,enumerable:l.enumerable,value:r[i]})}return Object.create(_t(r),n)}else{const n=_t(r);if(n!==null&&t)return{...r};const s=Object.create(n);return Object.assign(s,r)}}function ms(r,e=!1){return Kr(r)||St(r)||!ot(r)||(Gr(r)>1&&Object.defineProperties(r,{set:{value:hr},add:{value:hr},clear:{value:hr},delete:{value:hr}}),Object.freeze(r),e&&Object.values(r).forEach(t=>ms(t,!0))),r}function hr(){we(2)}function Kr(r){return Object.isFrozen(r)}var Cc={};function at(r){const e=Cc[r];return e||we(0,r),e}var qt;function $a(){return qt}function jc(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function _o(r,e){e&&(at("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function Hn(r){qn(r),r.drafts_.forEach(Ac),r.drafts_=null}function qn(r){r===qt&&(qt=r.parent_)}function So(r){return qt=jc(qt,r)}function Ac(r){const e=r[Ae];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function Co(r,e){e.unfinalizedDrafts_=e.drafts_.length;const t=e.drafts_[0];return r!==void 0&&r!==t?(t[Ae].modified_&&(Hn(e),we(4)),ot(r)&&(r=Dr(e,r),e.parent_||Fr(e,r)),e.patches_&&at("Patches").generateReplacementPatches_(t[Ae].base_,r,e.patches_,e.inversePatches_)):r=Dr(e,t,[]),Hn(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==Ta?r:void 0}function Dr(r,e,t){if(Kr(e))return e;const n=e[Ae];if(!n)return Lr(e,(s,o)=>jo(r,n,e,s,o,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return Fr(r,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const s=n.copy_;let o=s,i=!1;n.type_===3&&(o=new Set(s),s.clear(),i=!0),Lr(o,(l,d)=>jo(r,n,s,l,d,t,i)),Fr(r,s,!1),t&&r.patches_&&at("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function jo(r,e,t,n,s,o,i){if(process.env.NODE_ENV!=="production"&&s===t&&we(5),St(s)){const l=o&&e&&e.type_!==3&&!Bn(e.assigned_,n)?o.concat(n):void 0,d=Dr(r,s,l);if(Ra(t,n,d),St(d))r.canAutoFreeze_=!1;else return}else i&&t.add(s);if(ot(s)&&!Kr(s)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;Dr(r,s),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&(Yt(t)?t.has(n):Object.prototype.propertyIsEnumerable.call(t,n))&&Fr(r,s)}}function Fr(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&ms(e,t)}function kc(r,e){const t=Array.isArray(r),n={type_:t?1:0,scope_:e?e.scope_:$a(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=n,o=gs;t&&(s=[n],o=zt);const{revoke:i,proxy:l}=Proxy.revocable(s,o);return n.draft_=l,n.revoke_=i,l}var gs={get(r,e){if(e===Ae)return r;const t=Qe(r);if(!Bn(t,e))return Nc(r,t,e);const n=t[e];return r.finalized_||!ot(n)?n:n===_n(r.base_,e)?(Sn(r),r.copy_[e]=Jn(n,r)):n},has(r,e){return e in Qe(r)},ownKeys(r){return Reflect.ownKeys(Qe(r))},set(r,e,t){const n=La(Qe(r),e);if(n!=null&&n.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){const s=_n(Qe(r),e),o=s==null?void 0:s[Ae];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(Sc(t,s)&&(t!==void 0||Bn(r.base_,e)))return!0;Sn(r),zn(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 _n(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,Sn(r),zn(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){const t=Qe(r),n=Reflect.getOwnPropertyDescriptor(t,e);return n&&{writable:!0,configurable:r.type_!==1||e!=="length",enumerable:n.enumerable,value:t[e]}},defineProperty(){we(11)},getPrototypeOf(r){return _t(r.base_)},setPrototypeOf(){we(12)}},zt={};Lr(gs,(r,e)=>{zt[r]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});zt.deleteProperty=function(r,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&we(13),zt.set.call(this,r,e,void 0)};zt.set=function(r,e,t){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&we(14),gs.set.call(this,r[0],e,t,r[0])};function _n(r,e){const t=r[Ae];return(t?Qe(t):r)[e]}function Nc(r,e,t){var s;const n=La(e,t);return n?"value"in n?n.value:(s=n.get)==null?void 0:s.call(r.draft_):void 0}function La(r,e){if(!(e in r))return;let t=_t(r);for(;t;){const n=Object.getOwnPropertyDescriptor(t,e);if(n)return n;t=_t(t)}}function zn(r){r.modified_||(r.modified_=!0,r.parent_&&zn(r.parent_))}function Sn(r){r.copy_||(r.copy_=Wn(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Mc=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 i=this;return function(d=o,...f){return i.produce(d,g=>t.call(this,g,...f))}}typeof t!="function"&&we(6),n!==void 0&&typeof n!="function"&&we(7);let s;if(ot(e)){const o=So(this),i=Jn(e,void 0);let l=!0;try{s=t(i),l=!1}finally{l?Hn(o):qn(o)}return _o(o,n),Co(s,o)}else if(!e||typeof e!="object"){if(s=t(e),s===void 0&&(s=e),s===Ta&&(s=void 0),this.autoFreeze_&&ms(s,!0),n){const o=[],i=[];at("Patches").generateReplacementPatches_(e,s,o,i),n(o,i)}return s}else we(1,e)},this.produceWithPatches=(e,t)=>{if(typeof e=="function")return(i,...l)=>this.produceWithPatches(i,d=>e(d,...l));let n,s;return[this.produce(e,t,(i,l)=>{n=i,s=l}),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){ot(r)||we(8),St(r)&&(r=Ec(r));const e=So(this),t=Jn(r,void 0);return t[Ae].isManual_=!0,qn(e),t}finishDraft(r,e){const t=r&&r[Ae];(!t||!t.isManual_)&&we(9);const{scope_:n}=t;return _o(n,e),Co(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=at("Patches").applyPatches_;return St(r)?n(r,e):this.produce(r,s=>n(s,e))}};function Jn(r,e){const t=Yt(r)?at("MapSet").proxyMap_(r,e):Xr(r)?at("MapSet").proxySet_(r,e):kc(r,e);return(e?e.scope_:$a()).drafts_.push(t),t}function Ec(r){return St(r)||we(10,r),Da(r)}function Da(r){if(!ot(r)||Kr(r))return r;const e=r[Ae];let t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=Wn(r,e.scope_.immer_.useStrictShallowCopy_)}else t=Wn(r,!0);return Lr(t,(n,s)=>{Ra(t,n,Da(s))}),e&&(e.finalized_=!1),t}var Ic=new Mc,Pc=Ic.produce;const Tc=r=>(e,t,n)=>(n.setState=(s,o,...i)=>{const l=typeof s=="function"?Pc(s):s;return e(l,o,...i)},r(n.setState,t,n)),Oc=Tc,Rc={};function $c(r,e){let t;try{t=r()}catch{return}return{getItem:s=>{var o;const i=d=>d===null?null:JSON.parse(d,void 0),l=(o=t.getItem(s))!=null?o:null;return l instanceof Promise?l.then(i):i(l)},setItem:(s,o)=>t.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>t.removeItem(s)}}const Jt=r=>e=>{try{const t=r(e);return t instanceof Promise?t:{then(n){return Jt(n)(t)},catch(n){return this}}}catch(t){return{then(n){return this},catch(n){return Jt(n)(t)}}}},Lc=(r,e)=>(t,n,s)=>{let o={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:c=>c,version:0,merge:(c,b)=>({...b,...c}),...e},i=!1;const l=new Set,d=new Set;let f;try{f=o.getStorage()}catch{}if(!f)return r((...c)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...c)},n,s);const g=Jt(o.serialize),h=()=>{const c=o.partialize({...n()});let b;const x=g({state:c,version:o.version}).then(y=>f.setItem(o.name,y)).catch(y=>{b=y});if(b)throw b;return x},p=s.setState;s.setState=(c,b)=>{p(c,b),h()};const w=r((...c)=>{t(...c),h()},n,s);let m;const u=()=>{var c;if(!f)return;i=!1,l.forEach(x=>x(n()));const b=((c=o.onRehydrateStorage)==null?void 0:c.call(o,n()))||void 0;return Jt(f.getItem.bind(f))(o.name).then(x=>{if(x)return o.deserialize(x)}).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==o.version){if(o.migrate)return o.migrate(x.state,x.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return x.state}).then(x=>{var y;return m=o.merge(x,(y=n())!=null?y:w),t(m,!0),h()}).then(()=>{b==null||b(m,void 0),i=!0,d.forEach(x=>x(m))}).catch(x=>{b==null||b(void 0,x)})};return s.persist={setOptions:c=>{o={...o,...c},c.getStorage&&(f=c.getStorage())},clearStorage:()=>{f==null||f.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>u(),hasHydrated:()=>i,onHydrate:c=>(l.add(c),()=>{l.delete(c)}),onFinishHydration:c=>(d.add(c),()=>{d.delete(c)})},u(),m||w},Dc=(r,e)=>(t,n,s)=>{let o={storage:$c(()=>localStorage),partialize:u=>u,version:0,merge:(u,c)=>({...c,...u}),...e},i=!1;const l=new Set,d=new Set;let f=o.storage;if(!f)return r((...u)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...u)},n,s);const g=()=>{const u=o.partialize({...n()});return f.setItem(o.name,{state:u,version:o.version})},h=s.setState;s.setState=(u,c)=>{h(u,c),g()};const p=r((...u)=>{t(...u),g()},n,s);s.getInitialState=()=>p;let w;const m=()=>{var u,c;if(!f)return;i=!1,l.forEach(x=>{var y;return x((y=n())!=null?y:p)});const b=((c=o.onRehydrateStorage)==null?void 0:c.call(o,(u=n())!=null?u:p))||void 0;return Jt(f.getItem.bind(f))(o.name).then(x=>{if(x)if(typeof x.version=="number"&&x.version!==o.version){if(o.migrate)return[!0,o.migrate(x.state,x.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,x.state];return[!1,void 0]}).then(x=>{var y;const[v,S]=x;if(w=o.merge(S,(y=n())!=null?y:p),t(w,!0),v)return g()}).then(()=>{b==null||b(w,void 0),w=n(),i=!0,d.forEach(x=>x(w))}).catch(x=>{b==null||b(void 0,x)})};return s.persist={setOptions:u=>{o={...o,...u},u.storage&&(f=u.storage)},clearStorage:()=>{f==null||f.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>m(),hasHydrated:()=>i,onHydrate:u=>(l.add(u),()=>{l.delete(u)}),onFinishHydration:u=>(d.add(u),()=>{d.delete(u)})},o.skipHydration||m(),w||p},Fc=(r,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((Rc?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),Lc(r,e)):Dc(r,e),Uc=Fc,Bc="/api";class Vt{constructor(e=Bc){W(this,"baseUrl");this.baseUrl=e}getBaseUrl(){return this.baseUrl}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}`);const i=await o.text();if(!i)return{};try{return JSON.parse(i)}catch(l){throw console.error(`JSON parse error for ${e}:`,l,"Response text:",i),new Error(`Invalid JSON response: ${i}`)}}catch(o){throw console.error(`API request failed: ${e}`,o),o}}async getSessions(e,t){const n=new URLSearchParams;e&&n.append("user_id",e),t&&n.append("project_id",t);const s=n.toString();return console.log("🔍 getSessions API调用:",{userId:e,projectId:t,queryString:s}),this.request(`/sessions${s?`?${s}`:""}`)}async createSession(e){return console.log("🔍 createSession API调用:",e),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 updateSession(e,t){return console.log("🔍 updateSession API调用:",{id:e,data:t}),this.request(`/sessions/${e}`,{method:"PUT",body:JSON.stringify({...t,updated_at:new Date().toISOString()})})}async getSessionMessages(e,t){const n=[];(t==null?void 0:t.limit)!==void 0&&n.push(`limit=${encodeURIComponent(String(t.limit))}`),(t==null?void 0:t.offset)!==void 0&&n.push(`offset=${encodeURIComponent(String(t.offset))}`);const s=n.length?`?${n.join("&")}`:"";return this.request(`/sessions/${e}/messages${s}`)}async createMessage(e){const t={...e,createdAt:e.createdAt?e.createdAt.toISOString():void 0};return this.request(`/sessions/${e.sessionId}/messages`,{method:"POST",body:JSON.stringify(t)})}async getMcpConfigs(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return console.log("🔍 getMcpConfigs API调用:",{userId:e,params:t}),this.request(`/mcp-configs${t}`)}async createMcpConfig(e){return console.log("🔍 API client createMcpConfig 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),this.request("/mcp-configs",{method:"POST",body:JSON.stringify(e)})}async updateMcpConfig(e,t){return console.log("🔍 API client updateMcpConfig 调用:",{id:e,data:t}),console.log("🔍 [关键] app_ids 字段:",t.app_ids,"类型:",typeof t.app_ids,"是否为数组:",Array.isArray(t.app_ids)),this.request(`/mcp-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteMcpConfig(e){return this.request(`/mcp-configs/${e}`,{method:"DELETE"})}async getAiModelConfigs(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return console.log("🔍 getAiModelConfigs API调用:",{userId:e,params:t}),this.request(`/ai-model-configs${t}`)}async createAiModelConfig(e){return this.request("/ai-model-configs",{method:"POST",body:JSON.stringify(e)})}async updateAiModelConfig(e,t){return this.request(`/ai-model-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteAiModelConfig(e){return this.request(`/ai-model-configs/${e}`,{method:"DELETE"})}async getSystemContexts(e){return this.request(`/system-contexts?user_id=${e}`)}async getActiveSystemContext(e){return this.request(`/system-context/active?user_id=${e}`)}async createSystemContext(e){return console.log("🔍 API client createSystemContext 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),this.request("/system-contexts",{method:"POST",body:JSON.stringify(e)})}async updateSystemContext(e,t){return console.log("🔍 API client updateSystemContext 调用:",{id:e,data:t}),console.log("🔍 [关键] app_ids 字段:",t.app_ids,"类型:",typeof t.app_ids,"是否为数组:",Array.isArray(t.app_ids)),this.request(`/system-contexts/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteSystemContext(e){return this.request(`/system-contexts/${e}`,{method:"DELETE"})}async activateSystemContext(e,t){return this.request(`/system-contexts/${e}/activate`,{method:"POST",body:JSON.stringify({user_id:t,is_active:!0})})}async getApplications(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return this.request(`/applications${t}`)}async getApplication(e){return this.request(`/applications/${e}`)}async createApplication(e){return this.request("/applications",{method:"POST",body:JSON.stringify(e)})}async updateApplication(e,t){return this.request(`/applications/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteApplication(e){return this.request(`/applications/${e}`,{method:"DELETE"})}async getAgents(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return this.request(`/agents${t}`)}async createAgent(e){return console.log("🔍 API client createAgent 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),this.request("/agents",{method:"POST",body:JSON.stringify(e)})}async updateAgent(e,t){return console.log("🔍 API client updateAgent 调用:",{agentId:e,data:t}),console.log("🔍 [关键] app_ids 字段:",t.app_ids,"类型:",typeof t.app_ids,"是否为数组:",Array.isArray(t.app_ids)),this.request(`/agents/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteAgent(e){return this.request(`/agents/${e}`,{method:"DELETE"})}async getConversationDetails(e){try{const t=await this.request(`/sessions/${e}`);return{data:{conversation:{id:t.id,title:t.title,created_at:t.created_at,updated_at:t.updated_at}}}}catch(t){return console.error("Failed to get conversation details:",t),{data:{conversation:{id:e,title:"Default Conversation",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}}}}}async getAssistant(e){try{const t=await this.request("/ai-model-configs"),n=t.find(s=>s.enabled)||t[0];if(!n)throw new Error("No AI model configuration found");return{data:{assistant:{id:n.id,name:n.name,model_config:{model_name:n.model_name,temperature:.7,max_tokens:4e3,api_key:n.api_key,base_url:n.base_url}}}}}catch(t){return console.error("Failed to get assistant:",t),{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(e){try{return{data:{mcp_servers:(await this.request("/mcp-configs")).filter(s=>s.enabled).map(s=>({name:s.name,url:s.command}))}}}catch(t){return console.error("Failed to get MCP servers:",t),{data:{mcp_servers:[]}}}}async getMcpConfigResource(e){try{return await this.request(`/mcp-configs/${e}/resource/config`)}catch(t){return console.error("Failed to get MCP config resource:",t),{success:!1,config:null}}}async getMcpConfigResourceByCommand(e){try{return await this.request("/mcp-configs/resource/config",{method:"POST",body:JSON.stringify(e)})}catch(t){return console.error("Failed to get MCP config resource by command:",t),{success:!1,config:null}}}async getMcpConfigProfiles(e){const t=await this.request(`/mcp-configs/${e}/profiles`);return Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.items)?t.items:[]}async createMcpConfigProfile(e,t){return this.request(`/mcp-configs/${e}/profiles`,{method:"POST",body:JSON.stringify(t)})}async updateMcpConfigProfile(e,t,n){return this.request(`/mcp-configs/${e}/profiles/${t}`,{method:"PUT",body:JSON.stringify(n)})}async deleteMcpConfigProfile(e,t){return this.request(`/mcp-configs/${e}/profiles/${t}`,{method:"DELETE"})}async activateMcpConfigProfile(e,t){return this.request(`/mcp-configs/${e}/profiles/${t}/activate`,{method:"POST",body:JSON.stringify({is_active:!0})})}async saveMessage(e,t){try{const n=t.id||`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{data:{message:await this.request("/messages",{method:"POST",body:JSON.stringify({id:n,sessionId:e,role:t.role,content:t.content,toolCalls:t.tool_calls||null,toolCallId:t.tool_call_id||null,reasoning:t.reasoning||null,metadata:t.metadata||null})})}}}catch(n){return console.error("Failed to save message:",n),{data:{message:{...t,id:Date.now().toString(),created_at:new Date().toISOString()}}}}}async getMessages(e,t={}){try{const n=[];t.limit!==void 0&&n.push(`limit=${encodeURIComponent(String(t.limit))}`),t.offset!==void 0&&n.push(`offset=${encodeURIComponent(String(t.offset))}`);const s=n.length?`?${n.join("&")}`:"";return{data:{messages:await this.request(`/sessions/${e}/messages${s}`)}}}catch(n){return console.error("Failed to get messages:",n),{data:{messages:[]}}}}async addMessage(e,t){return this.saveMessage(e,t)}async streamChat(e,t,n,s){const o=`${this.baseUrl}/agent_v2/chat/stream`,i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:e,content:t,user_id:s,ai_model_config:{model_name:n.model_name,temperature:n.temperature||.7,max_tokens:n.max_tokens||1e3,api_key:n.api_key,base_url:n.base_url}})});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);if(!i.body)throw new Error("Response body is null");return i.body}async streamAgentChat(e,t,n,s){const o=`${this.baseUrl}/agents/chat/stream`,i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({session_id:e,content:t,agent_id:n,user_id:s})});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);if(!i.body)throw new Error("Response body is null");return i.body}async stopChat(e){return this.request("/chat/stop",{method:"POST",body:JSON.stringify({session_id:e})})}}const ee=new Vt,Ar={getDetails:r=>ee.getConversationDetails(r),getAssistant:r=>ee.getAssistant(r),getMcpServers:r=>ee.getMcpServers(r),saveMessage:(r,e)=>ee.saveMessage(r,e),getMessages:(r,e)=>ee.getMessages(r,e),addMessage:(r,e)=>ee.addMessage(r,e)};class ps{constructor(e,t,n=ee){W(this,"userId");W(this,"projectId");W(this,"client");this.userId=e,this.projectId=t,this.client=n}async createSession(e){const t={id:crypto.randomUUID(),title:e.title,user_id:this.userId,project_id:this.projectId},n=await this.client.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 this.client.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(){console.log("🔍 DatabaseService.getAllSessions 调用:",{userId:this.userId,projectId:this.projectId});const e=await this.client.getSessions(this.userId,this.projectId);console.log("🔍 API返回的会话数据:",e);const t=e.map(n=>({id:n.id,title:n.title,createdAt:new Date(n.created_at||n.createdAt),updatedAt:new Date(n.updated_at||n.updatedAt),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}));return console.log("🔍 格式化后的会话数据:",t),t}async updateSession(e,t){try{const n={};t.title!==void 0&&(n.title=t.title),t.metadata!==void 0&&(n.metadata=t.metadata);const s=await this.client.updateSession(e,n);return s?{id:s.id,title:s.title,createdAt:new Date(s.created_at||s.createdAt),updatedAt:new Date(s.updated_at||s.updatedAt),messageCount:s.message_count||s.messageCount||0,tokenUsage:s.token_usage||s.tokenUsage||0,pinned:s.pinned||!1,archived:s.archived||!1,tags:s.tags||null,metadata:s.metadata||null}:null}catch(n){return console.error("Failed to update session:",n),null}}async deleteSession(e){try{return await this.client.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?typeof t.metadata=="string"?JSON.parse(t.metadata):t.metadata:void 0,toolCalls:t.tool_calls?typeof t.tool_calls=="string"?JSON.parse(t.tool_calls):t.tool_calls:void 0},s=await this.client.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?typeof s.metadata=="string"?JSON.parse(s.metadata):s.metadata:e.metadata}}async getSessionMessages(e,t={limit:10,offset:0}){var g,h,p,w,m;const n=t.limit??10,s=t.offset??0,i=(await this.client.getSessionMessages(e,{limit:n,offset:s})).map(u=>{let c;if(u.metadata)try{c=typeof u.metadata=="string"?JSON.parse(u.metadata):u.metadata}catch(x){console.warn("Failed to parse message metadata:",x),c={}}let b;if(u.toolCalls)try{b=typeof u.toolCalls=="string"?JSON.parse(u.toolCalls):u.toolCalls}catch(x){console.warn("Failed to parse top-level toolCalls:",x)}return{id:u.id,sessionId:u.session_id,role:u.role,content:u.content,summary:u.summary,toolCallId:u.tool_call_id,reasoning:u.reasoning,metadata:c,topLevelToolCalls:b,createdAt:new Date(u.created_at),originalMessage:u}}),l=new Map;i.forEach(u=>{var c;if(u.role==="tool"&&u.toolCallId){const b=((c=u.metadata)==null?void 0:c.isError)||!1;l.set(u.toolCallId,{content:u.content,error:b?u.content:void 0})}});const d=i.map(u=>{var v,S;let c;const b=u.topLevelToolCalls||((v=u.metadata)==null?void 0:v.toolCalls);u.role==="assistant"&&b&&Array.isArray(b)&&(console.log("[Database] 处理工具调用:",{messageId:u.id,sourceToolCalls:b}),c=b.map(C=>{if(C.function){let _={};try{_=typeof C.function.arguments=="string"?JSON.parse(C.function.arguments):C.function.arguments}catch(T){console.warn("Failed to parse tool call arguments:",T),_={}}const I=l.get(C.id);return{id:C.id||`tool_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,messageId:u.id,name:C.function.name,arguments:_,result:(I==null?void 0:I.content)||void 0,error:(I==null?void 0:I.error)||void 0,createdAt:u.createdAt}}return null}).filter(Boolean));const x=[],y=typeof u.reasoning=="string"&&u.reasoning.trim().length>0;return u.role==="assistant"&&y&&x.push({type:"thinking",content:u.reasoning}),typeof u.content=="string"&&u.content.trim().length>0&&x.push({type:"text",content:u.content}),c&&Array.isArray(c)&&c.length>0&&c.forEach(C=>{x.push({type:"tool_call",toolCallId:C.id})}),{id:u.id,sessionId:u.sessionId,role:u.role,content:u.content,rawContent:u.summary,tokensUsed:void 0,status:"completed",createdAt:u.createdAt,updatedAt:void 0,toolCallId:u.toolCallId,metadata:{...u.metadata,toolCalls:c,contentSegments:x.length>0?x:(S=u.metadata)==null?void 0:S.contentSegments}}}),f=new Set;for(let u=0;u<d.length;u++){const c=d[u];if(((g=c==null?void 0:c.metadata)==null?void 0:g.type)==="session_summary"){const b=typeof c.rawContent=="string"&&c.rawContent.length>0?c.rawContent:typeof((h=c.metadata)==null?void 0:h.summary)=="string"&&c.metadata.summary.length>0?c.metadata.summary:typeof c.content=="string"?c.content:"";let x=-1;for(let y=u+1;y<d.length;y++)if(((p=d[y])==null?void 0:p.role)==="assistant"){x=y;break}if(x===-1){for(let y=u-1;y>=0;y--)if(((w=d[y])==null?void 0:w.role)==="assistant"){x=y;break}}if(x!==-1){const y=d[x],v=`【上下文摘要】
34
+ `,S=(((m=y.metadata)==null?void 0:m.contentSegments)||[]).slice(),C=S.length-1;C>=0&&S[C].type==="thinking"&&String(S[C].content||"").startsWith(v)?S[C].content=v+String(b||""):S.push({type:"thinking",content:v+String(b||"")}),y.metadata=y.metadata||{},y.metadata.contentSegments=S,c.metadata=c.metadata||{},c.metadata.hidden=!0,f.add(c.id)}}}return d}async updateMessage(e,t){return console.warn("updateMessage not implemented yet"),null}async deleteMessage(e){return console.warn("deleteMessage not implemented yet"),!1}}const Vn="RFC3986",Gn={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},Wc="RFC1738",Hc=Array.isArray,Te=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),Cn=1024,qc=(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(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=Cn){const d=o.length>=Cn?o.slice(l,l+Cn):o,f=[];for(let g=0;g<d.length;++g){let h=d.charCodeAt(g);if(h===45||h===46||h===95||h===126||h>=48&&h<=57||h>=65&&h<=90||h>=97&&h<=122||s===Wc&&(h===40||h===41)){f[f.length]=d.charAt(g);continue}if(h<128){f[f.length]=Te[h];continue}if(h<2048){f[f.length]=Te[192|h>>6]+Te[128|h&63];continue}if(h<55296||h>=57344){f[f.length]=Te[224|h>>12]+Te[128|h>>6&63]+Te[128|h&63];continue}g+=1,h=65536+((h&1023)<<10|d.charCodeAt(g)&1023),f[f.length]=Te[240|h>>18]+Te[128|h>>12&63]+Te[128|h>>6&63]+Te[128|h&63]}i+=f.join("")}return i};function zc(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Ao(r,e){if(Hc(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const Jc=Object.prototype.hasOwnProperty,Fa={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Re=Array.isArray,Vc=Array.prototype.push,Ua=function(r,e){Vc.apply(r,Re(e)?e:[e])},Gc=Date.prototype.toISOString,ce={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:qc,encodeValuesOnly:!1,format:Vn,formatter:Gn[Vn],indices:!1,serializeDate(r){return Gc.call(r)},skipNulls:!1,strictNullHandling:!1};function Xc(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const jn={};function Ba(r,e,t,n,s,o,i,l,d,f,g,h,p,w,m,u,c,b){let x=r,y=b,v=0,S=!1;for(;(y=y.get(jn))!==void 0&&!S;){const $=y.get(r);if(v+=1,typeof $<"u"){if($===v)throw new RangeError("Cyclic object value");S=!0}typeof y.get(jn)>"u"&&(v=0)}if(typeof f=="function"?x=f(e,x):x instanceof Date?x=p==null?void 0:p(x):t==="comma"&&Re(x)&&(x=Ao(x,function($){return $ instanceof Date?p==null?void 0:p($):$})),x===null){if(o)return d&&!u?d(e,ce.encoder,c,"key",w):e;x=""}if(Xc(x)||zc(x)){if(d){const $=u?e:d(e,ce.encoder,c,"key",w);return[(m==null?void 0:m($))+"="+(m==null?void 0:m(d(x,ce.encoder,c,"value",w)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(x)))]}const C=[];if(typeof x>"u")return C;let _;if(t==="comma"&&Re(x))u&&d&&(x=Ao(x,d)),_=[{value:x.length>0?x.join(",")||null:void 0}];else if(Re(f))_=f;else{const $=Object.keys(x);_=g?$.sort(g):$}const I=l?String(e).replace(/\./g,"%2E"):String(e),T=n&&Re(x)&&x.length===1?I+"[]":I;if(s&&Re(x)&&x.length===0)return T+"[]";for(let $=0;$<_.length;++$){const F=_[$],k=typeof F=="object"&&typeof F.value<"u"?F.value:x[F];if(i&&k===null)continue;const U=h&&l?F.replace(/\./g,"%2E"):F,H=Re(x)?typeof t=="function"?t(T,U):T:T+(h?"."+U:"["+U+"]");b.set(r,v);const Z=new WeakMap;Z.set(jn,b),Ua(C,Ba(k,H,t,n,s,o,i,l,t==="comma"&&u&&Re(x)?null:d,f,g,h,p,w,m,u,c,Z))}return C}function Kc(r=ce){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||ce.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=Vn;if(typeof r.format<"u"){if(!Jc.call(Gn,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=Gn[t];let s=ce.filter;(typeof r.filter=="function"||Re(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in Fa?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=ce.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:ce.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:ce.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:ce.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:ce.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?ce.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:ce.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:ce.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:ce.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:ce.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:ce.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:ce.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:ce.strictNullHandling}}function Yc(r,e={}){let t=r;const n=Kc(e);let s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):Re(n.filter)&&(o=n.filter,s=o);const i=[];if(typeof t!="object"||t===null)return"";const l=Fa[n.arrayFormat],d=l==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const f=new WeakMap;for(let p=0;p<s.length;++p){const w=s[p];n.skipNulls&&t[w]===null||Ua(i,Ba(t[w],w,l,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,f))}const g=i.join(n.delimiter);let h=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?h+="utf8=%26%2310003%3B&":h+="utf8=%E2%9C%93&"),g.length>0?h+g:""}const pt="4.104.0";let ko=!1,Wt,Wa,Ha,Xn,qa,za,Ja,Va,Ga;function Qc(r,e={auto:!1}){if(ko)throw new Error(`you must \`import 'openai/shims/${r.kind}'\` before importing anything else from openai`);if(Wt)throw new Error(`can't \`import 'openai/shims/${r.kind}'\` after \`import 'openai/shims/${Wt}'\``);ko=e.auto,Wt=r.kind,Wa=r.fetch,Ha=r.FormData,Xn=r.File,qa=r.ReadableStream,za=r.getMultipartRequestOptions,Ja=r.getDefaultAgent,Va=r.fileFromPath,Ga=r.isFsReadStream}class Zc{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function ed({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(i){throw new Error(`this environment is missing the following Web Fetch API type: ${i.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(i,l)=>({...l,body:new Zc(i)}),getDefaultAgent:i=>{},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:i=>!1}}const Xa=()=>{Wt||Qc(ed(),{auto:!0})};Xa();class V extends Error{}class ge extends V{constructor(e,t,n,s){super(`${ge.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 Yr({message:n,cause:Yn(t)});const o=t==null?void 0:t.error;return e===400?new Ka(e,o,n,s):e===401?new Ya(e,o,n,s):e===403?new Qa(e,o,n,s):e===404?new Za(e,o,n,s):e===409?new ei(e,o,n,s):e===422?new ti(e,o,n,s):e===429?new ri(e,o,n,s):e>=500?new ni(e,o,n,s):new ge(e,o,n,s)}}class Ne extends ge{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Yr extends ge{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class xs extends Yr{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Ka extends ge{}class Ya extends ge{}class Qa extends ge{}class Za extends ge{}class ei extends ge{}class ti extends ge{}class ri extends ge{}class ni extends ge{}class si extends V{constructor(){super("Could not parse response content as the length limit was reached")}}class oi extends V{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var mr=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},Ye=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)},Ce;class Qr{constructor(){Ce.set(this,void 0),this.buffer=new Uint8Array,mr(this,Ce,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=td(this.buffer,Ye(this,Ce,"f")))!=null;){if(o.carriage&&Ye(this,Ce,"f")==null){mr(this,Ce,o.index,"f");continue}if(Ye(this,Ce,"f")!=null&&(o.index!==Ye(this,Ce,"f")+1||o.carriage)){s.push(this.decodeText(this.buffer.slice(0,Ye(this,Ce,"f")-1))),this.buffer=this.buffer.slice(Ye(this,Ce,"f")),mr(this,Ce,null,"f");continue}const i=Ye(this,Ce,"f")!==null?o.preceding-1:o.preceding,l=this.decodeText(this.buffer.slice(0,i));s.push(l),this.buffer=this.buffer.slice(o.index),mr(this,Ce,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 V(`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 V(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new V("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
35
+ `):[]}}Ce=new WeakMap;Qr.NEWLINE_CHARS=new Set([`
36
+ `,"\r"]);Qr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function td(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 rd(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 ai(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 Le{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 i of nd(e,t))if(!o){if(i.data.startsWith("[DONE]")){o=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let l;try{l=JSON.parse(i.data)}catch(d){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),d}if(l&&l.error)throw new ge(void 0,l.error,void 0,hi(e.headers));yield l}else{let l;try{l=JSON.parse(i.data)}catch(d){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),d}if(i.event=="error")throw new ge(void 0,l.error,l.message,void 0);yield{event:i.event,data:l}}}o=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{o||t.abort()}}return new Le(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){const i=new Qr,l=ai(e);for await(const d of l)for(const f of i.decode(d))yield f;for(const d of i.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 i=!1;try{for await(const l of s())i||l&&(yield JSON.parse(l));i=!0}catch(l){if(l instanceof Error&&l.name==="AbortError")return;throw l}finally{i||t.abort()}}return new Le(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){const i=n.next();e.push(i),t.push(i)}return o.shift()}});return[new Le(()=>s(e),this.controller),new Le(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new qa({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:o,done:i}=await t.next();if(i)return s.close();const l=n.encode(JSON.stringify(o)+`
37
+ `);s.enqueue(l)}catch(o){s.error(o)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}}async function*nd(r,e){if(!r.body)throw e.abort(),new V("Attempted to iterate over a response with no body");const t=new od,n=new Qr,s=ai(r.body);for await(const o of sd(s))for(const i of n.decode(o)){const l=t.decode(i);l&&(yield l)}for(const o of n.flush()){const i=t.decode(o);i&&(yield i)}}async function*sd(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=rd(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}class od{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(`
38
+ `),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]=ad(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function ad(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}const ii=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",li=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Zr(r),Zr=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",id=r=>li(r)||ii(r)||Ga(r);async function ci(r,e,t){var s;if(r=await r,li(r))return r;if(ii(r)){const o=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");const i=Zr(o)?[await o.arrayBuffer()]:[o];return new Xn(i,e,t)}const n=await ld(r);if(e||(e=dd(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 Xn(n,e,t)}async function ld(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Zr(r))e.push(await r.arrayBuffer());else if(ud(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: ${cd(r)}`);return e}function cd(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function dd(r){var e;return An(r.name)||An(r.filename)||((e=An(r.path))==null?void 0:e.split(/[\\/]/).pop())}const An=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},ud=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",No=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody",it=async r=>{const e=await fd(r.body);return za(e,r)},fd=async r=>{const e=new Ha;return await Promise.all(Object.entries(r||{}).map(([t,n])=>Kn(e,t,n))),e},Kn=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(id(t)){const n=await ci(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>Kn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>Kn(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 hd=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},md=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)},gr;Xa();async function di(r){var i;const{response:e}=r;if(r.options.stream)return Ge("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):Le.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;const t=e.headers.get("content-type"),n=(i=t==null?void 0:t.split(";")[0])==null?void 0:i.trim();if((n==null?void 0:n.includes("application/json"))||(n==null?void 0:n.endsWith("+json"))){const l=await e.json();return Ge("response",e.status,e.url,e.headers,l),ui(l,e)}const o=await e.text();return Ge("response",e.status,e.url,e.headers,o),o}function ui(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 en extends Promise{constructor(e,t=di){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new en(this.responsePromise,async t=>ui(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 gd{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:o}){this.baseURL=e,this.maxRetries=kn("maxRetries",t),this.timeout=kn("timeout",n),this.httpAgent=s,this.fetch=o??Wa}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...wd(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Cd()}`}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&&Zr(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 u;const n={...e},{method:s,path:o,query:i,headers:l={}}=n,d=ArrayBuffer.isView(n.body)||n.__binaryRequest&&typeof n.body=="string"?n.body:No(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,f=this.calculateContentLength(d),g=this.buildURL(o,i);"timeout"in n&&kn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const h=n.httpAgent??this.httpAgent??Ja(g),p=n.timeout+1e3;typeof((u=h==null?void 0:h.options)==null?void 0:u.timeout)=="number"&&p>(h.options.timeout??0)&&(h.options.timeout=p),this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),l[this.idempotencyHeader]=e.idempotencyKey);const w=this.buildHeaders({options:n,headers:l,contentLength:f,retryCount:t});return{req:{method:s,...d&&{body:d},headers:w,...h&&{agent:h},signal:n.signal??null},url:g,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const o={};n&&(o["content-length"]=n);const i=this.defaultHeaders(e);return Po(o,i),Po(o,t),No(e.body)&&Wt!=="node"&&delete o["content-type"],xr(i,"x-stainless-retry-count")===void 0&&xr(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(s)),xr(i,"x-stainless-timeout")===void 0&&xr(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 ge.generate(e,t,n,s)}request(e,t=null){return new en(this.makeRequest(e,t))}async makeRequest(e,t){var h,p;const n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);const{req:o,url:i,timeout:l}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(o,{url:i,options:n}),Ge("request",i,n,o.headers),(h=n.signal)!=null&&h.aborted)throw new Ne;const d=new AbortController,f=await this.fetchWithTimeout(i,o,l,d).catch(Yn);if(f instanceof Error){if((p=n.signal)!=null&&p.aborted)throw new Ne;if(t)return this.retryRequest(n,t);throw f.name==="AbortError"?new xs:new Yr({cause:f})}const g=hi(f.headers);if(!f.ok){if(t&&this.shouldRetry(f)){const x=`retrying, ${t} attempts remaining`;return Ge(`response (error; ${x})`,f.status,i,g),this.retryRequest(n,t,g)}const w=await f.text().catch(x=>Yn(x).message),m=vd(w),u=m?void 0:w;throw Ge(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,f.status,i,g,u),this.makeStatusError(f.status,m,u,g)}return{response:f,options:n,controller:d}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new pd(this,n,e)}buildURL(e,t){const n=Sd(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return mi(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 V(`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,...i}=t||{};o&&o.addEventListener("abort",()=>s.abort());const l=setTimeout(()=>s.abort(),n),d={signal:s.signal,...i};return d.method&&(d.method=d.method.toUpperCase()),this.fetch.call(void 0,e,d).finally(()=>{clearTimeout(l)})}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 l=parseFloat(o);Number.isNaN(l)||(s=l)}const i=n==null?void 0:n["retry-after"];if(i&&!s){const l=parseFloat(i);Number.isNaN(l)?s=Date.parse(i)-Date.now():s=l*1e3}if(!(s&&0<=s&&s<60*1e3)){const l=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Qt(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}getUserAgent(){return`${this.constructor.name}/JS ${pt}`}}class fi{constructor(e,t,n,s){gr.set(this,void 0),hd(this,gr,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 V("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 md(this,gr,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(gr=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class pd extends en{constructor(e,t,n){super(t,async s=>new n(e,s.response,await di(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const hi=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),xd={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},oe=r=>typeof r=="object"&&r!==null&&!mi(r)&&Object.keys(r).every(e=>gi(xd,e)),bd=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":pt,"X-Stainless-OS":Eo(Deno.build.os),"X-Stainless-Arch":Mo(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":pt,"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":pt,"X-Stainless-OS":Eo(process.platform),"X-Stainless-Arch":Mo(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const r=yd();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":pt,"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":pt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function yd(){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,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}const Mo=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Eo=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 Io;const wd=()=>Io??(Io=bd()),vd=r=>{try{return JSON.parse(r)}catch{return}},_d=/^[a-z][a-z0-9+.-]*:/i,Sd=r=>_d.test(r),Qt=r=>new Promise(e=>setTimeout(e,r)),kn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new V(`${r} must be an integer`);if(e<0)throw new V(`${r} must be a positive integer`);return e},Yn=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)},pr=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 mi(r){if(!r)return!0;for(const e in r)return!1;return!0}function gi(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Po(r,e){for(const t in e){if(!gi(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 To=new Set(["authorization","api-key"]);function Ge(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 i={...s,headers:{...s.headers}};for(const l in s.headers)To.has(l.toLowerCase())&&(i.headers[l]="REDACTED");return i}let o=null;for(const i in s)To.has(i.toLowerCase())&&(o??(o={...s}),o[i]="REDACTED");return o??s});console.log(`OpenAI:DEBUG:${r}`,...n)}}const Cd=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),jd=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Ad=r=>typeof(r==null?void 0:r.get)=="function",xr=(r,e)=>{var n;const t=e.toLowerCase();if(Ad(r)){const s=((n=e[0])==null?void 0:n.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(o,i,l)=>i+l.toUpperCase());for(const o of[e,t,e.toUpperCase(),s]){const i=r.get(o);if(i)return i}}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},kd=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 Nn(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}class tn extends fi{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 de extends fi{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 G{constructor(e){this._client=e}}let pi=class extends G{list(e,t={},n){return oe(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Nd,{query:t,...n})}},rn=class extends G{constructor(){super(...arguments),this.messages=new pi(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 oe(e)?this.list({},e):this._client.getAPIList("/chat/completions",nn,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class nn extends de{}class Nd extends de{}rn.ChatCompletionsPage=nn;rn.Messages=pi;let sn=class extends G{constructor(){super(...arguments),this.completions=new rn(this._client)}};sn.Completions=rn;sn.ChatCompletionsPage=nn;class xi extends G{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 G{create(e,t){return this._client.post("/audio/transcriptions",it({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class yi extends G{create(e,t){return this._client.post("/audio/translations",it({body:e,...t,__metadata:{model:e.model}}))}}class Zt extends G{constructor(){super(...arguments),this.transcriptions=new bi(this._client),this.translations=new yi(this._client),this.speech=new xi(this._client)}}Zt.Transcriptions=bi;Zt.Translations=yi;Zt.Speech=xi;class bs extends G{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 oe(e)?this.list({},e):this._client.getAPIList("/batches",ys,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class ys extends de{}bs.BatchesPage=ys;var Me=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},se=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)},Qn,kr,Nr,$t,Lt,Mr,Dt,Ue,Ft,Ur,Br,xt,wi;class ws{constructor(){Qn.add(this),this.controller=new AbortController,kr.set(this,void 0),Nr.set(this,()=>{}),$t.set(this,()=>{}),Lt.set(this,void 0),Mr.set(this,()=>{}),Dt.set(this,()=>{}),Ue.set(this,{}),Ft.set(this,!1),Ur.set(this,!1),Br.set(this,!1),xt.set(this,!1),Me(this,kr,new Promise((e,t)=>{Me(this,Nr,e,"f"),Me(this,$t,t,"f")}),"f"),Me(this,Lt,new Promise((e,t)=>{Me(this,Mr,e,"f"),Me(this,Dt,t,"f")}),"f"),se(this,kr,"f").catch(()=>{}),se(this,Lt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},se(this,Qn,"m",wi).bind(this))},0)}_connected(){this.ended||(se(this,Nr,"f").call(this),this._emit("connect"))}get ended(){return se(this,Ft,"f")}get errored(){return se(this,Ur,"f")}get aborted(){return se(this,Br,"f")}abort(){this.controller.abort()}on(e,t){return(se(this,Ue,"f")[e]||(se(this,Ue,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=se(this,Ue,"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(se(this,Ue,"f")[e]||(se(this,Ue,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Me(this,xt,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){Me(this,xt,!0,"f"),await se(this,Lt,"f")}_emit(e,...t){if(se(this,Ft,"f"))return;e==="end"&&(Me(this,Ft,!0,"f"),se(this,Mr,"f").call(this));const n=se(this,Ue,"f")[e];if(n&&(se(this,Ue,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!se(this,xt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),se(this,$t,"f").call(this,s),se(this,Dt,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!se(this,xt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),se(this,$t,"f").call(this,s),se(this,Dt,"f").call(this,s),this._emit("end")}}_emitFinal(){}}kr=new WeakMap,Nr=new WeakMap,$t=new WeakMap,Lt=new WeakMap,Mr=new WeakMap,Dt=new WeakMap,Ue=new WeakMap,Ft=new WeakMap,Ur=new WeakMap,Br=new WeakMap,xt=new WeakMap,Qn=new WeakSet,wi=function(e){if(Me(this,Ur,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Ne),e instanceof Ne)return Me(this,Br,!0,"f"),this._emit("abort",e);if(e instanceof V)return this._emit("error",e);if(e instanceof Error){const t=new V(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new V(String(e)))};var J=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)},Se=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},me,Zn,$e,Er,Ee,tt,bt,et,Wr,je,Ir,Pr,Ht,Ut,Bt,Oo,Ro,$o,Lo,Do,Fo,Uo;class Ie extends ws{constructor(){super(...arguments),me.add(this),Zn.set(this,[]),$e.set(this,{}),Er.set(this,{}),Ee.set(this,void 0),tt.set(this,void 0),bt.set(this,void 0),et.set(this,void 0),Wr.set(this,void 0),je.set(this,void 0),Ir.set(this,void 0),Pr.set(this,void 0),Ht.set(this,void 0)}[(Zn=new WeakMap,$e=new WeakMap,Er=new WeakMap,Ee=new WeakMap,tt=new WeakMap,bt=new WeakMap,et=new WeakMap,Wr=new WeakMap,je=new WeakMap,Ir=new WeakMap,Pr=new WeakMap,Ht=new WeakMap,me=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,i)=>t.push({resolve:o,reject:i})).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 Ie;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=Le.fromReadableStream(e,this.controller);for await(const i of s)J(this,me,"m",Ut).call(this,i);if((o=s.controller.signal)!=null&&o.aborted)throw new Ne;return this._addRun(J(this,me,"m",Bt).call(this))}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,o){const i=new Ie;return i._run(()=>i._runToolAssistantStream(e,t,n,s,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,n,s,o){var f;const i=o==null?void 0:o.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const l={...s,stream:!0},d=await e.submitToolOutputs(t,n,l,{...o,signal:this.controller.signal});this._connected();for await(const g of d)J(this,me,"m",Ut).call(this,g);if((f=d.controller.signal)!=null&&f.aborted)throw new Ne;return this._addRun(J(this,me,"m",Bt).call(this))}static createThreadAssistantStream(e,t,n){const s=new Ie;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 Ie;return o._run(()=>o._runAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return J(this,Ir,"f")}currentRun(){return J(this,Pr,"f")}currentMessageSnapshot(){return J(this,Ee,"f")}currentRunStepSnapshot(){return J(this,Ht,"f")}async finalRunSteps(){return await this.done(),Object.values(J(this,$e,"f"))}async finalMessages(){return await this.done(),Object.values(J(this,Er,"f"))}async finalRun(){if(await this.done(),!J(this,tt,"f"))throw Error("Final run was not received.");return J(this,tt,"f")}async _createThreadAssistantStream(e,t,n){var l;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},i=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(const d of i)J(this,me,"m",Ut).call(this,d);if((l=i.controller.signal)!=null&&l.aborted)throw new Ne;return this._addRun(J(this,me,"m",Bt).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 i={...n,stream:!0},l=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const f of l)J(this,me,"m",Ut).call(this,f);if((d=l.controller.signal)!=null&&d.aborted)throw new Ne;return this._addRun(J(this,me,"m",Bt).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(Nn(o)&&Nn(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(const i of s){if(!Nn(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const l=i.index;if(l==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof l!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${l}`);const d=o[l];d==null?o.push(i):o[l]=this.accumulateDelta(d,i)}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)}}Ut=function(e){if(!this.ended)switch(Se(this,Ir,e,"f"),J(this,me,"m",$o).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":J(this,me,"m",Uo).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":J(this,me,"m",Ro).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":J(this,me,"m",Oo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Bt=function(){if(this.ended)throw new V("stream has ended, this shouldn't happen");if(!J(this,tt,"f"))throw Error("Final run has not been received");return J(this,tt,"f")},Oo=function(e){const[t,n]=J(this,me,"m",Do).call(this,e,J(this,Ee,"f"));Se(this,Ee,t,"f"),J(this,Er,"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,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=J(this,bt,"f")){if(J(this,et,"f"))switch(J(this,et,"f").type){case"text":this._emit("textDone",J(this,et,"f").text,J(this,Ee,"f"));break;case"image_file":this._emit("imageFileDone",J(this,et,"f").image_file,J(this,Ee,"f"));break}Se(this,bt,s.index,"f")}Se(this,et,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(J(this,bt,"f")!==void 0){const s=e.data.content[J(this,bt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,J(this,Ee,"f"));break;case"text":this._emit("textDone",s.text,J(this,Ee,"f"));break}}J(this,Ee,"f")&&this._emit("messageDone",e.data),Se(this,Ee,void 0,"f")}},Ro=function(e){const t=J(this,me,"m",Lo).call(this,e);switch(Se(this,Ht,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==J(this,Wr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(J(this,je,"f")&&this._emit("toolCallDone",J(this,je,"f")),Se(this,Wr,o.index,"f"),Se(this,je,t.step_details.tool_calls[o.index],"f"),J(this,je,"f")&&this._emit("toolCallCreated",J(this,je,"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":Se(this,Ht,void 0,"f"),e.data.step_details.type=="tool_calls"&&J(this,je,"f")&&(this._emit("toolCallDone",J(this,je,"f")),Se(this,je,void 0,"f")),this._emit("runStepDone",e.data,t);break}},$o=function(e){J(this,Zn,"f").push(e),this._emit("event",e)},Lo=function(e){switch(e.event){case"thread.run.step.created":return J(this,$e,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=J(this,$e,"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=Ie.accumulateDelta(t,n.delta);J(this,$e,"f")[e.data.id]=s}return J(this,$e,"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":J(this,$e,"f")[e.data.id]=e.data;break}if(J(this,$e,"f")[e.data.id])return J(this,$e,"f")[e.data.id];throw new Error("No snapshot available")},Do=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 i=t.content[o.index];t.content[o.index]=J(this,me,"m",Fo).call(this,o,i)}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")},Fo=function(e,t){return Ie.accumulateDelta(t,e)},Uo=function(e){switch(Se(this,Pr,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":Se(this,tt,e.data,"f"),J(this,je,"f")&&(this._emit("toolCallDone",J(this,je,"f")),Se(this,je,void 0,"f"));break}};class vs extends G{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 oe(e)?this.list({},e):this._client.getAPIList("/assistants",_s,{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 _s extends de{}vs.AssistantsPage=_s;function Bo(r){return typeof r.parse=="function"}const yt=r=>(r==null?void 0:r.role)==="assistant",vi=r=>(r==null?void 0:r.role)==="function",_i=r=>(r==null?void 0:r.role)==="tool";function Ss(r){return(r==null?void 0:r.$brand)==="auto-parseable-response-format"}function er(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function Md(r,e){return!e||!Si(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}}))}:Cs(r,e)}function Cs(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new si;if(n.finish_reason==="content_filter")throw new oi;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(o=>Id(e,o)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Ed(e,n.message.content):null}}});return{...r,choices:t}}function Ed(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 Id(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:er(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function Pd(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 er(t)||(t==null?void 0:t.function.strict)||!1}function Si(r){var e;return Ss(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>er(t)||t.type==="function"&&t.function.strict===!0))??!1}function Td(r){for(const e of r??[]){if(e.type!=="function")throw new V(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new V(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var ye=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)},pe,es,Hr,ts,rs,ns,Ci,ss;const Wo=10;class ji extends ws{constructor(){super(...arguments),pe.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),(vi(e)||_i(e))&&e.content)this._emit("functionCallResult",e.content);else if(yt(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(yt(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 V("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),ye(this,pe,"m",es).call(this)}async finalMessage(){return await this.done(),ye(this,pe,"m",Hr).call(this)}async finalFunctionCall(){return await this.done(),ye(this,pe,"m",ts).call(this)}async finalFunctionCallResult(){return await this.done(),ye(this,pe,"m",rs).call(this)}async totalUsage(){return await this.done(),ye(this,pe,"m",ns).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=ye(this,pe,"m",Hr).call(this);t&&this._emit("finalMessage",t);const n=ye(this,pe,"m",es).call(this);n&&this._emit("finalContent",n);const s=ye(this,pe,"m",ts).call(this);s&&this._emit("finalFunctionCall",s);const o=ye(this,pe,"m",rs).call(this);o!=null&&this._emit("finalFunctionCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",ye(this,pe,"m",ns).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())),ye(this,pe,"m",Ci).call(this,t);const o=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Cs(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 p;const s="function",{function_call:o="auto",stream:i,...l}=t,d=typeof o!="string"&&(o==null?void 0:o.name),{maxChatCompletions:f=Wo}=n||{},g={};for(const w of t.functions)g[w.name||w.function.name]=w;const h=t.functions.map(w=>({name:w.name||w.function.name,parameters:w.parameters,description:w.description}));for(const w of t.messages)this._addMessage(w,!1);for(let w=0;w<f;++w){const u=(p=(await this._createChatCompletion(e,{...l,function_call:o,functions:h,messages:[...this.messages]},n)).choices[0])==null?void 0:p.message;if(!u)throw new V("missing message in ChatCompletion response");if(!u.function_call)return;const{name:c,arguments:b}=u.function_call,x=g[c];if(x){if(d&&d!==c){const C=`Invalid function_call: ${JSON.stringify(c)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,name:c,content:C});continue}}else{const C=`Invalid function_call: ${JSON.stringify(c)}. Available options are: ${h.map(_=>JSON.stringify(_.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:c,content:C});continue}let y;try{y=Bo(x)?await x.parse(b):b}catch(C){this._addMessage({role:s,name:c,content:C instanceof Error?C.message:String(C)});continue}const v=await x.function(y,this),S=ye(this,pe,"m",ss).call(this,v);if(this._addMessage({role:s,name:c,content:S}),d)return}}async _runTools(e,t,n){var w,m,u;const s="tool",{tool_choice:o="auto",stream:i,...l}=t,d=typeof o!="string"&&((w=o==null?void 0:o.function)==null?void 0:w.name),{maxChatCompletions:f=Wo}=n||{},g=t.tools.map(c=>{if(er(c)){if(!c.$callback)throw new V("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:c.$callback,name:c.function.name,description:c.function.description||"",parameters:c.function.parameters,parse:c.$parseRaw,strict:!0}}}return c}),h={};for(const c of g)c.type==="function"&&(h[c.function.name||c.function.function.name]=c.function);const p="tools"in t?g.map(c=>c.type==="function"?{type:"function",function:{name:c.function.name||c.function.function.name,parameters:c.function.parameters,description:c.function.description,strict:c.function.strict}}:c):void 0;for(const c of t.messages)this._addMessage(c,!1);for(let c=0;c<f;++c){const x=(m=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:p,messages:[...this.messages]},n)).choices[0])==null?void 0:m.message;if(!x)throw new V("missing message in ChatCompletion response");if(!((u=x.tool_calls)!=null&&u.length))return;for(const y of x.tool_calls){if(y.type!=="function")continue;const v=y.id,{name:S,arguments:C}=y.function,_=h[S];if(_){if(d&&d!==S){const F=`Invalid tool_call: ${JSON.stringify(S)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,tool_call_id:v,content:F});continue}}else{const F=`Invalid tool_call: ${JSON.stringify(S)}. Available options are: ${Object.keys(h).map(k=>JSON.stringify(k)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:v,content:F});continue}let I;try{I=Bo(_)?await _.parse(C):C}catch(F){const k=F instanceof Error?F.message:String(F);this._addMessage({role:s,tool_call_id:v,content:k});continue}const T=await _.function(I,this),$=ye(this,pe,"m",ss).call(this,T);if(this._addMessage({role:s,tool_call_id:v,content:$}),d)return}}}}pe=new WeakSet,es=function(){return ye(this,pe,"m",Hr).call(this).content??null},Hr=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(yt(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 V("stream ended without producing a ChatCompletionMessage with role=assistant")},ts=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const s=this.messages[n];if(yt(s)&&(s!=null&&s.function_call))return s.function_call;if(yt(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},rs=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(vi(t)&&t.content!=null||_i(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}},ns=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},Ci=function(e){if(e.n!=null&&e.n>1)throw new V("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ss=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Gt extends ji{static runFunctions(e,t,n){const s=new Gt,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 Gt,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),yt(e)&&e.content&&this._emit("content",e.content)}}const Ai=1,ki=2,Ni=4,Mi=8,Ei=16,Ii=32,Pi=64,Ti=128,Oi=256,Ri=Ti|Oi,$i=Ei|Ii|Ri|Pi,Li=Ai|ki|$i,Di=Ni|Mi,Od=Li|Di,ue={STR:Ai,NUM:ki,ARR:Ni,OBJ:Mi,NULL:Ei,BOOL:Ii,NAN:Pi,INFINITY:Ti,MINUS_INFINITY:Oi,INF:Ri,SPECIAL:$i,ATOM:Li,COLLECTION:Di,ALL:Od};class Rd extends Error{}class $d extends Error{}function Ld(r,e=ue.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Dd(r.trim(),e)}const Dd=(r,e)=>{const t=r.length;let n=0;const s=p=>{throw new Rd(`${p} at position ${n}`)},o=p=>{throw new $d(`${p} at position ${n}`)},i=()=>(h(),n>=t&&s("Unexpected end of input"),r[n]==='"'?l():r[n]==="{"?d():r[n]==="["?f():r.substring(n,n+4)==="null"||ue.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||ue.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||ue.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||ue.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||ue.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||ue.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):g()),l=()=>{const p=n;let w=!1;for(n++;n<t&&(r[n]!=='"'||w&&r[n-1]==="\\");)w=r[n]==="\\"?!w:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(p,++n-Number(w)))}catch(m){o(String(m))}else if(ue.STR&e)try{return JSON.parse(r.substring(p,n-Number(w))+'"')}catch{return JSON.parse(r.substring(p,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},d=()=>{n++,h();const p={};try{for(;r[n]!=="}";){if(h(),n>=t&&ue.OBJ&e)return p;const w=l();h(),n++;try{const m=i();Object.defineProperty(p,w,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(ue.OBJ&e)return p;throw m}h(),r[n]===","&&n++}}catch{if(ue.OBJ&e)return p;s("Expected '}' at end of object")}return n++,p},f=()=>{n++;const p=[];try{for(;r[n]!=="]";)p.push(i()),h(),r[n]===","&&n++}catch{if(ue.ARR&e)return p;s("Expected ']' at end of array")}return n++,p},g=()=>{if(n===0){r==="-"&&ue.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(w){if(ue.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(w))}}const p=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(ue.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(p,n))}catch{r.substring(p,n)==="-"&&ue.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(p,r.lastIndexOf("e")))}catch(m){o(String(m))}}},h=()=>{for(;n<t&&`
39
+ \r `.includes(r[n]);)n++};return i()},Ho=r=>Ld(r,ue.ALL^ue.NUM);var ut=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},re=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)},le,De,ft,We,Mn,br,En,In,Pn,yr,Tn,qo;class Xt extends ji{constructor(e){super(),le.add(this),De.set(this,void 0),ft.set(this,void 0),We.set(this,void 0),ut(this,De,e,"f"),ut(this,ft,[],"f")}get currentChatCompletionSnapshot(){return re(this,We,"f")}static fromReadableStream(e){const t=new Xt(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new Xt(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 i;super._createChatCompletion;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),re(this,le,"m",Mn).call(this);const o=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of o)re(this,le,"m",En).call(this,l);if((i=o.controller.signal)!=null&&i.aborted)throw new Ne;return this._addChatCompletion(re(this,le,"m",yr).call(this))}async _fromReadableStream(e,t){var i;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),re(this,le,"m",Mn).call(this),this._connected();const s=Le.fromReadableStream(e,this.controller);let o;for await(const l of s)o&&o!==l.id&&this._addChatCompletion(re(this,le,"m",yr).call(this)),re(this,le,"m",En).call(this,l),o=l.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Ne;return this._addChatCompletion(re(this,le,"m",yr).call(this))}[(De=new WeakMap,ft=new WeakMap,We=new WeakMap,le=new WeakSet,Mn=function(){this.ended||ut(this,We,void 0,"f")},br=function(t){let n=re(this,ft,"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},re(this,ft,"f")[t.index]=n,n)},En=function(t){var s,o,i,l,d,f,g,h,p,w,m,u,c,b,x;if(this.ended)return;const n=re(this,le,"m",qo).call(this,t);this._emit("chunk",t,n);for(const y of t.choices){const v=n.choices[y.index];y.delta.content!=null&&((s=v.message)==null?void 0:s.role)==="assistant"&&((o=v.message)!=null&&o.content)&&(this._emit("content",y.delta.content,v.message.content),this._emit("content.delta",{delta:y.delta.content,snapshot:v.message.content,parsed:v.message.parsed})),y.delta.refusal!=null&&((i=v.message)==null?void 0:i.role)==="assistant"&&((l=v.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:y.delta.refusal,snapshot:v.message.refusal}),((d=y.logprobs)==null?void 0:d.content)!=null&&((f=v.message)==null?void 0:f.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(g=y.logprobs)==null?void 0:g.content,snapshot:((h=v.logprobs)==null?void 0:h.content)??[]}),((p=y.logprobs)==null?void 0:p.refusal)!=null&&((w=v.message)==null?void 0:w.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(m=y.logprobs)==null?void 0:m.refusal,snapshot:((u=v.logprobs)==null?void 0:u.refusal)??[]});const S=re(this,le,"m",br).call(this,v);v.finish_reason&&(re(this,le,"m",Pn).call(this,v),S.current_tool_call_index!=null&&re(this,le,"m",In).call(this,v,S.current_tool_call_index));for(const C of y.delta.tool_calls??[])S.current_tool_call_index!==C.index&&(re(this,le,"m",Pn).call(this,v),S.current_tool_call_index!=null&&re(this,le,"m",In).call(this,v,S.current_tool_call_index)),S.current_tool_call_index=C.index;for(const C of y.delta.tool_calls??[]){const _=(c=v.message.tool_calls)==null?void 0:c[C.index];_!=null&&_.type&&((_==null?void 0:_.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(b=_.function)==null?void 0:b.name,index:C.index,arguments:_.function.arguments,parsed_arguments:_.function.parsed_arguments,arguments_delta:((x=C.function)==null?void 0:x.arguments)??""}):(_==null||_.type,void 0))}}},In=function(t,n){var i,l,d;if(re(this,le,"m",br).call(this,t).done_tool_calls.has(n))return;const o=(i=t.message.tool_calls)==null?void 0:i[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 f=(d=(l=re(this,De,"f"))==null?void 0:l.tools)==null?void 0:d.find(g=>g.type==="function"&&g.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:er(f)?f.$parseRaw(o.function.arguments):f!=null&&f.function.strict?JSON.parse(o.function.arguments):null})}else o.type},Pn=function(t){var s,o;const n=re(this,le,"m",br).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=re(this,le,"m",Tn).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$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}))},yr=function(){if(this.ended)throw new V("stream has ended, this shouldn't happen");const t=re(this,We,"f");if(!t)throw new V("request ended without sending any chunks");return ut(this,We,void 0,"f"),ut(this,ft,[],"f"),Fd(t,re(this,De,"f"))},Tn=function(){var n;const t=(n=re(this,De,"f"))==null?void 0:n.response_format;return Ss(t)?t:null},qo=function(t){var n,s,o,i;let l=re(this,We,"f");const{choices:d,...f}=t;l?Object.assign(l,f):l=ut(this,We,{...f,choices:[]},"f");for(const{delta:g,finish_reason:h,index:p,logprobs:w=null,...m}of t.choices){let u=l.choices[p];if(u||(u=l.choices[p]={finish_reason:h,index:p,message:{},logprobs:w,...m}),w)if(!u.logprobs)u.logprobs=Object.assign({},w);else{const{content:C,refusal:_,...I}=w;Object.assign(u.logprobs,I),C&&((n=u.logprobs).content??(n.content=[]),u.logprobs.content.push(...C)),_&&((s=u.logprobs).refusal??(s.refusal=[]),u.logprobs.refusal.push(..._))}if(h&&(u.finish_reason=h,re(this,De,"f")&&Si(re(this,De,"f")))){if(h==="length")throw new si;if(h==="content_filter")throw new oi}if(Object.assign(u,m),!g)continue;const{content:c,refusal:b,function_call:x,role:y,tool_calls:v,...S}=g;if(Object.assign(u.message,S),b&&(u.message.refusal=(u.message.refusal||"")+b),y&&(u.message.role=y),x&&(u.message.function_call?(x.name&&(u.message.function_call.name=x.name),x.arguments&&((o=u.message.function_call).arguments??(o.arguments=""),u.message.function_call.arguments+=x.arguments)):u.message.function_call=x),c&&(u.message.content=(u.message.content||"")+c,!u.message.refusal&&re(this,le,"m",Tn).call(this)&&(u.message.parsed=Ho(u.message.content))),v){u.message.tool_calls||(u.message.tool_calls=[]);for(const{index:C,id:_,type:I,function:T,...$}of v){const F=(i=u.message.tool_calls)[C]??(i[C]={});Object.assign(F,$),_&&(F.id=_),I&&(F.type=I),T&&(F.function??(F.function={name:T.name??"",arguments:""})),T!=null&&T.name&&(F.function.name=T.name),T!=null&&T.arguments&&(F.function.arguments+=T.arguments,Pd(re(this,De,"f"),F)&&(F.function.parsed_arguments=Ho(F.function.arguments)))}}}return l},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,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Fd(r,e){const{id:t,choices:n,created:s,model:o,system_fingerprint:i,...l}=r,d={...l,id:t,choices:n.map(({message:f,finish_reason:g,index:h,logprobs:p,...w})=>{if(!g)throw new V(`missing finish_reason for choice ${h}`);const{content:m=null,function_call:u,tool_calls:c,...b}=f,x=f.role;if(!x)throw new V(`missing role for choice ${h}`);if(u){const{arguments:y,name:v}=u;if(y==null)throw new V(`missing function_call.arguments for choice ${h}`);if(!v)throw new V(`missing function_call.name for choice ${h}`);return{...w,message:{content:m,function_call:{arguments:y,name:v},role:x,refusal:f.refusal??null},finish_reason:g,index:h,logprobs:p}}return c?{...w,index:h,finish_reason:g,logprobs:p,message:{...b,role:x,content:m,refusal:f.refusal??null,tool_calls:c.map((y,v)=>{const{function:S,type:C,id:_,...I}=y,{arguments:T,name:$,...F}=S||{};if(_==null)throw new V(`missing choices[${h}].tool_calls[${v}].id
40
+ ${wr(r)}`);if(C==null)throw new V(`missing choices[${h}].tool_calls[${v}].type
41
+ ${wr(r)}`);if($==null)throw new V(`missing choices[${h}].tool_calls[${v}].function.name
42
+ ${wr(r)}`);if(T==null)throw new V(`missing choices[${h}].tool_calls[${v}].function.arguments
43
+ ${wr(r)}`);return{...I,id:_,type:C,function:{...F,name:$,arguments:T}}})}}:{...w,message:{...b,content:m,role:x,refusal:f.refusal??null},finish_reason:g,index:h,logprobs:p}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Md(d,e)}function wr(r){return JSON.stringify(r)}class wt extends Xt{static fromReadableStream(e){const t=new wt(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new wt(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 wt(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 Fi=class extends G{parse(e,t){return Td(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=>Cs(n,e))}runFunctions(e,t){return e.stream?wt.runFunctions(this._client,e,t):Gt.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?wt.runTools(this._client,e,t):Gt.runTools(this._client,e,t)}stream(e,t){return Xt.createChatCompletion(this._client,e,t)}};class os extends G{constructor(){super(...arguments),this.completions=new Fi(this._client)}}(function(r){r.Completions=Fi})(os||(os={}));class Ui extends G{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Bi extends G{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 on extends G{constructor(){super(...arguments),this.sessions=new Ui(this._client),this.transcriptionSessions=new Bi(this._client)}}on.Sessions=Ui;on.TranscriptionSessions=Bi;class js extends G{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 oe(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,As,{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 As extends de{}js.MessagesPage=As;class ks extends G{retrieve(e,t,n,s={},o){return oe(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 oe(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 de{}ks.RunStepsPage=Ns;let tr=class extends G{constructor(){super(...arguments),this.steps=new ks(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 oe(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Ms,{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 Ie.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:i}=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 l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const d=i.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(l=f)}}await Qt(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,n){return Ie.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 Ie.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class Ms extends de{}tr.RunsPage=Ms;tr.Steps=ks;tr.RunStepsPage=Ns;class jt extends G{constructor(){super(...arguments),this.runs=new tr(this._client),this.messages=new js(this._client)}create(e={},t){return oe(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 Ie.createThreadAssistantStream(e,this._client.beta.threads,t)}}jt.Runs=tr;jt.RunsPage=Ms;jt.Messages=js;jt.MessagesPage=As;class At extends G{constructor(){super(...arguments),this.realtime=new on(this._client),this.chat=new os(this._client),this.assistants=new vs(this._client),this.threads=new jt(this._client)}}At.Realtime=on;At.Assistants=vs;At.AssistantsPage=_s;At.Threads=jt;class Wi extends G{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Hi extends G{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 an=class extends G{constructor(){super(...arguments),this.content=new Hi(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,it({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return oe(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Es,{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 Es extends de{}an.FileListResponsesPage=Es;an.Content=Hi;class rr extends G{constructor(){super(...arguments),this.files=new an(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 oe(e)?this.list({},e):this._client.getAPIList("/containers",Is,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}}class Is extends de{}rr.ContainerListResponsesPage=Is;rr.Files=an;rr.FileListResponsesPage=Es;class qi extends G{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&Ge("Request","User defined encoding_format:",e.encoding_format);const o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?o:(Ge("response","Decoding base64 embeddings to float32 array"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const d=l.embedding;l.embedding=kd(d)}),i)))}}class Ps extends G{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return oe(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Ts,{query:n,...s})}}class Ts extends de{}Ps.OutputItemListResponsesPage=Ts;class nr extends G{constructor(){super(...arguments),this.outputItems=new Ps(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 oe(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Os,{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 Os extends de{}nr.RunListResponsesPage=Os;nr.OutputItems=Ps;nr.OutputItemListResponsesPage=Ts;class sr extends G{constructor(){super(...arguments),this.runs=new nr(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 oe(e)?this.list({},e):this._client.getAPIList("/evals",Rs,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class Rs extends de{}sr.EvalListResponsesPage=Rs;sr.Runs=nr;sr.RunListResponsesPage=Os;let $s=class extends G{create(e,t){return this._client.post("/files",it({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return oe(e)?this.list({},e):this._client.getAPIList("/files",Ls,{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 i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await Qt(t),i=await this.retrieve(e),Date.now()-o>n)throw new xs({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class Ls extends de{}$s.FileObjectsPage=Ls;class zi extends G{}let Ji=class extends G{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 Ds extends G{constructor(){super(...arguments),this.graders=new Ji(this._client)}}Ds.Graders=Ji;class Fs extends G{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Us,{body:t,method:"post",...n})}retrieve(e,t={},n){return oe(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 Us extends tn{}Fs.PermissionCreateResponsesPage=Us;let ln=class extends G{constructor(){super(...arguments),this.permissions=new Fs(this._client)}};ln.Permissions=Fs;ln.PermissionCreateResponsesPage=Us;class Bs extends G{list(e,t={},n){return oe(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Ws,{query:t,...n})}}class Ws extends de{}Bs.FineTuningJobCheckpointsPage=Ws;class kt extends G{constructor(){super(...arguments),this.checkpoints=new Bs(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 oe(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Hs,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return oe(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,qs,{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 Hs extends de{}class qs extends de{}kt.FineTuningJobsPage=Hs;kt.FineTuningJobEventsPage=qs;kt.Checkpoints=Bs;kt.FineTuningJobCheckpointsPage=Ws;class Xe extends G{constructor(){super(...arguments),this.methods=new zi(this._client),this.jobs=new kt(this._client),this.checkpoints=new ln(this._client),this.alpha=new Ds(this._client)}}Xe.Methods=zi;Xe.Jobs=kt;Xe.FineTuningJobsPage=Hs;Xe.FineTuningJobEventsPage=qs;Xe.Checkpoints=ln;Xe.Alpha=Ds;class Vi extends G{}class zs extends G{constructor(){super(...arguments),this.graderModels=new Vi(this._client)}}zs.GraderModels=Vi;class Gi extends G{createVariation(e,t){return this._client.post("/images/variations",it({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",it({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Js extends G{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Vs,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Vs extends tn{}Js.ModelsPage=Vs;class Xi extends G{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Ud(r,e){return!e||!Wd(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)}:Ki(r,e)}function Ki(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:zd(e,s)};if(s.type==="message"){const o=s.content.map(i=>i.type==="output_text"?{...i,parsed:Bd(e,i.text)}:i);return{...s,content:o}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||Yi(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 Bd(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 Wd(r){var e;return!!Ss((e=r.text)==null?void 0:e.format)}function Hd(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function qd(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function zd(r,e){const t=qd(r.tools??[],e.name);return{...e,...e,parsed_arguments:Hd(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function Yi(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 Qi extends G{list(e,t={},n){return oe(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Vd,{query:t,...n})}}var ht=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)},mt,vr,qe,_r,zo,Jo,Vo,Go;class Gs extends ws{constructor(e){super(),mt.add(this),vr.set(this,void 0),qe.set(this,void 0),_r.set(this,void 0),ht(this,vr,e,"f")}static createResponse(e,t,n){const s=new Gs(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 l;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),He(this,mt,"m",zo).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=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)He(this,mt,"m",Jo).call(this,d,i);if((l=o.controller.signal)!=null&&l.aborted)throw new Ne;return He(this,mt,"m",Vo).call(this)}[(vr=new WeakMap,qe=new WeakMap,_r=new WeakMap,mt=new WeakSet,zo=function(){this.ended||ht(this,qe,void 0,"f")},Jo=function(t,n){if(this.ended)return;const s=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},o=He(this,mt,"m",Go).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const i=o.output[t.output_index];if(!i)throw new V(`missing output at index ${t.output_index}`);if(i.type==="message"){const l=i.content[t.content_index];if(!l)throw new V(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new V(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const i=o.output[t.output_index];if(!i)throw new V(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},Vo=function(){if(this.ended)throw new V("stream has ended, this shouldn't happen");const t=He(this,qe,"f");if(!t)throw new V("request ended without sending any events");ht(this,qe,void 0,"f");const n=Jd(t,He(this,vr,"f"));return ht(this,_r,n,"f"),n},Go=function(t){let n=He(this,qe,"f");if(!n){if(t.type!=="response.created")throw new V(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=ht(this,qe,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 V(`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 V(`missing output at index ${t.output_index}`);if(s.type==="message"){const o=s.content[t.content_index];if(!o)throw new V(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new V(`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 V(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{ht(this,qe,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,i)=>t.push({resolve:o,reject:i})).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=He(this,_r,"f");if(!e)throw new V("stream ended without producing a ChatCompletion");return e}}function Jd(r,e){return Ud(r,e)}class Xs extends G{constructor(){super(...arguments),this.inputItems=new Qi(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"&&Yi(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=>Ki(n,e))}stream(e,t){return Gs.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 Vd extends de{}Xs.InputItems=Qi;class Zi extends G{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,it({body:t,...n}))}}class Ks extends G{constructor(){super(...arguments),this.parts=new Zi(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})}}Ks.Parts=Zi;const Gd=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 cn extends G{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 oe(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,dn,{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(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const d=o.response.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(l=f)}}await Qt(l);break;case"failed":case"completed":return i}}}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`,Ys,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class dn extends de{}class Ys extends tn{}cn.VectorStoreFilesPage=dn;cn.FileContentResponsesPage=Ys;class el extends G{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 oe(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,dn,{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:i}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const d=i.headers.get("openai-poll-after-ms");if(d){const f=parseInt(d);isNaN(f)||(l=f)}}await Qt(l);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,i=Math.min(o,t.length),l=this._client,d=t.values(),f=[...n];async function g(p){for(let w of p){const m=await l.files.create({file:w,purpose:"assistants"},s);f.push(m.id)}}const h=Array(i).fill(d).map(g);return await Gd(h),await this.createAndPoll(e,{file_ids:f})}}class Ke extends G{constructor(){super(...arguments),this.files=new cn(this._client),this.fileBatches=new el(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 oe(e)?this.list({},e):this._client.getAPIList("/vector_stores",Qs,{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`,Zs,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class Qs extends de{}class Zs extends tn{}Ke.VectorStoresPage=Qs;Ke.VectorStoreSearchResponsesPage=Zs;Ke.Files=cn;Ke.VectorStoreFilesPage=dn;Ke.FileContentResponsesPage=Ys;Ke.FileBatches=el;var tl;class X extends gd{constructor({baseURL:e=pr("OPENAI_BASE_URL"),apiKey:t=pr("OPENAI_API_KEY"),organization:n=pr("OPENAI_ORG_ID")??null,project:s=pr("OPENAI_PROJECT_ID")??null,...o}={}){if(t===void 0)throw new V("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 i={apiKey:t,organization:n,project:s,...o,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&jd())throw new V(`It looks like you're running in a browser-like environment.
44
44
 
45
45
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
46
46
  If you understand the risks and have appropriate mitigations in place,
@@ -49,53 +49,53 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
49
49
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
50
50
 
51
51
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
52
- `);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new zi(this),this.chat=new sn(this),this.embeddings=new Vi(this),this.files=new Fs(this),this.images=new Yi(this),this.audio=new tr(this),this.moderations=new Qi(this),this.models=new Xs(this),this.fineTuning=new Ye(this),this.graders=new Gs(this),this.vectorStores=new Qe(this),this.beta=new Nt(this),this.batches=new vs(this),this.uploads=new Zs(this),this.responses=new Qs(this),this.evals=new ar(this),this.containers=new sr(this),this._options=i,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 Zc(e,{arrayFormat:"brackets"})}}sl=Z;Z.OpenAI=sl;Z.DEFAULT_TIMEOUT=6e5;Z.OpenAIError=Y;Z.APIError=ye;Z.APIConnectionError=Yr;Z.APIConnectionTimeoutError=ws;Z.APIUserAbortError=Ee;Z.NotFoundError=ri;Z.ConflictError=ni;Z.RateLimitError=oi;Z.BadRequestError=Za;Z.AuthenticationError=ei;Z.InternalServerError=ai;Z.PermissionDeniedError=ti;Z.UnprocessableEntityError=si;Z.toFile=fi;Z.fileFromPath=Ka;Z.Completions=zi;Z.Chat=sn;Z.ChatCompletionsPage=nn;Z.Embeddings=Vi;Z.Files=Fs;Z.FileObjectsPage=Us;Z.Images=Yi;Z.Audio=tr;Z.Moderations=Qi;Z.Models=Xs;Z.ModelsPage=Ks;Z.FineTuning=Ye;Z.Graders=Gs;Z.VectorStores=Qe;Z.VectorStoresPage=to;Z.VectorStoreSearchResponsesPage=ro;Z.Beta=Nt;Z.Batches=vs;Z.BatchesPage=_s;Z.Uploads=Zs;Z.Responses=Qs;Z.Evals=ar;Z.EvalListResponsesPage=Ds;Z.Containers=sr;Z.ContainerListResponsesPage=Os;class ol{constructor(e,t,n,s,o,i,l){J(this,"messages");J(this,"tools");J(this,"callback");J(this,"modelConfig");J(this,"configUrl");J(this,"abortController");J(this,"isAborted");J(this,"sessionId");this.messages=e,this.tools=t,this.callback=s,this.modelConfig=o,this.configUrl=i||"/api",this.sessionId=l||n,console.log("🔧 AiRequestHandler Constructor - configUrl:",this.configUrl,"haha"),console.log("🔧 AiRequestHandler Constructor - modelConfig.base_url:",this.modelConfig.base_url),this.abortController=new AbortController,this.isAborted=!1;debugger}async chatCompletion(){var e,t;try{if(this.isAborted)return console.log("Chat completion aborted by user"),this.messages;console.log("Using OpenAI package with base URL:",this.configUrl),console.log("API Key:",this.modelConfig.api_key?"Present":"Missing"),console.log("Config Url: ",this.configUrl);const n=new Z({apiKey:this.modelConfig.api_key,baseURL:this.configUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{"x-target-url":this.modelConfig.base_url}}),s=this.buildPayLoad(),o=await n.chat.completions.create({...s,stream:!0},{signal:this.abortController.signal});return await this.handleOpenAIStreamResponse(o,this.callback),this.messages}catch(n){debugger;if(n.name==="AbortError"||n.message==="network error"||(e=n.message)!=null&&e.includes("aborted")||(t=n.message)!=null&&t.includes("cancelled")||this.isAborted)return console.log("Chat completion aborted by user"),this.messages;throw console.error("Chat completion failed:",n),console.error("Error type:",n.constructor.name),console.error("Error message:",n.message),console.error("Error stack:",n.stack),(n.message.includes("CORS")||n.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",n),n}}async handleOpenAIStreamResponse(e,t){var s,o;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 i=0,l=null;for await(const d of e){if(this.isAborted){console.log("Stream processing aborted");break}if(i++,d.choices&&d.choices.length>0){const p=d.choices[0].delta;if(p&&(p.content&&(n.content+=p.content,t&&t("chunk",{type:"text",content:p.content})),p.reasoning_content&&(n.reasoning_content+=p.reasoning_content,t&&t("chunk",{type:"reasoning_content",content:p.reasoning_content,accumulated:n.reasoning_content})),p.tool_calls))for(const f of p.tool_calls){if(!f){console.warn("Invalid tool call:",f);continue}let x=f.index;for((x==null||typeof x!="number")&&(x=n.tool_calls.length,console.log(`Tool call index was ${f.index}, using ${x} instead`));n.tool_calls.length<=x;)n.tool_calls.push({id:"",type:"function",function:{name:"",arguments:""}});l=n.tool_calls[x],l.function||(l.function={name:"",arguments:""}),f.id&&f.id!==""?l.id=f.id:(!l.id||l.id==="")&&(l.id=`call_${Date.now()}_${x}`),f.function&&(f.function.name&&(l.function.name=f.function.name),f.function.arguments&&(l.function.arguments+=f.function.arguments))}}}console.log(`OpenAI stream completed. Processed ${i} chunks.`),n.tool_calls.length>0&&(n.function_calls=n.tool_calls.map(d=>({id:d.id,name:d.function.name,arguments:d.function.arguments}))),this.messages.push(n)}catch(i){if(i.name==="AbortError"||i.message==="network error"||(s=i.message)!=null&&s.includes("aborted")||(o=i.message)!=null&&o.includes("cancelled")||this.isAborted){console.log("Stream processing aborted by user");return}throw console.error("Stream processing error:",i),t&&t("error",i),i}}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,sessionId:this.sessionId};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
+ `);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new Wi(this),this.chat=new sn(this),this.embeddings=new qi(this),this.files=new $s(this),this.images=new Gi(this),this.audio=new Zt(this),this.moderations=new Xi(this),this.models=new Js(this),this.fineTuning=new Xe(this),this.graders=new zs(this),this.vectorStores=new Ke(this),this.beta=new At(this),this.batches=new bs(this),this.uploads=new Ks(this),this.responses=new Xs(this),this.evals=new sr(this),this.containers=new rr(this),this._options=i,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 Yc(e,{arrayFormat:"brackets"})}}tl=X;X.OpenAI=tl;X.DEFAULT_TIMEOUT=6e5;X.OpenAIError=V;X.APIError=ge;X.APIConnectionError=Yr;X.APIConnectionTimeoutError=xs;X.APIUserAbortError=Ne;X.NotFoundError=Za;X.ConflictError=ei;X.RateLimitError=ri;X.BadRequestError=Ka;X.AuthenticationError=Ya;X.InternalServerError=ni;X.PermissionDeniedError=Qa;X.UnprocessableEntityError=ti;X.toFile=ci;X.fileFromPath=Va;X.Completions=Wi;X.Chat=sn;X.ChatCompletionsPage=nn;X.Embeddings=qi;X.Files=$s;X.FileObjectsPage=Ls;X.Images=Gi;X.Audio=Zt;X.Moderations=Xi;X.Models=Js;X.ModelsPage=Vs;X.FineTuning=Xe;X.Graders=zs;X.VectorStores=Ke;X.VectorStoresPage=Qs;X.VectorStoreSearchResponsesPage=Zs;X.Beta=At;X.Batches=bs;X.BatchesPage=ys;X.Uploads=Ks;X.Responses=Xs;X.Evals=sr;X.EvalListResponsesPage=Rs;X.Containers=rr;X.ContainerListResponsesPage=Is;class rl{constructor(e,t,n,s,o,i,l){W(this,"messages");W(this,"tools");W(this,"callback");W(this,"modelConfig");W(this,"configUrl");W(this,"abortController");W(this,"isAborted");W(this,"sessionId");this.messages=e,this.tools=t,this.callback=s,this.modelConfig=o,this.configUrl=i||"/api",this.sessionId=l||n,console.log("🔧 AiRequestHandler Constructor - configUrl:",this.configUrl,"haha"),console.log("🔧 AiRequestHandler Constructor - modelConfig.base_url:",this.modelConfig.base_url),this.abortController=new AbortController,this.isAborted=!1;debugger}async chatCompletion(){var e,t;try{if(this.isAborted)return console.log("Chat completion aborted by user"),this.messages;console.log("Using OpenAI package with base URL:",this.configUrl),console.log("API Key:",this.modelConfig.api_key?"Present":"Missing"),console.log("Config Url: ",this.configUrl);const n=new X({apiKey:this.modelConfig.api_key,baseURL:this.configUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{"x-target-url":this.modelConfig.base_url}}),s=this.buildPayLoad(),o=await n.chat.completions.create({...s,stream:!0},{signal:this.abortController.signal});return await this.handleOpenAIStreamResponse(o,this.callback),this.messages}catch(n){debugger;if(n.name==="AbortError"||n.message==="network error"||(e=n.message)!=null&&e.includes("aborted")||(t=n.message)!=null&&t.includes("cancelled")||this.isAborted)return console.log("Chat completion aborted by user"),this.messages;throw console.error("Chat completion failed:",n),console.error("Error type:",n.constructor.name),console.error("Error message:",n.message),console.error("Error stack:",n.stack),(n.message.includes("CORS")||n.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",n),n}}async handleOpenAIStreamResponse(e,t){var s,o;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 i=0,l=null;for await(const d of e){if(this.isAborted){console.log("Stream processing aborted");break}if(i++,d.choices&&d.choices.length>0){const g=d.choices[0].delta;if(g&&(g.content&&(n.content+=g.content,t&&t("chunk",{type:"text",content:g.content})),g.reasoning_content&&(n.reasoning_content+=g.reasoning_content,t&&t("chunk",{type:"reasoning_content",content:g.reasoning_content,accumulated:n.reasoning_content})),g.tool_calls))for(const h of g.tool_calls){if(!h){console.warn("Invalid tool call:",h);continue}let p=h.index;for((p==null||typeof p!="number")&&(p=n.tool_calls.length,console.log(`Tool call index was ${h.index}, using ${p} instead`));n.tool_calls.length<=p;)n.tool_calls.push({id:"",type:"function",function:{name:"",arguments:""}});l=n.tool_calls[p],l.function||(l.function={name:"",arguments:""}),h.id&&h.id!==""?l.id=h.id:(!l.id||l.id==="")&&(l.id=`call_${Date.now()}_${p}`),h.function&&(h.function.name&&(l.function.name=h.function.name),h.function.arguments&&(l.function.arguments+=h.function.arguments))}}}console.log(`OpenAI stream completed. Processed ${i} chunks.`),n.tool_calls.length>0&&(n.function_calls=n.tool_calls.map(d=>({id:d.id,name:d.function.name,arguments:d.function.arguments}))),this.messages.push(n)}catch(i){if(i.name==="AbortError"||i.message==="network error"||(s=i.message)!=null&&s.includes("aborted")||(o=i.message)!=null&&o.includes("cancelled")||this.isAborted){console.log("Stream processing aborted by user");return}throw console.error("Stream processing error:",i),t&&t("error",i),i}}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,sessionId:this.sessionId};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,`
53
53
  `).replace(/\n{3,}/g,`
54
54
 
55
- `).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(i=>{var f,x;const l=((f=i.function)==null?void 0:f.name)||i.name,d=((x=i.function)==null?void 0:x.arguments)||i.arguments;if(!l)return console.warn("Tool call missing function name:",i),null;let u;typeof d=="string"?u=d:d&&typeof d=="object"?u=JSON.stringify(d):u="{}";try{JSON.parse(u)}catch(w){console.warn("Invalid JSON in tool call arguments, using empty object:",u,w),u="{}"}const p={id:i.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:i.type||"function",function:{name:l,arguments:u}};return console.log("Converted tool call:",p),p}).filter(i=>i!==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 Yd{constructor(e,t,n,s,o,i="/api"){J(this,"messageManager");J(this,"modelConfig");J(this,"conversationId");J(this,"callback");J(this,"sessionId");J(this,"configUrl");this.messageManager=e,this.modelConfig=t,this.conversationId=n,this.callback=s,this.sessionId=o||n,this.configUrl=i}async processToolResult(e,t){const n=e;debugger;const s=(n.content||"").length,o=s>1e3;let i=n.content||"";if(o)try{const l=await this.generateContentSummary(n.content,n.tool_name);i=l,console.log(`[Tool Result Summary] 为工具 ${n.tool_name} 生成总结,原长度: ${s}, 总结长度: ${l.length}`)}catch(l){if(l.message==="Stream aborted by user"||l.name==="AbortError"){console.log("[Tool Result Summary] 总结生成被用户中断");return}console.error("[Tool Result Summary] 生成总结失败:",l)}return await this.messageManager.saveToolMessage({sessionId:t,role:"tool",content:n.content||"",summary:o?i: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:i,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
+ `).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(i=>{var h,p;const l=((h=i.function)==null?void 0:h.name)||i.name,d=((p=i.function)==null?void 0:p.arguments)||i.arguments;if(!l)return console.warn("Tool call missing function name:",i),null;let f;typeof d=="string"?f=d:d&&typeof d=="object"?f=JSON.stringify(d):f="{}";try{JSON.parse(f)}catch(w){console.warn("Invalid JSON in tool call arguments, using empty object:",f,w),f="{}"}const g={id:i.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:i.type||"function",function:{name:l,arguments:f}};return console.log("Converted tool call:",g),g}).filter(i=>i!==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 Xd{constructor(e,t,n,s,o,i="/api"){W(this,"messageManager");W(this,"modelConfig");W(this,"conversationId");W(this,"callback");W(this,"sessionId");W(this,"configUrl");this.messageManager=e,this.modelConfig=t,this.conversationId=n,this.callback=s,this.sessionId=o||n,this.configUrl=i}async processToolResult(e,t){const n=e;debugger;const s=(n.content||"").length,o=s>1e3;let i=n.content||"";if(o)try{const l=await this.generateContentSummary(n.content,n.tool_name);i=l,console.log(`[Tool Result Summary] 为工具 ${n.tool_name} 生成总结,原长度: ${s}, 总结长度: ${l.length}`)}catch(l){if(l.message==="Stream aborted by user"||l.name==="AbortError"){console.log("[Tool Result Summary] 总结生成被用户中断");return}console.error("[Tool Result Summary] 生成总结失败:",l)}return await this.messageManager.saveToolMessage({sessionId:t,role:"tool",content:n.content||"",summary:o?i: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:i,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:`请帮我对以下内容进行总结:
56
56
 
57
57
  ${e}`,rawContent:`请帮我对以下内容进行总结:
58
58
 
59
- ${e}`,status:"completed",createdAt:new Date}];let s="";return await new ol(n,[],this.conversationId,(i,l)=>{i==="chunk"&&(l!=null&&l.content)&&(s+=l.content,this.callback("summary_chunk",{content:l.content,accumulated:s}))},this.modelConfig,this.configUrl,this.sessionId).chatCompletion(),s.trim()||`工具 ${t} 执行完成,内容长度: ${e.length} 字符`}catch(n){return n.message==="Stream aborted by user"||n.name==="AbortError"?(console.log("总结生成被用户中断"),`工具 ${t} 执行完成,内容长度: ${e.length} 字符`):(console.error("生成总结时出错:",n),`工具 ${t} 执行完成,内容长度: ${e.length} 字符`)}}}class Qo{constructor(e,t,n,s,o,i,l,d,u,p){J(this,"messages");J(this,"conversationId");J(this,"tools");J(this,"modelConfig");J(this,"callBack");J(this,"mcpToolExecute");J(this,"configUrl");J(this,"isAborted");J(this,"currentAiRequestHandler");J(this,"toolResultProcessor");J(this,"sessionId");this.messages=e,this.conversationId=t,this.tools=n,this.modelConfig=s,this.callBack=o,this.mcpToolExecute=i,this.configUrl=d||"/api",this.sessionId=p||this.conversationId,console.log("🔧 AiClient Constructor - configUrl:",this.configUrl),this.isAborted=!1,this.currentAiRequestHandler=null,this.toolResultProcessor=new Yd(l,this.modelConfig,this.conversationId,this.callBack,this.sessionId,this.configUrl),u&&u.signal.addEventListener("abort",()=>{console.log("AiClient: External abort signal received"),this.abort()})}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 l of n.tool_calls){if(this.isAborted){console.log("AiClient: Aborted during tool execution");return}const d=((s=l.function)==null?void 0:s.name)||l.name;if(this.mcpToolExecute.toolSupportsStreaming(d)){console.log(`Using streaming execution for tool: ${d}`);const p={tool_call_id:l.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:d,content:""};try{await this.mcpToolExecute.executeStream(l,f=>{if(this.isAborted)return;console.log("chunk",f);const x=this.processChunk(f);p.content+=x,this.callBack("tool_stream_chunk",{toolCallId:l.id,chunk:x})},()=>{this.isAborted||console.log(`Stream completed for tool: ${d}`)},f=>{if(this.isAborted||f.message==="Stream aborted by user"||f.name==="AbortError"){console.log(`Tool ${d} stream aborted by user`);return}console.error(`Stream error for tool ${d}:`,f),p.content=JSON.stringify({error:f.message||"Tool execution failed"})}),p.content||(p.content=JSON.stringify({result:"Tool execution completed"}))}catch(f){if(this.isAborted||f.message==="Stream aborted by user"||f.name==="AbortError"){console.log(`Tool ${d} execution aborted by user`);return}console.error(`Failed to execute stream tool ${d}:`,f),p.content=JSON.stringify({error:f.message||"Tool execution failed"})}o.push(p)}else{console.log(`Using regular execution for tool: ${d}`);const p=await this.mcpToolExecute.execute([l]);o.push(...p)}}if(this.isAborted){console.log("AiClient: Aborted after tool execution");return}const i=await this.toolResultProcessor.processToolResult(o[0],this.conversationId);debugger;if(this.messages.push(i),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 ol(this.messages,this.tools,this.conversationId,this.callBack,this.modelConfig,this.configUrl,this.sessionId);this.currentAiRequestHandler=e;try{this.messages=await e.chatCompletion()}catch(t){if(this.isAborted||t.message==="Stream aborted by user"||t.name==="AbortError"){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?`
60
- `+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 al(r,e){return function(){return r.apply(e,arguments)}}const{toString:Qd}=Object.prototype,{getPrototypeOf:no}=Object,{iterator:un,toStringTag:il}=Symbol,fn=(r=>e=>{const t=Qd.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Oe=r=>(r=r.toLowerCase(),e=>fn(e)===r),hn=r=>e=>typeof e===r,{isArray:Et}=Array,At=hn("undefined");function ir(r){return r!==null&&!At(r)&&r.constructor!==null&&!At(r.constructor)&&Se(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const ll=Oe("ArrayBuffer");function Zd(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&ll(r.buffer),e}const eu=hn("string"),Se=hn("function"),cl=hn("number"),lr=r=>r!==null&&typeof r=="object",tu=r=>r===!0||r===!1,Pr=r=>{if(fn(r)!=="object")return!1;const e=no(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(il in r)&&!(un in r)},ru=r=>{if(!lr(r)||ir(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},nu=Oe("Date"),su=Oe("File"),ou=Oe("Blob"),au=Oe("FileList"),iu=r=>lr(r)&&Se(r.pipe),lu=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||Se(r.append)&&((e=fn(r))==="formdata"||e==="object"&&Se(r.toString)&&r.toString()==="[object FormData]"))},cu=Oe("URLSearchParams"),[du,uu,fu,hu]=["ReadableStream","Request","Response","Headers"].map(Oe),mu=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function cr(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let n,s;if(typeof r!="object"&&(r=[r]),Et(r))for(n=0,s=r.length;n<s;n++)e.call(null,r[n],n,r);else{if(ir(r))return;const o=t?Object.getOwnPropertyNames(r):Object.keys(r),i=o.length;let l;for(n=0;n<i;n++)l=o[n],e.call(null,r[l],l,r)}}function dl(r,e){if(ir(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 st=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ul=r=>!At(r)&&r!==st;function cs(){const{caseless:r,skipUndefined:e}=ul(this)&&this||{},t={},n=(s,o)=>{const i=r&&dl(t,o)||o;Pr(t[i])&&Pr(s)?t[i]=cs(t[i],s):Pr(s)?t[i]=cs({},s):Et(s)?t[i]=s.slice():(!e||!At(s))&&(t[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&cr(arguments[s],n);return t}const gu=(r,e,t,{allOwnKeys:n}={})=>(cr(e,(s,o)=>{t&&Se(s)?r[o]=al(s,t):r[o]=s},{allOwnKeys:n}),r),pu=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),xu=(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)},yu=(r,e,t,n)=>{let s,o,i;const l={};if(e=e||{},r==null)return e;do{for(s=Object.getOwnPropertyNames(r),o=s.length;o-- >0;)i=s[o],(!n||n(i,r,e))&&!l[i]&&(e[i]=r[i],l[i]=!0);r=t!==!1&&no(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},bu=(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},wu=r=>{if(!r)return null;if(Et(r))return r;let e=r.length;if(!cl(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},vu=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&no(Uint8Array)),_u=(r,e)=>{const n=(r&&r[un]).call(r);let s;for(;(s=n.next())&&!s.done;){const o=s.value;e.call(r,o[0],o[1])}},Su=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},Cu=Oe("HTMLFormElement"),ju=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,s){return n.toUpperCase()+s}),Zo=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),Au=Oe("RegExp"),fl=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};cr(t,(s,o)=>{let i;(i=e(s,o,r))!==!1&&(n[o]=i||s)}),Object.defineProperties(r,n)},ku=r=>{fl(r,(e,t)=>{if(Se(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=r[t];if(Se(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+"'")})}})},Nu=(r,e)=>{const t={},n=s=>{s.forEach(o=>{t[o]=!0})};return Et(r)?n(r):n(String(r).split(e)),t},Mu=()=>{},Eu=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function Iu(r){return!!(r&&Se(r.append)&&r[il]==="FormData"&&r[un])}const Tu=r=>{const e=new Array(10),t=(n,s)=>{if(lr(n)){if(e.indexOf(n)>=0)return;if(ir(n))return n;if(!("toJSON"in n)){e[s]=n;const o=Et(n)?[]:{};return cr(n,(i,l)=>{const d=t(i,s+1);!At(d)&&(o[l]=d)}),e[s]=void 0,o}}return n};return t(r,0)},Pu=Oe("AsyncFunction"),Ou=r=>r&&(lr(r)||Se(r))&&Se(r.then)&&Se(r.catch),hl=((r,e)=>r?setImmediate:e?((t,n)=>(st.addEventListener("message",({source:s,data:o})=>{s===st&&o===t&&n.length&&n.shift()()},!1),s=>{n.push(s),st.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",Se(st.postMessage)),Ru=typeof queueMicrotask<"u"?queueMicrotask.bind(st):typeof process<"u"&&process.nextTick||hl,$u=r=>r!=null&&Se(r[un]),M={isArray:Et,isArrayBuffer:ll,isBuffer:ir,isFormData:lu,isArrayBufferView:Zd,isString:eu,isNumber:cl,isBoolean:tu,isObject:lr,isPlainObject:Pr,isEmptyObject:ru,isReadableStream:du,isRequest:uu,isResponse:fu,isHeaders:hu,isUndefined:At,isDate:nu,isFile:su,isBlob:ou,isRegExp:Au,isFunction:Se,isStream:iu,isURLSearchParams:cu,isTypedArray:vu,isFileList:au,forEach:cr,merge:cs,extend:gu,trim:mu,stripBOM:pu,inherits:xu,toFlatObject:yu,kindOf:fn,kindOfTest:Oe,endsWith:bu,toArray:wu,forEachEntry:_u,matchAll:Su,isHTMLForm:Cu,hasOwnProperty:Zo,hasOwnProp:Zo,reduceDescriptors:fl,freezeMethods:ku,toObjectSet:Nu,toCamelCase:ju,noop:Mu,toFiniteNumber:Eu,findKey:dl,global:st,isContextDefined:ul,isSpecCompliantForm:Iu,toJSONObject:Tu,isAsyncFn:Pu,isThenable:Ou,setImmediate:hl,asap:Ru,isIterable:$u};function ee(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)}M.inherits(ee,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:M.toJSONObject(this.config),code:this.code,status:this.status}}});const ml=ee.prototype,gl={};["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=>{gl[r]={value:r}});Object.defineProperties(ee,gl);Object.defineProperty(ml,"isAxiosError",{value:!0});ee.from=(r,e,t,n,s,o)=>{const i=Object.create(ml);M.toFlatObject(r,i,function(p){return p!==Error.prototype},u=>u!=="isAxiosError");const l=r&&r.message?r.message:"Error",d=e==null&&r?r.code:e;return ee.call(i,l,d,t,n,s),r&&i.cause==null&&Object.defineProperty(i,"cause",{value:r,configurable:!0}),i.name=r&&r.name||"Error",o&&Object.assign(i,o),i};const Lu=null;function ds(r){return M.isPlainObject(r)||M.isArray(r)}function pl(r){return M.endsWith(r,"[]")?r.slice(0,-2):r}function ea(r,e,t){return r?r.concat(e).map(function(s,o){return s=pl(s),!t&&o?"["+s+"]":s}).join(t?".":""):e}function Du(r){return M.isArray(r)&&!r.some(ds)}const Fu=M.toFlatObject(M,{},null,function(e){return/^is[A-Z]/.test(e)});function mn(r,e,t){if(!M.isObject(r))throw new TypeError("target must be an object");e=e||new FormData,t=M.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,c){return!M.isUndefined(c[h])});const n=t.metaTokens,s=t.visitor||p,o=t.dots,i=t.indexes,d=(t.Blob||typeof Blob<"u"&&Blob)&&M.isSpecCompliantForm(e);if(!M.isFunction(s))throw new TypeError("visitor must be a function");function u(m){if(m===null)return"";if(M.isDate(m))return m.toISOString();if(M.isBoolean(m))return m.toString();if(!d&&M.isBlob(m))throw new ee("Blob is not supported. Use a Buffer instead.");return M.isArrayBuffer(m)||M.isTypedArray(m)?d&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function p(m,h,c){let g=m;if(m&&!c&&typeof m=="object"){if(M.endsWith(h,"{}"))h=n?h:h.slice(0,-2),m=JSON.stringify(m);else if(M.isArray(m)&&Du(m)||(M.isFileList(m)||M.endsWith(h,"[]"))&&(g=M.toArray(m)))return h=pl(h),g.forEach(function(b,_){!(M.isUndefined(b)||b===null)&&e.append(i===!0?ea([h],_,o):i===null?h:h+"[]",u(b))}),!1}return ds(m)?!0:(e.append(ea(c,h,o),u(m)),!1)}const f=[],x=Object.assign(Fu,{defaultVisitor:p,convertValue:u,isVisitable:ds});function w(m,h){if(!M.isUndefined(m)){if(f.indexOf(m)!==-1)throw Error("Circular reference detected in "+h.join("."));f.push(m),M.forEach(m,function(g,y){(!(M.isUndefined(g)||g===null)&&s.call(e,g,M.isString(y)?y.trim():y,h,x))===!0&&w(g,h?h.concat(y):[y])}),f.pop()}}if(!M.isObject(r))throw new TypeError("data must be an object");return w(r),e}function ta(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function so(r,e){this._pairs=[],r&&mn(r,this,e)}const xl=so.prototype;xl.append=function(e,t){this._pairs.push([e,t])};xl.toString=function(e){const t=e?function(n){return e.call(this,n,ta)}:ta;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function Uu(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function yl(r,e,t){if(!e)return r;const n=t&&t.encode||Uu;M.isFunction(t)&&(t={serialize:t});const s=t&&t.serialize;let o;if(s?o=s(e,t):o=M.isURLSearchParams(e)?e.toString():new so(e,t).toString(n),o){const i=r.indexOf("#");i!==-1&&(r=r.slice(0,i)),r+=(r.indexOf("?")===-1?"?":"&")+o}return r}class ra{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){M.forEach(this.handlers,function(n){n!==null&&e(n)})}}const bl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Bu=typeof URLSearchParams<"u"?URLSearchParams:so,Wu=typeof FormData<"u"?FormData:null,Hu=typeof Blob<"u"?Blob:null,qu={isBrowser:!0,classes:{URLSearchParams:Bu,FormData:Wu,Blob:Hu},protocols:["http","https","file","blob","url","data"]},oo=typeof window<"u"&&typeof document<"u",us=typeof navigator=="object"&&navigator||void 0,zu=oo&&(!us||["ReactNative","NativeScript","NS"].indexOf(us.product)<0),Ju=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Vu=oo&&window.location.href||"http://localhost",Gu=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:oo,hasStandardBrowserEnv:zu,hasStandardBrowserWebWorkerEnv:Ju,navigator:us,origin:Vu},Symbol.toStringTag,{value:"Module"})),we={...Gu,...qu};function Xu(r,e){return mn(r,new we.classes.URLSearchParams,{visitor:function(t,n,s,o){return we.isNode&&M.isBuffer(t)?(this.append(n,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function Ku(r){return M.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Yu(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 wl(r){function e(t,n,s,o){let i=t[o++];if(i==="__proto__")return!0;const l=Number.isFinite(+i),d=o>=t.length;return i=!i&&M.isArray(s)?s.length:i,d?(M.hasOwnProp(s,i)?s[i]=[s[i],n]:s[i]=n,!l):((!s[i]||!M.isObject(s[i]))&&(s[i]=[]),e(t,n,s[i],o)&&M.isArray(s[i])&&(s[i]=Yu(s[i])),!l)}if(M.isFormData(r)&&M.isFunction(r.entries)){const t={};return M.forEachEntry(r,(n,s)=>{e(Ku(n),s,t,0)}),t}return null}function Qu(r,e,t){if(M.isString(r))try{return(e||JSON.parse)(r),M.trim(r)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(r)}const dr={transitional:bl,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",s=n.indexOf("application/json")>-1,o=M.isObject(e);if(o&&M.isHTMLForm(e)&&(e=new FormData(e)),M.isFormData(e))return s?JSON.stringify(wl(e)):e;if(M.isArrayBuffer(e)||M.isBuffer(e)||M.isStream(e)||M.isFile(e)||M.isBlob(e)||M.isReadableStream(e))return e;if(M.isArrayBufferView(e))return e.buffer;if(M.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let l;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Xu(e,this.formSerializer).toString();if((l=M.isFileList(e))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return mn(l?{"files[]":e}:e,d&&new d,this.formSerializer)}}return o||s?(t.setContentType("application/json",!1),Qu(e)):e}],transformResponse:[function(e){const t=this.transitional||dr.transitional,n=t&&t.forcedJSONParsing,s=this.responseType==="json";if(M.isResponse(e)||M.isReadableStream(e))return e;if(e&&M.isString(e)&&(n&&!this.responseType||s)){const i=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e,this.parseReviver)}catch(l){if(i)throw l.name==="SyntaxError"?ee.from(l,ee.ERR_BAD_RESPONSE,this,null,this.response):l}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:we.classes.FormData,Blob:we.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};M.forEach(["delete","get","head","post","put","patch"],r=>{dr.headers[r]={}});const Zu=M.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"]),ef=r=>{const e={};let t,n,s;return r&&r.split(`
61
- `).forEach(function(i){s=i.indexOf(":"),t=i.substring(0,s).trim().toLowerCase(),n=i.substring(s+1).trim(),!(!t||e[t]&&Zu[t])&&(t==="set-cookie"?e[t]?e[t].push(n):e[t]=[n]:e[t]=e[t]?e[t]+", "+n:n)}),e},na=Symbol("internals");function Pt(r){return r&&String(r).trim().toLowerCase()}function Or(r){return r===!1||r==null?r:M.isArray(r)?r.map(Or):String(r)}function tf(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 rf=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function Ln(r,e,t,n,s){if(M.isFunction(n))return n.call(this,e,t);if(s&&(e=t),!!M.isString(e)){if(M.isString(n))return e.indexOf(n)!==-1;if(M.isRegExp(n))return n.test(e)}}function nf(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function sf(r,e){const t=M.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(r,n+t,{value:function(s,o,i){return this[n].call(this,e,s,o,i)},configurable:!0})})}let Ce=class{constructor(e){e&&this.set(e)}set(e,t,n){const s=this;function o(l,d,u){const p=Pt(d);if(!p)throw new Error("header name must be a non-empty string");const f=M.findKey(s,p);(!f||s[f]===void 0||u===!0||u===void 0&&s[f]!==!1)&&(s[f||d]=Or(l))}const i=(l,d)=>M.forEach(l,(u,p)=>o(u,p,d));if(M.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(M.isString(e)&&(e=e.trim())&&!rf(e))i(ef(e),t);else if(M.isObject(e)&&M.isIterable(e)){let l={},d,u;for(const p of e){if(!M.isArray(p))throw TypeError("Object iterator must return a key-value pair");l[u=p[0]]=(d=l[u])?M.isArray(d)?[...d,p[1]]:[d,p[1]]:p[1]}i(l,t)}else e!=null&&o(t,e,n);return this}get(e,t){if(e=Pt(e),e){const n=M.findKey(this,e);if(n){const s=this[n];if(!t)return s;if(t===!0)return tf(s);if(M.isFunction(t))return t.call(this,s,n);if(M.isRegExp(t))return t.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Pt(e),e){const n=M.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||Ln(this,this[n],n,t)))}return!1}delete(e,t){const n=this;let s=!1;function o(i){if(i=Pt(i),i){const l=M.findKey(n,i);l&&(!t||Ln(n,n[l],l,t))&&(delete n[l],s=!0)}}return M.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||Ln(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const t=this,n={};return M.forEach(this,(s,o)=>{const i=M.findKey(n,o);if(i){t[i]=Or(s),delete t[o];return}const l=e?nf(o):String(o).trim();l!==o&&delete t[o],t[l]=Or(s),n[l]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return M.forEach(this,(n,s)=>{n!=null&&n!==!1&&(t[s]=e&&M.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(`
62
- `)}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[na]=this[na]={accessors:{}}).accessors,s=this.prototype;function o(i){const l=Pt(i);n[l]||(sf(s,i),n[l]=!0)}return M.isArray(e)?e.forEach(o):o(e),this}};Ce.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);M.reduceDescriptors(Ce.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(n){this[t]=n}}});M.freezeMethods(Ce);function Dn(r,e){const t=this||dr,n=e||t,s=Ce.from(n.headers);let o=n.data;return M.forEach(r,function(l){o=l.call(t,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function vl(r){return!!(r&&r.__CANCEL__)}function It(r,e,t){ee.call(this,r??"canceled",ee.ERR_CANCELED,e,t),this.name="CanceledError"}M.inherits(It,ee,{__CANCEL__:!0});function _l(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new ee("Request failed with status code "+t.status,[ee.ERR_BAD_REQUEST,ee.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function of(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function af(r,e){r=r||10;const t=new Array(r),n=new Array(r);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(d){const u=Date.now(),p=n[o];i||(i=u),t[s]=d,n[s]=u;let f=o,x=0;for(;f!==s;)x+=t[f++],f=f%r;if(s=(s+1)%r,s===o&&(o=(o+1)%r),u-i<e)return;const w=p&&u-p;return w?Math.round(x*1e3/w):void 0}}function lf(r,e){let t=0,n=1e3/e,s,o;const i=(u,p=Date.now())=>{t=p,s=null,o&&(clearTimeout(o),o=null),r(...u)};return[(...u)=>{const p=Date.now(),f=p-t;f>=n?i(u,p):(s=u,o||(o=setTimeout(()=>{o=null,i(s)},n-f)))},()=>s&&i(s)]}const qr=(r,e,t=3)=>{let n=0;const s=af(50,250);return lf(o=>{const i=o.loaded,l=o.lengthComputable?o.total:void 0,d=i-n,u=s(d),p=i<=l;n=i;const f={loaded:i,total:l,progress:l?i/l:void 0,bytes:d,rate:u||void 0,estimated:u&&l&&p?(l-i)/u:void 0,event:o,lengthComputable:l!=null,[e?"download":"upload"]:!0};r(f)},t)},sa=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},oa=r=>(...e)=>M.asap(()=>r(...e)),cf=we.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,we.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(we.origin),we.navigator&&/(msie|trident)/i.test(we.navigator.userAgent)):()=>!0,df=we.hasStandardBrowserEnv?{write(r,e,t,n,s,o){const i=[r+"="+encodeURIComponent(e)];M.isNumber(t)&&i.push("expires="+new Date(t).toGMTString()),M.isString(n)&&i.push("path="+n),M.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.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 uf(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function ff(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function Sl(r,e,t){let n=!uf(e);return r&&(n||t==!1)?ff(r,e):e}const aa=r=>r instanceof Ce?{...r}:r;function dt(r,e){e=e||{};const t={};function n(u,p,f,x){return M.isPlainObject(u)&&M.isPlainObject(p)?M.merge.call({caseless:x},u,p):M.isPlainObject(p)?M.merge({},p):M.isArray(p)?p.slice():p}function s(u,p,f,x){if(M.isUndefined(p)){if(!M.isUndefined(u))return n(void 0,u,f,x)}else return n(u,p,f,x)}function o(u,p){if(!M.isUndefined(p))return n(void 0,p)}function i(u,p){if(M.isUndefined(p)){if(!M.isUndefined(u))return n(void 0,u)}else return n(void 0,p)}function l(u,p,f){if(f in e)return n(u,p);if(f in r)return n(void 0,u)}const d={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:l,headers:(u,p,f)=>s(aa(u),aa(p),f,!0)};return M.forEach(Object.keys({...r,...e}),function(p){const f=d[p]||s,x=f(r[p],e[p],p);M.isUndefined(x)&&f!==l||(t[p]=x)}),t}const Cl=r=>{const e=dt({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:l}=e;if(e.headers=i=Ce.from(i),e.url=yl(Sl(e.baseURL,e.url,e.allowAbsoluteUrls),r.params,r.paramsSerializer),l&&i.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):""))),M.isFormData(t)){if(we.hasStandardBrowserEnv||we.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(M.isFunction(t.getHeaders)){const d=t.getHeaders(),u=["content-type","content-length"];Object.entries(d).forEach(([p,f])=>{u.includes(p.toLowerCase())&&i.set(p,f)})}}if(we.hasStandardBrowserEnv&&(n&&M.isFunction(n)&&(n=n(e)),n||n!==!1&&cf(e.url))){const d=s&&o&&df.read(o);d&&i.set(s,d)}return e},hf=typeof XMLHttpRequest<"u",mf=hf&&function(r){return new Promise(function(t,n){const s=Cl(r);let o=s.data;const i=Ce.from(s.headers).normalize();let{responseType:l,onUploadProgress:d,onDownloadProgress:u}=s,p,f,x,w,m;function h(){w&&w(),m&&m(),s.cancelToken&&s.cancelToken.unsubscribe(p),s.signal&&s.signal.removeEventListener("abort",p)}let c=new XMLHttpRequest;c.open(s.method.toUpperCase(),s.url,!0),c.timeout=s.timeout;function g(){if(!c)return;const b=Ce.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),v={data:!l||l==="text"||l==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:b,config:r,request:c};_l(function(S){t(S),h()},function(S){n(S),h()},v),c=null}"onloadend"in c?c.onloadend=g:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(g)},c.onabort=function(){c&&(n(new ee("Request aborted",ee.ECONNABORTED,r,c)),c=null)},c.onerror=function(_){const v=_&&_.message?_.message:"Network Error",C=new ee(v,ee.ERR_NETWORK,r,c);C.event=_||null,n(C),c=null},c.ontimeout=function(){let _=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const v=s.transitional||bl;s.timeoutErrorMessage&&(_=s.timeoutErrorMessage),n(new ee(_,v.clarifyTimeoutError?ee.ETIMEDOUT:ee.ECONNABORTED,r,c)),c=null},o===void 0&&i.setContentType(null),"setRequestHeader"in c&&M.forEach(i.toJSON(),function(_,v){c.setRequestHeader(v,_)}),M.isUndefined(s.withCredentials)||(c.withCredentials=!!s.withCredentials),l&&l!=="json"&&(c.responseType=s.responseType),u&&([x,m]=qr(u,!0),c.addEventListener("progress",x)),d&&c.upload&&([f,w]=qr(d),c.upload.addEventListener("progress",f),c.upload.addEventListener("loadend",w)),(s.cancelToken||s.signal)&&(p=b=>{c&&(n(!b||b.type?new It(null,r,c):b),c.abort(),c=null)},s.cancelToken&&s.cancelToken.subscribe(p),s.signal&&(s.signal.aborted?p():s.signal.addEventListener("abort",p)));const y=of(s.url);if(y&&we.protocols.indexOf(y)===-1){n(new ee("Unsupported protocol "+y+":",ee.ERR_BAD_REQUEST,r));return}c.send(o||null)})},gf=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let n=new AbortController,s;const o=function(u){if(!s){s=!0,l();const p=u instanceof Error?u:this.reason;n.abort(p instanceof ee?p:new It(p instanceof Error?p.message:p))}};let i=e&&setTimeout(()=>{i=null,o(new ee(`timeout ${e} of ms exceeded`,ee.ETIMEDOUT))},e);const l=()=>{r&&(i&&clearTimeout(i),i=null,r.forEach(u=>{u.unsubscribe?u.unsubscribe(o):u.removeEventListener("abort",o)}),r=null)};r.forEach(u=>u.addEventListener("abort",o));const{signal:d}=n;return d.unsubscribe=()=>M.asap(l),d}},pf=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},xf=async function*(r,e){for await(const t of yf(r))yield*pf(t,e)},yf=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()}},ia=(r,e,t,n)=>{const s=xf(r,e);let o=0,i,l=d=>{i||(i=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:u,value:p}=await s.next();if(u){l(),d.close();return}let f=p.byteLength;if(t){let x=o+=f;t(x)}d.enqueue(new Uint8Array(p))}catch(u){throw l(u),u}},cancel(d){return l(d),s.return()}},{highWaterMark:2})},la=64*1024,{isFunction:Sr}=M,bf=(({Request:r,Response:e})=>({Request:r,Response:e}))(M.global),{ReadableStream:ca,TextEncoder:da}=M.global,ua=(r,...e)=>{try{return!!r(...e)}catch{return!1}},wf=r=>{r=M.merge.call({skipUndefined:!0},bf,r);const{fetch:e,Request:t,Response:n}=r,s=e?Sr(e):typeof fetch=="function",o=Sr(t),i=Sr(n);if(!s)return!1;const l=s&&Sr(ca),d=s&&(typeof da=="function"?(m=>h=>m.encode(h))(new da):async m=>new Uint8Array(await new t(m).arrayBuffer())),u=o&&l&&ua(()=>{let m=!1;const h=new t(we.origin,{body:new ca,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!h}),p=i&&l&&ua(()=>M.isReadableStream(new n("").body)),f={stream:p&&(m=>m.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!f[m]&&(f[m]=(h,c)=>{let g=h&&h[m];if(g)return g.call(h);throw new ee(`Response type '${m}' is not supported`,ee.ERR_NOT_SUPPORT,c)})});const x=async m=>{if(m==null)return 0;if(M.isBlob(m))return m.size;if(M.isSpecCompliantForm(m))return(await new t(we.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(M.isArrayBufferView(m)||M.isArrayBuffer(m))return m.byteLength;if(M.isURLSearchParams(m)&&(m=m+""),M.isString(m))return(await d(m)).byteLength},w=async(m,h)=>{const c=M.toFiniteNumber(m.getContentLength());return c??x(h)};return async m=>{let{url:h,method:c,data:g,signal:y,cancelToken:b,timeout:_,onDownloadProgress:v,onUploadProgress:C,responseType:S,headers:I,withCredentials:E="same-origin",fetchOptions:P}=Cl(m),R=e||fetch;S=S?(S+"").toLowerCase():"text";let j=gf([y,b&&b.toAbortSignal()],_),W=null;const D=j&&j.unsubscribe&&(()=>{j.unsubscribe()});let X;try{if(C&&u&&c!=="get"&&c!=="head"&&(X=await w(I,g))!==0){let O=new t(h,{method:"POST",body:g,duplex:"half"}),U;if(M.isFormData(g)&&(U=O.headers.get("content-type"))&&I.setContentType(U),O.body){const[V,k]=sa(X,qr(oa(C)));g=ia(O.body,la,V,k)}}M.isString(E)||(E=E?"include":"omit");const G=o&&"credentials"in t.prototype,N={...P,signal:j,method:c.toUpperCase(),headers:I.normalize().toJSON(),body:g,duplex:"half",credentials:G?E:void 0};W=o&&new t(h,N);let F=await(o?R(W,P):R(h,N));const z=p&&(S==="stream"||S==="response");if(p&&(v||z&&D)){const O={};["status","statusText","headers"].forEach(q=>{O[q]=F[q]});const U=M.toFiniteNumber(F.headers.get("content-length")),[V,k]=v&&sa(U,qr(oa(v),!0))||[];F=new n(ia(F.body,la,V,()=>{k&&k(),D&&D()}),O)}S=S||"text";let $=await f[M.findKey(f,S)||"text"](F,m);return!z&&D&&D(),await new Promise((O,U)=>{_l(O,U,{data:$,headers:Ce.from(F.headers),status:F.status,statusText:F.statusText,config:m,request:W})})}catch(G){throw D&&D(),G&&G.name==="TypeError"&&/Load failed|fetch/i.test(G.message)?Object.assign(new ee("Network Error",ee.ERR_NETWORK,m,W),{cause:G.cause||G}):ee.from(G,G&&G.code,m,W)}}},vf=new Map,jl=r=>{let e=r?r.env:{};const{fetch:t,Request:n,Response:s}=e,o=[n,s,t];let i=o.length,l=i,d,u,p=vf;for(;l--;)d=o[l],u=p.get(d),u===void 0&&p.set(d,u=l?new Map:wf(e)),p=u;return u};jl();const fs={http:Lu,xhr:mf,fetch:{get:jl}};M.forEach(fs,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const fa=r=>`- ${r}`,_f=r=>M.isFunction(r)||r===null||r===!1,Al={getAdapter:(r,e)=>{r=M.isArray(r)?r:[r];const{length:t}=r;let n,s;const o={};for(let i=0;i<t;i++){n=r[i];let l;if(s=n,!_f(n)&&(s=fs[(l=String(n)).toLowerCase()],s===void 0))throw new ee(`Unknown adapter '${l}'`);if(s&&(M.isFunction(s)||(s=s.get(e))))break;o[l||"#"+i]=s}if(!s){const i=Object.entries(o).map(([d,u])=>`adapter ${d} `+(u===!1?"is not supported by the environment":"is not available in the build"));let l=t?i.length>1?`since :
63
- `+i.map(fa).join(`
64
- `):" "+fa(i[0]):"as no adapter specified";throw new ee("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return s},adapters:fs};function Fn(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new It(null,r)}function ha(r){return Fn(r),r.headers=Ce.from(r.headers),r.data=Dn.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),Al.getAdapter(r.adapter||dr.adapter,r)(r).then(function(n){return Fn(r),n.data=Dn.call(r,r.transformResponse,n),n.headers=Ce.from(n.headers),n},function(n){return vl(n)||(Fn(r),n&&n.response&&(n.response.data=Dn.call(r,r.transformResponse,n.response),n.response.headers=Ce.from(n.response.headers))),Promise.reject(n)})}const kl="1.12.2",gn={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{gn[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});const ma={};gn.transitional=function(e,t,n){function s(o,i){return"[Axios v"+kl+"] Transitional option '"+o+"'"+i+(n?". "+n:"")}return(o,i,l)=>{if(e===!1)throw new ee(s(i," has been removed"+(t?" in "+t:"")),ee.ERR_DEPRECATED);return t&&!ma[i]&&(ma[i]=!0,console.warn(s(i," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(o,i,l):!0}};gn.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Sf(r,e,t){if(typeof r!="object")throw new ee("options must be an object",ee.ERR_BAD_OPTION_VALUE);const n=Object.keys(r);let s=n.length;for(;s-- >0;){const o=n[s],i=e[o];if(i){const l=r[o],d=l===void 0||i(l,o,r);if(d!==!0)throw new ee("option "+o+" must be "+d,ee.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new ee("Unknown option "+o,ee.ERR_BAD_OPTION)}}const Rr={assertOptions:Sf,validators:gn},$e=Rr.validators;let at=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ra,response:new ra}}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+=`
65
- `+o):n.stack=o}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=dt(this.defaults,t);const{transitional:n,paramsSerializer:s,headers:o}=t;n!==void 0&&Rr.assertOptions(n,{silentJSONParsing:$e.transitional($e.boolean),forcedJSONParsing:$e.transitional($e.boolean),clarifyTimeoutError:$e.transitional($e.boolean)},!1),s!=null&&(M.isFunction(s)?t.paramsSerializer={serialize:s}:Rr.assertOptions(s,{encode:$e.function,serialize:$e.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Rr.assertOptions(t,{baseUrl:$e.spelling("baseURL"),withXsrfToken:$e.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=o&&M.merge(o.common,o[t.method]);o&&M.forEach(["delete","get","head","post","put","patch","common"],m=>{delete o[m]}),t.headers=Ce.concat(i,o);const l=[];let d=!0;this.interceptors.request.forEach(function(h){typeof h.runWhen=="function"&&h.runWhen(t)===!1||(d=d&&h.synchronous,l.unshift(h.fulfilled,h.rejected))});const u=[];this.interceptors.response.forEach(function(h){u.push(h.fulfilled,h.rejected)});let p,f=0,x;if(!d){const m=[ha.bind(this),void 0];for(m.unshift(...l),m.push(...u),x=m.length,p=Promise.resolve(t);f<x;)p=p.then(m[f++],m[f++]);return p}x=l.length;let w=t;for(;f<x;){const m=l[f++],h=l[f++];try{w=m(w)}catch(c){h.call(this,c);break}}try{p=ha.call(this,w)}catch(m){return Promise.reject(m)}for(f=0,x=u.length;f<x;)p=p.then(u[f++],u[f++]);return p}getUri(e){e=dt(this.defaults,e);const t=Sl(e.baseURL,e.url,e.allowAbsoluteUrls);return yl(t,e.params,e.paramsSerializer)}};M.forEach(["delete","get","head","options"],function(e){at.prototype[e]=function(t,n){return this.request(dt(n||{},{method:e,url:t,data:(n||{}).data}))}});M.forEach(["post","put","patch"],function(e){function t(n){return function(o,i,l){return this.request(dt(l||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}at.prototype[e]=t(),at.prototype[e+"Form"]=t(!0)});let Cf=class Nl{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 i=new Promise(l=>{n.subscribe(l),o=l}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},e(function(o,i,l){n.reason||(n.reason=new It(o,i,l),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 Nl(function(s){e=s}),cancel:e}}};function jf(r){return function(t){return r.apply(null,t)}}function Af(r){return M.isObject(r)&&r.isAxiosError===!0}const hs={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(hs).forEach(([r,e])=>{hs[e]=r});function Ml(r){const e=new at(r),t=al(at.prototype.request,e);return M.extend(t,at.prototype,e,{allOwnKeys:!0}),M.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return Ml(dt(r,s))},t}const de=Ml(dr);de.Axios=at;de.CanceledError=It;de.CancelToken=Cf;de.isCancel=vl;de.VERSION=kl;de.toFormData=mn;de.AxiosError=ee;de.Cancel=de.CanceledError;de.all=function(e){return Promise.all(e)};de.spread=jf;de.isAxiosError=Af;de.mergeConfig=dt;de.AxiosHeaders=Ce;de.formToJSON=r=>wl(M.isHTMLForm(r)?new FormData(r):r);de.getAdapter=Al.getAdapter;de.HttpStatusCode=hs;de.default=de;const{Axios:Zg,AxiosError:ep,CanceledError:tp,isCancel:rp,CancelToken:np,VERSION:sp,all:op,Cancel:ap,isAxiosError:ip,spread:lp,toFormData:cp,AxiosHeaders:dp,HttpStatusCode:up,formToJSON:fp,getAdapter:hp,mergeConfig:mp}=de,ga=de.create({timeout:3e4,headers:{"Content-Type":"application/json"}});class kf{constructor(e){J(this,"mcpServers");J(this,"tools");J(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,i)=>{var l,d,u,p;try{const f=((l=e.function)==null?void 0:l.name)||e.name,x=((d=e.function)==null?void 0:d.arguments)||e.arguments||{};let w=x;if(typeof x=="string")try{w=JSON.parse(x)}catch(c){console.warn("Failed to parse tool arguments:",c),w={}}const m=this.findToolInfo(f);if(!m)throw new Error(`Tool not found: ${f}`);const h=this.toolSupportsStreaming(f);if(console.log("开始调用工具:",h),h)await this.callMcpToolStream(m.serverUrl,m.originalName,w,t,()=>{n(),o()},c=>{s(new Error(c.message||"Tool execution failed")),i(c)});else{const c=await this.callMcpTool(m.serverUrl,m.originalName,w);t(JSON.stringify(c)),n(),o()}}catch(f){if(f.message==="Stream aborted by user"||f.name==="AbortError"){console.log(`Tool ${((u=e.function)==null?void 0:u.name)||e.name} stream aborted by user`),o();return}console.error(`Failed to execute stream tool ${((p=e.function)==null?void 0:p.name)||e.name}:`,f),s(new Error(f.message||"Tool execution failed")),i(f)}})}async execute(e){var n,s,o,i,l,d;console.log("开始调用工具,但是没有用流式的方式");const t=[];for(const u of e)try{const p=((n=u.function)==null?void 0:n.name)||u.name,f=((s=u.function)==null?void 0:s.arguments)||u.arguments||{};if(!p)throw new Error("Tool name is required");let x=f;if(typeof f=="string")try{x=JSON.parse(f)}catch(h){console.warn("Failed to parse tool arguments:",h),x={}}const w=this.findToolInfo(p);if(!w)throw new Error(`Tool not found: ${p}`);const m=await this.callMcpTool(w.serverUrl,w.originalName,x||{});t.push({tool_call_id:u.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:p,content:JSON.stringify(m),createdAt:new Date})}catch(p){if(p.message==="Stream aborted by user"||p.name==="AbortError"){console.log(`Tool ${((o=u.function)==null?void 0:o.name)||u.name} execution aborted by user`),t.push({tool_call_id:u.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:((i=u.function)==null?void 0:i.name)||u.name,content:JSON.stringify({result:"Tool execution aborted by user"})});continue}console.error(`Failed to execute tool ${((l=u.function)==null?void 0:l.name)||u.name}:`,p),t.push({tool_call_id:u.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:((d=u.function)==null?void 0:d.name)||u.name,content:JSON.stringify({error:p.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,i){try{const l=`${e}/sse/openai/tool/call`;console.log("MCP Stream Tool Call URL:",l);const d=new AbortController,u=await fetch(l,{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(!u.ok)throw new Error(`HTTP error! status: ${u.status}`);const p=u.body.getReader(),f=new TextDecoder;let x="",w=Date.now();const m=setInterval(()=>{if(Date.now()-w>12e4){clearInterval(m),p.cancel(),i(new Error("Stream read timeout: no data received for 2 minutes"));return}},1e4);try{for(;;){const{done:h,value:c}=await p.read();if(h)break;w=Date.now(),x+=f.decode(c,{stream:!0});const g=this.parseSSEEvents(x);x=g.remaining;for(const y of g.parsed)if(await this.handleSSEEvent(y,s,o,i)){clearInterval(m),p.cancel();return}}}finally{clearInterval(m),p.releaseLock()}}catch(l){if(l.name==="AbortError"||l.message==="Stream aborted by user"){console.log("MCP stream request aborted by user");return}console.error(`Failed to call MCP stream tool ${t}:`,l),l.message&&l.message.includes("Stream read timeout")?i(l):l.message&&l.message.includes("fetch")?i(new Error(`Network error during stream request: ${l.message}`)):i(new Error(l.message||"Stream error"))}}parseSSEEvents(e){const t=[],n=e.split(`
66
- `);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 u=d.substring(5).trim();u==="[DONE]"?t.push({event:"end",data:"{}"}):s.data=u}o++}const i=e.lastIndexOf(`
59
+ ${e}`,status:"completed",createdAt:new Date}];let s="";return await new rl(n,[],this.conversationId,(i,l)=>{i==="chunk"&&(l!=null&&l.content)&&(s+=l.content,this.callback("summary_chunk",{content:l.content,accumulated:s}))},this.modelConfig,this.configUrl,this.sessionId).chatCompletion(),s.trim()||`工具 ${t} 执行完成,内容长度: ${e.length} 字符`}catch(n){return n.message==="Stream aborted by user"||n.name==="AbortError"?(console.log("总结生成被用户中断"),`工具 ${t} 执行完成,内容长度: ${e.length} 字符`):(console.error("生成总结时出错:",n),`工具 ${t} 执行完成,内容长度: ${e.length} 字符`)}}}class Xo{constructor(e,t,n,s,o,i,l,d,f,g){W(this,"messages");W(this,"conversationId");W(this,"tools");W(this,"modelConfig");W(this,"callBack");W(this,"mcpToolExecute");W(this,"configUrl");W(this,"isAborted");W(this,"currentAiRequestHandler");W(this,"toolResultProcessor");W(this,"sessionId");this.messages=e,this.conversationId=t,this.tools=n,this.modelConfig=s,this.callBack=o,this.mcpToolExecute=i,this.configUrl=d||"/api",this.sessionId=g||this.conversationId,console.log("🔧 AiClient Constructor - configUrl:",this.configUrl),this.isAborted=!1,this.currentAiRequestHandler=null,this.toolResultProcessor=new Xd(l,this.modelConfig,this.conversationId,this.callBack,this.sessionId,this.configUrl),f&&f.signal.addEventListener("abort",()=>{console.log("AiClient: External abort signal received"),this.abort()})}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 l of n.tool_calls){if(this.isAborted){console.log("AiClient: Aborted during tool execution");return}const d=((s=l.function)==null?void 0:s.name)||l.name;if(this.mcpToolExecute.toolSupportsStreaming(d)){console.log(`Using streaming execution for tool: ${d}`);const g={tool_call_id:l.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:d,content:""};try{await this.mcpToolExecute.executeStream(l,h=>{if(this.isAborted)return;console.log("chunk",h);const p=this.processChunk(h);g.content+=p,this.callBack("tool_stream_chunk",{toolCallId:l.id,chunk:p})},()=>{this.isAborted||console.log(`Stream completed for tool: ${d}`)},h=>{if(this.isAborted||h.message==="Stream aborted by user"||h.name==="AbortError"){console.log(`Tool ${d} stream aborted by user`);return}console.error(`Stream error for tool ${d}:`,h),g.content=JSON.stringify({error:h.message||"Tool execution failed"})}),g.content||(g.content=JSON.stringify({result:"Tool execution completed"}))}catch(h){if(this.isAborted||h.message==="Stream aborted by user"||h.name==="AbortError"){console.log(`Tool ${d} execution aborted by user`);return}console.error(`Failed to execute stream tool ${d}:`,h),g.content=JSON.stringify({error:h.message||"Tool execution failed"})}o.push(g)}else{console.log(`Using regular execution for tool: ${d}`);const g=await this.mcpToolExecute.execute([l]);o.push(...g)}}if(this.isAborted){console.log("AiClient: Aborted after tool execution");return}const i=await this.toolResultProcessor.processToolResult(o[0],this.conversationId);debugger;if(this.messages.push(i),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 rl(this.messages,this.tools,this.conversationId,this.callBack,this.modelConfig,this.configUrl,this.sessionId);this.currentAiRequestHandler=e;try{this.messages=await e.chatCompletion()}catch(t){if(this.isAborted||t.message==="Stream aborted by user"||t.name==="AbortError"){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?`
60
+ `+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 nl(r,e){return function(){return r.apply(e,arguments)}}const{toString:Kd}=Object.prototype,{getPrototypeOf:eo}=Object,{iterator:un,toStringTag:sl}=Symbol,fn=(r=>e=>{const t=Kd.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Pe=r=>(r=r.toLowerCase(),e=>fn(e)===r),hn=r=>e=>typeof e===r,{isArray:Nt}=Array,Ct=hn("undefined");function or(r){return r!==null&&!Ct(r)&&r.constructor!==null&&!Ct(r.constructor)&&ve(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const ol=Pe("ArrayBuffer");function Yd(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&ol(r.buffer),e}const Qd=hn("string"),ve=hn("function"),al=hn("number"),ar=r=>r!==null&&typeof r=="object",Zd=r=>r===!0||r===!1,Tr=r=>{if(fn(r)!=="object")return!1;const e=eo(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(sl in r)&&!(un in r)},eu=r=>{if(!ar(r)||or(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},tu=Pe("Date"),ru=Pe("File"),nu=Pe("Blob"),su=Pe("FileList"),ou=r=>ar(r)&&ve(r.pipe),au=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||ve(r.append)&&((e=fn(r))==="formdata"||e==="object"&&ve(r.toString)&&r.toString()==="[object FormData]"))},iu=Pe("URLSearchParams"),[lu,cu,du,uu]=["ReadableStream","Request","Response","Headers"].map(Pe),fu=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function ir(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let n,s;if(typeof r!="object"&&(r=[r]),Nt(r))for(n=0,s=r.length;n<s;n++)e.call(null,r[n],n,r);else{if(or(r))return;const o=t?Object.getOwnPropertyNames(r):Object.keys(r),i=o.length;let l;for(n=0;n<i;n++)l=o[n],e.call(null,r[l],l,r)}}function il(r,e){if(or(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 rt=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,ll=r=>!Ct(r)&&r!==rt;function as(){const{caseless:r,skipUndefined:e}=ll(this)&&this||{},t={},n=(s,o)=>{const i=r&&il(t,o)||o;Tr(t[i])&&Tr(s)?t[i]=as(t[i],s):Tr(s)?t[i]=as({},s):Nt(s)?t[i]=s.slice():(!e||!Ct(s))&&(t[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&ir(arguments[s],n);return t}const hu=(r,e,t,{allOwnKeys:n}={})=>(ir(e,(s,o)=>{t&&ve(s)?r[o]=nl(s,t):r[o]=s},{allOwnKeys:n}),r),mu=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),gu=(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)},pu=(r,e,t,n)=>{let s,o,i;const l={};if(e=e||{},r==null)return e;do{for(s=Object.getOwnPropertyNames(r),o=s.length;o-- >0;)i=s[o],(!n||n(i,r,e))&&!l[i]&&(e[i]=r[i],l[i]=!0);r=t!==!1&&eo(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},xu=(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},bu=r=>{if(!r)return null;if(Nt(r))return r;let e=r.length;if(!al(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},yu=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&eo(Uint8Array)),wu=(r,e)=>{const n=(r&&r[un]).call(r);let s;for(;(s=n.next())&&!s.done;){const o=s.value;e.call(r,o[0],o[1])}},vu=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},_u=Pe("HTMLFormElement"),Su=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,s){return n.toUpperCase()+s}),Ko=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),Cu=Pe("RegExp"),cl=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};ir(t,(s,o)=>{let i;(i=e(s,o,r))!==!1&&(n[o]=i||s)}),Object.defineProperties(r,n)},ju=r=>{cl(r,(e,t)=>{if(ve(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=r[t];if(ve(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+"'")})}})},Au=(r,e)=>{const t={},n=s=>{s.forEach(o=>{t[o]=!0})};return Nt(r)?n(r):n(String(r).split(e)),t},ku=()=>{},Nu=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function Mu(r){return!!(r&&ve(r.append)&&r[sl]==="FormData"&&r[un])}const Eu=r=>{const e=new Array(10),t=(n,s)=>{if(ar(n)){if(e.indexOf(n)>=0)return;if(or(n))return n;if(!("toJSON"in n)){e[s]=n;const o=Nt(n)?[]:{};return ir(n,(i,l)=>{const d=t(i,s+1);!Ct(d)&&(o[l]=d)}),e[s]=void 0,o}}return n};return t(r,0)},Iu=Pe("AsyncFunction"),Pu=r=>r&&(ar(r)||ve(r))&&ve(r.then)&&ve(r.catch),dl=((r,e)=>r?setImmediate:e?((t,n)=>(rt.addEventListener("message",({source:s,data:o})=>{s===rt&&o===t&&n.length&&n.shift()()},!1),s=>{n.push(s),rt.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",ve(rt.postMessage)),Tu=typeof queueMicrotask<"u"?queueMicrotask.bind(rt):typeof process<"u"&&process.nextTick||dl,Ou=r=>r!=null&&ve(r[un]),E={isArray:Nt,isArrayBuffer:ol,isBuffer:or,isFormData:au,isArrayBufferView:Yd,isString:Qd,isNumber:al,isBoolean:Zd,isObject:ar,isPlainObject:Tr,isEmptyObject:eu,isReadableStream:lu,isRequest:cu,isResponse:du,isHeaders:uu,isUndefined:Ct,isDate:tu,isFile:ru,isBlob:nu,isRegExp:Cu,isFunction:ve,isStream:ou,isURLSearchParams:iu,isTypedArray:yu,isFileList:su,forEach:ir,merge:as,extend:hu,trim:fu,stripBOM:mu,inherits:gu,toFlatObject:pu,kindOf:fn,kindOfTest:Pe,endsWith:xu,toArray:bu,forEachEntry:wu,matchAll:vu,isHTMLForm:_u,hasOwnProperty:Ko,hasOwnProp:Ko,reduceDescriptors:cl,freezeMethods:ju,toObjectSet:Au,toCamelCase:Su,noop:ku,toFiniteNumber:Nu,findKey:il,global:rt,isContextDefined:ll,isSpecCompliantForm:Mu,toJSONObject:Eu,isAsyncFn:Iu,isThenable:Pu,setImmediate:dl,asap:Tu,isIterable:Ou};function K(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)}E.inherits(K,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:E.toJSONObject(this.config),code:this.code,status:this.status}}});const ul=K.prototype,fl={};["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=>{fl[r]={value:r}});Object.defineProperties(K,fl);Object.defineProperty(ul,"isAxiosError",{value:!0});K.from=(r,e,t,n,s,o)=>{const i=Object.create(ul);E.toFlatObject(r,i,function(g){return g!==Error.prototype},f=>f!=="isAxiosError");const l=r&&r.message?r.message:"Error",d=e==null&&r?r.code:e;return K.call(i,l,d,t,n,s),r&&i.cause==null&&Object.defineProperty(i,"cause",{value:r,configurable:!0}),i.name=r&&r.name||"Error",o&&Object.assign(i,o),i};const Ru=null;function is(r){return E.isPlainObject(r)||E.isArray(r)}function hl(r){return E.endsWith(r,"[]")?r.slice(0,-2):r}function Yo(r,e,t){return r?r.concat(e).map(function(s,o){return s=hl(s),!t&&o?"["+s+"]":s}).join(t?".":""):e}function $u(r){return E.isArray(r)&&!r.some(is)}const Lu=E.toFlatObject(E,{},null,function(e){return/^is[A-Z]/.test(e)});function mn(r,e,t){if(!E.isObject(r))throw new TypeError("target must be an object");e=e||new FormData,t=E.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(u,c){return!E.isUndefined(c[u])});const n=t.metaTokens,s=t.visitor||g,o=t.dots,i=t.indexes,d=(t.Blob||typeof Blob<"u"&&Blob)&&E.isSpecCompliantForm(e);if(!E.isFunction(s))throw new TypeError("visitor must be a function");function f(m){if(m===null)return"";if(E.isDate(m))return m.toISOString();if(E.isBoolean(m))return m.toString();if(!d&&E.isBlob(m))throw new K("Blob is not supported. Use a Buffer instead.");return E.isArrayBuffer(m)||E.isTypedArray(m)?d&&typeof Blob=="function"?new Blob([m]):Buffer.from(m):m}function g(m,u,c){let b=m;if(m&&!c&&typeof m=="object"){if(E.endsWith(u,"{}"))u=n?u:u.slice(0,-2),m=JSON.stringify(m);else if(E.isArray(m)&&$u(m)||(E.isFileList(m)||E.endsWith(u,"[]"))&&(b=E.toArray(m)))return u=hl(u),b.forEach(function(y,v){!(E.isUndefined(y)||y===null)&&e.append(i===!0?Yo([u],v,o):i===null?u:u+"[]",f(y))}),!1}return is(m)?!0:(e.append(Yo(c,u,o),f(m)),!1)}const h=[],p=Object.assign(Lu,{defaultVisitor:g,convertValue:f,isVisitable:is});function w(m,u){if(!E.isUndefined(m)){if(h.indexOf(m)!==-1)throw Error("Circular reference detected in "+u.join("."));h.push(m),E.forEach(m,function(b,x){(!(E.isUndefined(b)||b===null)&&s.call(e,b,E.isString(x)?x.trim():x,u,p))===!0&&w(b,u?u.concat(x):[x])}),h.pop()}}if(!E.isObject(r))throw new TypeError("data must be an object");return w(r),e}function Qo(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function to(r,e){this._pairs=[],r&&mn(r,this,e)}const ml=to.prototype;ml.append=function(e,t){this._pairs.push([e,t])};ml.toString=function(e){const t=e?function(n){return e.call(this,n,Qo)}:Qo;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function Du(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function gl(r,e,t){if(!e)return r;const n=t&&t.encode||Du;E.isFunction(t)&&(t={serialize:t});const s=t&&t.serialize;let o;if(s?o=s(e,t):o=E.isURLSearchParams(e)?e.toString():new to(e,t).toString(n),o){const i=r.indexOf("#");i!==-1&&(r=r.slice(0,i)),r+=(r.indexOf("?")===-1?"?":"&")+o}return r}class Zo{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){E.forEach(this.handlers,function(n){n!==null&&e(n)})}}const pl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Fu=typeof URLSearchParams<"u"?URLSearchParams:to,Uu=typeof FormData<"u"?FormData:null,Bu=typeof Blob<"u"?Blob:null,Wu={isBrowser:!0,classes:{URLSearchParams:Fu,FormData:Uu,Blob:Bu},protocols:["http","https","file","blob","url","data"]},ro=typeof window<"u"&&typeof document<"u",ls=typeof navigator=="object"&&navigator||void 0,Hu=ro&&(!ls||["ReactNative","NativeScript","NS"].indexOf(ls.product)<0),qu=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",zu=ro&&window.location.href||"http://localhost",Ju=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ro,hasStandardBrowserEnv:Hu,hasStandardBrowserWebWorkerEnv:qu,navigator:ls,origin:zu},Symbol.toStringTag,{value:"Module"})),xe={...Ju,...Wu};function Vu(r,e){return mn(r,new xe.classes.URLSearchParams,{visitor:function(t,n,s,o){return xe.isNode&&E.isBuffer(t)?(this.append(n,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function Gu(r){return E.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Xu(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 xl(r){function e(t,n,s,o){let i=t[o++];if(i==="__proto__")return!0;const l=Number.isFinite(+i),d=o>=t.length;return i=!i&&E.isArray(s)?s.length:i,d?(E.hasOwnProp(s,i)?s[i]=[s[i],n]:s[i]=n,!l):((!s[i]||!E.isObject(s[i]))&&(s[i]=[]),e(t,n,s[i],o)&&E.isArray(s[i])&&(s[i]=Xu(s[i])),!l)}if(E.isFormData(r)&&E.isFunction(r.entries)){const t={};return E.forEachEntry(r,(n,s)=>{e(Gu(n),s,t,0)}),t}return null}function Ku(r,e,t){if(E.isString(r))try{return(e||JSON.parse)(r),E.trim(r)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(r)}const lr={transitional:pl,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",s=n.indexOf("application/json")>-1,o=E.isObject(e);if(o&&E.isHTMLForm(e)&&(e=new FormData(e)),E.isFormData(e))return s?JSON.stringify(xl(e)):e;if(E.isArrayBuffer(e)||E.isBuffer(e)||E.isStream(e)||E.isFile(e)||E.isBlob(e)||E.isReadableStream(e))return e;if(E.isArrayBufferView(e))return e.buffer;if(E.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let l;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Vu(e,this.formSerializer).toString();if((l=E.isFileList(e))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return mn(l?{"files[]":e}:e,d&&new d,this.formSerializer)}}return o||s?(t.setContentType("application/json",!1),Ku(e)):e}],transformResponse:[function(e){const t=this.transitional||lr.transitional,n=t&&t.forcedJSONParsing,s=this.responseType==="json";if(E.isResponse(e)||E.isReadableStream(e))return e;if(e&&E.isString(e)&&(n&&!this.responseType||s)){const i=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e,this.parseReviver)}catch(l){if(i)throw l.name==="SyntaxError"?K.from(l,K.ERR_BAD_RESPONSE,this,null,this.response):l}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:xe.classes.FormData,Blob:xe.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};E.forEach(["delete","get","head","post","put","patch"],r=>{lr.headers[r]={}});const Yu=E.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"]),Qu=r=>{const e={};let t,n,s;return r&&r.split(`
61
+ `).forEach(function(i){s=i.indexOf(":"),t=i.substring(0,s).trim().toLowerCase(),n=i.substring(s+1).trim(),!(!t||e[t]&&Yu[t])&&(t==="set-cookie"?e[t]?e[t].push(n):e[t]=[n]:e[t]=e[t]?e[t]+", "+n:n)}),e},ea=Symbol("internals");function It(r){return r&&String(r).trim().toLowerCase()}function Or(r){return r===!1||r==null?r:E.isArray(r)?r.map(Or):String(r)}function Zu(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 ef=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function On(r,e,t,n,s){if(E.isFunction(n))return n.call(this,e,t);if(s&&(e=t),!!E.isString(e)){if(E.isString(n))return e.indexOf(n)!==-1;if(E.isRegExp(n))return n.test(e)}}function tf(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function rf(r,e){const t=E.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(r,n+t,{value:function(s,o,i){return this[n].call(this,e,s,o,i)},configurable:!0})})}let _e=class{constructor(e){e&&this.set(e)}set(e,t,n){const s=this;function o(l,d,f){const g=It(d);if(!g)throw new Error("header name must be a non-empty string");const h=E.findKey(s,g);(!h||s[h]===void 0||f===!0||f===void 0&&s[h]!==!1)&&(s[h||d]=Or(l))}const i=(l,d)=>E.forEach(l,(f,g)=>o(f,g,d));if(E.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(E.isString(e)&&(e=e.trim())&&!ef(e))i(Qu(e),t);else if(E.isObject(e)&&E.isIterable(e)){let l={},d,f;for(const g of e){if(!E.isArray(g))throw TypeError("Object iterator must return a key-value pair");l[f=g[0]]=(d=l[f])?E.isArray(d)?[...d,g[1]]:[d,g[1]]:g[1]}i(l,t)}else e!=null&&o(t,e,n);return this}get(e,t){if(e=It(e),e){const n=E.findKey(this,e);if(n){const s=this[n];if(!t)return s;if(t===!0)return Zu(s);if(E.isFunction(t))return t.call(this,s,n);if(E.isRegExp(t))return t.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=It(e),e){const n=E.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||On(this,this[n],n,t)))}return!1}delete(e,t){const n=this;let s=!1;function o(i){if(i=It(i),i){const l=E.findKey(n,i);l&&(!t||On(n,n[l],l,t))&&(delete n[l],s=!0)}}return E.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||On(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const t=this,n={};return E.forEach(this,(s,o)=>{const i=E.findKey(n,o);if(i){t[i]=Or(s),delete t[o];return}const l=e?tf(o):String(o).trim();l!==o&&delete t[o],t[l]=Or(s),n[l]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return E.forEach(this,(n,s)=>{n!=null&&n!==!1&&(t[s]=e&&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(`
62
+ `)}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[ea]=this[ea]={accessors:{}}).accessors,s=this.prototype;function o(i){const l=It(i);n[l]||(rf(s,i),n[l]=!0)}return E.isArray(e)?e.forEach(o):o(e),this}};_e.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);E.reduceDescriptors(_e.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(n){this[t]=n}}});E.freezeMethods(_e);function Rn(r,e){const t=this||lr,n=e||t,s=_e.from(n.headers);let o=n.data;return E.forEach(r,function(l){o=l.call(t,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function bl(r){return!!(r&&r.__CANCEL__)}function Mt(r,e,t){K.call(this,r??"canceled",K.ERR_CANCELED,e,t),this.name="CanceledError"}E.inherits(Mt,K,{__CANCEL__:!0});function yl(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new K("Request failed with status code "+t.status,[K.ERR_BAD_REQUEST,K.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function nf(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function sf(r,e){r=r||10;const t=new Array(r),n=new Array(r);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(d){const f=Date.now(),g=n[o];i||(i=f),t[s]=d,n[s]=f;let h=o,p=0;for(;h!==s;)p+=t[h++],h=h%r;if(s=(s+1)%r,s===o&&(o=(o+1)%r),f-i<e)return;const w=g&&f-g;return w?Math.round(p*1e3/w):void 0}}function of(r,e){let t=0,n=1e3/e,s,o;const i=(f,g=Date.now())=>{t=g,s=null,o&&(clearTimeout(o),o=null),r(...f)};return[(...f)=>{const g=Date.now(),h=g-t;h>=n?i(f,g):(s=f,o||(o=setTimeout(()=>{o=null,i(s)},n-h)))},()=>s&&i(s)]}const qr=(r,e,t=3)=>{let n=0;const s=sf(50,250);return of(o=>{const i=o.loaded,l=o.lengthComputable?o.total:void 0,d=i-n,f=s(d),g=i<=l;n=i;const h={loaded:i,total:l,progress:l?i/l:void 0,bytes:d,rate:f||void 0,estimated:f&&l&&g?(l-i)/f:void 0,event:o,lengthComputable:l!=null,[e?"download":"upload"]:!0};r(h)},t)},ta=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},ra=r=>(...e)=>E.asap(()=>r(...e)),af=xe.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,xe.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(xe.origin),xe.navigator&&/(msie|trident)/i.test(xe.navigator.userAgent)):()=>!0,lf=xe.hasStandardBrowserEnv?{write(r,e,t,n,s,o){const i=[r+"="+encodeURIComponent(e)];E.isNumber(t)&&i.push("expires="+new Date(t).toGMTString()),E.isString(n)&&i.push("path="+n),E.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.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 cf(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function df(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function wl(r,e,t){let n=!cf(e);return r&&(n||t==!1)?df(r,e):e}const na=r=>r instanceof _e?{...r}:r;function lt(r,e){e=e||{};const t={};function n(f,g,h,p){return E.isPlainObject(f)&&E.isPlainObject(g)?E.merge.call({caseless:p},f,g):E.isPlainObject(g)?E.merge({},g):E.isArray(g)?g.slice():g}function s(f,g,h,p){if(E.isUndefined(g)){if(!E.isUndefined(f))return n(void 0,f,h,p)}else return n(f,g,h,p)}function o(f,g){if(!E.isUndefined(g))return n(void 0,g)}function i(f,g){if(E.isUndefined(g)){if(!E.isUndefined(f))return n(void 0,f)}else return n(void 0,g)}function l(f,g,h){if(h in e)return n(f,g);if(h in r)return n(void 0,f)}const d={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:l,headers:(f,g,h)=>s(na(f),na(g),h,!0)};return E.forEach(Object.keys({...r,...e}),function(g){const h=d[g]||s,p=h(r[g],e[g],g);E.isUndefined(p)&&h!==l||(t[g]=p)}),t}const vl=r=>{const e=lt({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:l}=e;if(e.headers=i=_e.from(i),e.url=gl(wl(e.baseURL,e.url,e.allowAbsoluteUrls),r.params,r.paramsSerializer),l&&i.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):""))),E.isFormData(t)){if(xe.hasStandardBrowserEnv||xe.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(E.isFunction(t.getHeaders)){const d=t.getHeaders(),f=["content-type","content-length"];Object.entries(d).forEach(([g,h])=>{f.includes(g.toLowerCase())&&i.set(g,h)})}}if(xe.hasStandardBrowserEnv&&(n&&E.isFunction(n)&&(n=n(e)),n||n!==!1&&af(e.url))){const d=s&&o&&lf.read(o);d&&i.set(s,d)}return e},uf=typeof XMLHttpRequest<"u",ff=uf&&function(r){return new Promise(function(t,n){const s=vl(r);let o=s.data;const i=_e.from(s.headers).normalize();let{responseType:l,onUploadProgress:d,onDownloadProgress:f}=s,g,h,p,w,m;function u(){w&&w(),m&&m(),s.cancelToken&&s.cancelToken.unsubscribe(g),s.signal&&s.signal.removeEventListener("abort",g)}let c=new XMLHttpRequest;c.open(s.method.toUpperCase(),s.url,!0),c.timeout=s.timeout;function b(){if(!c)return;const y=_e.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),S={data:!l||l==="text"||l==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:y,config:r,request:c};yl(function(_){t(_),u()},function(_){n(_),u()},S),c=null}"onloadend"in c?c.onloadend=b:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(b)},c.onabort=function(){c&&(n(new K("Request aborted",K.ECONNABORTED,r,c)),c=null)},c.onerror=function(v){const S=v&&v.message?v.message:"Network Error",C=new K(S,K.ERR_NETWORK,r,c);C.event=v||null,n(C),c=null},c.ontimeout=function(){let v=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const S=s.transitional||pl;s.timeoutErrorMessage&&(v=s.timeoutErrorMessage),n(new K(v,S.clarifyTimeoutError?K.ETIMEDOUT:K.ECONNABORTED,r,c)),c=null},o===void 0&&i.setContentType(null),"setRequestHeader"in c&&E.forEach(i.toJSON(),function(v,S){c.setRequestHeader(S,v)}),E.isUndefined(s.withCredentials)||(c.withCredentials=!!s.withCredentials),l&&l!=="json"&&(c.responseType=s.responseType),f&&([p,m]=qr(f,!0),c.addEventListener("progress",p)),d&&c.upload&&([h,w]=qr(d),c.upload.addEventListener("progress",h),c.upload.addEventListener("loadend",w)),(s.cancelToken||s.signal)&&(g=y=>{c&&(n(!y||y.type?new Mt(null,r,c):y),c.abort(),c=null)},s.cancelToken&&s.cancelToken.subscribe(g),s.signal&&(s.signal.aborted?g():s.signal.addEventListener("abort",g)));const x=nf(s.url);if(x&&xe.protocols.indexOf(x)===-1){n(new K("Unsupported protocol "+x+":",K.ERR_BAD_REQUEST,r));return}c.send(o||null)})},hf=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let n=new AbortController,s;const o=function(f){if(!s){s=!0,l();const g=f instanceof Error?f:this.reason;n.abort(g instanceof K?g:new Mt(g instanceof Error?g.message:g))}};let i=e&&setTimeout(()=>{i=null,o(new K(`timeout ${e} of ms exceeded`,K.ETIMEDOUT))},e);const l=()=>{r&&(i&&clearTimeout(i),i=null,r.forEach(f=>{f.unsubscribe?f.unsubscribe(o):f.removeEventListener("abort",o)}),r=null)};r.forEach(f=>f.addEventListener("abort",o));const{signal:d}=n;return d.unsubscribe=()=>E.asap(l),d}},mf=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},gf=async function*(r,e){for await(const t of pf(r))yield*mf(t,e)},pf=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()}},sa=(r,e,t,n)=>{const s=gf(r,e);let o=0,i,l=d=>{i||(i=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:f,value:g}=await s.next();if(f){l(),d.close();return}let h=g.byteLength;if(t){let p=o+=h;t(p)}d.enqueue(new Uint8Array(g))}catch(f){throw l(f),f}},cancel(d){return l(d),s.return()}},{highWaterMark:2})},oa=64*1024,{isFunction:Sr}=E,xf=(({Request:r,Response:e})=>({Request:r,Response:e}))(E.global),{ReadableStream:aa,TextEncoder:ia}=E.global,la=(r,...e)=>{try{return!!r(...e)}catch{return!1}},bf=r=>{r=E.merge.call({skipUndefined:!0},xf,r);const{fetch:e,Request:t,Response:n}=r,s=e?Sr(e):typeof fetch=="function",o=Sr(t),i=Sr(n);if(!s)return!1;const l=s&&Sr(aa),d=s&&(typeof ia=="function"?(m=>u=>m.encode(u))(new ia):async m=>new Uint8Array(await new t(m).arrayBuffer())),f=o&&l&&la(()=>{let m=!1;const u=new t(xe.origin,{body:new aa,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!u}),g=i&&l&&la(()=>E.isReadableStream(new n("").body)),h={stream:g&&(m=>m.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!h[m]&&(h[m]=(u,c)=>{let b=u&&u[m];if(b)return b.call(u);throw new K(`Response type '${m}' is not supported`,K.ERR_NOT_SUPPORT,c)})});const p=async m=>{if(m==null)return 0;if(E.isBlob(m))return m.size;if(E.isSpecCompliantForm(m))return(await new t(xe.origin,{method:"POST",body:m}).arrayBuffer()).byteLength;if(E.isArrayBufferView(m)||E.isArrayBuffer(m))return m.byteLength;if(E.isURLSearchParams(m)&&(m=m+""),E.isString(m))return(await d(m)).byteLength},w=async(m,u)=>{const c=E.toFiniteNumber(m.getContentLength());return c??p(u)};return async m=>{let{url:u,method:c,data:b,signal:x,cancelToken:y,timeout:v,onDownloadProgress:S,onUploadProgress:C,responseType:_,headers:I,withCredentials:T="same-origin",fetchOptions:$}=vl(m),F=e||fetch;_=_?(_+"").toLowerCase():"text";let k=hf([x,y&&y.toAbortSignal()],v),U=null;const H=k&&k.unsubscribe&&(()=>{k.unsubscribe()});let Z;try{if(C&&f&&c!=="get"&&c!=="head"&&(Z=await w(I,b))!==0){let D=new t(u,{method:"POST",body:b,duplex:"half"}),A;if(E.isFormData(b)&&(A=D.headers.get("content-type"))&&I.setContentType(A),D.body){const[j,M]=ta(Z,qr(ra(C)));b=sa(D.body,oa,j,M)}}E.isString(T)||(T=T?"include":"omit");const P=o&&"credentials"in t.prototype,N={...$,signal:k,method:c.toUpperCase(),headers:I.normalize().toJSON(),body:b,duplex:"half",credentials:P?T:void 0};U=o&&new t(u,N);let R=await(o?F(U,$):F(u,N));const B=g&&(_==="stream"||_==="response");if(g&&(S||B&&H)){const D={};["status","statusText","headers"].forEach(L=>{D[L]=R[L]});const A=E.toFiniteNumber(R.headers.get("content-length")),[j,M]=S&&ta(A,qr(ra(S),!0))||[];R=new n(sa(R.body,oa,j,()=>{M&&M(),H&&H()}),D)}_=_||"text";let q=await h[E.findKey(h,_)||"text"](R,m);return!B&&H&&H(),await new Promise((D,A)=>{yl(D,A,{data:q,headers:_e.from(R.headers),status:R.status,statusText:R.statusText,config:m,request:U})})}catch(P){throw H&&H(),P&&P.name==="TypeError"&&/Load failed|fetch/i.test(P.message)?Object.assign(new K("Network Error",K.ERR_NETWORK,m,U),{cause:P.cause||P}):K.from(P,P&&P.code,m,U)}}},yf=new Map,_l=r=>{let e=r?r.env:{};const{fetch:t,Request:n,Response:s}=e,o=[n,s,t];let i=o.length,l=i,d,f,g=yf;for(;l--;)d=o[l],f=g.get(d),f===void 0&&g.set(d,f=l?new Map:bf(e)),g=f;return f};_l();const cs={http:Ru,xhr:ff,fetch:{get:_l}};E.forEach(cs,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const ca=r=>`- ${r}`,wf=r=>E.isFunction(r)||r===null||r===!1,Sl={getAdapter:(r,e)=>{r=E.isArray(r)?r:[r];const{length:t}=r;let n,s;const o={};for(let i=0;i<t;i++){n=r[i];let l;if(s=n,!wf(n)&&(s=cs[(l=String(n)).toLowerCase()],s===void 0))throw new K(`Unknown adapter '${l}'`);if(s&&(E.isFunction(s)||(s=s.get(e))))break;o[l||"#"+i]=s}if(!s){const i=Object.entries(o).map(([d,f])=>`adapter ${d} `+(f===!1?"is not supported by the environment":"is not available in the build"));let l=t?i.length>1?`since :
63
+ `+i.map(ca).join(`
64
+ `):" "+ca(i[0]):"as no adapter specified";throw new K("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return s},adapters:cs};function $n(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Mt(null,r)}function da(r){return $n(r),r.headers=_e.from(r.headers),r.data=Rn.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),Sl.getAdapter(r.adapter||lr.adapter,r)(r).then(function(n){return $n(r),n.data=Rn.call(r,r.transformResponse,n),n.headers=_e.from(n.headers),n},function(n){return bl(n)||($n(r),n&&n.response&&(n.response.data=Rn.call(r,r.transformResponse,n.response),n.response.headers=_e.from(n.response.headers))),Promise.reject(n)})}const Cl="1.12.2",gn={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{gn[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});const ua={};gn.transitional=function(e,t,n){function s(o,i){return"[Axios v"+Cl+"] Transitional option '"+o+"'"+i+(n?". "+n:"")}return(o,i,l)=>{if(e===!1)throw new K(s(i," has been removed"+(t?" in "+t:"")),K.ERR_DEPRECATED);return t&&!ua[i]&&(ua[i]=!0,console.warn(s(i," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(o,i,l):!0}};gn.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function vf(r,e,t){if(typeof r!="object")throw new K("options must be an object",K.ERR_BAD_OPTION_VALUE);const n=Object.keys(r);let s=n.length;for(;s-- >0;){const o=n[s],i=e[o];if(i){const l=r[o],d=l===void 0||i(l,o,r);if(d!==!0)throw new K("option "+o+" must be "+d,K.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new K("Unknown option "+o,K.ERR_BAD_OPTION)}}const Rr={assertOptions:vf,validators:gn},Oe=Rr.validators;let st=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Zo,response:new Zo}}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+=`
65
+ `+o):n.stack=o}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=lt(this.defaults,t);const{transitional:n,paramsSerializer:s,headers:o}=t;n!==void 0&&Rr.assertOptions(n,{silentJSONParsing:Oe.transitional(Oe.boolean),forcedJSONParsing:Oe.transitional(Oe.boolean),clarifyTimeoutError:Oe.transitional(Oe.boolean)},!1),s!=null&&(E.isFunction(s)?t.paramsSerializer={serialize:s}:Rr.assertOptions(s,{encode:Oe.function,serialize:Oe.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Rr.assertOptions(t,{baseUrl:Oe.spelling("baseURL"),withXsrfToken:Oe.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=o&&E.merge(o.common,o[t.method]);o&&E.forEach(["delete","get","head","post","put","patch","common"],m=>{delete o[m]}),t.headers=_e.concat(i,o);const l=[];let d=!0;this.interceptors.request.forEach(function(u){typeof u.runWhen=="function"&&u.runWhen(t)===!1||(d=d&&u.synchronous,l.unshift(u.fulfilled,u.rejected))});const f=[];this.interceptors.response.forEach(function(u){f.push(u.fulfilled,u.rejected)});let g,h=0,p;if(!d){const m=[da.bind(this),void 0];for(m.unshift(...l),m.push(...f),p=m.length,g=Promise.resolve(t);h<p;)g=g.then(m[h++],m[h++]);return g}p=l.length;let w=t;for(;h<p;){const m=l[h++],u=l[h++];try{w=m(w)}catch(c){u.call(this,c);break}}try{g=da.call(this,w)}catch(m){return Promise.reject(m)}for(h=0,p=f.length;h<p;)g=g.then(f[h++],f[h++]);return g}getUri(e){e=lt(this.defaults,e);const t=wl(e.baseURL,e.url,e.allowAbsoluteUrls);return gl(t,e.params,e.paramsSerializer)}};E.forEach(["delete","get","head","options"],function(e){st.prototype[e]=function(t,n){return this.request(lt(n||{},{method:e,url:t,data:(n||{}).data}))}});E.forEach(["post","put","patch"],function(e){function t(n){return function(o,i,l){return this.request(lt(l||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}st.prototype[e]=t(),st.prototype[e+"Form"]=t(!0)});let _f=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 i=new Promise(l=>{n.subscribe(l),o=l}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},e(function(o,i,l){n.reason||(n.reason=new Mt(o,i,l),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 Sf(r){return function(t){return r.apply(null,t)}}function Cf(r){return E.isObject(r)&&r.isAxiosError===!0}const ds={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(ds).forEach(([r,e])=>{ds[e]=r});function Al(r){const e=new st(r),t=nl(st.prototype.request,e);return E.extend(t,st.prototype,e,{allOwnKeys:!0}),E.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return Al(lt(r,s))},t}const ie=Al(lr);ie.Axios=st;ie.CanceledError=Mt;ie.CancelToken=_f;ie.isCancel=bl;ie.VERSION=Cl;ie.toFormData=mn;ie.AxiosError=K;ie.Cancel=ie.CanceledError;ie.all=function(e){return Promise.all(e)};ie.spread=Sf;ie.isAxiosError=Cf;ie.mergeConfig=lt;ie.AxiosHeaders=_e;ie.formToJSON=r=>xl(E.isHTMLForm(r)?new FormData(r):r);ie.getAdapter=Sl.getAdapter;ie.HttpStatusCode=ds;ie.default=ie;const{Axios:Yg,AxiosError:Qg,CanceledError:Zg,isCancel:ep,CancelToken:tp,VERSION:rp,all:np,Cancel:sp,isAxiosError:op,spread:ap,toFormData:ip,AxiosHeaders:lp,HttpStatusCode:cp,formToJSON:dp,getAdapter:up,mergeConfig:fp}=ie,fa=ie.create({timeout:3e4,headers:{"Content-Type":"application/json"}});class jf{constructor(e){W(this,"mcpServers");W(this,"tools");W(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,i)=>{var l,d,f,g;try{const h=((l=e.function)==null?void 0:l.name)||e.name,p=((d=e.function)==null?void 0:d.arguments)||e.arguments||{};let w=p;if(typeof p=="string")try{w=JSON.parse(p)}catch(c){console.warn("Failed to parse tool arguments:",c),w={}}const m=this.findToolInfo(h);if(!m)throw new Error(`Tool not found: ${h}`);const u=this.toolSupportsStreaming(h);if(console.log("开始调用工具:",u),u)await this.callMcpToolStream(m.serverUrl,m.originalName,w,t,()=>{n(),o()},c=>{s(new Error(c.message||"Tool execution failed")),i(c)});else{const c=await this.callMcpTool(m.serverUrl,m.originalName,w);t(JSON.stringify(c)),n(),o()}}catch(h){if(h.message==="Stream aborted by user"||h.name==="AbortError"){console.log(`Tool ${((f=e.function)==null?void 0:f.name)||e.name} stream aborted by user`),o();return}console.error(`Failed to execute stream tool ${((g=e.function)==null?void 0:g.name)||e.name}:`,h),s(new Error(h.message||"Tool execution failed")),i(h)}})}async execute(e){var n,s,o,i,l,d;console.log("开始调用工具,但是没有用流式的方式");const t=[];for(const f of e)try{const g=((n=f.function)==null?void 0:n.name)||f.name,h=((s=f.function)==null?void 0:s.arguments)||f.arguments||{};if(!g)throw new Error("Tool name is required");let p=h;if(typeof h=="string")try{p=JSON.parse(h)}catch(u){console.warn("Failed to parse tool arguments:",u),p={}}const w=this.findToolInfo(g);if(!w)throw new Error(`Tool not found: ${g}`);const m=await this.callMcpTool(w.serverUrl,w.originalName,p||{});t.push({tool_call_id:f.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:g,content:JSON.stringify(m),createdAt:new Date})}catch(g){if(g.message==="Stream aborted by user"||g.name==="AbortError"){console.log(`Tool ${((o=f.function)==null?void 0:o.name)||f.name} execution aborted by user`),t.push({tool_call_id:f.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:((i=f.function)==null?void 0:i.name)||f.name,content:JSON.stringify({result:"Tool execution aborted by user"})});continue}console.error(`Failed to execute tool ${((l=f.function)==null?void 0:l.name)||f.name}:`,g),t.push({tool_call_id:f.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:((d=f.function)==null?void 0:d.name)||f.name,content:JSON.stringify({error:g.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,i){try{const l=`${e}/sse/openai/tool/call`;console.log("MCP Stream Tool Call URL:",l);const d=new AbortController,f=await fetch(l,{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(!f.ok)throw new Error(`HTTP error! status: ${f.status}`);const g=f.body.getReader(),h=new TextDecoder;let p="",w=Date.now();const m=setInterval(()=>{if(Date.now()-w>12e4){clearInterval(m),g.cancel(),i(new Error("Stream read timeout: no data received for 2 minutes"));return}},1e4);try{for(;;){const{done:u,value:c}=await g.read();if(u)break;w=Date.now(),p+=h.decode(c,{stream:!0});const b=this.parseSSEEvents(p);p=b.remaining;for(const x of b.parsed)if(await this.handleSSEEvent(x,s,o,i)){clearInterval(m),g.cancel();return}}}finally{clearInterval(m),g.releaseLock()}}catch(l){if(l.name==="AbortError"||l.message==="Stream aborted by user"){console.log("MCP stream request aborted by user");return}console.error(`Failed to call MCP stream tool ${t}:`,l),l.message&&l.message.includes("Stream read timeout")?i(l):l.message&&l.message.includes("fetch")?i(new Error(`Network error during stream request: ${l.message}`)):i(new Error(l.message||"Stream error"))}}parseSSEEvents(e){const t=[],n=e.split(`
66
+ `);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 f=d.substring(5).trim();f==="[DONE]"?t.push({event:"end",data:"{}"}):s.data=f}o++}const i=e.lastIndexOf(`
67
67
 
68
- `),l=i>=0?e.substring(i+2):e;return{parsed:t,remaining:l}}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 i=o.choices[0];if(i.delta){const l=i.delta;l.content&&l.content?t(l.content):l.function_call&&l.function_call.arguments&&t(l.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 i=await ga.post(o,s);if(i.data.error)throw new Error(`MCP tool call failed: ${i.data.error.message}`);return i.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 ga.post(s,n);if(o.data.error)throw new Error(`MCP tools/list failed: ${o.data.error.message}`);const l=(((e=o.data.result)==null?void 0:e.tools)||[]).map(d=>{const u={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}),u});this.tools.push(...l)}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 El{constructor(e,t,n,s=null,o,i){J(this,"conversationId");J(this,"userId");J(this,"conversation");J(this,"mcpServers");J(this,"messages");J(this,"tools");J(this,"mcpToolsExecute");J(this,"modelConfig");J(this,"currentThread");J(this,"isAborted");J(this,"messageManager");J(this,"configUrl");J(this,"sessionId");this.conversationId=e,this.userId=t,this.conversation=null,this.mcpServers=[],this.messages=[],this.tools=[],this.mcpToolsExecute=null,this.modelConfig=s,this.messageManager=n,this.configUrl=o||"/api",this.sessionId=i||e,console.log("🔧 AiServer Constructor - configUrl:",this.configUrl),this.currentThread=null,this.isAborted=!1}async init(){var e;try{const t=await Ar.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 ne.getMcpConfigs(this.userId);console.log("mcpResponse",n);const o=(Array.isArray(n)?n:[]).filter(i=>i.enabled);this.mcpServers=o.map((i,l)=>({id:i.id||`mcp-server-${l}`,name:i.name,url:i.command,config:i.config||{}})),this.mcpToolsExecute=new kf(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,n;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 i=((await Ar.getMessages(this.conversationId,{limit:2})).data.messages||[]).sort((w,m)=>{const h=new Date(w.created_at||w.timestamp||0),c=new Date(m.created_at||m.timestamp||0),g=isNaN(h.getTime())?0:h.getTime(),y=isNaN(c.getTime())?0:c.getTime();return g-y});this.messages=[];let l="";try{const w=await fetch(`/api/system-context/active?userId=${this.userId}`);w.ok&&(l=(await w.json()).content||"")}catch(w){console.log("Failed to load system context:",w)}this.conversation&&this.conversation.global_prompt&&(l?l=this.conversation.global_prompt+`
68
+ `),l=i>=0?e.substring(i+2):e;return{parsed:t,remaining:l}}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 i=o.choices[0];if(i.delta){const l=i.delta;l.content&&l.content?t(l.content):l.function_call&&l.function_call.arguments&&t(l.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 i=await fa.post(o,s);if(i.data.error)throw new Error(`MCP tool call failed: ${i.data.error.message}`);return i.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 fa.post(s,n);if(o.data.error)throw new Error(`MCP tools/list failed: ${o.data.error.message}`);const l=(((e=o.data.result)==null?void 0:e.tools)||[]).map(d=>{const f={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}),f});this.tools.push(...l)}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 kl{constructor(e,t,n,s=null,o,i){W(this,"conversationId");W(this,"userId");W(this,"conversation");W(this,"mcpServers");W(this,"messages");W(this,"tools");W(this,"mcpToolsExecute");W(this,"modelConfig");W(this,"currentThread");W(this,"isAborted");W(this,"messageManager");W(this,"configUrl");W(this,"sessionId");this.conversationId=e,this.userId=t,this.conversation=null,this.mcpServers=[],this.messages=[],this.tools=[],this.mcpToolsExecute=null,this.modelConfig=s,this.messageManager=n,this.configUrl=o||"/api",this.sessionId=i||e,console.log("🔧 AiServer Constructor - configUrl:",this.configUrl),this.currentThread=null,this.isAborted=!1}async init(){var e;try{const t=await Ar.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 ee.getMcpConfigs(this.userId);console.log("mcpResponse",n);const o=(Array.isArray(n)?n:[]).filter(i=>i.enabled);this.mcpServers=o.map((i,l)=>({id:i.id||`mcp-server-${l}`,name:i.name,url:i.command,config:i.config||{}})),this.mcpToolsExecute=new jf(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,n;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 i=((await Ar.getMessages(this.conversationId,{limit:2})).data.messages||[]).sort((w,m)=>{const u=new Date(w.created_at||w.timestamp||0),c=new Date(m.created_at||m.timestamp||0),b=isNaN(u.getTime())?0:u.getTime(),x=isNaN(c.getTime())?0:c.getTime();return b-x});this.messages=[];let l="";try{const w=await fetch(`/api/system-context/active?userId=${this.userId}`);w.ok&&(l=(await w.json()).content||"")}catch(w){console.log("Failed to load system context:",w)}this.conversation&&this.conversation.global_prompt&&(l?l=this.conversation.global_prompt+`
69
69
 
70
- `+l:l=this.conversation.global_prompt,console.log("Added global prompt to system prompt:",this.conversation.global_prompt.substring(0,100)+"...")),l&&(this.messages.push({role:"system",content:l}),console.log("Final system prompt added to messages:",l.substring(0,100)+"..."));const d=i.slice(-2);this.messages.push(...d),console.log("Messages prepared for AI:",this.messages.map(w=>({role:w.role,content:(w.content||w.message||"").substring(0,50)+"...",created_at:w.created_at})));const u=`thread_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,p=new AbortController,f=new Qo(this.messages,this.conversationId,this.tools,this.modelConfig,(w,m)=>this.callback(w,m),this.mcpToolsExecute,this.messageManager,this.configUrl,p,this.sessionId),x={id:u,aiClient:f,abortController:p,isRunning:!0,startTime:Date.now()};this.currentThread=x,console.log(`AiServer: Created request thread ${u}`);try{if(this.isAborted||!x.isRunning){console.log(`AiServer: Thread ${u} was aborted before start`);return}await f.start(),console.log(`AiServer: Thread ${u} completed successfully`)}catch(w){if(this.isAborted||!x.isRunning){console.log(`AiServer: Thread ${u} was aborted during execution`);return}if(w.message==="Stream aborted by user"||w.name==="AbortError"){console.log(`AiServer: Thread ${u} aborted by user`);return}throw console.error(`AiServer: Thread ${u} failed:`,w),w}finally{((t=this.currentThread)==null?void 0:t.id)===u&&(this.currentThread.isRunning=!1,this.currentThread=null,console.log(`AiServer: Thread ${u} cleaned up`))}}catch(s){if(s.message==="Stream aborted by user"||s.name==="AbortError"||this.isAborted){console.log("sendMessage aborted by user");return}throw console.error("sendMessage failed:",s),console.error("Error details:",(n=s.response)==null?void 0:n.data),this.callback("error",s),s}}async sendMessageDirect(e){var t;try{console.log("AiServer sendMessageDirect called with:",e),this.messages=[{role:"user",content:e}],console.log("Messages prepared for AI:",this.messages);const n=`direct_thread_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=new AbortController,o=new Qo(this.messages,this.conversationId,[],this.modelConfig,(l,d)=>this.callback(l,d),null,this.messageManager,this.configUrl,s,this.sessionId),i={id:n,aiClient:o,abortController:s,isRunning:!0,startTime:Date.now()};this.currentThread=i,console.log(`AiServer: Created direct thread ${n}`);try{if(this.isAborted||!i.isRunning){console.log(`AiServer: Direct thread ${n} was aborted before start`);return}await o.start(),console.log(`AiServer: Direct thread ${n} completed successfully`)}catch(l){if(this.isAborted||!i.isRunning){console.log(`AiServer: Direct thread ${n} was aborted during execution`);return}throw console.error(`AiServer: Direct thread ${n} failed:`,l),l}finally{((t=this.currentThread)==null?void 0:t.id)===n&&(this.currentThread.isRunning=!1,this.currentThread=null,console.log(`AiServer: Direct thread ${n} cleaned up`))}}catch(n){throw console.error("sendMessageDirect failed:",n),this.callback("error",n),n}}async getMessages(e={}){try{const t=await Ar.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 this.messageManager.saveMessage({content:e,role:t,sessionId:this.conversationId,createdAt:new Date})}}catch(n){throw console.error("addMessage failed:",n),n}}abort(){console.log("AiServer: Abort called"),this.isAborted=!0;debugger;this.currentThread?(console.log(`AiServer: Aborting thread ${this.currentThread.id}`),this.currentThread.isRunning=!1,this.currentThread.abortController.signal.aborted||(this.currentThread.abortController.abort(),console.log(`AiServer: Thread ${this.currentThread.id} AbortController aborted`)),this.currentThread.aiClient&&(this.currentThread.aiClient.abort(),console.log(`AiServer: Thread ${this.currentThread.id} AI client aborted`)),this.currentThread=null,console.log("AiServer: Thread reference cleared")):console.log("AiServer: No active thread to abort")}isRequestAborted(){return this.isAborted}resetAbortState(){this.isAborted=!1,this.currentThread&&(this.currentThread.isRunning=!1,this.currentThread=null)}}class Il{constructor(e){J(this,"pendingSaves",new Set);J(this,"savedMessages",new Map);J(this,"databaseService");this.databaseService=e}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 this.databaseService.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(i=>setTimeout(i,10));const o=this.savedMessages.get(t);if(o)return o}this.pendingSaves.add(t);try{const o=await this.databaseService.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 this.databaseService.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 this.databaseService.createMessage(e)}}clearCache(){this.savedMessages.clear()}getCacheStats(){return{pendingCount:this.pendingSaves.size,cachedCount:this.savedMessages.size}}}class Nf extends bs{constructor(e,t){super(e,t)}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 Tl{constructor(e,t,n,s){J(this,"currentAiClient",null);J(this,"currentSessionId",null);J(this,"dbService");J(this,"messageManager");J(this,"userId");J(this,"configUrl");this.userId=e,this.dbService=new Nf(e,t),this.messageManager=n,this.configUrl=s||"/api",console.log("🔧 ChatService Constructor - configUrl:",this.configUrl)}async sendMessage(e,t,n=[],s={},o){var i,l,d,u,p;try{if(this.currentSessionId=e,!await this.dbService.getSession(e))throw new Error("Session not found");let x;if(o)x=o;else{const h=await this.getChatConfig();x={model_name:h.model,temperature:h.temperature,max_tokens:16e3,api_key:h.apiKey,base_url:h.baseUrl}}const w=new El(e,this.userId,this.messageManager,x,this.configUrl,e);let m=3;for(;m>0;)try{await w.init();break}catch(h){if(m--,m===0)throw new Error(`AI服务初始化失败: ${h instanceof Error?h.message:"未知错误"}`);await new Promise(c=>setTimeout(c,1e3))}w.callback=(h,c)=>{var g,y,b,_,v,C,S,I;try{switch(h){case"chunk":const E=typeof c=="string"?c:c.content||c.accumulated||"";(g=s.onChunk)==null||g.call(s,{type:"text",content:E,accumulated:E});break;case"summary_chunk":const P=typeof c=="string"?c:c.content||c.accumulated||"";(y=s.onChunk)==null||y.call(s,{type:"text",content:P,accumulated:P});break;case"tool_call":(b=s.onToolCall)==null||b.call(s,c);break;case"tool_result":(_=s.onToolResult)==null||_.call(s,c);break;case"tool_stream_chunk":(v=s.onToolStreamChunk)==null||v.call(s,c);break;case"complete":debugger;break;case"conversation_complete":(C=s.onComplete)==null||C.call(s,c);break;case"error":const R=c instanceof Error?c.message:typeof c=="string"?c:"AI响应出错";(S=s.onError)==null||S.call(s,new Error(R));break;default:console.warn("Unknown AI response type:",h)}}catch(E){console.error("Callback error:",E),(I=s.onError)==null||I.call(s,new Error(`处理AI响应时出错: ${E instanceof Error?E.message:"未知错误"}`))}},this.currentAiClient=w,await w.sendMessage(t)}catch(f){if(f.message==="Stream aborted by user"||f.name==="AbortError"){console.log("Message sending aborted by user");return}if((i=f.message)!=null&&i.includes("ERR_INCOMPLETE_CHUNKED_ENCODING")||(l=f.message)!=null&&l.includes("net::ERR_")||(d=f.message)!=null&&d.includes("Failed to fetch")){console.log("Network connection error during streaming:",f.message),(u=s.onError)==null||u.call(s,new Error("网络连接中断,请检查网络状态后重试"));return}throw console.error("Failed to send message:",f),(p=s.onError)==null||p.call(s,f instanceof Error?f:new Error(String(f))),f}}async abortCurrentConversation(){if(console.log("🛑 ChatService: 中止当前对话"),this.currentSessionId)try{console.log(`🛑 ChatService: 调用服务端停止接口,会话ID: ${this.currentSessionId}`);const t=await(await fetch(`${this.configUrl}/chat/stop`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.currentSessionId})})).json();t.success?console.log(`✅ ChatService: 服务端停止成功 - ${t.message}`):console.warn(`⚠️ ChatService: 服务端停止失败 - ${t.message||"未知错误"}`);debugger;this.currentAiClient&&(console.log("🔄 ChatService: 尝试客户端停止作为备用方案"),this.currentAiClient.abort()),this.currentAiClient=null,this.currentSessionId=null}catch(e){console.error("❌ ChatService: 调用服务端停止接口失败:",e),this.currentAiClient&&(console.log("🔄 ChatService: 尝试客户端停止作为备用方案"),this.currentAiClient.abort()),this.currentAiClient=null,this.currentSessionId=null}else console.log("⚠️ ChatService: 没有活动的会话可以中止"),this.currentAiClient&&(console.log("🔄 ChatService: 尝试停止当前AI客户端"),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"}}}function Mf({set:r,get:e,client:t,getUserIdParam:n}){return async function(o,i=[]){var y;const{currentSessionId:l,selectedModelId:d,aiModelConfigs:u,chatConfig:p,isLoading:f,isStreaming:x,activeSystemContext:w,selectedAgentId:m,agents:h}=e();if(!l)throw new Error("No active session");if(f||x){console.log("Message sending already in progress, ignoring duplicate request");return}let c=null,g=null;if(m){if(g=h.find(b=>b.id===m),!g||g.enabled===!1)throw new Error("选择的智能体不可用")}else if(d){if(c=u.find(b=>b.id===d),!c||!c.enabled)throw new Error("选择的模型不可用")}else throw new Error("请先选择一个模型或智能体");try{const b=new Date,_={id:`temp_user_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:l,role:"user",content:o,status:"completed",createdAt:b,metadata:{...i.length>0?{attachments:i}:{},model:g?`[Agent] ${g.name}`:c.model_name,...c?{modelConfig:{id:c.id,name:c.name,base_url:c.base_url,model_name:c.model_name}}:{}}};r(R=>{R.messages.push(_),R.isLoading=!0,R.isStreaming=!0});const v=new Date(b.getTime()+1),C={id:`temp_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:l,role:"assistant",content:"",status:"streaming",createdAt:v,metadata:{model:g?`[Agent] ${g.name}`:c.model_name,...c?{modelConfig:{id:c.id,name:c.name,base_url:c.base_url,model_name:c.model_name}}:{},toolCalls:[],contentSegments:[{content:"",type:"text"}],currentSegmentIndex:0}};r(R=>{R.messages.push(C),R.streamingMessageId=C.id});const S=g?{session_id:l,message:o,agent_id:g.id,system_context:(w==null?void 0:w.content)||p.systemPrompt||"",attachments:i||[]}:{session_id:l,message:o,model_config:{model:c.model_name,base_url:c.base_url,api_key:c.api_key||"",temperature:p.temperature,max_tokens:p.maxTokens},system_context:(w==null?void 0:w.content)||p.systemPrompt||"",attachments:i||[]};console.log("🚀 开始调用后端流式聊天API:",S);const I=g?await t.streamAgentChat(l,o,g.id,n()):await t.streamChat(l,o,c,n());if(!I)throw new Error("No response received");const E=I.getReader(),P=new TextDecoder;try{for(;;){const{done:R,value:j}=await E.read();if(R){console.log("✅ 流式响应完成");break}const D=P.decode(j,{stream:!0}).split(`
71
- `);for(const X of D)if(X.trim()!==""&&X.startsWith("data: ")){const G=X.slice(6);if(G==="[DONE]"){console.log("✅ 收到完成信号");break}try{const N=JSON.parse(G);if(typeof N=="string"&&N==="[DONE]"){console.log("✅ 收到完成信号");break}if(N.type==="chunk")N.content&&r(F=>{const z=F.messages.find($=>$.id===C.id);if(z&&z.metadata){const $=typeof N.content=="string"?N.content:typeof N=="string"?N:N.content||"",O=z.metadata.currentSegmentIndex||0,U=z.metadata.contentSegments||[];U[O]&&U[O].type==="text"?U[O].content+=$:(U.push({content:$,type:"text"}),z.metadata.currentSegmentIndex=U.length-1),z.content=U.filter(V=>V.type==="text").map(V=>V.content).join("")}});else if(N.type==="thinking")N.content&&r(F=>{const z=F.messages.find($=>$.id===C.id);if(z&&z.metadata){const $=typeof N.content=="string"?N.content:typeof N=="string"?N:N.content||"",O=z.metadata.contentSegments||[],U=O.length-1;U>=0&&O[U].type==="thinking"?(O[U].content+=$,z.metadata.currentSegmentIndex=U):(O.push({content:$,type:"thinking"}),z.metadata.currentSegmentIndex=O.length-1),z.content=O.filter(V=>V.type==="text").map(V=>V.content).join("")}});else if(N.type==="context_summarized"||N.type==="context_summarized_start"||N.type==="context_summarized_stream"||N.type==="context_summarized_end"){const F=N.data||{},z="【上下文摘要】\\n";r($=>{const O=$.messages.find(k=>k.id===C.id);if(!O||!O.metadata)return;const U=O.metadata.contentSegments||[],V=()=>{const k=U.length-1;return k>=0&&U[k].type==="thinking"&&String(U[k].content||"").startsWith(z)?k:(U.push({content:z,type:"thinking"}),O.metadata.contentSegments=U,O.metadata.currentSegmentIndex=U.length-1,U.length-1)};if(N.type==="context_summarized_start")V();else if(N.type==="context_summarized_stream"){const k=V(),q=F.content||F.chunk||F.data||"";U[k].content+=String(q),O.metadata.currentSegmentIndex=k}else if(N.type==="context_summarized_end"||N.type==="context_summarized"){const k=V(),q=typeof F.full_summary=="string"&&F.full_summary.length>0?F.full_summary:F.summary_preview||"";U[k].content=z+String(q),O.metadata.contentSegments=U,O.metadata.currentSegmentIndex=k}O.updatedAt=new Date})}else if(N.type==="content")r(F=>{const z=F.messages.find($=>$.id===C.id);if(z&&z.metadata){const $=typeof N.content=="string"?N.content:typeof N=="string"?N:N.content||"",O=z.metadata.currentSegmentIndex||0,U=z.metadata.contentSegments||[];U[O]&&U[O].type==="text"?U[O].content+=$:(U.push({content:$,type:"text"}),z.metadata.currentSegmentIndex=U.length-1),z.content=U.filter(V=>V.type==="text").map(V=>V.content).join("")}});else if(N.type==="tools_start"){console.log("🔧 收到工具调用:",N.data),console.log("🔧 工具调用数据类型:",typeof N.data,"是否为数组:",Array.isArray(N.data));const F=O=>{var V,k,q;console.log("🔧 [DEBUG] 原始工具调用数据:",O),console.log("🔧 [DEBUG] tc.function:",O.function),console.log("🔧 [DEBUG] tc.function?.name:",(V=O.function)==null?void 0:V.name),console.log("🔧 [DEBUG] tc.name:",O.name);const U={id:O.id||O.tool_call_id||`tool_${Date.now()}_${Math.random()}`,messageId:C.id,name:((k=O.function)==null?void 0:k.name)||O.name||"unknown_tool",arguments:((q=O.function)==null?void 0:q.arguments)||O.arguments||"{}",result:O.result||"",error:O.error||void 0,createdAt:O.createdAt||O.created_at||new Date};return console.log("🔧 [DEBUG] 转换后的工具调用:",U),U};console.log("🔧 [DEBUG] tools_start 原始数据:",N.data);const z=N.data.tool_calls||N.data,$=Array.isArray(z)?z:[z];console.log("🔧 [DEBUG] 提取的工具调用数组:",$),r(O=>{const U=O.messages.findIndex(V=>V.id===C.id);if(console.log("🔧 查找消息索引:",U,"消息ID:",C.id),U!==-1){const V=O.messages[U];console.log("🔧 找到消息,当前metadata:",V.metadata),V.metadata||(V.metadata={}),V.metadata.toolCalls||(V.metadata.toolCalls=[]);const k=V.metadata.contentSegments||[];console.log("🔧 处理工具调用数组,长度:",$.length),$.forEach(q=>{const A=F(q);console.log("🔧 添加转换后的工具调用:",A),V.metadata.toolCalls.push(A),k.push({content:"",type:"tool_call",toolCallId:A.id})}),k.push({content:"",type:"text"}),V.metadata.currentSegmentIndex=k.length-1,console.log("🔧 更新后的toolCalls:",V.metadata.toolCalls)}else console.log("🔧 ❌ 未找到对应的消息")})}else if(N.type==="tools_end"){console.log("🔧 收到工具结果:",N.data),console.log("🔧 工具结果数据类型:",typeof N.data);const F=Array.isArray(N.data)?N.data:[N.data];r(z=>{const $=z.messages.findIndex(O=>O.id===C.id);if($!==-1){const O=z.messages[$];O.metadata&&O.metadata.toolCalls&&(F.forEach(U=>{var q,A,L,B;const V=U.tool_call_id||U.id||U.toolCallId;if(!V){console.warn("⚠️ 工具结果缺少工具调用ID:",U);return}console.log("🔍 查找工具调用:",V,"在消息中:",(A=(q=O.metadata)==null?void 0:q.toolCalls)==null?void 0:A.map(H=>H.id));const k=O.metadata.toolCalls.find(H=>H.id===V);if(k){console.log("✅ 找到工具调用,更新最终结果:",k.id);const H=U.result||U.content||U.output||"";U.success===!1||U.is_error===!0?(k.error=U.error||H||"工具执行失败",console.log("❌ 工具执行失败:",{id:k.id,name:U.name||k.name,error:k.error,success:U.success,is_error:U.is_error})):((!k.result||k.result.trim()==="")&&(k.result=H),k.error&&delete k.error,console.log("✅ 工具执行成功,最终结果已更新:",{id:k.id,name:U.name||k.name,resultLength:k.result.length,success:U.success,is_stream:U.is_stream}))}else console.log("❌ 未找到对应的工具调用:",V),console.log("📋 当前可用的工具调用ID:",(B=(L=O.metadata)==null?void 0:L.toolCalls)==null?void 0:B.map(H=>H.id))}),O.updatedAt=new Date)}})}else if(N.type==="tools_stream"){console.log("🔧 收到工具流式数据:",N.data);const F=N.data;r(z=>{const $=z.messages.findIndex(O=>O.id===C.id);if($!==-1){const O=z.messages[$];if(O.metadata&&O.metadata.toolCalls){const U=F.toolCallId||F.tool_call_id||F.id;if(!U){console.warn("⚠️ 工具流式数据缺少工具调用ID:",F);return}console.log("🔍 查找工具调用进行流式更新:",U);const V=O.metadata.toolCalls.find(k=>k.id===U);if(V){const k=F.content||F.chunk||F.data||"";F.is_error||!F.success?(V.error=k||"工具执行出错",console.log("❌ 工具流式执行出错:",{id:V.id,error:V.error,success:F.success,is_error:F.is_error})):(V.result=(V.result||"")+k,console.log("🔧 工具流式数据已更新:",{id:V.id,name:F.name,chunkLength:k.length,totalLength:V.result.length,success:F.success,is_stream:F.is_stream})),O.updatedAt=new Date}}}})}else{if(N.type==="error")throw new Error(N.message||((y=N.data)==null?void 0:y.message)||"Stream error");if(N.type==="cancelled"){console.log("⚠️ 流式会话已被取消");break}else if(N.type==="done"){console.log("✅ 收到完成信号");break}}}catch(N){console.warn("解析流式数据失败:",N,"data:",G)}}}}finally{E.releaseLock(),r(R=>{R.isLoading=!1,R.isStreaming=!1,R.streamingMessageId=null})}console.log("✅ 消息发送完成")}catch(b){throw console.error("❌ 发送消息失败:",b),r(_=>{const v=_.messages.findIndex(C=>{var S;return(S=C.id)==null?void 0:S.startsWith("temp_")});v!==-1&&_.messages.splice(v,1),_.isLoading=!1,_.isStreaming=!1,_.streamingMessageId=null,_.error=b instanceof Error?b.message:"Failed to send message"}),b}}}function Ef({set:r,get:e,client:t,getUserIdParam:n}){const s=o=>({id:o.id,name:o.name,url:o.url,iconUrl:o.icon_url??void 0,createdAt:new Date(o.created_at),updatedAt:new Date(o.updated_at??o.created_at)});return{loadApplications:async()=>{try{console.log("[Store] loadApplications: start");const o=n(),l=(await t.getApplications(o)||[]).map(s);r(d=>{d.applications=l}),console.log("[Store] loadApplications: loaded",l.length,"items")}catch(o){console.error("Failed to load applications:",o),r(i=>{i.applications=[]})}},createApplication:async(o,i,l)=>{try{const d=await t.createApplication({name:o,url:i,icon_url:l??null,user_id:n()}),u=s(d);r(p=>{p.applications=[u,...p.applications]})}catch(d){console.error("Failed to create application:",d),r(u=>{u.error=d instanceof Error?d.message:"Failed to create application"})}},updateApplication:async(o,i)=>{try{const l={};i.name!==void 0&&(l.name=i.name),i.url!==void 0&&(l.url=i.url),i.iconUrl!==void 0&&(l.icon_url=i.iconUrl??null);const d=await t.updateApplication(o,l),u=s(d);r(p=>{p.applications=p.applications.map(f=>f.id===o?u:f)})}catch(l){console.error("Failed to update application:",l),r(d=>{d.error=l instanceof Error?l.message:"Failed to update application"})}},deleteApplication:async o=>{try{await t.deleteApplication(o),r(i=>{i.applications=i.applications.filter(l=>l.id!==o),i.mcpConfigs=i.mcpConfigs.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==o):[]})),i.systemContexts=i.systemContexts.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==o):[]})),i.agents=i.agents.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==o):[]}))})}catch(i){console.error("Failed to delete application:",i),r(l=>{l.error=i instanceof Error?i.message:"Failed to delete application"})}},setSelectedApplication:o=>{console.log("[Store] setSelectedApplication:",o);const i=e().selectedApplicationId;console.log("[Store] setSelectedApplication - before:",{oldId:i,newId:o}),r(d=>({...d,selectedApplicationId:o}));const l=e().selectedApplicationId;console.log("[Store] setSelectedApplication - after:",{oldId:i,newId:l})},setMcpAppAssociation:(o,i)=>{r(l=>{l.mcpConfigs=l.mcpConfigs.map(d=>d.id===o?{...d,app_ids:Array.isArray(i)?i:[]}:d)})},setSystemContextAppAssociation:(o,i)=>{r(l=>{l.systemContexts=l.systemContexts.map(d=>d.id===o?{...d,app_ids:Array.isArray(i)?i:[]}:d)});try{(async()=>await t.updateSystemContext(o,{name:void 0,content:void 0,app_ids:Array.isArray(i)?i:[]}))()}catch{}},setAgentAppAssociation:(o,i)=>{r(l=>{l.agents=l.agents.map(d=>d.id===o?{...d,app_ids:Array.isArray(i)?i:[]}:d)});try{(async()=>await t.updateAgent(o,{app_ids:Array.isArray(i)?i:[]}))()}catch{}}}}function If({set:r,get:e,client:t,getUserIdParam:n}){return{loadAiModelConfigs:async()=>{try{const s=n(),i=(await t.getAiModelConfigs(s)).map(l=>({id:l.id,name:l.name,base_url:l.base_url,api_key:l.api_key,model_name:l.model,enabled:l.enabled,createdAt:new Date(l.created_at),updatedAt:new Date(l.created_at)}));r(l=>{l.aiModelConfigs=i})}catch(s){console.error("Failed to load AI model configs:",s),r(o=>{o.error=s instanceof Error?s.message:"Failed to load AI model configs"})}},updateAiModelConfig:async s=>{try{const o=n(),l=e().aiModelConfigs.find(u=>u.id===s.id)?"update":"create",d={id:s.id||crypto.randomUUID(),name:s.name,provider:"openai",model:s.model_name,api_key:s.api_key,base_url:s.base_url,enabled:s.enabled,user_id:o};l==="update"?await t.updateAiModelConfig(s.id,d):await t.createAiModelConfig(d),await e().loadAiModelConfigs()}catch(o){console.error("Failed to update AI model config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to update AI model config"})}},deleteAiModelConfig:async s=>{try{await t.deleteAiModelConfig(s),r(o=>{o.aiModelConfigs=o.aiModelConfigs.filter(i=>i.id!==s)})}catch(o){console.error("Failed to delete AI model config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to delete AI model config"})}},setSelectedModel:s=>{r(o=>{o.selectedModelId=s,s&&(o.selectedAgentId=null)})}}}function Tf({set:r,get:e,client:t,getUserIdParam:n}){return{loadMcpConfigs:async()=>{var s;try{const o=n(),i=await t.getMcpConfigs(o);console.log("🔍 [后端返回] loadMcpConfigs 返回的数据:",i),console.log("🔍 [后端返回] 第一个配置的 app_ids:",(s=i==null?void 0:i[0])==null?void 0:s.app_ids),r(l=>{l.mcpConfigs=i})}catch(o){console.error("Failed to load MCP configs:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to load MCP configs"})}},updateMcpConfig:async s=>{try{const o=n();console.log("🔍 updateMcpConfig 调用:",{userId:o,configId:s.id,configName:s.name});let i=null;if(s.id){const u={id:s.id,name:s.name,command:s.command,type:s.type,args:s.args??void 0,env:s.env??void 0,cwd:s.cwd??void 0,enabled:s.enabled,userId:o,app_ids:Array.isArray(s.app_ids)?s.app_ids:void 0};console.log("🔍 updateMcpConfig 更新数据:",u),i=await t.updateMcpConfig(s.id,u)}else{const u={name:s.name,command:s.command,type:s.type,args:s.args??void 0,env:s.env??void 0,cwd:s.cwd??void 0,enabled:s.enabled,user_id:o,app_ids:Array.isArray(s.app_ids)?s.app_ids:void 0};i=await t.createMcpConfig(u)}const l=(i==null?void 0:i.id)??s.id,d=Array.isArray(i==null?void 0:i.app_ids)?i.app_ids:Array.isArray(s.app_ids)?s.app_ids:[];return r(u=>{u.mcpConfigs=u.mcpConfigs.map(p=>p.id===l?{...p,app_ids:d}:p)}),await e().loadMcpConfigs(),i}catch(o){return console.error("Failed to update MCP config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to update MCP config"}),null}},deleteMcpConfig:async s=>{try{await t.deleteMcpConfig(s),r(o=>{o.mcpConfigs=o.mcpConfigs.filter(i=>i.id!==s)})}catch(o){console.error("Failed to delete MCP config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to delete MCP config"})}}}}function Pf({set:r}){return{updateChatConfig:async e=>{r(t=>{t.chatConfig={...t.chatConfig,...e}})}}}function zr(r,e){const t=r||ne,n=e==null?void 0:e.userId,s=e==null?void 0:e.projectId,o=e==null?void 0:e.configUrl,i=n||"default-user",l=s||"default-project",d=o||"/api",u=()=>i,p=()=>({userId:i,projectId:l}),f=new bs(i,l,t),x=new Il(f),w=new Tl(i,l,x,d);return console.log("chatService:",w),_c()($c(Wc((m,h)=>({sessions:[],currentSessionId:null,currentSession:null,messages:[],isLoading:!1,isStreaming:!1,streamingMessageId:null,hasMoreMessages:!0,sidebarOpen:!0,theme:"light",chatConfig:{model:"gpt-4",temperature:.7,maxTokens:2048,systemPrompt:"",enableMcp:!0},mcpConfigs:[],aiModelConfigs:[],selectedModelId:null,agents:[],selectedAgentId:null,systemContexts:[],activeSystemContext:null,applications:[],selectedApplicationId:null,error:null,loadSessions:async()=>{try{console.log("🔍 loadSessions 被调用"),m(_=>{_.isLoading=!0,_.error=null}),console.log("🔍 loadSessions isLoading 设置为 true");const{userId:c,projectId:g}=p();console.log("🔍 loadSessions 调用 client.getSessions",{userId:c,projectId:g,customUserId:n,customProjectId:s});const y=await t.getSessions(c,g);console.log("🔍 loadSessions 返回结果:",y),m(_=>{_.sessions=y,_.isLoading=!1});const b=h();if(y.length>0&&!b.currentSessionId){const _=localStorage.getItem(`lastSessionId_${c}_${g}`);let v=null;_&&(v=y.find(C=>C.id===_)),v||(v=[...y].sort((C,S)=>new Date(S.createdAt).getTime()-new Date(C.createdAt).getTime())[0]),v&&(console.log("🔍 自动选择会话:",v.id),setTimeout(()=>{h().selectSession(v.id)},0))}console.log("🔍 loadSessions 完成")}catch(c){console.error("🔍 loadSessions 错误:",c),m(g=>{g.error=c instanceof Error?c.message:"Failed to load sessions",g.isLoading=!1})}},createSession:async(c="New Chat")=>{try{const{userId:g,projectId:y}=p();console.log("🔍 createSession 使用参数:",{userId:g,projectId:y,title:c}),console.log("🔍 createSession 自定义参数:",{customUserId:n,customProjectId:s}),console.log("🔍 createSession 最终使用的参数:",{userId:g,projectId:y,isCustomUserId:!!n,isCustomProjectId:!!s});const b={id:crypto.randomUUID(),title:c,user_id:g,project_id:y},_=await t.createSession(b);console.log("✅ createSession API调用成功:",_);const v={id:_.id,title:_.title,createdAt:new Date(_.created_at),updatedAt:new Date(_.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null};return m(C=>{C.sessions.unshift(v),C.currentSessionId=v.id,C.currentSession=v,C.messages=[],C.error=null}),localStorage.setItem(`lastSessionId_${g}_${y}`,v.id),console.log("🔍 保存新创建的会话ID到 localStorage:",v.id),v.id}catch(g){throw console.error("❌ createSession 失败:",g),m(y=>{y.error=g instanceof Error?g.message:"Failed to create session"}),g}},selectSession:async c=>{try{m(b=>{b.isLoading=!0,b.error=null});const g=await f.getSession(c),y=await f.getSessionMessages(c,{limit:10,offset:0});if(m(b=>{b.currentSessionId=c,b.currentSession=g,b.messages=y,b.isLoading=!1,b.hasMoreMessages=y.length===10,g||(b.error="Session not found")}),g){const{userId:b,projectId:_}=p();localStorage.setItem(`lastSessionId_${b}_${_}`,c),console.log("🔍 保存会话ID到 localStorage:",c)}}catch(g){console.error("Failed to select session:",g),m(y=>{y.error=g instanceof Error?g.message:"Failed to select session",y.isLoading=!1})}},updateSession:async(c,g)=>{try{const y=await f.updateSession(c,g);m(b=>{const _=b.sessions.findIndex(v=>v.id===c);_!==-1&&y&&(b.sessions[_]=y),b.currentSessionId===c&&(b.currentSession=y)})}catch(y){console.error("Failed to update session:",y),m(b=>{b.error=y instanceof Error?y.message:"Failed to update session"})}},deleteSession:async c=>{try{await f.deleteSession(c),m(g=>{g.sessions=g.sessions.filter(y=>y.id!==c),g.currentSessionId===c&&(g.currentSessionId=null,g.currentSession=null,g.messages=[])})}catch(g){console.error("Failed to delete session:",g),m(y=>{y.error=g instanceof Error?g.message:"Failed to delete session"})}},loadMessages:async c=>{try{m(y=>{y.isLoading=!0,y.error=null});const g=await f.getSessionMessages(c,{limit:10,offset:0});m(y=>{y.messages=g,y.isLoading=!1,y.hasMoreMessages=g.length===10})}catch(g){console.error("Failed to load messages:",g),m(y=>{y.error=g instanceof Error?g.message:"Failed to load messages",y.isLoading=!1})}},loadMoreMessages:async c=>{try{const y=h().messages.length,b=await f.getSessionMessages(c,{limit:10,offset:y});m(_=>{const v=new Set(_.messages.map(S=>S.id)),C=b.filter(S=>!v.has(S.id));_.messages=[...C,..._.messages],_.hasMoreMessages=b.length===10})}catch(g){console.error("Failed to load more messages:",g),m(y=>{y.error=g instanceof Error?g.message:"Failed to load more messages"})}},sendMessage:Mf({set:m,get:h,client:t,getUserIdParam:u}),updateMessage:async(c,g)=>{try{const y=await f.updateMessage(c,g);m(b=>{const _=b.messages.findIndex(v=>v.id===c);_!==-1&&y&&(b.messages[_]=y)})}catch(y){console.error("Failed to update message:",y),m(b=>{b.error=y instanceof Error?y.message:"Failed to update message"})}},deleteMessage:async c=>{try{await f.deleteMessage(c),m(g=>{g.messages=g.messages.filter(y=>y.id!==c)})}catch(g){console.error("Failed to delete message:",g),m(y=>{y.error=g instanceof Error?g.message:"Failed to delete message"})}},startStreaming:c=>{m(g=>{g.isStreaming=!0,g.streamingMessageId=c})},updateStreamingMessage:c=>{m(g=>{if(g.streamingMessageId){const y=g.messages.findIndex(b=>b.id===g.streamingMessageId);y!==-1&&(g.messages[y].content=c)}})},stopStreaming:()=>{m(c=>{c.isStreaming=!1,c.streamingMessageId=null})},abortCurrentConversation:async()=>{const{currentSessionId:c}=h();if(c)try{await t.stopChat(c),console.log("✅ 成功停止当前对话")}catch(g){console.error("❌ 停止对话失败:",g)}m(g=>{g.isStreaming=!1,g.streamingMessageId=null,g.isLoading=!1})},toggleSidebar:()=>{m(c=>{c.sidebarOpen=!c.sidebarOpen})},setTheme:c=>{m(g=>{g.theme=c})},...Pf({set:m}),...Tf({set:m,get:h,client:t,getUserIdParam:u}),...Ef({set:m,get:h,client:t,getUserIdParam:u}),...If({set:m,get:h,client:t,getUserIdParam:u}),loadAgents:async()=>{var c;try{const g=await t.getAgents(u());console.log("🔍 [后端返回] loadAgents 返回的数据:",g),console.log("🔍 [后端返回] 第一个智能体的 app_ids:",(c=g==null?void 0:g[0])==null?void 0:c.app_ids),m(y=>{y.agents=g||[]})}catch(g){console.error("Failed to load agents:",g),m(y=>{y.agents=[],y.error=g instanceof Error?g.message:"Failed to load agents"})}},setSelectedAgent:c=>{m(g=>{g.selectedAgentId=c,c&&(g.selectedModelId=null)})},loadSystemContexts:async()=>{try{const c=await t.getSystemContexts(u()),g=await t.getActiveSystemContext(u());m(y=>{const b=(c||[]).map(_=>({..._,isActive:!1}));if(g&&g.context){const _=g.context,v=b.findIndex(C=>C.id===_.id);v!==-1?(b[v].isActive=!0,y.activeSystemContext={...b[v]}):y.activeSystemContext=null}else y.activeSystemContext=null;y.systemContexts=b})}catch(c){console.error("Failed to load system contexts:",c),m(g=>{g.systemContexts=[],g.activeSystemContext=null})}},createSystemContext:async(c,g,y)=>{try{const b=await t.createSystemContext({name:c,content:g,user_id:u(),app_ids:Array.isArray(y)?y:void 0});return m(_=>{_.systemContexts.push(b)}),b}catch(b){return console.error("Failed to create system context:",b),m(_=>{_.error=b instanceof Error?b.message:"Failed to create system context"}),null}},updateSystemContext:async(c,g,y,b)=>{try{const _=await t.updateSystemContext(c,{name:g,content:y,app_ids:Array.isArray(b)?b:void 0});return m(v=>{const C=v.systemContexts.findIndex(S=>S.id===c);C!==-1&&(v.systemContexts[C]=_)}),_}catch(_){return console.error("Failed to update system context:",_),m(v=>{v.error=_ instanceof Error?_.message:"Failed to update system context"}),null}},deleteSystemContext:async c=>{try{await t.deleteSystemContext(c),m(g=>{var y;g.systemContexts=g.systemContexts.filter(b=>b.id!==c),((y=g.activeSystemContext)==null?void 0:y.id)===c&&(g.activeSystemContext=null)})}catch(g){console.error("Failed to delete system context:",g),m(y=>{y.error=g instanceof Error?g.message:"Failed to delete system context"})}},activateSystemContext:async c=>{try{await t.activateSystemContext(c,u()),m(g=>{const y=g.systemContexts.find(b=>b.id===c);y&&(g.systemContexts.forEach(b=>{b.isActive=b.id===c}),g.activeSystemContext={...y,isActive:!0})})}catch(g){console.error("Failed to activate system context:",g),m(y=>{y.error=g instanceof Error?g.message:"Failed to activate system context"})}},setError:c=>{m(g=>{g.error=c})},clearError:()=>{m(c=>{c.error=null})}}),{name:"chat-store-with-backend",partialize:m=>({theme:m.theme,sidebarOpen:m.sidebarOpen,chatConfig:m.chatConfig,selectedModelId:m.selectedModelId})})))}const ut=zr();function Of(r,e,t){return zr(t,{userId:r,projectId:e})}const pn=T.createContext(null),Rf=({children:r,userId:e,projectId:t,customApiClient:n})=>{const s=T.useMemo(()=>e||t||n?(console.log("🏪 创建自定义store:",{userId:e,projectId:t,hasCustomApiClient:!!n}),Of(e||"default-user",t||"default-project",n)):(console.log("🏪 使用默认store"),ut),[e,t,n]);return a.jsx(pn.Provider,{value:{store:s,userId:e,projectId:t,apiClient:n},children:r})},Pl=()=>{const r=T.useContext(pn);if(!r)throw new Error("useChatStoreContext must be used within a ChatStoreProvider");return r.store},ft=()=>Pl()(),$f=()=>{const r=T.useContext(pn);return r?{userId:r.userId,projectId:r.projectId}:{userId:void 0,projectId:void 0}},Lf=()=>{const r=T.useContext(pn);return r==null?void 0:r.apiClient},ot=({content:r,isStreaming:e=!1,className:t="",onApplyCode:n})=>{const[s,o]=T.useState(new Set),i=T.useCallback(async f=>{try{await navigator.clipboard.writeText(f)}catch(x){console.error("Failed to copy code:",x)}},[]),l=T.useCallback(f=>{o(x=>{const w=new Set(x);return w.has(f)?w.delete(f):w.add(f),w})},[]),d=T.useMemo(()=>f=>{if(!f)return"";let x=f;const w=/\$\$([\s\S]*?)\$\$/g;x=x.replace(w,(_,v)=>`<div class="math-block">${v.trim()}</div>`);const m=/\$([^$]+)\$/g;x=x.replace(m,(_,v)=>`<span class="math-inline">${v}</span>`);const h=/\|(.+)\|\n\|[-\s|:]+\|\n((?:\|.+\|\n?)*)/g;if(x=x.replace(h,(_,v,C)=>{const S=v.split("|").map(P=>P.trim()).filter(P=>P),I=C.trim().split(`
72
- `).map(P=>P.split("|").map(R=>R.trim()).filter(R=>R));let E="<table>";return S.length>0&&(E+="<thead><tr>",S.forEach(P=>{E+=`<th>${P}</th>`}),E+="</tr></thead>"),I.length>0&&(E+="<tbody>",I.forEach(P=>{P.length>0&&(E+="<tr>",P.forEach(R=>{E+=`<td>${R}</td>`}),E+="</tr>")}),E+="</tbody>"),E+="</table>",e?`<div class="streaming-table-wrapper">
70
+ `+l:l=this.conversation.global_prompt,console.log("Added global prompt to system prompt:",this.conversation.global_prompt.substring(0,100)+"...")),l&&(this.messages.push({role:"system",content:l}),console.log("Final system prompt added to messages:",l.substring(0,100)+"..."));const d=i.slice(-2);this.messages.push(...d),console.log("Messages prepared for AI:",this.messages.map(w=>({role:w.role,content:(w.content||w.message||"").substring(0,50)+"...",created_at:w.created_at})));const f=`thread_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=new AbortController,h=new Xo(this.messages,this.conversationId,this.tools,this.modelConfig,(w,m)=>this.callback(w,m),this.mcpToolsExecute,this.messageManager,this.configUrl,g,this.sessionId),p={id:f,aiClient:h,abortController:g,isRunning:!0,startTime:Date.now()};this.currentThread=p,console.log(`AiServer: Created request thread ${f}`);try{if(this.isAborted||!p.isRunning){console.log(`AiServer: Thread ${f} was aborted before start`);return}await h.start(),console.log(`AiServer: Thread ${f} completed successfully`)}catch(w){if(this.isAborted||!p.isRunning){console.log(`AiServer: Thread ${f} was aborted during execution`);return}if(w.message==="Stream aborted by user"||w.name==="AbortError"){console.log(`AiServer: Thread ${f} aborted by user`);return}throw console.error(`AiServer: Thread ${f} failed:`,w),w}finally{((t=this.currentThread)==null?void 0:t.id)===f&&(this.currentThread.isRunning=!1,this.currentThread=null,console.log(`AiServer: Thread ${f} cleaned up`))}}catch(s){if(s.message==="Stream aborted by user"||s.name==="AbortError"||this.isAborted){console.log("sendMessage aborted by user");return}throw console.error("sendMessage failed:",s),console.error("Error details:",(n=s.response)==null?void 0:n.data),this.callback("error",s),s}}async sendMessageDirect(e){var t;try{console.log("AiServer sendMessageDirect called with:",e),this.messages=[{role:"user",content:e}],console.log("Messages prepared for AI:",this.messages);const n=`direct_thread_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=new AbortController,o=new Xo(this.messages,this.conversationId,[],this.modelConfig,(l,d)=>this.callback(l,d),null,this.messageManager,this.configUrl,s,this.sessionId),i={id:n,aiClient:o,abortController:s,isRunning:!0,startTime:Date.now()};this.currentThread=i,console.log(`AiServer: Created direct thread ${n}`);try{if(this.isAborted||!i.isRunning){console.log(`AiServer: Direct thread ${n} was aborted before start`);return}await o.start(),console.log(`AiServer: Direct thread ${n} completed successfully`)}catch(l){if(this.isAborted||!i.isRunning){console.log(`AiServer: Direct thread ${n} was aborted during execution`);return}throw console.error(`AiServer: Direct thread ${n} failed:`,l),l}finally{((t=this.currentThread)==null?void 0:t.id)===n&&(this.currentThread.isRunning=!1,this.currentThread=null,console.log(`AiServer: Direct thread ${n} cleaned up`))}}catch(n){throw console.error("sendMessageDirect failed:",n),this.callback("error",n),n}}async getMessages(e={}){try{const t=await Ar.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 this.messageManager.saveMessage({content:e,role:t,sessionId:this.conversationId,createdAt:new Date})}}catch(n){throw console.error("addMessage failed:",n),n}}abort(){console.log("AiServer: Abort called"),this.isAborted=!0;debugger;this.currentThread?(console.log(`AiServer: Aborting thread ${this.currentThread.id}`),this.currentThread.isRunning=!1,this.currentThread.abortController.signal.aborted||(this.currentThread.abortController.abort(),console.log(`AiServer: Thread ${this.currentThread.id} AbortController aborted`)),this.currentThread.aiClient&&(this.currentThread.aiClient.abort(),console.log(`AiServer: Thread ${this.currentThread.id} AI client aborted`)),this.currentThread=null,console.log("AiServer: Thread reference cleared")):console.log("AiServer: No active thread to abort")}isRequestAborted(){return this.isAborted}resetAbortState(){this.isAborted=!1,this.currentThread&&(this.currentThread.isRunning=!1,this.currentThread=null)}}class Nl{constructor(e){W(this,"pendingSaves",new Set);W(this,"savedMessages",new Map);W(this,"databaseService");this.databaseService=e}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 this.databaseService.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(i=>setTimeout(i,10));const o=this.savedMessages.get(t);if(o)return o}this.pendingSaves.add(t);try{const o=await this.databaseService.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 this.databaseService.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 this.databaseService.createMessage(e)}}clearCache(){this.savedMessages.clear()}getCacheStats(){return{pendingCount:this.pendingSaves.size,cachedCount:this.savedMessages.size}}}class Af extends ps{constructor(e,t){super(e,t)}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 Ml{constructor(e,t,n,s){W(this,"currentAiClient",null);W(this,"currentSessionId",null);W(this,"dbService");W(this,"messageManager");W(this,"userId");W(this,"configUrl");this.userId=e,this.dbService=new Af(e,t),this.messageManager=n,this.configUrl=s||"/api",console.log("🔧 ChatService Constructor - configUrl:",this.configUrl)}async sendMessage(e,t,n=[],s={},o){var i,l,d,f,g;try{if(this.currentSessionId=e,!await this.dbService.getSession(e))throw new Error("Session not found");let p;if(o)p=o;else{const u=await this.getChatConfig();p={model_name:u.model,temperature:u.temperature,max_tokens:16e3,api_key:u.apiKey,base_url:u.baseUrl}}const w=new kl(e,this.userId,this.messageManager,p,this.configUrl,e);let m=3;for(;m>0;)try{await w.init();break}catch(u){if(m--,m===0)throw new Error(`AI服务初始化失败: ${u instanceof Error?u.message:"未知错误"}`);await new Promise(c=>setTimeout(c,1e3))}w.callback=(u,c)=>{var b,x,y,v,S,C,_,I;try{switch(u){case"chunk":const T=typeof c=="string"?c:c.content||c.accumulated||"";(b=s.onChunk)==null||b.call(s,{type:"text",content:T,accumulated:T});break;case"summary_chunk":const $=typeof c=="string"?c:c.content||c.accumulated||"";(x=s.onChunk)==null||x.call(s,{type:"text",content:$,accumulated:$});break;case"tool_call":(y=s.onToolCall)==null||y.call(s,c);break;case"tool_result":(v=s.onToolResult)==null||v.call(s,c);break;case"tool_stream_chunk":(S=s.onToolStreamChunk)==null||S.call(s,c);break;case"complete":debugger;break;case"conversation_complete":(C=s.onComplete)==null||C.call(s,c);break;case"error":const F=c instanceof Error?c.message:typeof c=="string"?c:"AI响应出错";(_=s.onError)==null||_.call(s,new Error(F));break;default:console.warn("Unknown AI response type:",u)}}catch(T){console.error("Callback error:",T),(I=s.onError)==null||I.call(s,new Error(`处理AI响应时出错: ${T instanceof Error?T.message:"未知错误"}`))}},this.currentAiClient=w,await w.sendMessage(t)}catch(h){if(h.message==="Stream aborted by user"||h.name==="AbortError"){console.log("Message sending aborted by user");return}if((i=h.message)!=null&&i.includes("ERR_INCOMPLETE_CHUNKED_ENCODING")||(l=h.message)!=null&&l.includes("net::ERR_")||(d=h.message)!=null&&d.includes("Failed to fetch")){console.log("Network connection error during streaming:",h.message),(f=s.onError)==null||f.call(s,new Error("网络连接中断,请检查网络状态后重试"));return}throw console.error("Failed to send message:",h),(g=s.onError)==null||g.call(s,h instanceof Error?h:new Error(String(h))),h}}async abortCurrentConversation(){if(console.log("🛑 ChatService: 中止当前对话"),this.currentSessionId)try{console.log(`🛑 ChatService: 调用服务端停止接口,会话ID: ${this.currentSessionId}`);const t=await(await fetch(`${this.configUrl}/chat/stop`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.currentSessionId})})).json();t.success?console.log(`✅ ChatService: 服务端停止成功 - ${t.message}`):console.warn(`⚠️ ChatService: 服务端停止失败 - ${t.message||"未知错误"}`);debugger;this.currentAiClient&&(console.log("🔄 ChatService: 尝试客户端停止作为备用方案"),this.currentAiClient.abort()),this.currentAiClient=null,this.currentSessionId=null}catch(e){console.error("❌ ChatService: 调用服务端停止接口失败:",e),this.currentAiClient&&(console.log("🔄 ChatService: 尝试客户端停止作为备用方案"),this.currentAiClient.abort()),this.currentAiClient=null,this.currentSessionId=null}else console.log("⚠️ ChatService: 没有活动的会话可以中止"),this.currentAiClient&&(console.log("🔄 ChatService: 尝试停止当前AI客户端"),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"}}}function kf({set:r,get:e,client:t,getUserIdParam:n}){return async function(o,i=[]){var x;const{currentSessionId:l,selectedModelId:d,aiModelConfigs:f,chatConfig:g,isLoading:h,isStreaming:p,activeSystemContext:w,selectedAgentId:m,agents:u}=e();if(!l)throw new Error("No active session");if(h||p){console.log("Message sending already in progress, ignoring duplicate request");return}let c=null,b=null;if(m){if(b=u.find(y=>y.id===m),!b||b.enabled===!1)throw new Error("选择的智能体不可用")}else if(d){if(c=f.find(y=>y.id===d),!c||!c.enabled)throw new Error("选择的模型不可用")}else throw new Error("请先选择一个模型或智能体");try{const y=new Date,v={id:`temp_user_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:l,role:"user",content:o,status:"completed",createdAt:y,metadata:{...i.length>0?{attachments:i}:{},model:b?`[Agent] ${b.name}`:c.model_name,...c?{modelConfig:{id:c.id,name:c.name,base_url:c.base_url,model_name:c.model_name}}:{}}};r(F=>{F.messages.push(v),F.isLoading=!0,F.isStreaming=!0});const S=new Date(y.getTime()+1),C={id:`temp_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:l,role:"assistant",content:"",status:"streaming",createdAt:S,metadata:{model:b?`[Agent] ${b.name}`:c.model_name,...c?{modelConfig:{id:c.id,name:c.name,base_url:c.base_url,model_name:c.model_name}}:{},toolCalls:[],contentSegments:[{content:"",type:"text"}],currentSegmentIndex:0}};r(F=>{F.messages.push(C),F.streamingMessageId=C.id});const _=b?{session_id:l,message:o,agent_id:b.id,system_context:(w==null?void 0:w.content)||g.systemPrompt||"",attachments:i||[]}:{session_id:l,message:o,model_config:{model:c.model_name,base_url:c.base_url,api_key:c.api_key||"",temperature:g.temperature,max_tokens:g.maxTokens},system_context:(w==null?void 0:w.content)||g.systemPrompt||"",attachments:i||[]};console.log("🚀 开始调用后端流式聊天API:",_);const I=b?await t.streamAgentChat(l,o,b.id,n()):await t.streamChat(l,o,c,n());if(!I)throw new Error("No response received");const T=I.getReader(),$=new TextDecoder;try{for(;;){const{done:F,value:k}=await T.read();if(F){console.log("✅ 流式响应完成");break}const H=$.decode(k,{stream:!0}).split(`
71
+ `);for(const Z of H)if(Z.trim()!==""&&Z.startsWith("data: ")){const P=Z.slice(6);if(P==="[DONE]"){console.log("✅ 收到完成信号");break}try{const N=JSON.parse(P);if(typeof N=="string"&&N==="[DONE]"){console.log("✅ 收到完成信号");break}if(N.type==="chunk")N.content&&r(R=>{const B=R.messages.find(q=>q.id===C.id);if(B&&B.metadata){const q=typeof N.content=="string"?N.content:typeof N=="string"?N:N.content||"",D=B.metadata.currentSegmentIndex||0,A=B.metadata.contentSegments||[];A[D]&&A[D].type==="text"?A[D].content+=q:(A.push({content:q,type:"text"}),B.metadata.currentSegmentIndex=A.length-1),B.content=A.filter(j=>j.type==="text").map(j=>j.content).join("")}});else if(N.type==="thinking")N.content&&r(R=>{const B=R.messages.find(q=>q.id===C.id);if(B&&B.metadata){const q=typeof N.content=="string"?N.content:typeof N=="string"?N:N.content||"",D=B.metadata.contentSegments||[],A=D.length-1;A>=0&&D[A].type==="thinking"?(D[A].content+=q,B.metadata.currentSegmentIndex=A):(D.push({content:q,type:"thinking"}),B.metadata.currentSegmentIndex=D.length-1),B.content=D.filter(j=>j.type==="text").map(j=>j.content).join("")}});else if(N.type==="context_summarized"||N.type==="context_summarized_start"||N.type==="context_summarized_stream"||N.type==="context_summarized_end"){const R=N.data||{},B="【上下文摘要】\\n";r(q=>{const D=q.messages.find(M=>M.id===C.id);if(!D||!D.metadata)return;const A=D.metadata.contentSegments||[],j=()=>{const M=A.length-1;return M>=0&&A[M].type==="thinking"&&String(A[M].content||"").startsWith(B)?M:(A.push({content:B,type:"thinking"}),D.metadata.contentSegments=A,D.metadata.currentSegmentIndex=A.length-1,A.length-1)};if(N.type==="context_summarized_start")j();else if(N.type==="context_summarized_stream"){const M=j(),L=R.content||R.chunk||R.data||"";A[M].content+=String(L),D.metadata.currentSegmentIndex=M}else if(N.type==="context_summarized_end"||N.type==="context_summarized"){const M=j(),L=typeof R.full_summary=="string"&&R.full_summary.length>0?R.full_summary:R.summary_preview||"";A[M].content=B+String(L),D.metadata.contentSegments=A,D.metadata.currentSegmentIndex=M}D.updatedAt=new Date})}else if(N.type==="content")r(R=>{const B=R.messages.find(q=>q.id===C.id);if(B&&B.metadata){const q=typeof N.content=="string"?N.content:typeof N=="string"?N:N.content||"",D=B.metadata.currentSegmentIndex||0,A=B.metadata.contentSegments||[];A[D]&&A[D].type==="text"?A[D].content+=q:(A.push({content:q,type:"text"}),B.metadata.currentSegmentIndex=A.length-1),B.content=A.filter(j=>j.type==="text").map(j=>j.content).join("")}});else if(N.type==="tools_start"){console.log("🔧 收到工具调用:",N.data),console.log("🔧 工具调用数据类型:",typeof N.data,"是否为数组:",Array.isArray(N.data));const R=D=>{var j,M,L;console.log("🔧 [DEBUG] 原始工具调用数据:",D),console.log("🔧 [DEBUG] tc.function:",D.function),console.log("🔧 [DEBUG] tc.function?.name:",(j=D.function)==null?void 0:j.name),console.log("🔧 [DEBUG] tc.name:",D.name);const A={id:D.id||D.tool_call_id||`tool_${Date.now()}_${Math.random()}`,messageId:C.id,name:((M=D.function)==null?void 0:M.name)||D.name||"unknown_tool",arguments:((L=D.function)==null?void 0:L.arguments)||D.arguments||"{}",result:D.result||"",error:D.error||void 0,createdAt:D.createdAt||D.created_at||new Date};return console.log("🔧 [DEBUG] 转换后的工具调用:",A),A};console.log("🔧 [DEBUG] tools_start 原始数据:",N.data);const B=N.data.tool_calls||N.data,q=Array.isArray(B)?B:[B];console.log("🔧 [DEBUG] 提取的工具调用数组:",q),r(D=>{const A=D.messages.findIndex(j=>j.id===C.id);if(console.log("🔧 查找消息索引:",A,"消息ID:",C.id),A!==-1){const j=D.messages[A];console.log("🔧 找到消息,当前metadata:",j.metadata),j.metadata||(j.metadata={}),j.metadata.toolCalls||(j.metadata.toolCalls=[]);const M=j.metadata.contentSegments||[];console.log("🔧 处理工具调用数组,长度:",q.length),q.forEach(L=>{const z=R(L);console.log("🔧 添加转换后的工具调用:",z),j.metadata.toolCalls.push(z),M.push({content:"",type:"tool_call",toolCallId:z.id})}),M.push({content:"",type:"text"}),j.metadata.currentSegmentIndex=M.length-1,console.log("🔧 更新后的toolCalls:",j.metadata.toolCalls)}else console.log("🔧 ❌ 未找到对应的消息")})}else if(N.type==="tools_end"){console.log("🔧 收到工具结果:",N.data),console.log("🔧 工具结果数据类型:",typeof N.data);const R=Array.isArray(N.data)?N.data:[N.data];r(B=>{const q=B.messages.findIndex(D=>D.id===C.id);if(q!==-1){const D=B.messages[q];D.metadata&&D.metadata.toolCalls&&(R.forEach(A=>{var L,z,Q,ae;const j=A.tool_call_id||A.id||A.toolCallId;if(!j){console.warn("⚠️ 工具结果缺少工具调用ID:",A);return}console.log("🔍 查找工具调用:",j,"在消息中:",(z=(L=D.metadata)==null?void 0:L.toolCalls)==null?void 0:z.map(be=>be.id));const M=D.metadata.toolCalls.find(be=>be.id===j);if(M){console.log("✅ 找到工具调用,更新最终结果:",M.id);const be=A.result||A.content||A.output||"";A.success===!1||A.is_error===!0?(M.error=A.error||be||"工具执行失败",console.log("❌ 工具执行失败:",{id:M.id,name:A.name||M.name,error:M.error,success:A.success,is_error:A.is_error})):((!M.result||M.result.trim()==="")&&(M.result=be),M.error&&delete M.error,console.log("✅ 工具执行成功,最终结果已更新:",{id:M.id,name:A.name||M.name,resultLength:M.result.length,success:A.success,is_stream:A.is_stream}))}else console.log("❌ 未找到对应的工具调用:",j),console.log("📋 当前可用的工具调用ID:",(ae=(Q=D.metadata)==null?void 0:Q.toolCalls)==null?void 0:ae.map(be=>be.id))}),D.updatedAt=new Date)}})}else if(N.type==="tools_stream"){console.log("🔧 收到工具流式数据:",N.data);const R=N.data;r(B=>{const q=B.messages.findIndex(D=>D.id===C.id);if(q!==-1){const D=B.messages[q];if(D.metadata&&D.metadata.toolCalls){const A=R.toolCallId||R.tool_call_id||R.id;if(!A){console.warn("⚠️ 工具流式数据缺少工具调用ID:",R);return}console.log("🔍 查找工具调用进行流式更新:",A);const j=D.metadata.toolCalls.find(M=>M.id===A);if(j){const M=R.content||R.chunk||R.data||"";R.is_error||!R.success?(j.error=M||"工具执行出错",console.log("❌ 工具流式执行出错:",{id:j.id,error:j.error,success:R.success,is_error:R.is_error})):(j.result=(j.result||"")+M,console.log("🔧 工具流式数据已更新:",{id:j.id,name:R.name,chunkLength:M.length,totalLength:j.result.length,success:R.success,is_stream:R.is_stream})),D.updatedAt=new Date}}}})}else{if(N.type==="error")throw new Error(N.message||((x=N.data)==null?void 0:x.message)||"Stream error");if(N.type==="cancelled"){console.log("⚠️ 流式会话已被取消");break}else if(N.type==="done"){console.log("✅ 收到完成信号");break}}}catch(N){console.warn("解析流式数据失败:",N,"data:",P)}}}}finally{T.releaseLock(),r(F=>{F.isLoading=!1,F.isStreaming=!1,F.streamingMessageId=null})}console.log("✅ 消息发送完成")}catch(y){throw console.error("❌ 发送消息失败:",y),r(v=>{const S=v.messages.findIndex(C=>{var _;return(_=C.id)==null?void 0:_.startsWith("temp_")});S!==-1&&v.messages.splice(S,1),v.isLoading=!1,v.isStreaming=!1,v.streamingMessageId=null,v.error=y instanceof Error?y.message:"Failed to send message"}),y}}}function Nf({set:r,get:e,client:t,getUserIdParam:n}){const s=o=>({id:o.id,name:o.name,url:o.url,iconUrl:o.icon_url??void 0,createdAt:new Date(o.created_at),updatedAt:new Date(o.updated_at??o.created_at)});return{loadApplications:async()=>{try{console.log("[Store] loadApplications: start");const o=n(),l=(await t.getApplications(o)||[]).map(s);r(d=>{d.applications=l}),console.log("[Store] loadApplications: loaded",l.length,"items")}catch(o){console.error("Failed to load applications:",o),r(i=>{i.applications=[]})}},createApplication:async(o,i,l)=>{try{const d=await t.createApplication({name:o,url:i,icon_url:l??null,user_id:n()}),f=s(d);r(g=>{g.applications=[f,...g.applications]})}catch(d){console.error("Failed to create application:",d),r(f=>{f.error=d instanceof Error?d.message:"Failed to create application"})}},updateApplication:async(o,i)=>{try{const l={};i.name!==void 0&&(l.name=i.name),i.url!==void 0&&(l.url=i.url),i.iconUrl!==void 0&&(l.icon_url=i.iconUrl??null);const d=await t.updateApplication(o,l),f=s(d);r(g=>{g.applications=g.applications.map(h=>h.id===o?f:h)})}catch(l){console.error("Failed to update application:",l),r(d=>{d.error=l instanceof Error?l.message:"Failed to update application"})}},deleteApplication:async o=>{try{await t.deleteApplication(o),r(i=>{i.applications=i.applications.filter(l=>l.id!==o),i.mcpConfigs=i.mcpConfigs.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==o):[]})),i.systemContexts=i.systemContexts.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==o):[]})),i.agents=i.agents.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==o):[]}))})}catch(i){console.error("Failed to delete application:",i),r(l=>{l.error=i instanceof Error?i.message:"Failed to delete application"})}},setSelectedApplication:o=>{console.log("[Store] setSelectedApplication:",o);const i=e().selectedApplicationId;console.log("[Store] setSelectedApplication - before:",{oldId:i,newId:o}),r(d=>({...d,selectedApplicationId:o}));const l=e().selectedApplicationId;console.log("[Store] setSelectedApplication - after:",{oldId:i,newId:l})},setMcpAppAssociation:(o,i)=>{r(l=>{l.mcpConfigs=l.mcpConfigs.map(d=>d.id===o?{...d,app_ids:Array.isArray(i)?i:[]}:d)})},setSystemContextAppAssociation:(o,i)=>{r(l=>{l.systemContexts=l.systemContexts.map(d=>d.id===o?{...d,app_ids:Array.isArray(i)?i:[]}:d)});try{(async()=>await t.updateSystemContext(o,{name:void 0,content:void 0,app_ids:Array.isArray(i)?i:[]}))()}catch{}},setAgentAppAssociation:(o,i)=>{r(l=>{l.agents=l.agents.map(d=>d.id===o?{...d,app_ids:Array.isArray(i)?i:[]}:d)});try{(async()=>await t.updateAgent(o,{app_ids:Array.isArray(i)?i:[]}))()}catch{}}}}function Mf({set:r,get:e,client:t,getUserIdParam:n}){return{loadAiModelConfigs:async()=>{try{const s=n(),i=(await t.getAiModelConfigs(s)).map(l=>({id:l.id,name:l.name,base_url:l.base_url,api_key:l.api_key,model_name:l.model,enabled:l.enabled,createdAt:new Date(l.created_at),updatedAt:new Date(l.created_at)}));r(l=>{l.aiModelConfigs=i})}catch(s){console.error("Failed to load AI model configs:",s),r(o=>{o.error=s instanceof Error?s.message:"Failed to load AI model configs"})}},updateAiModelConfig:async s=>{try{const o=n(),l=e().aiModelConfigs.find(f=>f.id===s.id)?"update":"create",d={id:s.id||crypto.randomUUID(),name:s.name,provider:"openai",model:s.model_name,api_key:s.api_key,base_url:s.base_url,enabled:s.enabled,user_id:o};l==="update"?await t.updateAiModelConfig(s.id,d):await t.createAiModelConfig(d),await e().loadAiModelConfigs()}catch(o){console.error("Failed to update AI model config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to update AI model config"})}},deleteAiModelConfig:async s=>{try{await t.deleteAiModelConfig(s),r(o=>{o.aiModelConfigs=o.aiModelConfigs.filter(i=>i.id!==s)})}catch(o){console.error("Failed to delete AI model config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to delete AI model config"})}},setSelectedModel:s=>{r(o=>{o.selectedModelId=s,s&&(o.selectedAgentId=null)})}}}function Ef({set:r,get:e,client:t,getUserIdParam:n}){return{loadMcpConfigs:async()=>{var s;try{const o=n(),i=await t.getMcpConfigs(o);console.log("🔍 [后端返回] loadMcpConfigs 返回的数据:",i),console.log("🔍 [后端返回] 第一个配置的 app_ids:",(s=i==null?void 0:i[0])==null?void 0:s.app_ids),r(l=>{l.mcpConfigs=i})}catch(o){console.error("Failed to load MCP configs:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to load MCP configs"})}},updateMcpConfig:async s=>{try{const o=n();console.log("🔍 updateMcpConfig 调用:",{userId:o,configId:s.id,configName:s.name});let i=null;if(s.id){const f={id:s.id,name:s.name,command:s.command,type:s.type,args:s.args??void 0,env:s.env??void 0,cwd:s.cwd??void 0,enabled:s.enabled,userId:o,app_ids:Array.isArray(s.app_ids)?s.app_ids:void 0};console.log("🔍 updateMcpConfig 更新数据:",f),i=await t.updateMcpConfig(s.id,f)}else{const f={name:s.name,command:s.command,type:s.type,args:s.args??void 0,env:s.env??void 0,cwd:s.cwd??void 0,enabled:s.enabled,user_id:o,app_ids:Array.isArray(s.app_ids)?s.app_ids:void 0};i=await t.createMcpConfig(f)}const l=(i==null?void 0:i.id)??s.id,d=Array.isArray(i==null?void 0:i.app_ids)?i.app_ids:Array.isArray(s.app_ids)?s.app_ids:[];return r(f=>{f.mcpConfigs=f.mcpConfigs.map(g=>g.id===l?{...g,app_ids:d}:g)}),await e().loadMcpConfigs(),i}catch(o){return console.error("Failed to update MCP config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to update MCP config"}),null}},deleteMcpConfig:async s=>{try{await t.deleteMcpConfig(s),r(o=>{o.mcpConfigs=o.mcpConfigs.filter(i=>i.id!==s)})}catch(o){console.error("Failed to delete MCP config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to delete MCP config"})}}}}function If({set:r}){return{updateChatConfig:async e=>{r(t=>{t.chatConfig={...t.chatConfig,...e}})}}}function zr(r,e){const t=r||ee,n=e==null?void 0:e.userId,s=e==null?void 0:e.projectId,o=e==null?void 0:e.configUrl,i=n||"default-user",l=s||"default-project",d=o||"/api",f=()=>i,g=()=>({userId:i,projectId:l}),h=new ps(i,l,t),p=new Nl(h),w=new Ml(i,l,p,d);return console.log("chatService:",w),wc()(Oc(Uc((m,u)=>({sessions:[],currentSessionId:null,currentSession:null,messages:[],isLoading:!1,isStreaming:!1,streamingMessageId:null,hasMoreMessages:!0,sidebarOpen:!0,theme:"light",chatConfig:{model:"gpt-4",temperature:.7,maxTokens:2048,systemPrompt:"",enableMcp:!0},mcpConfigs:[],aiModelConfigs:[],selectedModelId:null,agents:[],selectedAgentId:null,systemContexts:[],activeSystemContext:null,applications:[],selectedApplicationId:null,error:null,loadSessions:async()=>{try{console.log("🔍 loadSessions 被调用"),m(v=>{v.isLoading=!0,v.error=null}),console.log("🔍 loadSessions isLoading 设置为 true");const{userId:c,projectId:b}=g();console.log("🔍 loadSessions 调用 client.getSessions",{userId:c,projectId:b,customUserId:n,customProjectId:s});const x=await t.getSessions(c,b);console.log("🔍 loadSessions 返回结果:",x),m(v=>{v.sessions=x,v.isLoading=!1});const y=u();if(x.length>0&&!y.currentSessionId){const v=localStorage.getItem(`lastSessionId_${c}_${b}`);let S=null;v&&(S=x.find(C=>C.id===v)),S||(S=[...x].sort((C,_)=>new Date(_.createdAt).getTime()-new Date(C.createdAt).getTime())[0]),S&&(console.log("🔍 自动选择会话:",S.id),setTimeout(()=>{u().selectSession(S.id)},0))}console.log("🔍 loadSessions 完成")}catch(c){console.error("🔍 loadSessions 错误:",c),m(b=>{b.error=c instanceof Error?c.message:"Failed to load sessions",b.isLoading=!1})}},createSession:async(c="New Chat")=>{try{const{userId:b,projectId:x}=g();console.log("🔍 createSession 使用参数:",{userId:b,projectId:x,title:c}),console.log("🔍 createSession 自定义参数:",{customUserId:n,customProjectId:s}),console.log("🔍 createSession 最终使用的参数:",{userId:b,projectId:x,isCustomUserId:!!n,isCustomProjectId:!!s});const y={id:crypto.randomUUID(),title:c,user_id:b,project_id:x},v=await t.createSession(y);console.log("✅ createSession API调用成功:",v);const S={id:v.id,title:v.title,createdAt:new Date(v.created_at),updatedAt:new Date(v.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null};return m(C=>{C.sessions.unshift(S),C.currentSessionId=S.id,C.currentSession=S,C.messages=[],C.error=null}),localStorage.setItem(`lastSessionId_${b}_${x}`,S.id),console.log("🔍 保存新创建的会话ID到 localStorage:",S.id),S.id}catch(b){throw console.error("❌ createSession 失败:",b),m(x=>{x.error=b instanceof Error?b.message:"Failed to create session"}),b}},selectSession:async c=>{try{m(y=>{y.isLoading=!0,y.error=null});const b=await h.getSession(c),x=await h.getSessionMessages(c,{limit:10,offset:0});if(m(y=>{y.currentSessionId=c,y.currentSession=b,y.messages=x,y.isLoading=!1,y.hasMoreMessages=x.length===10,b||(y.error="Session not found")}),b){const{userId:y,projectId:v}=g();localStorage.setItem(`lastSessionId_${y}_${v}`,c),console.log("🔍 保存会话ID到 localStorage:",c)}}catch(b){console.error("Failed to select session:",b),m(x=>{x.error=b instanceof Error?b.message:"Failed to select session",x.isLoading=!1})}},updateSession:async(c,b)=>{try{const x=await h.updateSession(c,b);m(y=>{const v=y.sessions.findIndex(S=>S.id===c);v!==-1&&x&&(y.sessions[v]=x),y.currentSessionId===c&&(y.currentSession=x)})}catch(x){console.error("Failed to update session:",x),m(y=>{y.error=x instanceof Error?x.message:"Failed to update session"})}},deleteSession:async c=>{try{await h.deleteSession(c),m(b=>{b.sessions=b.sessions.filter(x=>x.id!==c),b.currentSessionId===c&&(b.currentSessionId=null,b.currentSession=null,b.messages=[])})}catch(b){console.error("Failed to delete session:",b),m(x=>{x.error=b instanceof Error?b.message:"Failed to delete session"})}},loadMessages:async c=>{try{m(x=>{x.isLoading=!0,x.error=null});const b=await h.getSessionMessages(c,{limit:10,offset:0});m(x=>{x.messages=b,x.isLoading=!1,x.hasMoreMessages=b.length===10})}catch(b){console.error("Failed to load messages:",b),m(x=>{x.error=b instanceof Error?b.message:"Failed to load messages",x.isLoading=!1})}},loadMoreMessages:async c=>{try{const x=u().messages.length,y=await h.getSessionMessages(c,{limit:10,offset:x});m(v=>{const S=new Set(v.messages.map(_=>_.id)),C=y.filter(_=>!S.has(_.id));v.messages=[...C,...v.messages],v.hasMoreMessages=y.length===10})}catch(b){console.error("Failed to load more messages:",b),m(x=>{x.error=b instanceof Error?b.message:"Failed to load more messages"})}},sendMessage:kf({set:m,get:u,client:t,getUserIdParam:f}),updateMessage:async(c,b)=>{try{const x=await h.updateMessage(c,b);m(y=>{const v=y.messages.findIndex(S=>S.id===c);v!==-1&&x&&(y.messages[v]=x)})}catch(x){console.error("Failed to update message:",x),m(y=>{y.error=x instanceof Error?x.message:"Failed to update message"})}},deleteMessage:async c=>{try{await h.deleteMessage(c),m(b=>{b.messages=b.messages.filter(x=>x.id!==c)})}catch(b){console.error("Failed to delete message:",b),m(x=>{x.error=b instanceof Error?b.message:"Failed to delete message"})}},startStreaming:c=>{m(b=>{b.isStreaming=!0,b.streamingMessageId=c})},updateStreamingMessage:c=>{m(b=>{if(b.streamingMessageId){const x=b.messages.findIndex(y=>y.id===b.streamingMessageId);x!==-1&&(b.messages[x].content=c)}})},stopStreaming:()=>{m(c=>{c.isStreaming=!1,c.streamingMessageId=null})},abortCurrentConversation:async()=>{const{currentSessionId:c}=u();if(c)try{await t.stopChat(c),console.log("✅ 成功停止当前对话")}catch(b){console.error("❌ 停止对话失败:",b)}m(b=>{b.isStreaming=!1,b.streamingMessageId=null,b.isLoading=!1})},toggleSidebar:()=>{m(c=>{c.sidebarOpen=!c.sidebarOpen})},setTheme:c=>{m(b=>{b.theme=c})},...If({set:m}),...Ef({set:m,get:u,client:t,getUserIdParam:f}),...Nf({set:m,get:u,client:t,getUserIdParam:f}),...Mf({set:m,get:u,client:t,getUserIdParam:f}),loadAgents:async()=>{var c;try{const b=await t.getAgents(f());console.log("🔍 [后端返回] loadAgents 返回的数据:",b),console.log("🔍 [后端返回] 第一个智能体的 app_ids:",(c=b==null?void 0:b[0])==null?void 0:c.app_ids),m(x=>{x.agents=b||[]})}catch(b){console.error("Failed to load agents:",b),m(x=>{x.agents=[],x.error=b instanceof Error?b.message:"Failed to load agents"})}},setSelectedAgent:c=>{m(b=>{b.selectedAgentId=c,c&&(b.selectedModelId=null)})},loadSystemContexts:async()=>{try{const c=await t.getSystemContexts(f()),b=await t.getActiveSystemContext(f());m(x=>{const y=(c||[]).map(v=>({...v,isActive:!1}));if(b&&b.context){const v=b.context,S=y.findIndex(C=>C.id===v.id);S!==-1?(y[S].isActive=!0,x.activeSystemContext={...y[S]}):x.activeSystemContext=null}else x.activeSystemContext=null;x.systemContexts=y})}catch(c){console.error("Failed to load system contexts:",c),m(b=>{b.systemContexts=[],b.activeSystemContext=null})}},createSystemContext:async(c,b,x)=>{try{const y=await t.createSystemContext({name:c,content:b,user_id:f(),app_ids:Array.isArray(x)?x:void 0});return m(v=>{v.systemContexts.push(y)}),y}catch(y){return console.error("Failed to create system context:",y),m(v=>{v.error=y instanceof Error?y.message:"Failed to create system context"}),null}},updateSystemContext:async(c,b,x,y)=>{try{const v=await t.updateSystemContext(c,{name:b,content:x,app_ids:Array.isArray(y)?y:void 0});return m(S=>{const C=S.systemContexts.findIndex(_=>_.id===c);C!==-1&&(S.systemContexts[C]=v)}),v}catch(v){return console.error("Failed to update system context:",v),m(S=>{S.error=v instanceof Error?v.message:"Failed to update system context"}),null}},deleteSystemContext:async c=>{try{await t.deleteSystemContext(c),m(b=>{var x;b.systemContexts=b.systemContexts.filter(y=>y.id!==c),((x=b.activeSystemContext)==null?void 0:x.id)===c&&(b.activeSystemContext=null)})}catch(b){console.error("Failed to delete system context:",b),m(x=>{x.error=b instanceof Error?b.message:"Failed to delete system context"})}},activateSystemContext:async c=>{try{await t.activateSystemContext(c,f()),m(b=>{const x=b.systemContexts.find(y=>y.id===c);x&&(b.systemContexts.forEach(y=>{y.isActive=y.id===c}),b.activeSystemContext={...x,isActive:!0})})}catch(b){console.error("Failed to activate system context:",b),m(x=>{x.error=b instanceof Error?b.message:"Failed to activate system context"})}},setError:c=>{m(b=>{b.error=c})},clearError:()=>{m(c=>{c.error=null})}}),{name:"chat-store-with-backend",partialize:m=>({theme:m.theme,sidebarOpen:m.sidebarOpen,chatConfig:m.chatConfig,selectedModelId:m.selectedModelId})})))}const ct=zr();function Pf(r,e,t){return zr(t,{userId:r,projectId:e})}const pn=O.createContext(null),Tf=({children:r,userId:e,projectId:t,customApiClient:n})=>{const s=O.useMemo(()=>e||t||n?(console.log("🏪 创建自定义store:",{userId:e,projectId:t,hasCustomApiClient:!!n}),Pf(e||"default-user",t||"default-project",n)):(console.log("🏪 使用默认store"),ct),[e,t,n]);return a.jsx(pn.Provider,{value:{store:s,userId:e,projectId:t,apiClient:n},children:r})},El=()=>{const r=O.useContext(pn);if(!r)throw new Error("useChatStoreContext must be used within a ChatStoreProvider");return r.store},dt=()=>El()(),Of=()=>{const r=O.useContext(pn);return r?{userId:r.userId,projectId:r.projectId}:{userId:void 0,projectId:void 0}},Rf=()=>{const r=O.useContext(pn);return r==null?void 0:r.apiClient},nt=({content:r,isStreaming:e=!1,className:t="",onApplyCode:n})=>{const[s,o]=O.useState(new Set),i=O.useCallback(async h=>{try{await navigator.clipboard.writeText(h)}catch(p){console.error("Failed to copy code:",p)}},[]),l=O.useCallback(h=>{o(p=>{const w=new Set(p);return w.has(h)?w.delete(h):w.add(h),w})},[]),d=O.useMemo(()=>h=>{if(!h)return"";let p=h;const w=/\$\$([\s\S]*?)\$\$/g;p=p.replace(w,(v,S)=>`<div class="math-block">${S.trim()}</div>`);const m=/\$([^$]+)\$/g;p=p.replace(m,(v,S)=>`<span class="math-inline">${S}</span>`);const u=/\|(.+)\|\n\|[-\s|:]+\|\n((?:\|.+\|\n?)*)/g;if(p=p.replace(u,(v,S,C)=>{const _=S.split("|").map($=>$.trim()).filter($=>$),I=C.trim().split(`
72
+ `).map($=>$.split("|").map(F=>F.trim()).filter(F=>F));let T="<table>";return _.length>0&&(T+="<thead><tr>",_.forEach($=>{T+=`<th>${$}</th>`}),T+="</tr></thead>"),I.length>0&&(T+="<tbody>",I.forEach($=>{$.length>0&&(T+="<tr>",$.forEach(F=>{T+=`<td>${F}</td>`}),T+="</tr>")}),T+="</tbody>"),T+="</table>",e?`<div class="streaming-table-wrapper">
73
73
  <div class="streaming-table-indicator">● 正在生成表格...</div>
74
- ${E}
75
- </div>`:E}),e){const _=/\|(.+)\|\n\|[-\s|:]+\|(?:\n(?:\|.+\|)*)?$/,v=x.match(_);if(v){const[C,S]=v,I=S.split("|").map(W=>W.trim()).filter(W=>W),R=C.split(`
76
- `).slice(2).map(W=>W.split("|").map(D=>D.trim()).filter(D=>D)).filter(W=>W.length>0);let j='<div class="streaming-table-wrapper">';j+='<div class="streaming-table-indicator">● 正在生成表格...</div>',j+='<table class="streaming-table">',I.length>0&&(j+="<thead><tr>",I.forEach(W=>{j+=`<th>${W}</th>`}),j+="</tr></thead>"),R.length>0&&(j+="<tbody>",R.forEach(W=>{j+="<tr>",W.forEach(D=>{j+=`<td>${D}</td>`}),j+="</tr>"}),j+="</tbody>"),j+="</table></div>",x=x.replace(_,j)}}const c=/```(\w+)?\n?([\s\S]*?)```/g;let g=0;if(x=x.replace(c,(_,v,C)=>{const S=v||"text",I=u(C.trim()),E=`code-block-${g++}`,P=s.has(E),R=C.trim();return`<div class="code-block ${P?"expanded":""}" data-block-id="${E}">
74
+ ${T}
75
+ </div>`:T}),e){const v=/\|(.+)\|\n\|[-\s|:]+\|(?:\n(?:\|.+\|)*)?$/,S=p.match(v);if(S){const[C,_]=S,I=_.split("|").map(U=>U.trim()).filter(U=>U),F=C.split(`
76
+ `).slice(2).map(U=>U.split("|").map(H=>H.trim()).filter(H=>H)).filter(U=>U.length>0);let k='<div class="streaming-table-wrapper">';k+='<div class="streaming-table-indicator">● 正在生成表格...</div>',k+='<table class="streaming-table">',I.length>0&&(k+="<thead><tr>",I.forEach(U=>{k+=`<th>${U}</th>`}),k+="</tr></thead>"),F.length>0&&(k+="<tbody>",F.forEach(U=>{k+="<tr>",U.forEach(H=>{k+=`<td>${H}</td>`}),k+="</tr>"}),k+="</tbody>"),k+="</table></div>",p=p.replace(v,k)}}const c=/```(\w+)?\n?([\s\S]*?)```/g;let b=0;if(p=p.replace(c,(v,S,C)=>{const _=S||"text",I=f(C.trim()),T=`code-block-${b++}`,$=s.has(T),F=C.trim();return`<div class="code-block ${$?"expanded":""}" data-block-id="${T}">
77
77
  <div class="code-header">
78
- <span class="code-language">${S}</span>
78
+ <span class="code-language">${_}</span>
79
79
  <div class="code-actions">
80
- <button class="code-action-btn copy-btn" data-code="${encodeURIComponent(R)}" title="复制代码">
80
+ <button class="code-action-btn copy-btn" data-code="${encodeURIComponent(F)}" title="复制代码">
81
81
  <span class="icon">复制</span>
82
82
  </button>
83
- <button class="code-action-btn apply-btn" data-code="${encodeURIComponent(R)}" data-language="${S}" title="应用代码">
83
+ <button class="code-action-btn apply-btn" data-code="${encodeURIComponent(F)}" data-language="${_}" title="应用代码">
84
84
  <span class="icon">应用</span>
85
85
  </button>
86
- <button class="code-action-btn expand-btn" data-block-id="${E}" title="${P?"收起":"展开"}">
87
- <span class="icon">${P?"收起":"展开"}</span>
86
+ <button class="code-action-btn expand-btn" data-block-id="${T}" title="${$?"收起":"展开"}">
87
+ <span class="icon">${$?"收起":"展开"}</span>
88
88
  </button>
89
89
  </div>
90
90
  </div>
91
91
  <div class="code-content">
92
92
  <pre><code>${I}</code></pre>
93
93
  </div>
94
- </div>`}),x=x.replace(/`([^`\n]+)`/g,"<code>$1</code>"),e){const _=/```(\w+)?\n?([\s\S]*?)$/,v=x.match(_);if(v&&!v[0].includes("```",3)){const[,C,S]=v,I=C||"text",E=u(S);x=x.replace(_,`<div class="code-block streaming-code">
94
+ </div>`}),p=p.replace(/`([^`\n]+)`/g,"<code>$1</code>"),e){const v=/```(\w+)?\n?([\s\S]*?)$/,S=p.match(v);if(S&&!S[0].includes("```",3)){const[,C,_]=S,I=C||"text",T=f(_);p=p.replace(v,`<div class="code-block streaming-code">
95
95
  <div class="code-header">${I} <span class="streaming-indicator">● 正在输入...</span></div>
96
- <pre><code>${E}</code></pre>
97
- </div>`)}}x=x.replace(/^### (.*$)/gm,"<h3>$1</h3>"),x=x.replace(/^## (.*$)/gm,"<h2>$1</h2>"),x=x.replace(/^# (.*$)/gm,"<h1>$1</h1>"),x=x.replace(/^\* (.*$)/gm,"<li>• $1</li>"),x=x.replace(/^\d+\. (.*$)/gm,"<li>$1</li>"),x=x.replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>"),x=x.replace(/\*(.*?)\*/g,"<em>$1</em>"),x=x.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),x=x.replace(/^> (.*$)/gm,"<blockquote>$1</blockquote>"),x=x.replace(/^---$/gm,"<hr>");const y=[];let b=0;return x=x.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g,_=>{const v=`__PROTECTED_HTML_${b++}__`;return y.push(_),v}),x=x.replace(/<[^>]+>/g,_=>{const v=`__PROTECTED_HTML_${b++}__`;return y.push(_),v}),x=x.replace(/\n\n/g,"</p><p>"),x=x.replace(/\n/g,"<br>"),y.forEach((_,v)=>{x=x.replace(`__PROTECTED_HTML_${v}__`,_)}),x&&!x.startsWith("<")&&(x=`<p>${x}</p>`),x},[e,s,n]),u=(f,x)=>f.replace(/</g,"&lt;").replace(/>/g,"&gt;"),p=T.useCallback(f=>{const w=f.target.closest("button");if(w){if(w.classList.contains("copy-btn")){const m=decodeURIComponent(w.getAttribute("data-code")||"");i(m)}else if(w.classList.contains("apply-btn")){const m=decodeURIComponent(w.getAttribute("data-code")||""),h=w.getAttribute("data-language")||"text";n==null||n(m,h)}else if(w.classList.contains("expand-btn")){const m=w.getAttribute("data-block-id");m&&l(m)}}},[i,n,l]);return a.jsxs("div",{className:`markdown-renderer ${t}`,onClick:p,children:[a.jsx("div",{dangerouslySetInnerHTML:{__html:d(r)}}),e&&a.jsx("span",{className:"streaming-cursor"})]})};function Ol(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=Ol(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Df(){for(var r,e,t=0,n="",s=arguments.length;t<s;t++)(r=arguments[t])&&(e=Ol(r))&&(n&&(n+=" "),n+=e);return n}const ao="-",Ff=r=>{const e=Bf(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:i=>{const l=i.split(ao);return l[0]===""&&l.length!==1&&l.shift(),Rl(l,e)||Uf(i)},getConflictingClassGroupIds:(i,l)=>{const d=t[i]||[];return l&&n[i]?[...d,...n[i]]:d}}},Rl=(r,e)=>{var i;if(r.length===0)return e.classGroupId;const t=r[0],n=e.nextPart.get(t),s=n?Rl(r.slice(1),n):void 0;if(s)return s;if(e.validators.length===0)return;const o=r.join(ao);return(i=e.validators.find(({validator:l})=>l(o)))==null?void 0:i.classGroupId},pa=/^\[(.+)\]$/,Uf=r=>{if(pa.test(r)){const e=pa.exec(r)[1],t=e==null?void 0:e.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},Bf=r=>{const{theme:e,prefix:t}=r,n={nextPart:new Map,validators:[]};return Hf(Object.entries(r.classGroups),t).forEach(([o,i])=>{ms(i,n,o,e)}),n},ms=(r,e,t,n)=>{r.forEach(s=>{if(typeof s=="string"){const o=s===""?e:xa(e,s);o.classGroupId=t;return}if(typeof s=="function"){if(Wf(s)){ms(s(n),e,t,n);return}e.validators.push({validator:s,classGroupId:t});return}Object.entries(s).forEach(([o,i])=>{ms(i,xa(e,o),t,n)})})},xa=(r,e)=>{let t=r;return e.split(ao).forEach(n=>{t.nextPart.has(n)||t.nextPart.set(n,{nextPart:new Map,validators:[]}),t=t.nextPart.get(n)}),t},Wf=r=>r.isThemeGetter,Hf=(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(([i,l])=>[e+i,l])):o);return[t,s]}):r,qf=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,n=new Map;const s=(o,i)=>{t.set(o,i),e++,e>r&&(e=0,n=t,t=new Map)};return{get(o){let i=t.get(o);if(i!==void 0)return i;if((i=n.get(o))!==void 0)return s(o,i),i},set(o,i){t.has(o)?t.set(o,i):s(o,i)}}},$l="!",zf=r=>{const{separator:e,experimentalParseClassName:t}=r,n=e.length===1,s=e[0],o=e.length,i=l=>{const d=[];let u=0,p=0,f;for(let c=0;c<l.length;c++){let g=l[c];if(u===0){if(g===s&&(n||l.slice(c,c+o)===e)){d.push(l.slice(p,c)),p=c+o;continue}if(g==="/"){f=c;continue}}g==="["?u++:g==="]"&&u--}const x=d.length===0?l:l.substring(p),w=x.startsWith($l),m=w?x.substring(1):x,h=f&&f>p?f-p:void 0;return{modifiers:d,hasImportantModifier:w,baseClassName:m,maybePostfixModifierPosition:h}};return t?l=>t({className:l,parseClassName:i}):i},Jf=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},Vf=r=>({cache:qf(r.cacheSize),parseClassName:zf(r),...Ff(r)}),Gf=/\s+/,Xf=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:s}=e,o=[],i=r.trim().split(Gf);let l="";for(let d=i.length-1;d>=0;d-=1){const u=i[d],{modifiers:p,hasImportantModifier:f,baseClassName:x,maybePostfixModifierPosition:w}=t(u);let m=!!w,h=n(m?x.substring(0,w):x);if(!h){if(!m){l=u+(l.length>0?" "+l:l);continue}if(h=n(x),!h){l=u+(l.length>0?" "+l:l);continue}m=!1}const c=Jf(p).join(":"),g=f?c+$l:c,y=g+h;if(o.includes(y))continue;o.push(y);const b=s(h,m);for(let _=0;_<b.length;++_){const v=b[_];o.push(g+v)}l=u+(l.length>0?" "+l:l)}return l};function Kf(){let r=0,e,t,n="";for(;r<arguments.length;)(e=arguments[r++])&&(t=Ll(e))&&(n&&(n+=" "),n+=t);return n}const Ll=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=Ll(r[n]))&&(t&&(t+=" "),t+=e);return t};function Yf(r,...e){let t,n,s,o=i;function i(d){const u=e.reduce((p,f)=>f(p),r());return t=Vf(u),n=t.cache.get,s=t.cache.set,o=l,l(d)}function l(d){const u=n(d);if(u)return u;const p=Xf(d,t);return s(d,p),p}return function(){return o(Kf.apply(null,arguments))}}const ae=r=>{const e=t=>t[r]||[];return e.isThemeGetter=!0,e},Dl=/^\[(?:([a-z-]+):)?(.+)\]$/i,Qf=/^\d+\/\d+$/,Zf=new Set(["px","full","screen"]),eh=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,th=/\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$/,rh=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,nh=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,sh=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Be=r=>St(r)||Zf.has(r)||Qf.test(r),Ve=r=>Tt(r,"length",fh),St=r=>!!r&&!Number.isNaN(Number(r)),Un=r=>Tt(r,"number",St),Ot=r=>!!r&&Number.isInteger(Number(r)),oh=r=>r.endsWith("%")&&St(r.slice(0,-1)),te=r=>Dl.test(r),Ge=r=>eh.test(r),ah=new Set(["length","size","percentage"]),ih=r=>Tt(r,ah,Fl),lh=r=>Tt(r,"position",Fl),ch=new Set(["image","url"]),dh=r=>Tt(r,ch,mh),uh=r=>Tt(r,"",hh),Rt=()=>!0,Tt=(r,e,t)=>{const n=Dl.exec(r);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):t(n[2]):!1},fh=r=>th.test(r)&&!rh.test(r),Fl=()=>!1,hh=r=>nh.test(r),mh=r=>sh.test(r),gh=()=>{const r=ae("colors"),e=ae("spacing"),t=ae("blur"),n=ae("brightness"),s=ae("borderColor"),o=ae("borderRadius"),i=ae("borderSpacing"),l=ae("borderWidth"),d=ae("contrast"),u=ae("grayscale"),p=ae("hueRotate"),f=ae("invert"),x=ae("gap"),w=ae("gradientColorStops"),m=ae("gradientColorStopPositions"),h=ae("inset"),c=ae("margin"),g=ae("opacity"),y=ae("padding"),b=ae("saturate"),_=ae("scale"),v=ae("sepia"),C=ae("skew"),S=ae("space"),I=ae("translate"),E=()=>["auto","contain","none"],P=()=>["auto","hidden","clip","visible","scroll"],R=()=>["auto",te,e],j=()=>[te,e],W=()=>["",Be,Ve],D=()=>["auto",St,te],X=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],G=()=>["solid","dashed","dotted","double","none"],N=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],F=()=>["start","end","center","between","around","evenly","stretch"],z=()=>["","0",te],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],O=()=>[St,te];return{cacheSize:500,separator:":",theme:{colors:[Rt],spacing:[Be,Ve],blur:["none","",Ge,te],brightness:O(),borderColor:[r],borderRadius:["none","","full",Ge,te],borderSpacing:j(),borderWidth:W(),contrast:O(),grayscale:z(),hueRotate:O(),invert:z(),gap:j(),gradientColorStops:[r],gradientColorStopPositions:[oh,Ve],inset:R(),margin:R(),opacity:O(),padding:j(),saturate:O(),scale:O(),sepia:z(),skew:O(),space:j(),translate:j()},classGroups:{aspect:[{aspect:["auto","square","video",te]}],container:["container"],columns:[{columns:[Ge]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"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:[...X(),te]}],overflow:[{overflow:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:E()}],"overscroll-x":[{"overscroll-x":E()}],"overscroll-y":[{"overscroll-y":E()}],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",Ot,te]}],basis:[{basis:R()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",te]}],grow:[{grow:z()}],shrink:[{shrink:z()}],order:[{order:["first","last","none",Ot,te]}],"grid-cols":[{"grid-cols":[Rt]}],"col-start-end":[{col:["auto",{span:["full",Ot,te]},te]}],"col-start":[{"col-start":D()}],"col-end":[{"col-end":D()}],"grid-rows":[{"grid-rows":[Rt]}],"row-start-end":[{row:["auto",{span:[Ot,te]},te]}],"row-start":[{"row-start":D()}],"row-end":[{"row-end":D()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",te]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",te]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...F()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...F(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...F(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[c]}],mx:[{mx:[c]}],my:[{my:[c]}],ms:[{ms:[c]}],me:[{me:[c]}],mt:[{mt:[c]}],mr:[{mr:[c]}],mb:[{mb:[c]}],ml:[{ml:[c]}],"space-x":[{"space-x":[S]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[S]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",te,e]}],"min-w":[{"min-w":[te,e,"min","max","fit"]}],"max-w":[{"max-w":[te,e,"none","full","min","max","fit","prose",{screen:[Ge]},Ge]}],h:[{h:[te,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[te,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[te,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[te,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Ge,Ve]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Un]}],"font-family":[{font:[Rt]}],"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",te]}],"line-clamp":[{"line-clamp":["none",St,Un]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Be,te]}],"list-image":[{"list-image":["none",te]}],"list-style-type":[{list:["none","disc","decimal",te]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[r]}],"placeholder-opacity":[{"placeholder-opacity":[g]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[r]}],"text-opacity":[{"text-opacity":[g]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...G(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Be,Ve]}],"underline-offset":[{"underline-offset":["auto",Be,te]}],"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:j()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",te]}],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",te]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[g]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...X(),lh]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",ih]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},dh]}],"bg-color":[{bg:[r]}],"gradient-from-pos":[{from:[m]}],"gradient-via-pos":[{via:[m]}],"gradient-to-pos":[{to:[m]}],"gradient-from":[{from:[w]}],"gradient-via":[{via:[w]}],"gradient-to":[{to:[w]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[g]}],"border-style":[{border:[...G(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[g]}],"divide-style":[{divide:G()}],"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:["",...G()]}],"outline-offset":[{"outline-offset":[Be,te]}],"outline-w":[{outline:[Be,Ve]}],"outline-color":[{outline:[r]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[r]}],"ring-opacity":[{"ring-opacity":[g]}],"ring-offset-w":[{"ring-offset":[Be,Ve]}],"ring-offset-color":[{"ring-offset":[r]}],shadow:[{shadow:["","inner","none",Ge,uh]}],"shadow-color":[{shadow:[Rt]}],opacity:[{opacity:[g]}],"mix-blend":[{"mix-blend":[...N(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":N()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[n]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",Ge,te]}],grayscale:[{grayscale:[u]}],"hue-rotate":[{"hue-rotate":[p]}],invert:[{invert:[f]}],saturate:[{saturate:[b]}],sepia:[{sepia:[v]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[t]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[d]}],"backdrop-grayscale":[{"backdrop-grayscale":[u]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[p]}],"backdrop-invert":[{"backdrop-invert":[f]}],"backdrop-opacity":[{"backdrop-opacity":[g]}],"backdrop-saturate":[{"backdrop-saturate":[b]}],"backdrop-sepia":[{"backdrop-sepia":[v]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[i]}],"border-spacing-x":[{"border-spacing-x":[i]}],"border-spacing-y":[{"border-spacing-y":[i]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",te]}],duration:[{duration:O()}],ease:[{ease:["linear","in","out","in-out",te]}],delay:[{delay:O()}],animate:[{animate:["none","spin","ping","pulse","bounce",te]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[_]}],"scale-x":[{"scale-x":[_]}],"scale-y":[{"scale-y":[_]}],rotate:[{rotate:[Ot,te]}],"translate-x":[{"translate-x":[I]}],"translate-y":[{"translate-y":[I]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",te]}],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",te]}],"caret-color":[{caret:[r]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":j()}],"scroll-mx":[{"scroll-mx":j()}],"scroll-my":[{"scroll-my":j()}],"scroll-ms":[{"scroll-ms":j()}],"scroll-me":[{"scroll-me":j()}],"scroll-mt":[{"scroll-mt":j()}],"scroll-mr":[{"scroll-mr":j()}],"scroll-mb":[{"scroll-mb":j()}],"scroll-ml":[{"scroll-ml":j()}],"scroll-p":[{"scroll-p":j()}],"scroll-px":[{"scroll-px":j()}],"scroll-py":[{"scroll-py":j()}],"scroll-ps":[{"scroll-ps":j()}],"scroll-pe":[{"scroll-pe":j()}],"scroll-pt":[{"scroll-pt":j()}],"scroll-pr":[{"scroll-pr":j()}],"scroll-pb":[{"scroll-pb":j()}],"scroll-pl":[{"scroll-pl":j()}],"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",te]}],fill:[{fill:[r,"none"]}],"stroke-w":[{stroke:[Be,Ve,Un]}],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"]}}},ph=Yf(gh);let Cr;const xh=new Uint8Array(16);function yh(){if(!Cr&&(Cr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Cr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Cr(xh)}const pe=[];for(let r=0;r<256;++r)pe.push((r+256).toString(16).slice(1));function bh(r,e=0){return pe[r[e+0]]+pe[r[e+1]]+pe[r[e+2]]+pe[r[e+3]]+"-"+pe[r[e+4]]+pe[r[e+5]]+"-"+pe[r[e+6]]+pe[r[e+7]]+"-"+pe[r[e+8]]+pe[r[e+9]]+"-"+pe[r[e+10]]+pe[r[e+11]]+pe[r[e+12]]+pe[r[e+13]]+pe[r[e+14]]+pe[r[e+15]]}const wh=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ya={randomUUID:wh};function vh(r,e,t){if(ya.randomUUID&&!r)return ya.randomUUID();r=r||{};const n=r.random||(r.rng||yh)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,bh(n)}const Ul=6048e5,_h=864e5,jr=43200,ba=1440,wa=Symbol.for("constructDateFrom");function He(r,e){return typeof r=="function"?r(e):r&&typeof r=="object"&&wa in r?r[wa](e):r instanceof Date?new r.constructor(e):new Date(e)}function ge(r,e){return He(e||r,r)}let Sh={};function ur(){return Sh}function Qt(r,e){var l,d,u,p;const t=ur(),n=(e==null?void 0:e.weekStartsOn)??((d=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:d.weekStartsOn)??t.weekStartsOn??((p=(u=t.locale)==null?void 0:u.options)==null?void 0:p.weekStartsOn)??0,s=ge(r,e==null?void 0:e.in),o=s.getDay(),i=(o<n?7:0)+o-n;return s.setDate(s.getDate()-i),s.setHours(0,0,0,0),s}function Jr(r,e){return Qt(r,{...e,weekStartsOn:1})}function Bl(r,e){const t=ge(r,e==null?void 0:e.in),n=t.getFullYear(),s=He(t,0);s.setFullYear(n+1,0,4),s.setHours(0,0,0,0);const o=Jr(s),i=He(t,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=Jr(i);return t.getTime()>=o.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function Vr(r){const e=ge(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 xn(r,...e){const t=He.bind(null,r||e.find(n=>typeof n=="object"));return e.map(t)}function va(r,e){const t=ge(r,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function Ch(r,e,t){const[n,s]=xn(t==null?void 0:t.in,r,e),o=va(n),i=va(s),l=+o-Vr(o),d=+i-Vr(i);return Math.round((l-d)/_h)}function jh(r,e){const t=Bl(r,e),n=He(r,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),Jr(n)}function $r(r,e){const t=+ge(r)-+ge(e);return t<0?-1:t>0?1:t}function Ah(r){return He(r,Date.now())}function kh(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function Nh(r){return!(!kh(r)&&typeof r!="number"||isNaN(+ge(r)))}function Mh(r,e,t){const[n,s]=xn(t==null?void 0:t.in,r,e),o=n.getFullYear()-s.getFullYear(),i=n.getMonth()-s.getMonth();return o*12+i}function Eh(r){return e=>{const n=(r?Math[r]:Math.trunc)(e);return n===0?0:n}}function Ih(r,e){return+ge(r)-+ge(e)}function Th(r,e){const t=ge(r,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Ph(r,e){const t=ge(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 Oh(r,e){const t=ge(r,e==null?void 0:e.in);return+Th(t,e)==+Ph(t,e)}function Rh(r,e,t){const[n,s,o]=xn(t==null?void 0:t.in,r,r,e),i=$r(s,o),l=Math.abs(Mh(s,o));if(l<1)return 0;s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-i*l);let d=$r(s,o)===-i;Oh(n)&&l===1&&$r(n,o)===1&&(d=!1);const u=i*(l-+d);return u===0?0:u}function $h(r,e,t){const n=Ih(r,e)/1e3;return Eh(t==null?void 0:t.roundingMethod)(n)}function Lh(r,e){const t=ge(r,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}const Dh={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"}},Fh=(r,e,t)=>{let n;const s=Dh[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 Bn(r){return(e={})=>{const t=e.width?String(e.width):r.defaultWidth;return r.formats[t]||r.formats[r.defaultWidth]}}const Uh={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Bh={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Wh={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Hh={date:Bn({formats:Uh,defaultWidth:"full"}),time:Bn({formats:Bh,defaultWidth:"full"}),dateTime:Bn({formats:Wh,defaultWidth:"full"})},qh={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},zh=(r,e,t,n)=>qh[r];function $t(r){return(e,t)=>{const n=t!=null&&t.context?String(t.context):"standalone";let s;if(n==="formatting"&&r.formattingValues){const i=r.defaultFormattingWidth||r.defaultWidth,l=t!=null&&t.width?String(t.width):i;s=r.formattingValues[l]||r.formattingValues[i]}else{const i=r.defaultWidth,l=t!=null&&t.width?String(t.width):r.defaultWidth;s=r.values[l]||r.values[i]}const o=r.argumentCallback?r.argumentCallback(e):e;return s[o]}}const Jh={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Vh={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Gh={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"]},Xh={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"]},Kh={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"}},Yh={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"}},Qh=(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"},Zh={ordinalNumber:Qh,era:$t({values:Jh,defaultWidth:"wide"}),quarter:$t({values:Vh,defaultWidth:"wide",argumentCallback:r=>r-1}),month:$t({values:Gh,defaultWidth:"wide"}),day:$t({values:Xh,defaultWidth:"wide"}),dayPeriod:$t({values:Kh,defaultWidth:"wide",formattingValues:Yh,defaultFormattingWidth:"wide"})};function Lt(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 i=o[0],l=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],d=Array.isArray(l)?tm(l,f=>f.test(i)):em(l,f=>f.test(i));let u;u=r.valueCallback?r.valueCallback(d):d,u=t.valueCallback?t.valueCallback(u):u;const p=e.slice(i.length);return{value:u,rest:p}}}function em(r,e){for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&e(r[t]))return t}function tm(r,e){for(let t=0;t<r.length;t++)if(e(r[t]))return t}function rm(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 i=r.valueCallback?r.valueCallback(o[0]):o[0];i=t.valueCallback?t.valueCallback(i):i;const l=e.slice(s.length);return{value:i,rest:l}}}const nm=/^(\d+)(th|st|nd|rd)?/i,sm=/\d+/i,om={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},am={any:[/^b/i,/^(a|c)/i]},im={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},lm={any:[/1/i,/2/i,/3/i,/4/i]},cm={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},dm={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]},um={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},fm={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]},hm={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},mm={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}},gm={ordinalNumber:rm({matchPattern:nm,parsePattern:sm,valueCallback:r=>parseInt(r,10)}),era:Lt({matchPatterns:om,defaultMatchWidth:"wide",parsePatterns:am,defaultParseWidth:"any"}),quarter:Lt({matchPatterns:im,defaultMatchWidth:"wide",parsePatterns:lm,defaultParseWidth:"any",valueCallback:r=>r+1}),month:Lt({matchPatterns:cm,defaultMatchWidth:"wide",parsePatterns:dm,defaultParseWidth:"any"}),day:Lt({matchPatterns:um,defaultMatchWidth:"wide",parsePatterns:fm,defaultParseWidth:"any"}),dayPeriod:Lt({matchPatterns:hm,defaultMatchWidth:"any",parsePatterns:mm,defaultParseWidth:"any"})},Wl={code:"en-US",formatDistance:Fh,formatLong:Hh,formatRelative:zh,localize:Zh,match:gm,options:{weekStartsOn:0,firstWeekContainsDate:1}};function pm(r,e){const t=ge(r,e==null?void 0:e.in);return Ch(t,Lh(t))+1}function xm(r,e){const t=ge(r,e==null?void 0:e.in),n=+Jr(t)-+jh(t);return Math.round(n/Ul)+1}function Hl(r,e){var p,f,x,w;const t=ge(r,e==null?void 0:e.in),n=t.getFullYear(),s=ur(),o=(e==null?void 0:e.firstWeekContainsDate)??((f=(p=e==null?void 0:e.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??s.firstWeekContainsDate??((w=(x=s.locale)==null?void 0:x.options)==null?void 0:w.firstWeekContainsDate)??1,i=He((e==null?void 0:e.in)||r,0);i.setFullYear(n+1,0,o),i.setHours(0,0,0,0);const l=Qt(i,e),d=He((e==null?void 0:e.in)||r,0);d.setFullYear(n,0,o),d.setHours(0,0,0,0);const u=Qt(d,e);return+t>=+l?n+1:+t>=+u?n:n-1}function ym(r,e){var l,d,u,p;const t=ur(),n=(e==null?void 0:e.firstWeekContainsDate)??((d=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:d.firstWeekContainsDate)??t.firstWeekContainsDate??((p=(u=t.locale)==null?void 0:u.options)==null?void 0:p.firstWeekContainsDate)??1,s=Hl(r,e),o=He((e==null?void 0:e.in)||r,0);return o.setFullYear(s,0,n),o.setHours(0,0,0,0),Qt(o,e)}function bm(r,e){const t=ge(r,e==null?void 0:e.in),n=+Qt(t,e)-+ym(t,e);return Math.round(n/Ul)+1}function se(r,e){const t=r<0?"-":"",n=Math.abs(r).toString().padStart(e,"0");return t+n}const Xe={y(r,e){const t=r.getFullYear(),n=t>0?t:1-t;return se(e==="yy"?n%100:n,e.length)},M(r,e){const t=r.getMonth();return e==="M"?String(t+1):se(t+1,2)},d(r,e){return se(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 se(r.getHours()%12||12,e.length)},H(r,e){return se(r.getHours(),e.length)},m(r,e){return se(r.getMinutes(),e.length)},s(r,e){return se(r.getSeconds(),e.length)},S(r,e){const t=e.length,n=r.getMilliseconds(),s=Math.trunc(n*Math.pow(10,t-3));return se(s,e.length)}},xt={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},_a={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 Xe.y(r,e)},Y:function(r,e,t,n){const s=Hl(r,n),o=s>0?s:1-s;if(e==="YY"){const i=o%100;return se(i,2)}return e==="Yo"?t.ordinalNumber(o,{unit:"year"}):se(o,e.length)},R:function(r,e){const t=Bl(r);return se(t,e.length)},u:function(r,e){const t=r.getFullYear();return se(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 se(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 se(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 Xe.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 se(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=bm(r,n);return e==="wo"?t.ordinalNumber(s,{unit:"week"}):se(s,e.length)},I:function(r,e,t){const n=xm(r);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):se(n,e.length)},d:function(r,e,t){return e==="do"?t.ordinalNumber(r.getDate(),{unit:"date"}):Xe.d(r,e)},D:function(r,e,t){const n=pm(r);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):se(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 se(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 se(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 se(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=xt.noon:n===0?s=xt.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=xt.evening:n>=12?s=xt.afternoon:n>=4?s=xt.morning:s=xt.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 Xe.h(r,e)},H:function(r,e,t){return e==="Ho"?t.ordinalNumber(r.getHours(),{unit:"hour"}):Xe.H(r,e)},K:function(r,e,t){const n=r.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):se(n,e.length)},k:function(r,e,t){let n=r.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):se(n,e.length)},m:function(r,e,t){return e==="mo"?t.ordinalNumber(r.getMinutes(),{unit:"minute"}):Xe.m(r,e)},s:function(r,e,t){return e==="so"?t.ordinalNumber(r.getSeconds(),{unit:"second"}):Xe.s(r,e)},S:function(r,e){return Xe.S(r,e)},X:function(r,e,t){const n=r.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return Ca(n);case"XXXX":case"XX":return tt(n);case"XXXXX":case"XXX":default:return tt(n,":")}},x:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"x":return Ca(n);case"xxxx":case"xx":return tt(n);case"xxxxx":case"xxx":default:return tt(n,":")}},O:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Sa(n,":");case"OOOO":default:return"GMT"+tt(n,":")}},z:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Sa(n,":");case"zzzz":default:return"GMT"+tt(n,":")}},t:function(r,e,t){const n=Math.trunc(+r/1e3);return se(n,e.length)},T:function(r,e,t){return se(+r,e.length)}};function Sa(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+se(o,2)}function Ca(r,e){return r%60===0?(r>0?"-":"+")+se(Math.abs(r)/60,2):tt(r,e)}function tt(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=se(Math.trunc(n/60),2),o=se(n%60,2);return t+s+e+o}const ja=(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"})}},ql=(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"})}},wm=(r,e)=>{const t=r.match(/(P+)(p+)?/)||[],n=t[1],s=t[2];if(!s)return ja(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}}",ja(n,e)).replace("{{time}}",ql(s,e))},vm={p:ql,P:wm},_m=/^D+$/,Sm=/^Y+$/,Cm=["D","DD","YY","YYYY"];function jm(r){return _m.test(r)}function Am(r){return Sm.test(r)}function km(r,e,t){const n=Nm(r,e,t);if(console.warn(n),Cm.includes(r))throw new RangeError(n)}function Nm(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 Mm=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Em=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Im=/^'([^]*?)'?$/,Tm=/''/g,Pm=/[a-zA-Z]/;function io(r,e,t){var p,f,x,w;const n=ur(),s=n.locale??Wl,o=n.firstWeekContainsDate??((f=(p=n.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,i=n.weekStartsOn??((w=(x=n.locale)==null?void 0:x.options)==null?void 0:w.weekStartsOn)??0,l=ge(r,t==null?void 0:t.in);if(!Nh(l))throw new RangeError("Invalid time value");let d=e.match(Em).map(m=>{const h=m[0];if(h==="p"||h==="P"){const c=vm[h];return c(m,s.formatLong)}return m}).join("").match(Mm).map(m=>{if(m==="''")return{isToken:!1,value:"'"};const h=m[0];if(h==="'")return{isToken:!1,value:Om(m)};if(_a[h])return{isToken:!0,value:m};if(h.match(Pm))throw new RangeError("Format string contains an unescaped latin alphabet character `"+h+"`");return{isToken:!1,value:m}});s.localize.preprocessor&&(d=s.localize.preprocessor(l,d));const u={firstWeekContainsDate:o,weekStartsOn:i,locale:s};return d.map(m=>{if(!m.isToken)return m.value;const h=m.value;(Am(h)||jm(h))&&km(h,e,String(r));const c=_a[h[0]];return c(l,h,s.localize,u)}).join("")}function Om(r){const e=r.match(Im);return e?e[1].replace(Tm,"'"):r}function Rm(r,e,t){const n=ur(),s=(t==null?void 0:t.locale)??n.locale??Wl,o=2520,i=$r(r,e);if(isNaN(i))throw new RangeError("Invalid time value");const l=Object.assign({},t,{addSuffix:t==null?void 0:t.addSuffix,comparison:i}),[d,u]=xn(t==null?void 0:t.in,...i>0?[e,r]:[r,e]),p=$h(u,d),f=(Vr(u)-Vr(d))/1e3,x=Math.round((p-f)/60);let w;if(x<2)return t!=null&&t.includeSeconds?p<5?s.formatDistance("lessThanXSeconds",5,l):p<10?s.formatDistance("lessThanXSeconds",10,l):p<20?s.formatDistance("lessThanXSeconds",20,l):p<40?s.formatDistance("halfAMinute",0,l):p<60?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",1,l):x===0?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",x,l);if(x<45)return s.formatDistance("xMinutes",x,l);if(x<90)return s.formatDistance("aboutXHours",1,l);if(x<ba){const m=Math.round(x/60);return s.formatDistance("aboutXHours",m,l)}else{if(x<o)return s.formatDistance("xDays",1,l);if(x<jr){const m=Math.round(x/ba);return s.formatDistance("xDays",m,l)}else if(x<jr*2)return w=Math.round(x/jr),s.formatDistance("aboutXMonths",w,l)}if(w=Rh(u,d),w<12){const m=Math.round(x/jr);return s.formatDistance("xMonths",m,l)}else{const m=w%12,h=Math.trunc(w/12);return m<3?s.formatDistance("aboutXYears",h,l):m<9?s.formatDistance("overXYears",h,l):s.formatDistance("almostXYears",h+1,l)}}function $m(r,e){return Rm(r,Ah(r),e)}function Me(...r){return ph(Df(r))}function Lm(){return vh()}function zl(r){if(!r)return"--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"--:--":io(e,"HH:mm")}function Dm(r){if(!r)return"时间未知";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"时间未知":$m(e,{addSuffix:!0})}function Fm(r){if(!r)return"----/--/--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/--":io(e,"yyyy-MM-dd")}function Um(r){if(!r)return"----/--/-- --:--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/-- --:--:--":io(e,"yyyy-MM-dd HH:mm:ss")}function Bm(r,e){return r.length<=e?r:r.slice(0,e)+"..."}function Wm(r){return r.replace(/<[^>]*>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').trim()}function Hm(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function qm(r){try{return new URL(r),!0}catch{return!1}}function gs(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=>gs(e));if(typeof r=="object"){const e={};for(const t in r)r.hasOwnProperty(t)&&(e[t]=gs(r[t]));return e}return r}function zm(r,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function Jm(r,e){let t;return(...n)=>{t||(r(...n),t=!0,setTimeout(()=>t=!1,e))}}function Jl(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 Vl(r){return r.slice((r.lastIndexOf(".")-1>>>0)+2)}function Vm(r){const e=["jpg","jpeg","png","gif","bmp","webp","svg"],t=Vl(r).toLowerCase();return e.includes(t)}function Gm(){const r=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6366f1"];return r[Math.floor(Math.random()*r.length)]}async function Xm(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){return console.error("Failed to copy text to clipboard:",e),!1}}function Km(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 Ym(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Qm(){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 Zm extends Error{constructor(t,n="UNKNOWN_ERROR",s=500){super(t);J(this,"code");J(this,"statusCode");this.name="AppError",this.code=n,this.statusCode=s}}async function eg(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(i=>setTimeout(i,t*s))}throw n}const tg={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)}}},Gl=({attachment:r,customRenderer:e,className:t})=>{if(e)return a.jsx("div",{children:e(r)});const n=r.type==="image",s=r.type==="audio",o=()=>n?a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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?a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}):a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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 a.jsxs("div",{className:Me("inline-flex items-center gap-2 p-2 bg-muted rounded-lg border max-w-sm",t),children:[a.jsx("div",{className:"flex-shrink-0 text-muted-foreground",children:o()}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium truncate",children:r.name}),a.jsx("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:Jl(r.size)})]}),r.mimeType&&a.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:r.mimeType})]}),a.jsx("div",{className:"flex-shrink-0",children:n?a.jsx("button",{onClick:()=>window.open(r.url,"_blank"),className:"p-1 hover:bg-background rounded transition-colors",title:"View image",children:a.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),a.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"})]})}):a.jsx("a",{href:r.url,download:r.name,className:"p-1 hover:bg-background rounded transition-colors inline-block",title:"Download file",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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&&a.jsx("div",{className:"w-full mt-2",children:a.jsx("img",{src:r.url,alt:r.name,className:"max-w-full h-auto rounded border",style:{maxHeight:"200px"},loading:"lazy"})}),s&&a.jsx("div",{className:"w-full mt-2",children:a.jsxs("audio",{controls:!0,className:"w-full",preload:"metadata",children:[a.jsx("source",{src:r.url,type:r.mimeType}),"Your browser does not support the audio element."]})})]})},ps=({toolCall:r,allMessages:e=[],className:t})=>{const[n,s]=T.useState(!1);console.log("🔍 ToolCallRenderer - 开始查找工具结果消息"),console.log("🔍 当前工具调用ID:",r.id),console.log("🔍 所有消息数量:",e.length),console.log("🔍 所有消息:",e.map(v=>{var C;return{id:v.id,role:v.role,tool_call_id:v.tool_call_id||v.toolCallId,metadata:v.metadata,content:((C=v.content)==null?void 0:C.substring(0,100))+"..."}}));const o=e.find(v=>{var I,E;if(v.role!=="tool")return!1;const C=v.tool_call_id||v.toolCallId,S=((I=v.metadata)==null?void 0:I.tool_call_id)||((E=v.metadata)==null?void 0:E.toolCallId);return C===r.id||S===r.id});console.log("🔍 找到的工具结果消息:",o),console.log("🎨 ToolCallRenderer - 工具调用:",r.id,"结果:",r.result,"工具消息:",o==null?void 0:o.content);const i=r.result||(o==null?void 0:o.content),l=!!r.error,d=!!i,p=(()=>{if(!r.arguments)return{};if(typeof r.arguments=="object")return r.arguments;if(typeof r.arguments=="string")try{return JSON.parse(r.arguments)}catch(v){return console.warn("Failed to parse tool arguments:",r.arguments,v),{}}return{}})(),f=p&&Object.keys(p).length>0,x=(v,C="")=>{const S={};for(const I in v)if(v.hasOwnProperty(I)){const E=v[I],P=C?`${C}.${I}`:I;E!==null&&typeof E=="object"&&!Array.isArray(E)?Object.assign(S,x(E,P)):S[P]=E}return S},m=(()=>{if(!f)return"";const v=x(p),C=Object.keys(v);let S=`| 参数 | 值 |
96
+ <pre><code>${T}</code></pre>
97
+ </div>`)}}p=p.replace(/^### (.*$)/gm,"<h3>$1</h3>"),p=p.replace(/^## (.*$)/gm,"<h2>$1</h2>"),p=p.replace(/^# (.*$)/gm,"<h1>$1</h1>"),p=p.replace(/^\* (.*$)/gm,"<li>• $1</li>"),p=p.replace(/^\d+\. (.*$)/gm,"<li>$1</li>"),p=p.replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>"),p=p.replace(/\*(.*?)\*/g,"<em>$1</em>"),p=p.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),p=p.replace(/^> (.*$)/gm,"<blockquote>$1</blockquote>"),p=p.replace(/^---$/gm,"<hr>");const x=[];let y=0;return p=p.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g,v=>{const S=`__PROTECTED_HTML_${y++}__`;return x.push(v),S}),p=p.replace(/<[^>]+>/g,v=>{const S=`__PROTECTED_HTML_${y++}__`;return x.push(v),S}),p=p.replace(/\n\n/g,"</p><p>"),p=p.replace(/\n/g,"<br>"),x.forEach((v,S)=>{p=p.replace(`__PROTECTED_HTML_${S}__`,v)}),p&&!p.startsWith("<")&&(p=`<p>${p}</p>`),p},[e,s,n]),f=(h,p)=>h.replace(/</g,"&lt;").replace(/>/g,"&gt;"),g=O.useCallback(h=>{const w=h.target.closest("button");if(w){if(w.classList.contains("copy-btn")){const m=decodeURIComponent(w.getAttribute("data-code")||"");i(m)}else if(w.classList.contains("apply-btn")){const m=decodeURIComponent(w.getAttribute("data-code")||""),u=w.getAttribute("data-language")||"text";n==null||n(m,u)}else if(w.classList.contains("expand-btn")){const m=w.getAttribute("data-block-id");m&&l(m)}}},[i,n,l]);return a.jsxs("div",{className:`markdown-renderer ${t}`,onClick:g,children:[a.jsx("div",{dangerouslySetInnerHTML:{__html:d(r)}}),e&&a.jsx("span",{className:"streaming-cursor"})]})};function Il(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=Il(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function $f(){for(var r,e,t=0,n="",s=arguments.length;t<s;t++)(r=arguments[t])&&(e=Il(r))&&(n&&(n+=" "),n+=e);return n}const no="-",Lf=r=>{const e=Ff(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:i=>{const l=i.split(no);return l[0]===""&&l.length!==1&&l.shift(),Pl(l,e)||Df(i)},getConflictingClassGroupIds:(i,l)=>{const d=t[i]||[];return l&&n[i]?[...d,...n[i]]:d}}},Pl=(r,e)=>{var i;if(r.length===0)return e.classGroupId;const t=r[0],n=e.nextPart.get(t),s=n?Pl(r.slice(1),n):void 0;if(s)return s;if(e.validators.length===0)return;const o=r.join(no);return(i=e.validators.find(({validator:l})=>l(o)))==null?void 0:i.classGroupId},ha=/^\[(.+)\]$/,Df=r=>{if(ha.test(r)){const e=ha.exec(r)[1],t=e==null?void 0:e.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},Ff=r=>{const{theme:e,prefix:t}=r,n={nextPart:new Map,validators:[]};return Bf(Object.entries(r.classGroups),t).forEach(([o,i])=>{us(i,n,o,e)}),n},us=(r,e,t,n)=>{r.forEach(s=>{if(typeof s=="string"){const o=s===""?e:ma(e,s);o.classGroupId=t;return}if(typeof s=="function"){if(Uf(s)){us(s(n),e,t,n);return}e.validators.push({validator:s,classGroupId:t});return}Object.entries(s).forEach(([o,i])=>{us(i,ma(e,o),t,n)})})},ma=(r,e)=>{let t=r;return e.split(no).forEach(n=>{t.nextPart.has(n)||t.nextPart.set(n,{nextPart:new Map,validators:[]}),t=t.nextPart.get(n)}),t},Uf=r=>r.isThemeGetter,Bf=(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(([i,l])=>[e+i,l])):o);return[t,s]}):r,Wf=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,n=new Map;const s=(o,i)=>{t.set(o,i),e++,e>r&&(e=0,n=t,t=new Map)};return{get(o){let i=t.get(o);if(i!==void 0)return i;if((i=n.get(o))!==void 0)return s(o,i),i},set(o,i){t.has(o)?t.set(o,i):s(o,i)}}},Tl="!",Hf=r=>{const{separator:e,experimentalParseClassName:t}=r,n=e.length===1,s=e[0],o=e.length,i=l=>{const d=[];let f=0,g=0,h;for(let c=0;c<l.length;c++){let b=l[c];if(f===0){if(b===s&&(n||l.slice(c,c+o)===e)){d.push(l.slice(g,c)),g=c+o;continue}if(b==="/"){h=c;continue}}b==="["?f++:b==="]"&&f--}const p=d.length===0?l:l.substring(g),w=p.startsWith(Tl),m=w?p.substring(1):p,u=h&&h>g?h-g:void 0;return{modifiers:d,hasImportantModifier:w,baseClassName:m,maybePostfixModifierPosition:u}};return t?l=>t({className:l,parseClassName:i}):i},qf=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},zf=r=>({cache:Wf(r.cacheSize),parseClassName:Hf(r),...Lf(r)}),Jf=/\s+/,Vf=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:s}=e,o=[],i=r.trim().split(Jf);let l="";for(let d=i.length-1;d>=0;d-=1){const f=i[d],{modifiers:g,hasImportantModifier:h,baseClassName:p,maybePostfixModifierPosition:w}=t(f);let m=!!w,u=n(m?p.substring(0,w):p);if(!u){if(!m){l=f+(l.length>0?" "+l:l);continue}if(u=n(p),!u){l=f+(l.length>0?" "+l:l);continue}m=!1}const c=qf(g).join(":"),b=h?c+Tl:c,x=b+u;if(o.includes(x))continue;o.push(x);const y=s(u,m);for(let v=0;v<y.length;++v){const S=y[v];o.push(b+S)}l=f+(l.length>0?" "+l:l)}return l};function Gf(){let r=0,e,t,n="";for(;r<arguments.length;)(e=arguments[r++])&&(t=Ol(e))&&(n&&(n+=" "),n+=t);return n}const Ol=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=Ol(r[n]))&&(t&&(t+=" "),t+=e);return t};function Xf(r,...e){let t,n,s,o=i;function i(d){const f=e.reduce((g,h)=>h(g),r());return t=zf(f),n=t.cache.get,s=t.cache.set,o=l,l(d)}function l(d){const f=n(d);if(f)return f;const g=Vf(d,t);return s(d,g),g}return function(){return o(Gf.apply(null,arguments))}}const ne=r=>{const e=t=>t[r]||[];return e.isThemeGetter=!0,e},Rl=/^\[(?:([a-z-]+):)?(.+)\]$/i,Kf=/^\d+\/\d+$/,Yf=new Set(["px","full","screen"]),Qf=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Zf=/\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$/,eh=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,th=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,rh=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Fe=r=>vt(r)||Yf.has(r)||Kf.test(r),ze=r=>Et(r,"length",dh),vt=r=>!!r&&!Number.isNaN(Number(r)),Ln=r=>Et(r,"number",vt),Pt=r=>!!r&&Number.isInteger(Number(r)),nh=r=>r.endsWith("%")&&vt(r.slice(0,-1)),Y=r=>Rl.test(r),Je=r=>Qf.test(r),sh=new Set(["length","size","percentage"]),oh=r=>Et(r,sh,$l),ah=r=>Et(r,"position",$l),ih=new Set(["image","url"]),lh=r=>Et(r,ih,fh),ch=r=>Et(r,"",uh),Tt=()=>!0,Et=(r,e,t)=>{const n=Rl.exec(r);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):t(n[2]):!1},dh=r=>Zf.test(r)&&!eh.test(r),$l=()=>!1,uh=r=>th.test(r),fh=r=>rh.test(r),hh=()=>{const r=ne("colors"),e=ne("spacing"),t=ne("blur"),n=ne("brightness"),s=ne("borderColor"),o=ne("borderRadius"),i=ne("borderSpacing"),l=ne("borderWidth"),d=ne("contrast"),f=ne("grayscale"),g=ne("hueRotate"),h=ne("invert"),p=ne("gap"),w=ne("gradientColorStops"),m=ne("gradientColorStopPositions"),u=ne("inset"),c=ne("margin"),b=ne("opacity"),x=ne("padding"),y=ne("saturate"),v=ne("scale"),S=ne("sepia"),C=ne("skew"),_=ne("space"),I=ne("translate"),T=()=>["auto","contain","none"],$=()=>["auto","hidden","clip","visible","scroll"],F=()=>["auto",Y,e],k=()=>[Y,e],U=()=>["",Fe,ze],H=()=>["auto",vt,Y],Z=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],P=()=>["solid","dashed","dotted","double","none"],N=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],R=()=>["start","end","center","between","around","evenly","stretch"],B=()=>["","0",Y],q=()=>["auto","avoid","all","avoid-page","page","left","right","column"],D=()=>[vt,Y];return{cacheSize:500,separator:":",theme:{colors:[Tt],spacing:[Fe,ze],blur:["none","",Je,Y],brightness:D(),borderColor:[r],borderRadius:["none","","full",Je,Y],borderSpacing:k(),borderWidth:U(),contrast:D(),grayscale:B(),hueRotate:D(),invert:B(),gap:k(),gradientColorStops:[r],gradientColorStopPositions:[nh,ze],inset:F(),margin:F(),opacity:D(),padding:k(),saturate:D(),scale:D(),sepia:B(),skew:D(),space:k(),translate:k()},classGroups:{aspect:[{aspect:["auto","square","video",Y]}],container:["container"],columns:[{columns:[Je]}],"break-after":[{"break-after":q()}],"break-before":[{"break-before":q()}],"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:[...Z(),Y]}],overflow:[{overflow:$()}],"overflow-x":[{"overflow-x":$()}],"overflow-y":[{"overflow-y":$()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[u]}],"inset-x":[{"inset-x":[u]}],"inset-y":[{"inset-y":[u]}],start:[{start:[u]}],end:[{end:[u]}],top:[{top:[u]}],right:[{right:[u]}],bottom:[{bottom:[u]}],left:[{left:[u]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Pt,Y]}],basis:[{basis:F()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Y]}],grow:[{grow:B()}],shrink:[{shrink:B()}],order:[{order:["first","last","none",Pt,Y]}],"grid-cols":[{"grid-cols":[Tt]}],"col-start-end":[{col:["auto",{span:["full",Pt,Y]},Y]}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":[Tt]}],"row-start-end":[{row:["auto",{span:[Pt,Y]},Y]}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Y]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Y]}],gap:[{gap:[p]}],"gap-x":[{"gap-x":[p]}],"gap-y":[{"gap-y":[p]}],"justify-content":[{justify:["normal",...R()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...R(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...R(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[x]}],px:[{px:[x]}],py:[{py:[x]}],ps:[{ps:[x]}],pe:[{pe:[x]}],pt:[{pt:[x]}],pr:[{pr:[x]}],pb:[{pb:[x]}],pl:[{pl:[x]}],m:[{m:[c]}],mx:[{mx:[c]}],my:[{my:[c]}],ms:[{ms:[c]}],me:[{me:[c]}],mt:[{mt:[c]}],mr:[{mr:[c]}],mb:[{mb:[c]}],ml:[{ml:[c]}],"space-x":[{"space-x":[_]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[_]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Y,e]}],"min-w":[{"min-w":[Y,e,"min","max","fit"]}],"max-w":[{"max-w":[Y,e,"none","full","min","max","fit","prose",{screen:[Je]},Je]}],h:[{h:[Y,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Y,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Y,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Y,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Je,ze]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Ln]}],"font-family":[{font:[Tt]}],"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",Y]}],"line-clamp":[{"line-clamp":["none",vt,Ln]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Fe,Y]}],"list-image":[{"list-image":["none",Y]}],"list-style-type":[{list:["none","disc","decimal",Y]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[r]}],"placeholder-opacity":[{"placeholder-opacity":[b]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[r]}],"text-opacity":[{"text-opacity":[b]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...P(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Fe,ze]}],"underline-offset":[{"underline-offset":["auto",Fe,Y]}],"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:k()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Y]}],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",Y]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[b]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Z(),ah]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",oh]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},lh]}],"bg-color":[{bg:[r]}],"gradient-from-pos":[{from:[m]}],"gradient-via-pos":[{via:[m]}],"gradient-to-pos":[{to:[m]}],"gradient-from":[{from:[w]}],"gradient-via":[{via:[w]}],"gradient-to":[{to:[w]}],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:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[b]}],"border-style":[{border:[...P(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[b]}],"divide-style":[{divide:P()}],"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:["",...P()]}],"outline-offset":[{"outline-offset":[Fe,Y]}],"outline-w":[{outline:[Fe,ze]}],"outline-color":[{outline:[r]}],"ring-w":[{ring:U()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[r]}],"ring-opacity":[{"ring-opacity":[b]}],"ring-offset-w":[{"ring-offset":[Fe,ze]}],"ring-offset-color":[{"ring-offset":[r]}],shadow:[{shadow:["","inner","none",Je,ch]}],"shadow-color":[{shadow:[Tt]}],opacity:[{opacity:[b]}],"mix-blend":[{"mix-blend":[...N(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":N()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[n]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",Je,Y]}],grayscale:[{grayscale:[f]}],"hue-rotate":[{"hue-rotate":[g]}],invert:[{invert:[h]}],saturate:[{saturate:[y]}],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":[f]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[g]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[b]}],"backdrop-saturate":[{"backdrop-saturate":[y]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[i]}],"border-spacing-x":[{"border-spacing-x":[i]}],"border-spacing-y":[{"border-spacing-y":[i]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",Y]}],duration:[{duration:D()}],ease:[{ease:["linear","in","out","in-out",Y]}],delay:[{delay:D()}],animate:[{animate:["none","spin","ping","pulse","bounce",Y]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[v]}],"scale-x":[{"scale-x":[v]}],"scale-y":[{"scale-y":[v]}],rotate:[{rotate:[Pt,Y]}],"translate-x":[{"translate-x":[I]}],"translate-y":[{"translate-y":[I]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Y]}],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",Y]}],"caret-color":[{caret:[r]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":k()}],"scroll-mx":[{"scroll-mx":k()}],"scroll-my":[{"scroll-my":k()}],"scroll-ms":[{"scroll-ms":k()}],"scroll-me":[{"scroll-me":k()}],"scroll-mt":[{"scroll-mt":k()}],"scroll-mr":[{"scroll-mr":k()}],"scroll-mb":[{"scroll-mb":k()}],"scroll-ml":[{"scroll-ml":k()}],"scroll-p":[{"scroll-p":k()}],"scroll-px":[{"scroll-px":k()}],"scroll-py":[{"scroll-py":k()}],"scroll-ps":[{"scroll-ps":k()}],"scroll-pe":[{"scroll-pe":k()}],"scroll-pt":[{"scroll-pt":k()}],"scroll-pr":[{"scroll-pr":k()}],"scroll-pb":[{"scroll-pb":k()}],"scroll-pl":[{"scroll-pl":k()}],"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",Y]}],fill:[{fill:[r,"none"]}],"stroke-w":[{stroke:[Fe,ze,Ln]}],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"]}}},mh=Xf(hh);let Cr;const gh=new Uint8Array(16);function ph(){if(!Cr&&(Cr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Cr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Cr(gh)}const he=[];for(let r=0;r<256;++r)he.push((r+256).toString(16).slice(1));function xh(r,e=0){return he[r[e+0]]+he[r[e+1]]+he[r[e+2]]+he[r[e+3]]+"-"+he[r[e+4]]+he[r[e+5]]+"-"+he[r[e+6]]+he[r[e+7]]+"-"+he[r[e+8]]+he[r[e+9]]+"-"+he[r[e+10]]+he[r[e+11]]+he[r[e+12]]+he[r[e+13]]+he[r[e+14]]+he[r[e+15]]}const bh=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ga={randomUUID:bh};function yh(r,e,t){if(ga.randomUUID&&!r)return ga.randomUUID();r=r||{};const n=r.random||(r.rng||ph)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,xh(n)}const Ll=6048e5,wh=864e5,jr=43200,pa=1440,xa=Symbol.for("constructDateFrom");function Be(r,e){return typeof r=="function"?r(e):r&&typeof r=="object"&&xa in r?r[xa](e):r instanceof Date?new r.constructor(e):new Date(e)}function fe(r,e){return Be(e||r,r)}let vh={};function cr(){return vh}function Kt(r,e){var l,d,f,g;const t=cr(),n=(e==null?void 0:e.weekStartsOn)??((d=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:d.weekStartsOn)??t.weekStartsOn??((g=(f=t.locale)==null?void 0:f.options)==null?void 0:g.weekStartsOn)??0,s=fe(r,e==null?void 0:e.in),o=s.getDay(),i=(o<n?7:0)+o-n;return s.setDate(s.getDate()-i),s.setHours(0,0,0,0),s}function Jr(r,e){return Kt(r,{...e,weekStartsOn:1})}function Dl(r,e){const t=fe(r,e==null?void 0:e.in),n=t.getFullYear(),s=Be(t,0);s.setFullYear(n+1,0,4),s.setHours(0,0,0,0);const o=Jr(s),i=Be(t,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=Jr(i);return t.getTime()>=o.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function Vr(r){const e=fe(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 xn(r,...e){const t=Be.bind(null,r||e.find(n=>typeof n=="object"));return e.map(t)}function ba(r,e){const t=fe(r,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function _h(r,e,t){const[n,s]=xn(t==null?void 0:t.in,r,e),o=ba(n),i=ba(s),l=+o-Vr(o),d=+i-Vr(i);return Math.round((l-d)/wh)}function Sh(r,e){const t=Dl(r,e),n=Be(r,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),Jr(n)}function $r(r,e){const t=+fe(r)-+fe(e);return t<0?-1:t>0?1:t}function Ch(r){return Be(r,Date.now())}function jh(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function Ah(r){return!(!jh(r)&&typeof r!="number"||isNaN(+fe(r)))}function kh(r,e,t){const[n,s]=xn(t==null?void 0:t.in,r,e),o=n.getFullYear()-s.getFullYear(),i=n.getMonth()-s.getMonth();return o*12+i}function Nh(r){return e=>{const n=(r?Math[r]:Math.trunc)(e);return n===0?0:n}}function Mh(r,e){return+fe(r)-+fe(e)}function Eh(r,e){const t=fe(r,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Ih(r,e){const t=fe(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 Ph(r,e){const t=fe(r,e==null?void 0:e.in);return+Eh(t,e)==+Ih(t,e)}function Th(r,e,t){const[n,s,o]=xn(t==null?void 0:t.in,r,r,e),i=$r(s,o),l=Math.abs(kh(s,o));if(l<1)return 0;s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-i*l);let d=$r(s,o)===-i;Ph(n)&&l===1&&$r(n,o)===1&&(d=!1);const f=i*(l-+d);return f===0?0:f}function Oh(r,e,t){const n=Mh(r,e)/1e3;return Nh(t==null?void 0:t.roundingMethod)(n)}function Rh(r,e){const t=fe(r,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}const $h={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"}},Lh=(r,e,t)=>{let n;const s=$h[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 Dn(r){return(e={})=>{const t=e.width?String(e.width):r.defaultWidth;return r.formats[t]||r.formats[r.defaultWidth]}}const Dh={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Fh={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Uh={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Bh={date:Dn({formats:Dh,defaultWidth:"full"}),time:Dn({formats:Fh,defaultWidth:"full"}),dateTime:Dn({formats:Uh,defaultWidth:"full"})},Wh={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Hh=(r,e,t,n)=>Wh[r];function Ot(r){return(e,t)=>{const n=t!=null&&t.context?String(t.context):"standalone";let s;if(n==="formatting"&&r.formattingValues){const i=r.defaultFormattingWidth||r.defaultWidth,l=t!=null&&t.width?String(t.width):i;s=r.formattingValues[l]||r.formattingValues[i]}else{const i=r.defaultWidth,l=t!=null&&t.width?String(t.width):r.defaultWidth;s=r.values[l]||r.values[i]}const o=r.argumentCallback?r.argumentCallback(e):e;return s[o]}}const qh={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},zh={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Jh={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"]},Vh={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"]},Gh={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"}},Xh={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"}},Kh=(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"},Yh={ordinalNumber:Kh,era:Ot({values:qh,defaultWidth:"wide"}),quarter:Ot({values:zh,defaultWidth:"wide",argumentCallback:r=>r-1}),month:Ot({values:Jh,defaultWidth:"wide"}),day:Ot({values:Vh,defaultWidth:"wide"}),dayPeriod:Ot({values:Gh,defaultWidth:"wide",formattingValues:Xh,defaultFormattingWidth:"wide"})};function Rt(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 i=o[0],l=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],d=Array.isArray(l)?Zh(l,h=>h.test(i)):Qh(l,h=>h.test(i));let f;f=r.valueCallback?r.valueCallback(d):d,f=t.valueCallback?t.valueCallback(f):f;const g=e.slice(i.length);return{value:f,rest:g}}}function Qh(r,e){for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&e(r[t]))return t}function Zh(r,e){for(let t=0;t<r.length;t++)if(e(r[t]))return t}function em(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 i=r.valueCallback?r.valueCallback(o[0]):o[0];i=t.valueCallback?t.valueCallback(i):i;const l=e.slice(s.length);return{value:i,rest:l}}}const tm=/^(\d+)(th|st|nd|rd)?/i,rm=/\d+/i,nm={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},sm={any:[/^b/i,/^(a|c)/i]},om={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},am={any:[/1/i,/2/i,/3/i,/4/i]},im={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},lm={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]},cm={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},dm={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]},um={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},fm={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}},hm={ordinalNumber:em({matchPattern:tm,parsePattern:rm,valueCallback:r=>parseInt(r,10)}),era:Rt({matchPatterns:nm,defaultMatchWidth:"wide",parsePatterns:sm,defaultParseWidth:"any"}),quarter:Rt({matchPatterns:om,defaultMatchWidth:"wide",parsePatterns:am,defaultParseWidth:"any",valueCallback:r=>r+1}),month:Rt({matchPatterns:im,defaultMatchWidth:"wide",parsePatterns:lm,defaultParseWidth:"any"}),day:Rt({matchPatterns:cm,defaultMatchWidth:"wide",parsePatterns:dm,defaultParseWidth:"any"}),dayPeriod:Rt({matchPatterns:um,defaultMatchWidth:"any",parsePatterns:fm,defaultParseWidth:"any"})},Fl={code:"en-US",formatDistance:Lh,formatLong:Bh,formatRelative:Hh,localize:Yh,match:hm,options:{weekStartsOn:0,firstWeekContainsDate:1}};function mm(r,e){const t=fe(r,e==null?void 0:e.in);return _h(t,Rh(t))+1}function gm(r,e){const t=fe(r,e==null?void 0:e.in),n=+Jr(t)-+Sh(t);return Math.round(n/Ll)+1}function Ul(r,e){var g,h,p,w;const t=fe(r,e==null?void 0:e.in),n=t.getFullYear(),s=cr(),o=(e==null?void 0:e.firstWeekContainsDate)??((h=(g=e==null?void 0:e.locale)==null?void 0:g.options)==null?void 0:h.firstWeekContainsDate)??s.firstWeekContainsDate??((w=(p=s.locale)==null?void 0:p.options)==null?void 0:w.firstWeekContainsDate)??1,i=Be((e==null?void 0:e.in)||r,0);i.setFullYear(n+1,0,o),i.setHours(0,0,0,0);const l=Kt(i,e),d=Be((e==null?void 0:e.in)||r,0);d.setFullYear(n,0,o),d.setHours(0,0,0,0);const f=Kt(d,e);return+t>=+l?n+1:+t>=+f?n:n-1}function pm(r,e){var l,d,f,g;const t=cr(),n=(e==null?void 0:e.firstWeekContainsDate)??((d=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:d.firstWeekContainsDate)??t.firstWeekContainsDate??((g=(f=t.locale)==null?void 0:f.options)==null?void 0:g.firstWeekContainsDate)??1,s=Ul(r,e),o=Be((e==null?void 0:e.in)||r,0);return o.setFullYear(s,0,n),o.setHours(0,0,0,0),Kt(o,e)}function xm(r,e){const t=fe(r,e==null?void 0:e.in),n=+Kt(t,e)-+pm(t,e);return Math.round(n/Ll)+1}function te(r,e){const t=r<0?"-":"",n=Math.abs(r).toString().padStart(e,"0");return t+n}const Ve={y(r,e){const t=r.getFullYear(),n=t>0?t:1-t;return te(e==="yy"?n%100:n,e.length)},M(r,e){const t=r.getMonth();return e==="M"?String(t+1):te(t+1,2)},d(r,e){return te(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 te(r.getHours()%12||12,e.length)},H(r,e){return te(r.getHours(),e.length)},m(r,e){return te(r.getMinutes(),e.length)},s(r,e){return te(r.getSeconds(),e.length)},S(r,e){const t=e.length,n=r.getMilliseconds(),s=Math.trunc(n*Math.pow(10,t-3));return te(s,e.length)}},gt={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},ya={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 Ve.y(r,e)},Y:function(r,e,t,n){const s=Ul(r,n),o=s>0?s:1-s;if(e==="YY"){const i=o%100;return te(i,2)}return e==="Yo"?t.ordinalNumber(o,{unit:"year"}):te(o,e.length)},R:function(r,e){const t=Dl(r);return te(t,e.length)},u:function(r,e){const t=r.getFullYear();return te(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 te(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 te(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 Ve.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 te(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=xm(r,n);return e==="wo"?t.ordinalNumber(s,{unit:"week"}):te(s,e.length)},I:function(r,e,t){const n=gm(r);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):te(n,e.length)},d:function(r,e,t){return e==="do"?t.ordinalNumber(r.getDate(),{unit:"date"}):Ve.d(r,e)},D:function(r,e,t){const n=mm(r);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):te(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 te(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 te(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 te(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=gt.noon:n===0?s=gt.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=gt.evening:n>=12?s=gt.afternoon:n>=4?s=gt.morning:s=gt.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 Ve.h(r,e)},H:function(r,e,t){return e==="Ho"?t.ordinalNumber(r.getHours(),{unit:"hour"}):Ve.H(r,e)},K:function(r,e,t){const n=r.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):te(n,e.length)},k:function(r,e,t){let n=r.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):te(n,e.length)},m:function(r,e,t){return e==="mo"?t.ordinalNumber(r.getMinutes(),{unit:"minute"}):Ve.m(r,e)},s:function(r,e,t){return e==="so"?t.ordinalNumber(r.getSeconds(),{unit:"second"}):Ve.s(r,e)},S:function(r,e){return Ve.S(r,e)},X:function(r,e,t){const n=r.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return va(n);case"XXXX":case"XX":return Ze(n);case"XXXXX":case"XXX":default:return Ze(n,":")}},x:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"x":return va(n);case"xxxx":case"xx":return Ze(n);case"xxxxx":case"xxx":default:return Ze(n,":")}},O:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+wa(n,":");case"OOOO":default:return"GMT"+Ze(n,":")}},z:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+wa(n,":");case"zzzz":default:return"GMT"+Ze(n,":")}},t:function(r,e,t){const n=Math.trunc(+r/1e3);return te(n,e.length)},T:function(r,e,t){return te(+r,e.length)}};function wa(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+te(o,2)}function va(r,e){return r%60===0?(r>0?"-":"+")+te(Math.abs(r)/60,2):Ze(r,e)}function Ze(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=te(Math.trunc(n/60),2),o=te(n%60,2);return t+s+e+o}const _a=(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"})}},Bl=(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"})}},bm=(r,e)=>{const t=r.match(/(P+)(p+)?/)||[],n=t[1],s=t[2];if(!s)return _a(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}}",_a(n,e)).replace("{{time}}",Bl(s,e))},ym={p:Bl,P:bm},wm=/^D+$/,vm=/^Y+$/,_m=["D","DD","YY","YYYY"];function Sm(r){return wm.test(r)}function Cm(r){return vm.test(r)}function jm(r,e,t){const n=Am(r,e,t);if(console.warn(n),_m.includes(r))throw new RangeError(n)}function Am(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 km=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Nm=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Mm=/^'([^]*?)'?$/,Em=/''/g,Im=/[a-zA-Z]/;function so(r,e,t){var g,h,p,w;const n=cr(),s=n.locale??Fl,o=n.firstWeekContainsDate??((h=(g=n.locale)==null?void 0:g.options)==null?void 0:h.firstWeekContainsDate)??1,i=n.weekStartsOn??((w=(p=n.locale)==null?void 0:p.options)==null?void 0:w.weekStartsOn)??0,l=fe(r,t==null?void 0:t.in);if(!Ah(l))throw new RangeError("Invalid time value");let d=e.match(Nm).map(m=>{const u=m[0];if(u==="p"||u==="P"){const c=ym[u];return c(m,s.formatLong)}return m}).join("").match(km).map(m=>{if(m==="''")return{isToken:!1,value:"'"};const u=m[0];if(u==="'")return{isToken:!1,value:Pm(m)};if(ya[u])return{isToken:!0,value:m};if(u.match(Im))throw new RangeError("Format string contains an unescaped latin alphabet character `"+u+"`");return{isToken:!1,value:m}});s.localize.preprocessor&&(d=s.localize.preprocessor(l,d));const f={firstWeekContainsDate:o,weekStartsOn:i,locale:s};return d.map(m=>{if(!m.isToken)return m.value;const u=m.value;(Cm(u)||Sm(u))&&jm(u,e,String(r));const c=ya[u[0]];return c(l,u,s.localize,f)}).join("")}function Pm(r){const e=r.match(Mm);return e?e[1].replace(Em,"'"):r}function Tm(r,e,t){const n=cr(),s=(t==null?void 0:t.locale)??n.locale??Fl,o=2520,i=$r(r,e);if(isNaN(i))throw new RangeError("Invalid time value");const l=Object.assign({},t,{addSuffix:t==null?void 0:t.addSuffix,comparison:i}),[d,f]=xn(t==null?void 0:t.in,...i>0?[e,r]:[r,e]),g=Oh(f,d),h=(Vr(f)-Vr(d))/1e3,p=Math.round((g-h)/60);let w;if(p<2)return t!=null&&t.includeSeconds?g<5?s.formatDistance("lessThanXSeconds",5,l):g<10?s.formatDistance("lessThanXSeconds",10,l):g<20?s.formatDistance("lessThanXSeconds",20,l):g<40?s.formatDistance("halfAMinute",0,l):g<60?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",1,l):p===0?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",p,l);if(p<45)return s.formatDistance("xMinutes",p,l);if(p<90)return s.formatDistance("aboutXHours",1,l);if(p<pa){const m=Math.round(p/60);return s.formatDistance("aboutXHours",m,l)}else{if(p<o)return s.formatDistance("xDays",1,l);if(p<jr){const m=Math.round(p/pa);return s.formatDistance("xDays",m,l)}else if(p<jr*2)return w=Math.round(p/jr),s.formatDistance("aboutXMonths",w,l)}if(w=Th(f,d),w<12){const m=Math.round(p/jr);return s.formatDistance("xMonths",m,l)}else{const m=w%12,u=Math.trunc(w/12);return m<3?s.formatDistance("aboutXYears",u,l):m<9?s.formatDistance("overXYears",u,l):s.formatDistance("almostXYears",u+1,l)}}function Om(r,e){return Tm(r,Ch(r),e)}function ke(...r){return mh($f(r))}function Rm(){return yh()}function Wl(r){if(!r)return"--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"--:--":so(e,"HH:mm")}function $m(r){if(!r)return"时间未知";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"时间未知":Om(e,{addSuffix:!0})}function Lm(r){if(!r)return"----/--/--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/--":so(e,"yyyy-MM-dd")}function Dm(r){if(!r)return"----/--/-- --:--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/-- --:--:--":so(e,"yyyy-MM-dd HH:mm:ss")}function Fm(r,e){return r.length<=e?r:r.slice(0,e)+"..."}function Um(r){return r.replace(/<[^>]*>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').trim()}function Bm(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function Wm(r){try{return new URL(r),!0}catch{return!1}}function fs(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=>fs(e));if(typeof r=="object"){const e={};for(const t in r)r.hasOwnProperty(t)&&(e[t]=fs(r[t]));return e}return r}function Hm(r,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function qm(r,e){let t;return(...n)=>{t||(r(...n),t=!0,setTimeout(()=>t=!1,e))}}function Hl(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 ql(r){return r.slice((r.lastIndexOf(".")-1>>>0)+2)}function zm(r){const e=["jpg","jpeg","png","gif","bmp","webp","svg"],t=ql(r).toLowerCase();return e.includes(t)}function Jm(){const r=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6366f1"];return r[Math.floor(Math.random()*r.length)]}async function Vm(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){return console.error("Failed to copy text to clipboard:",e),!1}}function Gm(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 Xm(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Km(){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 Ym extends Error{constructor(t,n="UNKNOWN_ERROR",s=500){super(t);W(this,"code");W(this,"statusCode");this.name="AppError",this.code=n,this.statusCode=s}}async function Qm(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(i=>setTimeout(i,t*s))}throw n}const Zm={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)}}},zl=({attachment:r,customRenderer:e,className:t})=>{if(e)return a.jsx("div",{children:e(r)});const n=r.type==="image",s=r.type==="audio",o=()=>n?a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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?a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}):a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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 a.jsxs("div",{className:ke("inline-flex items-center gap-2 p-2 bg-muted rounded-lg border max-w-sm",t),children:[a.jsx("div",{className:"flex-shrink-0 text-muted-foreground",children:o()}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium truncate",children:r.name}),a.jsx("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:Hl(r.size)})]}),r.mimeType&&a.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:r.mimeType})]}),a.jsx("div",{className:"flex-shrink-0",children:n?a.jsx("button",{onClick:()=>window.open(r.url,"_blank"),className:"p-1 hover:bg-background rounded transition-colors",title:"View image",children:a.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),a.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"})]})}):a.jsx("a",{href:r.url,download:r.name,className:"p-1 hover:bg-background rounded transition-colors inline-block",title:"Download file",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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&&a.jsx("div",{className:"w-full mt-2",children:a.jsx("img",{src:r.url,alt:r.name,className:"max-w-full h-auto rounded border",style:{maxHeight:"200px"},loading:"lazy"})}),s&&a.jsx("div",{className:"w-full mt-2",children:a.jsxs("audio",{controls:!0,className:"w-full",preload:"metadata",children:[a.jsx("source",{src:r.url,type:r.mimeType}),"Your browser does not support the audio element."]})})]})},hs=({toolCall:r,allMessages:e=[],className:t})=>{const[n,s]=O.useState(!1);console.log("🔍 ToolCallRenderer - 开始查找工具结果消息"),console.log("🔍 当前工具调用ID:",r.id),console.log("🔍 所有消息数量:",e.length),console.log("🔍 所有消息:",e.map(S=>{var C;return{id:S.id,role:S.role,tool_call_id:S.tool_call_id||S.toolCallId,metadata:S.metadata,content:((C=S.content)==null?void 0:C.substring(0,100))+"..."}}));const o=e.find(S=>{var I,T;if(S.role!=="tool")return!1;const C=S.tool_call_id||S.toolCallId,_=((I=S.metadata)==null?void 0:I.tool_call_id)||((T=S.metadata)==null?void 0:T.toolCallId);return C===r.id||_===r.id});console.log("🔍 找到的工具结果消息:",o),console.log("🎨 ToolCallRenderer - 工具调用:",r.id,"结果:",r.result,"工具消息:",o==null?void 0:o.content);const i=r.result||(o==null?void 0:o.content),l=!!r.error,d=!!i,g=(()=>{if(!r.arguments)return{};if(typeof r.arguments=="object")return r.arguments;if(typeof r.arguments=="string")try{return JSON.parse(r.arguments)}catch(S){return console.warn("Failed to parse tool arguments:",r.arguments,S),{}}return{}})(),h=g&&Object.keys(g).length>0,p=(S,C="")=>{const _={};for(const I in S)if(S.hasOwnProperty(I)){const T=S[I],$=C?`${C}.${I}`:I;T!==null&&typeof T=="object"&&!Array.isArray(T)?Object.assign(_,p(T,$)):_[$]=T}return _},m=(()=>{if(!h)return"";const S=p(g),C=Object.keys(S);let _=`| 参数 | 值 |
98
98
  |------|------|
99
- `;return C.forEach(I=>{const E=v[I];let P;typeof E=="string"?P=E.replace(/\n/g,"<br>").replace(/\|/g,"\\|"):Array.isArray(E)?P=`[${E.join(", ")}]`.replace(/\|/g,"\\|"):P=JSON.stringify(E).replace(/\|/g,"\\|"),S+=`| ${I} | ${P} |
100
- `}),S})(),c=(()=>{if(!d)return null;if(i&&typeof i=="object")return i;if(typeof i=="string")try{const v=JSON.parse(i);if(v&&typeof v=="object")return v}catch{return null}return null})(),g=!!(c&&typeof c=="object"),y=v=>{if(v===null)return"null";if(Array.isArray(v)){if(v.length===0)return"array []";const C=v[0],S=y(C);return S==="object"?"object []":`${S}[]`}switch(typeof v){case"string":return"string";case"number":return Number.isInteger(v)?"integer":"number";case"boolean":return"boolean";case"object":return"object";default:return typeof v}},b=(v,C="",S="")=>{const I=[];if(v==null)return I;if(Array.isArray(v)){const E={path:S||C||"list",name:C||"list",type:y(v),value:v,children:v.map((P,R)=>{const j=`${S||C||"list"}[${R}]`,W=y(P);return{path:j,name:`[${R}]`,type:W,value:P,children:W==="object"||Array.isArray(P)?b(P,`[${R}]`,j):[]}})};return I.push(E),I}return typeof v=="object"&&Object.keys(v).forEach(E=>{const P=v[E],R=S?`${S}.${E}`:E,j=y(P),W=j==="object"||Array.isArray(P)?b(P,E,R):[];I.push({path:R,name:E,type:j,value:P,children:W})}),I},_=({data:v})=>{const C=Array.isArray(v)?b(v,"list","list"):b(v,"",""),[S,I]=T.useState(()=>new Set(C.filter(j=>j.children.length>0).map(j=>j.path))),E=j=>{I(W=>{const D=new Set(W);return D.has(j)?D.delete(j):D.add(j),D})},P=j=>{if(j===null)return"null";if(Array.isArray(j))return`数组(${j.length})`;if(typeof j=="object")return"对象";if(typeof j=="string")return j;try{return JSON.stringify(j)}catch{return String(j)}},R=(j,W)=>j.map(D=>{const X=D.children&&D.children.length>0,G=S.has(D.path),N=X?G?"▾":"▸":"",F=P(D.value);return a.jsxs(T.Fragment,{children:[a.jsxs("tr",{children:[a.jsxs("td",{style:{paddingLeft:W*16},children:[X?a.jsx("button",{type:"button",onClick:()=>E(D.path),className:"mr-2 text-gray-600 dark:text-gray-300 hover:text-black dark:hover:text-white","aria-label":G?"收起":"展开",children:N}):a.jsx("span",{className:"mr-4"}),D.name]}),a.jsx("td",{style:{whiteSpace:"normal",wordBreak:"break-word"},children:F})]}),X&&G&&R(D.children,W+1)]},D.path)});return a.jsx("div",{className:"border-l-4 border-green-400 dark:border-green-500 rounded-lg overflow-hidden bg-green-50/50 dark:bg-green-900/20 mb-2",children:a.jsx("div",{className:"markdown-renderer",children:a.jsxs("table",{children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"字段"}),a.jsx("th",{children:"值"})]})}),a.jsx("tbody",{children:R(C,0)})]})})})};return a.jsxs("div",{className:"tool-call-renderer tool-call-container",children:[a.jsxs("div",{className:"tool-header",children:[a.jsxs("span",{className:"tool-name",children:["@",r.name]}),l&&a.jsx("span",{className:"status-badge status-error",children:"错误"}),d&&!l&&a.jsx("span",{className:"status-badge status-success",children:"完成"}),!d&&!l&&a.jsx("span",{className:"status-badge status-pending",children:"等待中"}),(f||d||l)&&a.jsx("button",{onClick:()=>s(!n),className:"toggle-button",children:n?"收起详情":"查看详情"})]}),n&&a.jsxs("div",{className:"details-container",children:[f&&a.jsx("div",{children:m&&a.jsx("div",{className:"border-l-4 border-blue-400 dark:border-blue-500 rounded-lg overflow-hidden bg-blue-50/50 dark:bg-blue-900/20 mb-4",children:a.jsx(ot,{content:m})})}),d&&a.jsxs("div",{children:[a.jsx("div",{className:"details-title",children:"结果:"}),g?a.jsx(_,{data:c}):a.jsx(ot,{content:typeof i=="string"?i:JSON.stringify(i)})]}),l&&a.jsxs("div",{children:[a.jsx("div",{className:"details-title",children:"错误:"}),a.jsx("div",{className:"status-badge status-error",style:{display:"block",padding:"0.5rem"},children:r.error})]}),a.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 border-t border-gray-200 dark:border-gray-700 pt-2",children:["执行时间: ",(()=>{const v=new Date(r.createdAt);return isNaN(v.getTime())?"时间未知":v.toLocaleString()})()]})]})]})},rg=({message:r,isLast:e=!1,isStreaming:t=!1,onEdit:n,onDelete:s,allMessages:o=[],customRenderer:i})=>{var S,I,E,P,R,j,W,D,X,G;console.log("🚀🚀🚀 MessageItem 组件被调用!消息ID:",r.id,"角色:",r.role),console.log("🚀🚀🚀 完整消息对象:",r);const[l,d]=T.useState(!1),[u,p]=T.useState(r.content),f=(N,F)=>{navigator.clipboard.writeText(N).then(()=>{console.log("代码已复制到剪贴板:",{code:N,language:F})}).catch(z=>{console.error("复制失败:",z)})},[x,w]=T.useState(!1),m=r.role==="user",h=r.role==="assistant",c=r.role==="system",g=r.role==="tool";if(g)return null;if(i!=null&&i.renderMessage)return a.jsx("div",{children:i.renderMessage(r)});const y=()=>{n&&u.trim()!==r.content&&n(r.id,u.trim()),d(!1)},b=()=>{p(r.content),d(!1)},_=async()=>{try{await navigator.clipboard.writeText(r.content)}catch(N){console.error("Failed to copy message:",N)}},v=((S=r.metadata)==null?void 0:S.attachments)||[],C=r.toolCalls||((I=r.metadata)==null?void 0:I.toolCalls)||[];return console.log("🔧 工具调用数据:",{顶层toolCalls:r.toolCalls,"metadata.toolCalls":(E=r.metadata)==null?void 0:E.toolCalls,最终toolCalls长度:C.length,消息ID:r.id,contentSegments:(P=r.metadata)==null?void 0:P.contentSegments,contentSegments长度:((j=(R=r.metadata)==null?void 0:R.contentSegments)==null?void 0:j.length)||0}),a.jsxs("div",{className:Me("group relative rounded-lg transition-colors",!h&&"flex gap-3 px-4 py-4",h&&"px-4 py-2",m&&"bg-user-message",c&&"bg-muted border-l-4 border-primary",g&&"bg-blue-50 dark:bg-blue-950/20 border-l-4 border-blue-500","hover:bg-opacity-80"),onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),children:[!h&&a.jsx("div",{className:"flex-shrink-0",children:a.jsx("div",{className:Me("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium",m&&"bg-primary text-primary-foreground",c&&"bg-muted text-muted-foreground",g&&"bg-blue-500 text-white"),children:m?"U":g?"T":"S"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[!h&&a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("span",{className:"text-sm font-medium",children:m?"You":g?"Tool Result":"System"}),a.jsx("span",{className:"text-xs text-muted-foreground",children:zl(r.createdAt)}),((W=r.metadata)==null?void 0:W.model)&&a.jsx("span",{className:"text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded",children:r.metadata.model})]}),((D=r.metadata)==null?void 0:D.type)==="session_summary"&&a.jsxs("div",{className:"mb-3 border border-amber-300 dark:border-amber-600/50 bg-amber-50 dark:bg-amber-950/20 rounded-md p-3",children:[a.jsxs("div",{className:"text-xs text-amber-900 dark:text-amber-200 font-medium mb-1",children:["上下文已压缩为摘要",typeof((X=r.metadata)==null?void 0:X.keepLastN)=="number"?`(保留最近 ${r.metadata.keepLastN} 条)`:""]}),a.jsxs("details",{className:"group",children:[a.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground select-none",children:"查看摘要内容"}),a.jsx("div",{className:"mt-2 prose prose-sm max-w-none",children:a.jsx(ot,{content:(r.rawContent||((G=r.metadata)==null?void 0:G.summary)||"").toString(),isStreaming:!1,onApplyCode:()=>{}})})]})]}),v.length>0&&a.jsx("div",{className:"mb-3 space-y-2",children:v.map(N=>a.jsx(Gl,{attachment:N,customRenderer:i==null?void 0:i.renderAttachment},N.id))}),l?a.jsxs("div",{className:"space-y-2",children:[a.jsx("textarea",{value:u,onChange:N=>p(N.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}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:y,className:"px-3 py-1 text-sm bg-primary text-primary-foreground rounded hover:bg-primary/90",children:"Save"}),a.jsx("button",{onClick:b,className:"px-3 py-1 text-sm bg-muted text-muted-foreground rounded hover:bg-muted/80",children:"Cancel"})]})]}):a.jsx("div",{className:"space-y-3",children:(()=>{var $;const N=(($=r.metadata)==null?void 0:$.contentSegments)||[],F=r.content&&r.content.trim().length>0,z=t&&e;return N.length>0?(console.log("🎨 使用分段渲染,分段数量:",N.length),console.log("🎨 分段详情:",N),a.jsx("div",{className:"space-y-0.5",children:N.map((O,U)=>{if(console.log(`🎨 渲染分段 ${U}:`,O),O.type==="text")return console.log(`🎨 渲染文本分段 ${U}:`,O.content),a.jsx("div",{className:"prose prose-sm max-w-none",children:a.jsx(ot,{content:O.content,isStreaming:z&&U===N.length-1,onApplyCode:f})},`segment-${U}`);if(O.type==="tool_call"){console.log(`🎨 渲染工具调用分段 ${U}:`,O);const V=C.find(k=>k.id===O.toolCallId);if(console.log(`🎨 查找工具调用 ${O.toolCallId}:`,V),V)return console.log("🎨 找到工具调用,开始渲染:",V),a.jsx("div",{children:a.jsx(ps,{toolCall:V,allMessages:o})},`tool-${V.id}`);console.log(`🎨 ❌ 未找到工具调用 ${O.toolCallId}`)}else if(O.type==="thinking")return console.log(`🎨 渲染思考分段 ${U}:`,O.content),a.jsxs("details",{className:"group border border-gray-200 dark:border-gray-700 rounded-md bg-muted px-3 py-2",children:[a.jsx("summary",{className:"cursor-pointer text-xs text-gray-500 dark:text-gray-400 select-none",children:"思考过程"}),a.jsx("div",{className:"mt-1",children:a.jsx(ot,{content:O.content||"",isStreaming:z&&U===N.length-1,onApplyCode:f,className:"thinking not-prose"})})]},`thinking-${U}`);return null})})):(console.log("🎨 使用传统渲染方式"),console.log("🎨 hasContent:",F),console.log("🎨 toolCalls.length:",C.length),a.jsxs("div",{className:"space-y-0.5",children:[F&&a.jsx("div",{className:"prose prose-sm max-w-none",children:a.jsx(ot,{content:r.content,isStreaming:z,onApplyCode:f})}),C.length>0&&a.jsxs("div",{className:"space-y-0.5",children:[a.jsx("div",{className:"text-sm text-muted-foreground font-medium",children:"工具调用:"}),C.map(O=>(console.log("🎨 传统方式渲染工具调用:",O),a.jsx("div",{children:a.jsx(ps,{toolCall:O,allMessages:o})},`tool-${O.id}`)))]})]}))})()}),r.tokensUsed&&a.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Tokens used: ",r.tokensUsed]})]}),x&&!l&&a.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:[a.jsx("button",{onClick:_,className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Copy message",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),m&&n&&a.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:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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&&a.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:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})})]})]})},Xl=T.memo(rg,(r,e)=>r.message.id===e.message.id&&r.message.content===e.message.content&&r.message.createdAt===e.message.createdAt&&r.isLast===e.isLast&&r.isStreaming===e.isStreaming&&JSON.stringify(r.message.metadata)===JSON.stringify(e.message.metadata)),Kl=({size:r="md",className:e})=>{const t={sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"};return a.jsx("div",{className:Me("animate-spin rounded-full border-2 border-current border-t-transparent",t[r],e),role:"status","aria-label":"Loading",children:a.jsx("span",{className:"sr-only",children:"Loading..."})})},lo=({messages:r,isLoading:e=!1,isStreaming:t=!1,hasMore:n=!1,onLoadMore:s,onMessageEdit:o,onMessageDelete:i,customRenderer:l})=>{const d=T.useRef(null),u=T.useRef(null),[p,f]=T.useState(!0),[x,w]=T.useState(!0),m=()=>{const y=d.current;return y?y.scrollHeight-y.scrollTop-y.clientHeight<=40:!0},h=(y=!0)=>{var b;(b=u.current)==null||b.scrollIntoView({behavior:y?"smooth":"auto"})};T.useEffect(()=>{t&&p&&h(!0)},[r,t,p]),T.useEffect(()=>{w(m())},[r,t]),T.useEffect(()=>{t&&x&&f(!0),t||f(!1)},[t,x]);const c=()=>{const y=m();w(y),y||f(!1)},g=()=>{h(!0),f(!0)};return r.length===0&&!e?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 mx-auto bg-muted rounded-full flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Start a conversation"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Send a message to begin your chat with AI"})]})]})}):a.jsxs("div",{className:"flex flex-col h-full relative",children:[a.jsxs("div",{ref:d,onScroll:c,className:"flex-1 overflow-y-auto px-4 py-6 space-y-1",style:{willChange:"scroll-position",transform:"translateZ(0)"},children:[n&&a.jsx("div",{className:"flex justify-center mb-2",children:a.jsx("button",{type:"button",onClick:s,className:"text-sm px-3 py-1 rounded border border-border text-foreground hover:bg-accent",children:"加载更多"})}),(r||[]).filter(y=>{var b;return!((b=y==null?void 0:y.metadata)!=null&&b.hidden)}).map((y,b,_)=>a.jsx(Xl,{message:y,isLast:b===_.length-1,isStreaming:t&&b===_.length-1,onEdit:o,onDelete:i,allMessages:r,customRenderer:l},y.id)),e&&a.jsx("div",{className:"flex justify-start",children:a.jsxs("div",{className:"flex items-center space-x-2 bg-muted px-4 py-3 rounded-lg max-w-xs",children:[a.jsx(Kl,{size:"sm"}),a.jsx("span",{className:"text-sm text-muted-foreground",children:"AI is thinking..."})]})}),a.jsx("div",{ref:u})]}),!x&&a.jsxs("button",{type:"button","aria-label":"回到底部",title:"回到底部",onClick:g,className:"absolute bottom-4 right-4 z-10 flex items-center gap-2 rounded-full bg-primary text-primary-foreground px-4 py-2 shadow-md hover:bg-primary/90",children:[a.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M12 5v12"}),a.jsx("path",{d:"M19 12l-7 7-7-7"})]}),a.jsx("span",{className:"text-sm",children:"回到底部"})]})]})},co=({onSend:r,onStop:e,disabled:t=!1,isStreaming:n=!1,placeholder:s="Type your message...",maxLength:o=4e3,allowAttachments:i=!1,supportedFileTypes:l=["image/*","text/*","application/pdf"],showModelSelector:d=!1,selectedModelId:u=null,availableModels:p=[],onModelChange:f,selectedAgentId:x=null,availableAgents:w=[],onAgentChange:m})=>{const[h,c]=T.useState(""),[g,y]=T.useState([]),[b,_]=T.useState(!1),v=T.useRef(null),C=T.useRef(null);T.useEffect(()=>{console.log("InputArea - isStreaming 状态变化:",{isStreaming:n,disabled:t,onStop:!!e,timestamp:new Date().toISOString()})},[n,t,e]);const S=T.useCallback(()=>{const N=v.current;if(N){N.style.height="auto";const F=N.scrollHeight,z=200;N.style.height=`${Math.min(F,z)}px`}},[]),I=N=>{const F=N.target.value;F.length<=o&&(c(F),S())},E=N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),P())},P=()=>{const N=h.trim();if(!(!N&&g.length===0)&&!t){if(d&&!u&&!x){alert("请先选择一个模型或智能体");return}r(N,g),c(""),y([]),v.current&&(v.current.style.height="auto")}},R=N=>{const F=Array.from(N.target.files||[]);y(z=>[...z,...F]),C.current&&(C.current.value="")},j=N=>{y(F=>F.filter((z,$)=>$!==N))},W=N=>{N.preventDefault(),i&&!t&&_(!0)},D=N=>{N.preventDefault(),_(!1)},X=N=>{if(N.preventDefault(),_(!1),!i||t)return;const F=Array.from(N.dataTransfer.files);y(z=>[...z,...F])},G=N=>{if(N===0)return"0 Bytes";const F=1024,z=["Bytes","KB","MB","GB"],$=Math.floor(Math.log(N)/Math.log(F));return parseFloat((N/Math.pow(F,$)).toFixed(2))+" "+z[$]};return a.jsxs("div",{className:"border-t bg-background p-4",children:[d&&a.jsx("div",{className:"mb-3",children:p.length>0||w.length>0?a.jsxs("select",{value:x?`agent:${x}`:u||"",onChange:N=>{const F=N.target.value;if(F.startsWith("agent:")){const z=F.replace("agent:","");m==null||m(z),f==null||f(null)}else f==null||f(F||null),m==null||m(null)},disabled:t,className:Me("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:[a.jsx("option",{value:"",children:"请选择模型或智能体..."}),w&&w.filter(N=>N.enabled).length>0&&a.jsx("optgroup",{label:"智能体",children:w.filter(N=>N.enabled).map(N=>a.jsxs("option",{value:`agent:${N.id}`,children:["[Agent] ",N.name]},N.id))}),p&&p.filter(N=>N.enabled).length>0&&a.jsx("optgroup",{label:"模型",children:p.filter(N=>N.enabled).map(N=>a.jsxs("option",{value:N.id,children:[N.name," (",N.model_name,")"]},N.id))})]}):a.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:"暂无可用模型或智能体,请先在右上角配置"})}),g.length>0&&a.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:g.map((N,F)=>a.jsxs("div",{className:"flex items-center gap-2 bg-muted px-3 py-2 rounded-lg text-sm",children:[a.jsx("svg",{className:"w-4 h-4 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),a.jsx("span",{className:"truncate max-w-32",children:N.name}),a.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",G(N.size),")"]}),a.jsx("button",{onClick:()=>j(F),className:"text-muted-foreground hover:text-destructive transition-colors",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},F))}),a.jsxs("div",{className:Me("relative flex items-end gap-2 p-3 border rounded-lg transition-colors","focus-within:border-primary",b&&"border-primary bg-primary/5",t&&"opacity-50 cursor-not-allowed"),onDragOver:W,onDragLeave:D,onDrop:X,children:[i&&a.jsx("button",{onClick:()=>{var N;return(N=C.current)==null?void 0:N.click()},disabled:t,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:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsx("textarea",{ref:v,value:h,onChange:I,onKeyDown:E,placeholder:s,disabled:t,className:Me("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"}}),a.jsxs("div",{className:"flex-shrink-0 text-xs text-muted-foreground",children:[h.length,"/",o]}),n?a.jsx("button",{onClick:()=>{console.log("停止按钮被点击",{onStop:e,disabled:t}),e&&e()},disabled:!1,className:Me("flex-shrink-0 p-2 rounded-md transition-colors","bg-red-500 text-white hover:bg-red-600","disabled:opacity-50 disabled:cursor-not-allowed"),title:"停止生成",style:{backgroundColor:"#ef4444",color:"white"},children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 6h12v12H6z"})})}):a.jsx("button",{onClick:P,disabled:t||n||!h.trim()&&g.length===0,className:Me("flex-shrink-0 p-2 rounded-md transition-colors","disabled:opacity-50 disabled:cursor-not-allowed",(h.trim()||g.length>0)&&!t&&!n?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground"),title:d&&!u?"请先选择AI模型":"Send message",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"})})}),i&&a.jsx("input",{ref:C,type:"file",multiple:!0,accept:l.join(","),onChange:R,className:"hidden"})]}),b&&i&&a.jsx("div",{className:"absolute inset-0 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center",children:a.jsxs("div",{className:"text-center",children:[a.jsx("svg",{className:"w-8 h-8 mx-auto text-primary mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),a.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to attach"})]})})]})},Yl=({className:r="w-5 h-5"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Ql=({className:r="w-5 h-5"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),Zl=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),ec=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),ng=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),sg=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),tc=({className:r="w-5 h-5"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),og=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),ag=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14.828 14.828a4 4 0 01-5.656 0M9 10h1m4 0h1m-6 4h8m-9 4h10a1 1 0 001-1V7a1 1 0 00-1-1H7a1 1 0 00-1 1v10a1 1 0 001 1z"})}),ig=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}),yn=({isOpen:r,title:e,message:t,confirmText:n="确认",cancelText:s="取消",onConfirm:o,onCancel:i,type:l="danger"})=>{if(!r)return null;const d=()=>{switch(l){case"danger":return"bg-red-600 hover:bg-red-700 text-white";case"warning":return"bg-yellow-600 hover:bg-yellow-700 text-white";default:return"bg-blue-600 hover:bg-blue-700 text-white"}};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx("div",{className:"bg-card rounded-lg shadow-lg w-full max-w-sm border border-border animate-breathing-border",children:a.jsxs("div",{className:"p-6",children:[a.jsx("h3",{className:"text-lg font-medium text-foreground mb-2",children:e}),a.jsx("p",{className:"text-muted-foreground text-sm mb-6",children:t}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx("button",{onClick:i,className:"flex-1 px-4 py-2 text-sm border border-border rounded-md hover:bg-accent transition-colors",children:s}),a.jsx("button",{onClick:o,className:`flex-1 px-4 py-2 text-sm rounded-md transition-colors ${d()}`,children:n})]})]})})})},bn=()=>{const[r,e]=T.useState({isOpen:!1,title:"",message:"",confirmText:"确认",cancelText:"取消",type:"danger"}),t=T.useCallback(i=>{e({isOpen:!0,title:i.title,message:i.message,confirmText:i.confirmText||"确认",cancelText:i.cancelText||"取消",type:i.type||"danger",onConfirm:i.onConfirm,onCancel:i.onCancel})},[]),n=T.useCallback(()=>{e(i=>({...i,isOpen:!1}))},[]),s=T.useCallback(()=>{var i;(i=r.onConfirm)==null||i.call(r),n()},[r.onConfirm,n]),o=T.useCallback(()=>{var i;(i=r.onCancel)==null||i.call(r),n()},[r.onCancel,n]);return{dialogState:r,showConfirmDialog:t,hideConfirmDialog:n,handleConfirm:s,handleCancel:o}},lg=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")},uo=({isOpen:r=!0,onClose:e,store:t})=>{let n=null;try{n=ft()}catch{}const s=t?t():n;if(!s)throw new Error("SessionList must be used within a ChatStoreProvider or receive a store prop");const{sessions:o,currentSession:i,createSession:l,selectSession:d,deleteSession:u,updateSession:p}=s,[f,x]=T.useState(null),[w,m]=T.useState(""),[h,c]=T.useState(!1),[g,y]=T.useState(!1),{dialogState:b,showConfirmDialog:_,handleConfirm:v,handleCancel:C}=bn();T.useEffect(()=>{if(r)y(!0),requestAnimationFrame(()=>{c(!0)});else{c(!1);const D=setTimeout(()=>{y(!1)},300);return()=>clearTimeout(D)}},[r]);const S=async()=>{try{await l(),e==null||e()}catch(D){console.error("Failed to create session:",D)}},I=async D=>{try{await d(D),e==null||e()}catch(X){console.error("Failed to select session:",X)}},E=async D=>{const X=o.find(G=>G.id===D);_({title:"删除确认",message:`确定要删除会话 "${(X==null?void 0:X.title)||"Untitled"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{try{await u(D)}catch(G){console.error("Failed to delete session:",G)}}})},P=(D,X)=>{x(D),m(X)},R=async()=>{if(f&&w.trim())try{await p(f,{title:w.trim()}),x(null),m("")}catch(D){console.error("Failed to update session:",D)}},j=()=>{x(null),m("")},W=D=>{D.key==="Enter"?R():D.key==="Escape"&&j()};return g?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:`fixed inset-0 bg-black/50 backdrop-blur-sm z-40 transition-opacity duration-300 ${h?"opacity-100":"opacity-0"}`,onClick:e}),a.jsx("div",{className:`fixed left-0 top-0 h-full w-80 sm:w-96 bg-card z-50 transform transition-all duration-300 ease-in-out ${h?"translate-x-0":"-translate-x-full"} shadow-xl breathing-border`,children:a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"会话列表"}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{onClick:S,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"新建会话",children:a.jsx(Yl,{className:"w-5 h-5"})}),e&&a.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto",children:o.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground",children:[a.jsx(tc,{className:"w-12 h-12 mb-4 opacity-50"}),a.jsx("p",{className:"text-sm",children:"还没有会话"}),a.jsx("button",{onClick:S,className:"mt-2 px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"创建第一个会话"})]}):a.jsx("div",{className:"p-2 space-y-1",children:o.map(D=>a.jsxs("div",{className:`group relative flex items-center p-3 rounded-lg cursor-pointer transition-colors ${(i==null?void 0:i.id)===D.id?"bg-accent border border-border":"hover:bg-accent/50"}`,onClick:()=>I(D.id),children:[a.jsx("div",{className:"flex-1 min-w-0",children:f===D.id?a.jsx("input",{type:"text",value:w,onChange:X=>m(X.target.value),onBlur:R,onKeyDown:W,className:"w-full px-2 py-1 text-sm bg-background border border-border rounded focus:outline-none focus:ring-2 focus:ring-ring",autoFocus:!0,onClick:X=>X.stopPropagation()}):a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-sm font-medium text-foreground truncate",children:D.title}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:lg(D.updatedAt)})]})}),f!==D.id&&a.jsxs("div",{className:"relative",children:[a.jsx("button",{className:"p-1 text-muted-foreground hover:text-foreground opacity-0 group-hover:opacity-100 transition-opacity",onClick:X=>{X.stopPropagation();const G=X.currentTarget.nextElementSibling;G&&G.classList.toggle("hidden")},children:a.jsx(Ql,{className:"w-4 h-4"})}),a.jsx("div",{className:"hidden absolute right-0 z-10 mt-1 w-32 bg-popover border border-border rounded-md shadow-lg",children:a.jsxs("div",{className:"py-1",children:[a.jsxs("button",{onClick:X=>{X.stopPropagation(),P(D.id,D.title);const G=X.currentTarget.closest(".absolute");G&&G.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-popover-foreground hover:bg-accent",children:[a.jsx(Zl,{className:"w-4 h-4 mr-2"}),"重命名"]}),a.jsxs("button",{onClick:X=>{X.stopPropagation(),E(D.id);const G=X.currentTarget.closest(".absolute");G&&G.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-destructive hover:bg-destructive/10",children:[a.jsx(ec,{className:"w-4 h-4 mr-2"}),"删除"]})]})})]})]},D.id))})}),a.jsx(yn,{isOpen:b.isOpen,title:b.title,message:b.message,confirmText:b.confirmText,cancelText:b.cancelText,type:b.type,onConfirm:v,onCancel:C})]})})]}):null},rc=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",Aa=r=>r==="system"?rc():r,Wn=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")},ka=()=>typeof window>"u"?"system":localStorage.getItem("theme")||"system",cg=r=>{typeof window>"u"||localStorage.setItem("theme",r)},nc=()=>{const[r,e]=T.useState(()=>ka()),[t,n]=T.useState(()=>Aa(ka())),s=i=>{e(i),cg(i);const l=Aa(i);n(l),Wn(l)},o=()=>{let i;switch(r){case"light":i="dark";break;case"dark":i="system";break;case"system":i="light";break;default:i="system"}s(i)};return T.useEffect(()=>{if(r!=="system")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),l=()=>{const d=rc();n(d),Wn(d)};return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[r]),T.useEffect(()=>{Wn(t)},[t]),{theme:r,actualTheme:t,setTheme:s,toggleTheme:o}},fo=({className:r=""})=>{const{theme:e,toggleTheme:t}=nc(),n=()=>{switch(e){case"light":return a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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 a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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 a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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 a.jsx("button",{onClick:t,className:`p-2 hover:bg-muted rounded-lg transition-colors ${r}`,title:s(),"aria-label":s(),children:n()})},dg={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},ug=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),Na=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),fg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),hg=({open:r,config:e,onClose:t})=>{const[n,s]=T.useState([]),[o,i]=T.useState(!1),[l,d]=T.useState(null),[u,p]=T.useState(null),[f,x]=T.useState(!1),[w,m]=T.useState({name:"",envJson:"",enabled:!1}),[h,c]=T.useState(null),[g,y]=T.useState({});if(T.useEffect(()=>{(async()=>{if(!(!r||!(e!=null&&e.id))){i(!0),d(null);try{const _=await ne.getMcpConfigProfiles(e.id);s(Array.isArray(_)?_:[])}catch(_){d((_==null?void 0:_.message)||"获取配置档案失败")}finally{i(!1)}}})()},[r,e==null?void 0:e.id]),!r)return null;try{const b={id:e==null?void 0:e.id,name:e==null?void 0:e.name,type:e==null?void 0:e.type,command:e==null?void 0:e.command,cwd:e==null?void 0:e.cwd,args:e==null?void 0:e.args};typeof window<"u"}catch{}return a.jsxs("div",{className:"modal-container",children:[a.jsxs("div",{className:"modal-content w-full max-w-3xl max-h-[85vh] overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(ug,{}),a.jsxs("h3",{className:"text-lg font-semibold text-foreground",children:["配置档案 - ",e==null?void 0:e.name]})]}),a.jsx("button",{onClick:()=>t(),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(Na,{})})]}),a.jsxs("div",{className:"p-4 overflow-y-auto overflow-x-hidden",style:{maxHeight:"calc(85vh - 100px)"},children:[e&&a.jsxs("div",{className:"mb-4 p-3 rounded-md border border-border bg-muted/40",children:[a.jsx("div",{className:"text-sm font-medium mb-2 text-foreground",children:"基本信息"}),a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-muted-foreground",children:[a.jsxs("div",{children:["协议类型:",a.jsx("span",{className:"ml-1 text-foreground",children:e.type==="http"?"HTTP":"Stdio"})]}),a.jsxs("div",{children:[e.type==="http"?"URL:":"命令:",a.jsx("span",{className:"ml-1 text-foreground break-all",children:e.command})]}),e.type==="stdio"&&e.cwd&&a.jsxs("div",{children:["cwd:",a.jsx("span",{className:"ml-1 text-foreground break-all",children:String(e.cwd)})]}),e.type==="stdio"&&a.jsxs("div",{className:"sm:col-span-2",children:["args:",a.jsx("span",{className:"ml-1 text-foreground break-all",children:(()=>{const b=e.args;if(!b)return"—";if(Array.isArray(b))return b.map(_=>String(_)).join(", ");if(typeof b=="string"){try{const _=JSON.parse(b);if(Array.isArray(_))return _.map(v=>String(v)).join(", ")}catch{}return b}return String(b)})()})]})]})]}),a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("span",{className:"text-sm text-muted-foreground",children:"已保存的配置档案"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{if(e!=null&&e.id){i(!0);try{const b=await ne.getMcpConfigProfiles(e.id);s(Array.isArray(b)?b:[])}finally{i(!1)}}},children:"刷新列表"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:async()=>{if(!(e!=null&&e.id))return;let b;try{const _=await ne.getMcpConfigResource(e.id),v=_&&_.config||{};v&&typeof v=="object"&&(b=v)}catch{}m({name:`配置_${new Date().toLocaleString("zh-CN")}`,envJson:"",enabled:!1}),y(b||{}),p(null),x(!0)},children:"新增配置档案"})]})]}),o?a.jsx("div",{className:"text-xs text-muted-foreground",children:"加载中..."}):l?a.jsx("div",{className:"text-xs text-destructive",children:l}):n.length===0?a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案,点击右上角“新增配置档案”。"}):a.jsx("div",{className:"space-y-2",children:n.map(b=>a.jsx("div",{className:"px-2 py-2 border border-border rounded-md",children:a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("div",{className:"text-sm text-foreground font-medium truncate",title:b.name,children:b.name}),b.enabled&&a.jsx("span",{className:"px-2 py-0.5 text-[10px] rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200",children:"已启用"})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{if(e!=null&&e.id)try{await ne.activateMcpConfigProfile(e.id,b.id);const _=await ne.getMcpConfigProfiles(e.id);s(Array.isArray(_)?_:[])}catch{}},children:"激活"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{p(b.id),m({name:b.name||"",envJson:(()=>{try{return JSON.stringify(b.env||{},null,2)}catch{return""}})(),enabled:!!b.enabled});const _=b.env||{},v={};Object.keys(_||{}).forEach(C=>{const S=_[C];if(typeof S=="string"){const I=S.trim();try{v[C]=JSON.parse(I)}catch{I.includes(",")?v[C]=I.split(",").map(E=>E.trim()).filter(Boolean):v[C]=I}}else v[C]=S}),y(v),x(!0)},children:"编辑"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-destructive text-destructive-foreground rounded-md hover:bg-destructive/80",onClick:async()=>{if(!(!(e!=null&&e.id)||!window.confirm(`确定删除配置档案 “${b.name}” 吗?`)))try{await ne.deleteMcpConfigProfile(e.id,b.id);const v=await ne.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[])}catch(v){console.error("删除配置档案失败:",v)}},children:"删除"})]})]})},b.id))})]})]}),f&&a.jsxs("div",{className:"modal-container z-[100]",children:[a.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-sm",onClick:()=>{x(!1),c(null)}}),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:a.jsxs("div",{className:"modal-content w-full max-w-2xl transform overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(fg,{}),a.jsx("h3",{className:"text-base font-semibold text-foreground",children:u?"编辑配置档案":"新增配置档案"})]}),a.jsx("button",{onClick:()=>{x(!1),c(null)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(Na,{})})]}),a.jsxs("div",{className:"p-4",children:[h&&a.jsx("div",{className:"mb-2 text-xs text-destructive",children:h}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),a.jsx("input",{type:"text",value:w.name,onChange:b=>m({...w,name:b.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md"})]}),a.jsx("div",{children:g&&Object.keys(g).length>0&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"动态参数"}),a.jsx("div",{className:"grid grid-cols-1 gap-3",children:Object.keys(g).map(b=>{const _=g[b],v=typeof _,C=Array.isArray(_);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:b}),v==="boolean"?a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",checked:!!_,onChange:S=>y({...g,[b]:S.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("span",{className:"ml-2 text-xs",children:String(_)})]}):C?a.jsx("input",{type:"text",value:_.join(", "),onChange:S=>y({...g,[b]:S.target.value.split(",").map(I=>I.trim()).filter(Boolean)}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"}):v==="object"&&_!==null?a.jsx("textarea",{value:(()=>{try{return JSON.stringify(_,null,2)}catch{return String(_)}})(),onChange:S=>{try{const I=JSON.parse(S.target.value);y({...g,[b]:I})}catch{y({...g,[b]:S.target.value})}},rows:4,className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md font-mono text-xs"}):a.jsx("input",{type:v==="number"?"number":"text",value:_??"",onChange:S=>y({...g,[b]:v==="number"?Number(S.target.value):S.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},b)})})]})})]}),a.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:()=>{x(!1),c(null)},children:"取消"}),a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:async()=>{c(null);try{if(!(e!=null&&e.id))throw new Error("缺少配置ID");let b=null;if(g&&Object.keys(g).length>0)b=g;else{const C=(w.envJson||"").trim();if(C)try{const S=JSON.parse(C);S&&typeof S=="object"&&(b=S)}catch{throw new Error("env JSON 格式错误")}}let v=null;if(b&&typeof b=="object"){v={};for(const C of Object.keys(b)){const S=b[C];Array.isArray(S)?v[C]=S.join(","):typeof S=="boolean"||typeof S=="number"?v[C]=String(S):S==null?v[C]="":typeof S=="object"?v[C]=JSON.stringify(S):v[C]=String(S)}}if(u)if(await ne.updateMcpConfigProfile(e.id,u,{name:w.name,env:v,enabled:w.enabled})){const S=await ne.getMcpConfigProfiles(e.id);s(Array.isArray(S)?S:[]),x(!1),p(null)}else throw new Error("更新失败");else{const C=await ne.createMcpConfigProfile(e.id,{name:w.name,env:v,enabled:w.enabled});if(C&&(C.id||C.success)){const S=await ne.getMcpConfigProfiles(e.id);s(Array.isArray(S)?S:[]),x(!1)}else throw new Error("创建失败")}}catch(b){c((b==null?void 0:b.message)||"保存失败")}},children:"保存"})]})]})]})})]})]})},mg={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Ma=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),gg=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),pg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),xg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),yg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),ho=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=ft()}catch{t=ut()}const{mcpConfigs:n,updateMcpConfig:s,deleteMcpConfig:o,loadMcpConfigs:i,applications:l,setMcpAppAssociation:d}=t,{dialogState:u,showConfirmDialog:p,handleConfirm:f,handleCancel:x}=bn(),[w,m]=T.useState(!1),[h,c]=T.useState(null),[g,y]=T.useState({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),[b,_]=T.useState(!1),[v,C]=T.useState(null),[S,I]=T.useState({}),[E,P]=T.useState([]),[R,j]=T.useState(""),[W,D]=T.useState(!1),[X,G]=T.useState(null),[N,F]=T.useState([]);T.useEffect(()=>{const A="__mcpManagerInitAt__",L=window[A]||0,B=Date.now();if(!(typeof L=="number"&&B-L<1e3)){window[A]=B,i();try{(t.loadApplications??(()=>{}))()}catch{}}},[i]);const z=async A=>{G(A),D(!0);try{const L=await ne.getMcpConfigProfiles(A.id);P(Array.isArray(L)?L:[])}catch{console.error("加载配置档案失败")}finally{}},$=()=>{y({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),c(null),m(!1),I({}),P([]),j(""),F([])},O=async A=>{var H,re;if(A.preventDefault(),!g.name.trim()||!g.command.trim())return;const L={name:g.name.trim(),command:g.command.trim(),type:g.type,enabled:g.enabled,cwd:(H=g.cwd)!=null&&H.trim()?g.cwd.trim():void 0,args:(re=g.argsInput)!=null&&re.trim()?g.argsInput.split(",").map(ce=>ce.trim()).filter(Boolean):void 0,createdAt:new Date,updatedAt:new Date,app_ids:N},B=await s(L);B!=null&&B.id&&(d==null||d(B.id,N)),$()},U=async A=>{var H,re;if(A.preventDefault(),!h||!g.name.trim()||!g.command.trim())return;const L={...h,name:g.name.trim(),command:g.command.trim(),type:g.type,enabled:g.enabled,cwd:(H=g.cwd)!=null&&H.trim()?g.cwd.trim():void 0,args:(re=g.argsInput)!=null&&re.trim()?g.argsInput.split(",").map(ce=>ce.trim()).filter(Boolean):void 0,updatedAt:new Date,app_ids:N},B=await s(L);B!=null&&B.id&&(d==null||d(B.id,N)),$()},V=A=>{c(A);let L="";const B=A.args;if(Array.isArray(B))L=B.map(H=>String(H)).join(", ");else if(typeof B=="string"&&B.trim()!=="")try{const H=JSON.parse(B);Array.isArray(H)?L=H.map(re=>String(re)).join(", "):L=B}catch{L=B}y({name:A.name,command:A.command,type:A.type||"stdio",enabled:A.enabled,cwd:A.cwd||"",argsInput:L}),m(!0),I({}),C(null),_(!1),F(Array.isArray(A.app_ids)?A.app_ids:[])},k=async A=>{const L=n.find(B=>B.id===A);p({title:"删除 MCP 服务器",message:`确定要删除服务器 "${(L==null?void 0:L.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:()=>o(A)})},q=async A=>{const L={...A,enabled:!A.enabled,updatedAt:new Date};await s(L)};return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),a.jsxs("div",{className:"fixed right-0 top-0 h-full w-[520px] sm:w-[560px] bg-card z-50 shadow-xl breathing-border flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Ma,{}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"MCP 服务器管理"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx(gg,{})})]}),a.jsxs("div",{className:"p-4 flex-1 overflow-y-auto overflow-x-hidden",children:[!w&&a.jsxs("button",{onClick:()=>m(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx(pg,{}),a.jsx("span",{children:"添加 MCP 服务器"})]}),w&&a.jsxs("form",{onSubmit:h?U:O,className:"mb-6 p-4 bg-muted rounded-lg",children:[a.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:h?"编辑服务器":"添加新服务器"}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"服务器名称"}),a.jsx("input",{type:"text",value:g.name,onChange:A=>y({...g,name:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: File System",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"关联应用(多选)"}),a.jsxs("div",{className:"space-y-2 max-h-32 overflow-y-auto p-2 border rounded-md",children:[(l||[]).map(A=>a.jsxs("label",{className:"flex items-center space-x-2",children:[a.jsx("input",{type:"checkbox",checked:N.includes(A.id),onChange:L=>{const B=L.target.checked;F(H=>B?[...H,A.id]:H.filter(re=>re!==A.id))}}),a.jsx("span",{children:A.name})]},A.id)),(l||[]).length===0&&a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无应用,可在“应用管理”中创建。"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"协议类型"}),a.jsxs("select",{value:g.type,onChange:A=>y({...g,type:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",children:[a.jsx("option",{value:"stdio",children:"Stdio (标准输入输出)"}),a.jsx("option",{value:"http",children:"HTTP (网络协议)"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:g.type==="http"?"URL地址":"命令"}),a.jsx("input",{type:"text",value:g.command,onChange:A=>y({...g,command:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:g.type==="http"?"https://api.example.com/mcp":"npx @modelcontextprotocol/server-filesystem /path/to/allowed/files",required:!0}),g.type==="stdio"&&a.jsx(a.Fragment,{})]}),g.type==="stdio"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"可执行地址(cwd)"}),a.jsx("input",{type:"text",value:g.cwd,onChange:A=>y({...g,cwd:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"/absolute/path/to/executable"}),a.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"为空则使用当前页面的工作目录"}),a.jsx("div",{className:"mt-2 flex gap-2",children:a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{var A,L;if(g.command.trim()){_(!0),C(null);try{const B=await ne.getMcpConfigResourceByCommand({type:g.type,command:g.command.trim(),args:(A=g.argsInput)!=null&&A.trim()?g.argsInput.split(",").map(H=>H.trim()).filter(Boolean):void 0,env:void 0,cwd:(L=g.cwd)!=null&&L.trim()?g.cwd.trim():void 0,alias:null});if(B&&B.success&&B.config){const H=B.config;if(I(H),h!=null&&h.id)try{const re=await ne.getMcpConfigProfiles(h.id);P(Array.isArray(re)?re:[])}catch{}}else C("无法获取服务器可配置参数")}catch(B){C((B==null?void 0:B.message)||"获取配置失败")}finally{_(!1)}}},children:b?"获取中…":"获取配置"})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"启动参数(args,逗号分隔)"}),a.jsx("input",{type:"text",value:g.argsInput,onChange:A=>y({...g,argsInput:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"--flag, value, --opt"}),a.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"将自动转换为参数数组"})]})]}),a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",id:"enabled",checked:g.enabled,onChange:A=>y({...g,enabled:A.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此服务器"})]}),g.type==="stdio"&&Object.keys(S).length>0&&a.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-foreground",children:"服务器可配置参数(动态解析)"}),b&&a.jsx("span",{className:"text-xs text-muted-foreground",children:"解析中…"})]}),v&&a.jsx("p",{className:"text-xs text-red-600 mb-2",children:v}),a.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[Object.keys(S).map(A=>{const L=S[A],B=typeof L,H=Array.isArray(L);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:A}),B==="boolean"?a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",checked:!!L,onChange:re=>I({...S,[A]:re.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("span",{className:"ml-2 text-xs",children:String(L)})]}):H?a.jsx("input",{type:"text",value:L.join(", "),onChange:re=>I({...S,[A]:re.target.value.split(",").map(ce=>ce.trim()).filter(Boolean)}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"}):a.jsx("input",{type:B==="number"?"number":"text",value:L??"",onChange:re=>I({...S,[A]:B==="number"?Number(re.target.value):re.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},A)}),(h==null?void 0:h.id)&&a.jsxs("div",{className:"mt-2 p-2 border border-dashed rounded-md",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"text",value:R,onChange:A=>j(A.target.value),className:"flex-1 px-2 py-1 border border-input bg-background text-foreground rounded-md",placeholder:"配置档案名称(例如:开发环境)"}),a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:async()=>{var A,L;if(h!=null&&h.id)try{await ne.createMcpConfigProfile(h.id,{name:R||`配置-${new Date().toLocaleString()}`,env:Object.keys(S).reduce((H,re)=>{const ce=S[re];return H[re]=typeof ce=="string"?ce:String(ce),H},{}),args:(A=g.argsInput)!=null&&A.trim()?g.argsInput.split(",").map(H=>H.trim()).filter(Boolean):void 0,cwd:(L=g.cwd)!=null&&L.trim()?g.cwd.trim():void 0,enabled:!1});const B=await ne.getMcpConfigProfiles(h.id);P(Array.isArray(B)?B:[]),j("")}catch(B){console.error("保存配置档案失败:",B),C("保存配置档案失败")}},children:"保存为配置档案"})]}),E.length>0&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:"text-xs text-muted-foreground",children:"已有配置档案:"}),E.map(A=>{const L=Array.isArray(A.args)?A.args.join(", "):"",B=A.env?Object.keys(A.env):[];return a.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"text-xs text-foreground font-medium",children:A.name}),A.enabled&&a.jsx("span",{className:"px-2 py-0.5 text-[10px] rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200",children:"已启用"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{try{await ne.activateMcpConfigProfile(h.id,A.id);const H=await ne.getMcpConfigProfiles(h.id);P(Array.isArray(H)?H:[])}catch{}},children:"激活"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{y(H=>({...H,argsInput:Array.isArray(A.args)?A.args.join(", "):H.argsInput,cwd:A.cwd??H.cwd})),I(A.env||{})},children:"应用到表单"})]})]}),a.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[a.jsxs("div",{className:"truncate",title:A.cwd||"未设置",children:[a.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),A.cwd||"未设置"]}),a.jsxs("div",{className:"truncate",title:L||"未设置",children:[a.jsx("span",{className:"text-muted-foreground",children:"args:"}),L||"未设置"]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-muted-foreground",children:["env(",B.length,"):"]}),B.length===0?"未设置":a.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:B.map(H=>a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-muted-foreground shrink-0",children:H}),a.jsx("span",{className:"text-foreground truncate",title:String(A.env[H]),children:String(A.env[H])})]},H))})]})]})]},A.id)})]})]})]})]})]}),(h==null?void 0:h.id)&&!w&&a.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-foreground",children:"配置档案列表"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{try{const A=await ne.getMcpConfigProfiles(h.id);P(Array.isArray(A)?A:[])}catch{}},children:"刷新"})]}),E.length===0?a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案"}):a.jsx("div",{className:"space-y-2",children:E.map(A=>{const L=Array.isArray(A.args)?A.args.join(", "):"",B=A.env?Object.keys(A.env):[];return a.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"text-xs text-foreground font-medium",children:A.name}),A.enabled&&a.jsx("span",{className:"px-2 py-0.5 text-[10px] rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200",children:"已启用"})]}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{try{await ne.activateMcpConfigProfile(h.id,A.id);const H=await ne.getMcpConfigProfiles(h.id);P(Array.isArray(H)?H:[])}catch{}},children:"激活"})})]}),a.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),A.cwd||"未设置"]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"args:"}),L||"未设置"]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-muted-foreground",children:["env(",B.length,"):"]}),B.length===0?"未设置":a.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:B.map(H=>a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-muted-foreground",children:H}),a.jsx("span",{className:"text-foreground",children:String(A.env[H])})]},H))})]})]})]},A.id)})})]}),a.jsxs("div",{className:"flex space-x-3 mt-6",children:[a.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:h?"更新":"添加"}),a.jsx("button",{type:"button",onClick:$,className:"px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 focus:outline-none focus:ring-2 focus:ring-ring",children:"取消"})]})]}),a.jsx("div",{className:"space-y-3",children:n.length===0?a.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[a.jsx(Ma,{}),a.jsx("p",{className:"mt-2",children:"暂无 MCP 服务器配置"}),a.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个服务器"})]}):n.map(A=>a.jsxs("div",{className:"flex items-center justify-between gap-3 p-4 bg-card border border-border rounded-lg",children:[a.jsxs("div",{className:"flex items-center space-x-3 flex-1 min-w-0",children:[a.jsx("div",{className:`w-3 h-3 rounded-full ${A.enabled?"bg-green-500":"bg-gray-400"}`}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center space-x-2 min-w-0",children:[a.jsx("h4",{className:"font-medium text-foreground truncate",title:A.name,children:A.name}),a.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${A.type==="http"?"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200":"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"}`,children:A.type==="http"?"HTTP":"Stdio"})]}),a.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground truncate break-all font-mono",title:A.command,children:A.command}),typeof window<"u"&&mg&&!1,A.type==="stdio"&&a.jsxs("div",{className:"mt-1 space-y-0.5 min-w-0",children:[A.cwd&&a.jsxs("div",{className:"text-xs text-muted-foreground truncate",title:String(A.cwd),children:["cwd: ",a.jsx("span",{className:"text-foreground",children:String(A.cwd)})]}),a.jsx("div",{className:"text-xs text-muted-foreground truncate",title:(()=>{const L=A.args;let B=null,H=!1;if(Array.isArray(L))B=L.map(ce=>String(ce));else if(typeof L=="string"&&L.trim()!=="")try{const ce=JSON.parse(L);Array.isArray(ce)&&(B=ce.map(wn=>String(wn)),H=!0)}catch{}const re=Array.isArray(B)&&B.length>0?B.join(", "):typeof L=="string"&&!H?L:"—";return String(re)})(),children:(()=>{const L=A.args;let B=null,H=!1;if(Array.isArray(L))B=L.map(ce=>String(ce));else if(typeof L=="string"&&L.trim()!=="")try{const ce=JSON.parse(L);Array.isArray(ce)&&(B=ce.map(wn=>String(wn)),H=!0)}catch{}const re=Array.isArray(B)&&B.length>0?B.join(", "):typeof L=="string"&&!H?L:"—";return a.jsxs("span",{children:["参数(args):",a.jsx("span",{className:"text-foreground",children:re})]})})()})]})]})]}),a.jsxs("div",{className:"flex items-center space-x-2 shrink-0",children:[a.jsx("button",{onClick:()=>q(A),className:`px-3 py-1 text-xs rounded-full ${A.enabled?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-secondary text-secondary-foreground"}`,children:A.enabled?"已启用":"已禁用"}),a.jsx("button",{onClick:()=>z(A),className:"p-2 text-muted-foreground hover:text-indigo-600 transition-colors",title:"查看配置档案",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 7.5l7.5 3 7.5-3M3 7.5V18l7.5 3 7.5-3V7.5M10.5 10.5V21"})})}),a.jsx("button",{onClick:()=>V(A),className:"p-2 text-muted-foreground hover:text-blue-600 transition-colors",title:"编辑",children:a.jsx(yg,{})}),a.jsx("button",{onClick:()=>k(A.id),className:"p-2 text-muted-foreground hover:text-red-600 transition-colors",title:"删除",children:a.jsx(xg,{})})]})]},A.id))})]})]}),a.jsx(hg,{open:W,config:X,onClose:()=>{D(!1),G(null)}}),a.jsx(yn,{isOpen:u.isOpen,title:u.title,message:u.message,confirmText:u.confirmText,cancelText:u.cancelText,type:u.type,onConfirm:f,onCancel:x})]})},Ea=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),bg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),wg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),vg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),_g=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),mo=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=ft()}catch{t=ut()}const{aiModelConfigs:n,loadAiModelConfigs:s,updateAiModelConfig:o,deleteAiModelConfig:i}=t,[l,d]=T.useState(!1),[u,p]=T.useState(null),[f,x]=T.useState({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),{dialogState:w,showConfirmDialog:m,handleConfirm:h,handleCancel:c}=bn();T.useEffect(()=>{const S="__aiModelManagerInitAt__",I=window[S]||0,E=Date.now();typeof I=="number"&&E-I<1e3||(window[S]=E,s())},[s]);const g=()=>{x({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),p(null),d(!1)},y=async S=>{if(S.preventDefault(),!f.name.trim()||!f.base_url.trim()||!f.api_key.trim()||!f.model_name.trim())return;const I={id:Math.random().toString(36).substr(2,9),name:f.name.trim(),base_url:f.base_url.trim(),api_key:f.api_key.trim(),model_name:f.model_name.trim(),enabled:f.enabled,createdAt:new Date,updatedAt:new Date};await o(I),g()},b=async S=>{if(S.preventDefault(),!u||!f.name.trim()||!f.base_url.trim()||!f.api_key.trim()||!f.model_name.trim())return;const I={...u,name:f.name.trim(),base_url:f.base_url.trim(),api_key:f.api_key.trim(),model_name:f.model_name.trim(),enabled:f.enabled,updatedAt:new Date};await o(I),g()},_=S=>{p(S),x({name:S.name,base_url:S.base_url,api_key:S.api_key,model_name:S.model_name,enabled:S.enabled}),d(!0)},v=async S=>{const I=n.find(E=>E.id===S);m({title:"删除确认",message:`确定要删除AI模型配置 "${(I==null?void 0:I.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{await i(S)}})},C=async S=>{const I={...S,enabled:!S.enabled,updatedAt:new Date};await o(I)};return a.jsxs("div",{className:"modal-container",children:[a.jsxs("div",{className:"modal-content w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Ea,{}),a.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"AI 模型管理"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(bg,{})})]}),a.jsxs("div",{className:"p-6 overflow-y-auto overflow-x-hidden max-h-[calc(80vh-120px)]",children:[!l&&a.jsxs("button",{onClick:()=>d(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx(wg,{}),a.jsx("span",{children:"添加 AI 模型"})]}),l&&a.jsxs("form",{onSubmit:u?b:y,className:"mb-6 p-4 bg-muted rounded-lg",children:[a.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:u?"编辑 AI 模型":"添加 AI 模型"}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),a.jsx("input",{type:"text",value:f.name,onChange:S=>x({...f,name:S.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: OpenAI GPT-4",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Base URL"}),a.jsx("input",{type:"url",value:f.base_url,onChange:S=>x({...f,base_url:S.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: https://api.openai.com/v1",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"API Key"}),a.jsx("input",{type:"password",value:f.api_key,onChange:S=>x({...f,api_key:S.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"输入API密钥",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"模型名称"}),a.jsx("input",{type:"text",value:f.model_name,onChange:S=>x({...f,model_name:S.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: gpt-4",required:!0})]}),a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",id:"enabled",checked:f.enabled,onChange:S=>x({...f,enabled:S.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此模型"})]})]}),a.jsxs("div",{className:"flex space-x-3 mt-6",children:[a.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:u?"更新":"添加"}),a.jsx("button",{type:"button",onClick:g,className:"px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 focus:outline-none focus:ring-2 focus:ring-ring",children:"取消"})]})]}),a.jsx("div",{className:"space-y-3",children:n.length===0?a.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[a.jsx(Ea,{}),a.jsx("p",{className:"mt-2",children:"暂无 AI 模型配置"}),a.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个模型"})]}):n.map(S=>a.jsxs("div",{className:"flex items-center justify-between gap-3 p-4 bg-card border border-border rounded-lg hover:shadow-md transition-shadow",children:[a.jsxs("div",{className:"flex items-center space-x-3 flex-1 min-w-0",children:[a.jsx("div",{className:`w-3 h-3 rounded-full ${S.enabled?"bg-green-500":"bg-gray-400"}`}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("h4",{className:"font-medium text-foreground truncate",title:S.name,children:S.name}),a.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground truncate",title:`${S.base_url} - ${S.model_name}`,children:[S.base_url," - ",S.model_name]})]})]}),a.jsxs("div",{className:"flex items-center space-x-2 shrink-0",children:[a.jsx("button",{onClick:()=>C(S),className:`px-3 py-1 text-xs rounded-full transition-colors ${S.enabled?"bg-green-100 text-green-800 hover:bg-green-200 dark:bg-green-900 dark:text-green-200":"bg-secondary text-secondary-foreground hover:bg-secondary/80"}`,children:S.enabled?"已启用":"已禁用"}),a.jsx("button",{onClick:()=>_(S),className:"p-2 text-muted-foreground hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded transition-colors",title:"编辑",children:a.jsx(vg,{})}),a.jsx("button",{onClick:()=>v(S.id),className:"p-2 text-muted-foreground hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded transition-colors",title:"删除",children:a.jsx(_g,{})})]})]},S.id))})]})]}),a.jsx(yn,{isOpen:w.isOpen,title:w.title,message:w.message,confirmText:w.confirmText,cancelText:w.cancelText,type:w.type,onConfirm:h,onCancel:c})]})},Ia=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),Sg=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),Cg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),jg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Ag=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),kg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),Ng=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),go=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=ft()}catch{t=ut()}const{systemContexts:n,activeSystemContext:s,loadSystemContexts:o,createSystemContext:i,updateSystemContext:l,deleteSystemContext:d,activateSystemContext:u,applications:p,loadApplications:f}=t,[x,w]=T.useState("list"),[m,h]=T.useState(null),[c,g]=T.useState({name:"",content:""}),[y,b]=T.useState(!1),[_,v]=T.useState(!1),[C,S]=T.useState([]),{dialogState:I,showConfirmDialog:E,handleConfirm:P,handleCancel:R}=bn();T.useEffect(()=>{const $="__systemContextEditorInitAt__",O=window[$]||0,U=Date.now();if(typeof O=="number"&&U-O<1e3)return;window[$]=U,(async()=>{b(!0);try{await o();try{await(f==null?void 0:f())}catch{}}catch(k){console.error("Failed to load system contexts:",k)}finally{b(!1)}})()},[o]);const j=()=>{g({name:"",content:""}),h(null),w("create")},W=$=>{g({name:$.name,content:$.content}),h($),S(Array.isArray($.app_ids)?$.app_ids:[]),w("edit")},D=async()=>{if(!c.name.trim()||!c.content.trim()){alert("请填写名称和内容");return}v(!0);try{x==="create"?await i(c.name,c.content,C):x==="edit"&&m&&await l(m.id,c.name,c.content,C),w("list")}catch($){console.error("Failed to save system context:",$),alert("保存失败,请重试")}finally{v(!1)}},X=async $=>{E({title:"删除确认",message:`确定要删除上下文 "${$.name}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{try{await d($.id)}catch(O){console.error("Failed to delete system context:",O),alert("删除失败,请重试")}}})},G=async $=>{try{await u($.id),await o()}catch(O){console.error("Failed to activate system context:",O),alert("激活失败,请重试")}},N=$=>{$.ctrlKey&&$.key==="s"&&($.preventDefault(),x!=="list"&&D())},F=()=>a.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[a.jsx("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:a.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:[a.jsx("strong",{children:"系统上下文"}),"将作为每次对话的系统提示词,支持 Markdown 格式。 您可以创建多个上下文配置,但同一时间只能激活一个。"]})}),a.jsx("div",{className:"flex-1 overflow-y-auto",children:y?a.jsx("div",{className:"flex items-center justify-center h-32",children:a.jsx("div",{className:"text-muted-foreground",children:"加载中..."})}):n.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-muted-foreground",children:[a.jsx(Ia,{}),a.jsx("p",{className:"mt-2",children:"暂无系统上下文配置"}),a.jsx("p",{className:"text-sm",children:'点击"新建"按钮创建第一个配置'})]}):a.jsx("div",{className:"space-y-3",children:n.map($=>a.jsx("div",{className:`p-4 border rounded-lg transition-colors ${$.isActive?"border-green-500 bg-green-50 dark:bg-green-900/20":"border-border bg-card"}`,children:a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("h3",{className:"font-medium text-foreground",children:$.name}),$.isActive&&a.jsxs("span",{className:"inline-flex items-center px-2 py-1 text-xs font-medium bg-green-100 text-green-800 rounded-full dark:bg-green-800 dark:text-green-100",children:[a.jsx(Ng,{}),a.jsx("span",{className:"ml-1",children:"已激活"})]})]}),a.jsxs("p",{className:"mt-1 text-sm text-muted-foreground line-clamp-2",children:[$.content.substring(0,100),$.content.length>100&&"..."]}),a.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["创建时间: ",new Date($.createdAt).toLocaleString()]})]}),a.jsxs("div",{className:"flex items-center space-x-2 ml-4",children:[!$.isActive&&a.jsx("button",{onClick:()=>G($),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"激活"}),a.jsx("button",{onClick:()=>W($),className:"p-2 text-muted-foreground hover:text-blue-600 hover:bg-accent rounded transition-colors",children:a.jsx(Ag,{})}),a.jsx("button",{onClick:()=>X($),className:"p-2 text-muted-foreground hover:text-red-600 hover:bg-accent rounded transition-colors",children:a.jsx(kg,{})})]})]})},$.id))})})]}),z=()=>a.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[a.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:[a.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:x==="create"?"创建新的系统上下文配置":"编辑系统上下文配置"}),a.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300 mt-2",children:"提示:使用 Ctrl+S 快速保存"})]}),a.jsxs("div",{className:"flex-1 flex flex-col space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),a.jsx("input",{type:"text",value:c.name,onChange:$=>g({...c,name:$.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-lg focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如:编程助手、翻译专家、创意写作等"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"关联应用(多选)"}),a.jsxs("div",{className:"space-y-2 max-h-32 overflow-y-auto p-2 border rounded-md",children:[(p||[]).map($=>a.jsxs("label",{className:"flex items-center space-x-2",children:[a.jsx("input",{type:"checkbox",checked:C.includes($.id),onChange:O=>{const U=O.target.checked;S(V=>U?[...V,$.id]:V.filter(k=>k!==$.id))}}),a.jsx("span",{children:$.name})]},$.id)),(p||[]).length===0&&a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无应用,可在“应用管理”中创建。"})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col",children:[a.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[a.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Markdown 内容"}),a.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.content.length," 字符"]})]}),a.jsx("textarea",{value:c.content,onChange:$=>g({...c,content:$.target.value}),onKeyDown:N,className:"flex-1 w-full px-4 py-3 border border-input bg-background text-foreground rounded-lg focus:outline-none focus:ring-2 focus:ring-ring resize-none font-mono text-sm",placeholder:"请输入系统上下文内容,支持 Markdown 格式...\\n\\n例如:\\n# AI 助手角色设定\\n\\n你是一个专业的编程助手,具有以下特点:\\n- 提供准确、简洁的代码解决方案\\n- 遵循最佳实践和代码规范\\n- 耐心解答技术问题\\n\\n## 回答风格\\n- 使用中文回答\\n- 代码示例要完整可运行\\n- 提供必要的解释说明",spellCheck:!1})]}),a.jsxs("div",{className:"text-xs text-muted-foreground",children:[a.jsx("p",{children:"• 支持标准 Markdown 语法:标题、列表、代码块、链接等"}),a.jsx("p",{children:"• 内容将在每次对话开始时自动发送给 AI"}),a.jsx("p",{children:"• 留空则使用默认系统提示词"})]})]})]});return a.jsxs("div",{className:"modal-container",children:[a.jsxs("div",{className:"modal-content w-full max-w-4xl max-h-[90vh] overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Ia,{}),a.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"系统上下文设置"})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[x==="list"?a.jsxs("button",{onClick:j,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 transition-colors",children:[a.jsx(jg,{}),a.jsx("span",{children:"新建"})]}):a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:D,disabled:_,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:[a.jsx(Cg,{}),a.jsx("span",{children:_?"保存中...":"保存"})]}),a.jsx("button",{onClick:()=>w("list"),className:"px-4 py-2 text-secondary-foreground border border-border rounded-md hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring transition-colors",children:"取消"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(Sg,{})})]})]}),x==="list"?F():z()]}),a.jsx(yn,{isOpen:I.isOpen,title:I.title,message:I.message,confirmText:I.confirmText,cancelText:I.cancelText,type:I.type,onConfirm:P,onCancel:R})]})},Ta=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6M9 16h6M6 8h12a2 2 0 012 2v8a2 2 0 01-2 2H6a2 2 0 01-2-2v-8a2 2 0 012-2z"})}),Pa=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),Mg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Eg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),sc=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=ft()}catch{t=ut()}const{aiModelConfigs:n,loadAiModelConfigs:s,mcpConfigs:o,loadMcpConfigs:i,systemContexts:l,loadSystemContexts:d,applications:u,loadApplications:p}=t,{userId:f}=$f(),x=f||"custom_user_123",m=Lf()||ne,[h,c]=T.useState([]),[g,y]=T.useState(!1),[b,_]=T.useState(!1),[v,C]=T.useState(null),[S,I]=T.useState(null),[E,P]=T.useState({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),[R,j]=T.useState([]),W=T.useRef(!1),D=async()=>{y(!0);try{await Promise.all([s(),i(),d(),p?p():Promise.resolve(),t.loadAgents?t.loadAgents():Promise.resolve()]);const k=t.agents&&Array.isArray(t.agents)?t.agents:await m.getAgents(x),q=Array.isArray(k)?k:[];c(q)}catch(k){console.error("加载智能体失败",k)}finally{y(!1)}},X=async k=>{for(let A=0;A<3;A++)try{t.loadAgents&&await t.loadAgents();const L=await m.getAgents(x),B=Array.isArray(L)?L:[];if(c(B),k&&Array.isArray(B)&&B.some(H=>H.id===k)||!k)break;await new Promise(H=>setTimeout(H,250))}catch(L){console.warn("刷新智能体列表失败,重试中…",L),await new Promise(B=>setTimeout(B,250))}};T.useEffect(()=>{const k="__agentManagerInitAt__",q=window[k]||0,A=Date.now();typeof q=="number"&&A-q<1e3||(window[k]=A,D())},[]);const G=()=>{P({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),_(!1),I(null),j([])};T.useEffect(()=>{if(W.current){W.current=!1;return}P(k=>{const q={...k};return q.mcp_config_ids=[],q.system_context_id=void 0,q})},[R]);const N=async k=>{var q;if(k.preventDefault(),!(!E.name.trim()||!E.ai_model_config_id))try{const A=await m.createAgent({name:E.name.trim(),description:((q=E.description)==null?void 0:q.trim())||void 0,ai_model_config_id:E.ai_model_config_id,mcp_config_ids:E.mcp_config_ids,system_context_id:E.system_context_id,user_id:x,enabled:!0,app_ids:R});A&&A.id&&c(L=>L.some(H=>H.id===A.id)?L.map(H=>H.id===A.id?{...H,...A}:H):[A,...L]),await X(A==null?void 0:A.id),G()}catch(A){console.error("创建智能体失败",A),alert("创建失败,请重试")}},F=async k=>{if(k.preventDefault(),!!S)try{const q=await m.updateAgent(S.id,{name:E.name,description:E.description,ai_model_config_id:E.ai_model_config_id,mcp_config_ids:E.mcp_config_ids,system_context_id:E.system_context_id,enabled:!0,app_ids:R});c(A=>A.map(L=>L.id===S.id?{...L,...q,name:E.name,description:E.description,ai_model_config_id:E.ai_model_config_id,mcp_config_ids:E.mcp_config_ids,system_context_id:E.system_context_id,enabled:!0}:L)),await X(S.id),G()}catch(q){console.error("更新智能体失败",q),alert("更新失败,请重试")}},z=async k=>{try{await m.deleteAgent(k),c(q=>q.filter(A=>A.id!==k)),await X()}catch(q){console.error("删除智能体失败",q),alert("删除失败,请重试")}},$=k=>{I(k),_(!0),P({name:k.name,description:k.description||"",ai_model_config_id:k.ai_model_config_id,mcp_config_ids:Array.isArray(k.mcp_config_ids)?k.mcp_config_ids:[],system_context_id:k.system_context_id}),W.current=!0,j(Array.isArray(k.app_ids)?k.app_ids:[])},O=k=>{const q=n.find(A=>A.id===k);return q?`${q.name}(${q.model_name})`:k},U=k=>{if(!k)return"未选择";const q=l.find(A=>A.id===k);return q?q.name:k},V=k=>k.map(A=>{const L=o.find(B=>B.id===A);return L?L.name:A}).join(",");return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),a.jsxs("div",{className:"fixed right-0 top-0 h-full w-[520px] sm:w-[560px] bg-card z-50 shadow-xl breathing-border flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Ta,{}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"智能体管理"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx(Pa,{})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[!b&&a.jsxs("button",{onClick:()=>_(!0),className:"w-full p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx(Mg,{}),a.jsx("span",{children:"新增智能体"})]}),b&&a.jsxs("form",{onSubmit:S?F:N,className:"p-4 bg-muted rounded-lg space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"关联应用(多选)"}),a.jsxs("div",{className:"space-y-2 max-h-32 overflow-y-auto p-2 border rounded-md",children:[(u||[]).map(k=>a.jsxs("label",{className:"flex items-center space-x-2",children:[a.jsx("input",{type:"checkbox",checked:R.includes(k.id),onChange:q=>{const A=q.target.checked;j(L=>A?[...L,k.id]:L.filter(B=>B!==k.id))}}),a.jsx("span",{children:k.name})]},k.id)),(u||[]).length===0&&a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无应用,可在“应用管理”中创建。"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),a.jsx("input",{type:"text",value:E.name,onChange:k=>P({...E,name:k.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如:项目助理",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"描述"}),a.jsx("textarea",{value:E.description,onChange:k=>P({...E,description:k.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"智能体用途说明",rows:3})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择模型(单选)"}),a.jsxs("select",{value:E.ai_model_config_id,onChange:k=>P({...E,ai_model_config_id:k.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",required:!0,children:[a.jsx("option",{value:"",children:"请选择模型"}),n.map(k=>a.jsxs("option",{value:k.id,children:[k.name,"(",k.model_name,")"]},k.id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 MCP 配置(多选)"}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 border rounded-md",children:[(R.length?o.filter(k=>Array.isArray(k.app_ids)&&k.app_ids.some(q=>R.includes(q))):o).map(k=>a.jsxs("label",{className:"flex items-center space-x-2",children:[a.jsx("input",{type:"checkbox",checked:E.mcp_config_ids.includes(k.id),onChange:q=>{const A=q.target.checked;P(L=>({...L,mcp_config_ids:A?[...L.mcp_config_ids,k.id]:L.mcp_config_ids.filter(B=>B!==k.id)}))}}),a.jsx("span",{children:k.name})]},k.id)),R.length>0&&o.filter(k=>Array.isArray(k.app_ids)&&k.app_ids.some(q=>R.includes(q))).length===0&&a.jsx("div",{className:"text-xs text-muted-foreground",children:"所选应用下暂无 MCP 配置"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择系统上下文"}),a.jsxs("select",{value:E.system_context_id||"",onChange:k=>P({...E,system_context_id:k.target.value||void 0}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",children:[a.jsx("option",{value:"",children:"不使用"}),(R.length?l.filter(k=>Array.isArray(k.app_ids)&&k.app_ids.some(q=>R.includes(q))):l).map(k=>a.jsx("option",{value:k.id,children:k.name},k.id)),R.length>0&&l.filter(k=>Array.isArray(k.app_ids)&&k.app_ids.some(q=>R.includes(q))).length===0&&a.jsx("option",{value:"",disabled:!0,children:"所选应用下暂无系统上下文"})]})]}),a.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[a.jsx("button",{type:"button",onClick:G,className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"取消"}),a.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:"保存"})]})]}),a.jsx("div",{children:g?a.jsx("div",{className:"text-muted-foreground",children:"加载中..."}):h.length===0?a.jsx("div",{className:"text-muted-foreground",children:"暂无智能体配置"}):a.jsx("div",{className:"space-y-3",children:h.map(k=>a.jsxs("div",{className:"p-4 border rounded-lg flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center space-x-2 min-w-0",children:[a.jsx("h3",{className:"font-medium text-foreground truncate",title:k.name,children:k.name}),!k.enabled&&a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-muted text-muted-foreground",children:"未启用"})]}),k.description&&a.jsx("p",{className:"mt-1 text-sm text-muted-foreground truncate",title:k.description,children:k.description}),a.jsxs("p",{className:"mt-2 text-xs text-muted-foreground truncate",title:O(k.ai_model_config_id),children:["模型:",O(k.ai_model_config_id)]}),a.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:U(k.system_context_id),children:["系统上下文:",U(k.system_context_id)]}),a.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:V(k.mcp_config_ids||[]),children:["MCP配置:",V(k.mcp_config_ids||[])]})]}),a.jsxs("div",{className:"flex items-center space-x-2 ml-4 shrink-0",children:[a.jsx("button",{onClick:()=>C(k),className:"px-3 py-1 text-sm bg-muted text-foreground rounded hover:bg-accent transition-colors",children:"详情"}),a.jsx("button",{onClick:()=>$(k),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"编辑"}),a.jsxs("button",{onClick:()=>z(k.id),className:"px-3 py-1 text-sm bg-destructive text-destructive-foreground rounded hover:bg-destructive/90 transition-colors flex items-center space-x-1",children:[a.jsx(Eg,{}),a.jsx("span",{children:"删除"})]})]})]},k.id))})})]}),v&&a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:()=>C(null)}),a.jsxs("div",{className:"relative bg-card border border-border rounded-lg shadow-xl w-[520px] p-6",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx(Ta,{}),a.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"智能体详情"})]}),a.jsx("button",{onClick:()=>C(null),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(Pa,{})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"名称:"}),v.name]}),v.description&&a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"描述:"}),v.description]}),a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"模型:"}),O(v.ai_model_config_id)]}),a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"系统上下文:"}),U(v.system_context_id)]}),a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"MCP配置:"}),V(v.mcp_config_ids||[])]}),Array.isArray(v.mcp_config_ids)&&v.mcp_config_ids.length>0&&a.jsx("div",{className:"mt-2 space-y-2",children:(v.mcp_config_ids||[]).map(k=>{var B,H;const q=(o||[]).find(re=>re.id===k);if(!q)return null;let A="—";const L=q.args;if(Array.isArray(L))A=L.map(re=>String(re)).join(", ");else if(typeof L=="string"&&L.trim()!=="")try{const re=JSON.parse(L);Array.isArray(re)?A=re.map(ce=>String(ce)).join(", "):A=L}catch{A=L}return a.jsxs("div",{className:"p-2 rounded border border-border",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-foreground",children:q.name}),a.jsx("span",{className:`px-1.5 py-0.5 text-xs rounded ${q.type==="http"?"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200":"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"}`,children:((H=(B=q.type)==null?void 0:B.toUpperCase)==null?void 0:H.call(B))||q.type})]}),a.jsxs("div",{className:"mt-1 text-xs text-muted-foreground break-all",children:[q.type==="http"?"URL:":"命令:",a.jsx("span",{className:"text-foreground",children:q.command})]}),q.cwd&&a.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground break-all",children:["cwd:",a.jsx("span",{className:"text-foreground",children:String(q.cwd)})]}),q.type==="stdio"&&a.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground break-all",children:["args:",a.jsx("span",{className:"text-foreground",children:A})]})]},k)})}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:["创建时间:",v.created_at?new Date(v.created_at).toLocaleString():"-"]})]}),a.jsx("div",{className:"mt-4 flex justify-end space-x-2",children:a.jsx("button",{onClick:()=>C(null),className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"关闭"})})]})]})]})]})},oc=({isOpen:r,onClose:e,manageOnly:t=!1,title:n,layout:s="modal",onApplicationSelect:o})=>{let i;try{i=ft()}catch{i=ut()}const{applications:l,loadApplications:d,createApplication:u,updateApplication:p,deleteApplication:f}=i,x=T.useRef(new Map),[w,m]=T.useState(!!t),[h,c]=T.useState(!1),[g,y]=T.useState(null),[b,_]=T.useState({name:"",url:"",iconUrl:""});T.useEffect(()=>{try{console.log("[ApplicationsPanel] useEffect -> loadApplications"),d==null||d()}catch(j){console.error("[ApplicationsPanel] loadApplications error:",j)}},[d]);const v=()=>{y(null),_({name:"",url:"",iconUrl:""}),c(!1)},C=async j=>{j.preventDefault(),b.name.trim()&&(g?await(p==null?void 0:p(g,{name:b.name.trim(),url:b.url.trim(),iconUrl:b.iconUrl.trim()||void 0})):await(u==null?void 0:u(b.name.trim(),b.url.trim(),b.iconUrl.trim()||void 0)),v())},S=j=>{console.log("[ApplicationsPanel] closeAppWindow:",j);const W=x.current.get(j);W&&!W.closed&&W.close(),x.current.delete(j)},I=j=>{console.log("[ApplicationsPanel] handleAppClick - 应用被点击:",{id:j.id,name:j.name,url:j.url}),o?(console.log("[ApplicationsPanel] 调用 onApplicationSelect 回调"),o(j)):console.log("[ApplicationsPanel] ⚠️ 未提供 onApplicationSelect 回调"),e&&(console.log("[ApplicationsPanel] 关闭应用列表面板"),e())};if(!(s==="modal"?!!r:!0))return null;const P=t?!0:w,R=n??(P?"应用管理":"应用列表");return s==="modal"?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:e}),a.jsxs("div",{className:"fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[90vw] max-w-4xl h-[85vh] bg-card z-50 shadow-xl breathing-border flex flex-col rounded-lg",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full bg-blue-500"}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:R})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&a.jsx("button",{onClick:()=>{m(!w),c(!1),v()},className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent transition-colors",children:P?"浏览模式":"管理模式"}),!P&&x.current.size>0&&a.jsx("button",{className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",onClick:()=>{x.current.forEach((j,W)=>S(W))},children:"关闭全部"}),a.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:P?a.jsxs("div",{className:"space-y-4",children:[!h&&a.jsxs("button",{type:"button",onClick:()=>c(!0),className:"w-full p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v12m6-6H6"})}),a.jsx("span",{children:"新增应用"})]}),h&&a.jsxs("form",{onSubmit:C,className:"p-4 bg-muted rounded-lg space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),a.jsx("input",{type:"text",value:b.name,onChange:j=>_({...b,name:j.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如:Jira、GitHub",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"URL"}),a.jsx("input",{type:"text",value:b.url,onChange:j=>_({...b,url:j.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"https://app.example.com"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"图标URL"}),a.jsx("input",{type:"text",value:b.iconUrl,onChange:j=>_({...b,iconUrl:j.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"https://app.example.com/icon.png"})]}),a.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[a.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-muted hover:bg-accent",onClick:v,children:"取消"}),a.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:g?"保存":"创建"})]})]}),a.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(j=>a.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center overflow-hidden shrink-0",children:j.iconUrl?a.jsx("img",{src:j.iconUrl,alt:j.name,className:"w-full h-full object-cover"}):a.jsx("span",{className:"text-white text-sm font-bold",children:j.name.charAt(0).toUpperCase()})}),a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-medium text-foreground",children:j.name}),j.url&&a.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:j.url})]})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{className:"px-2 py-1 text-xs bg-muted rounded hover:bg-accent",onClick:()=>{y(j.id),c(!0),_({name:j.name,url:j.url||"",iconUrl:j.iconUrl||""})},children:"编辑"}),a.jsx("button",{className:"px-2 py-1 text-xs bg-destructive text-destructive-foreground rounded hover:bg-destructive/90",onClick:()=>f==null?void 0:f(j.id),children:"删除"})]})]},j.id)),(l==null?void 0:l.length)===0&&a.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[a.jsx("svg",{className:"w-16 h-16 mx-auto mb-3 opacity-30",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm",children:"暂无应用,点击上方按钮添加"})]})]})]}):a.jsxs("div",{className:"grid grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-6",children:[l==null?void 0:l.map(j=>{const W=x.current.has(j.id);return a.jsxs("div",{className:"relative group/item",children:[a.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>I(j),title:j.url||"",children:[a.jsxs("div",{className:`relative w-16 h-16 rounded-full flex items-center justify-center overflow-hidden transition-all ${W?"ring-2 ring-green-500 ring-offset-2 ring-offset-background scale-110":"bg-gradient-to-br from-blue-500/20 to-purple-500/20 group-hover/item:scale-105"}`,children:[j.iconUrl?a.jsx("img",{src:j.iconUrl,alt:j.name,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:a.jsx("span",{className:"text-white text-xl font-bold",children:j.name.charAt(0).toUpperCase()})}),W&&a.jsx("div",{className:"absolute -top-1 -right-1 w-5 h-5 bg-green-500 rounded-full border-2 border-background flex items-center justify-center",children:a.jsx("div",{className:"w-2 h-2 bg-white rounded-full animate-pulse"})})]}),a.jsx("div",{className:"text-xs font-medium text-foreground text-center truncate w-full px-1",children:j.name})]}),W&&a.jsx("button",{onClick:D=>{D.stopPropagation(),S(j.id)},className:"absolute top-0 left-0 w-5 h-5 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover/item:opacity-100 transition-opacity z-10",title:"关闭",children:a.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},j.id)}),((l==null?void 0:l.length)??0)===0&&a.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-20 text-center",children:[a.jsx("svg",{className:"w-20 h-20 text-muted-foreground/30 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),a.jsx("button",{onClick:()=>m(!0),className:"text-sm text-blue-500 hover:text-blue-600 underline",children:"点击切换到管理模式添加应用"})]})]})})]})]}):a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-border bg-card/50",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-blue-500"}),a.jsx("span",{className:"text-sm font-medium text-foreground",children:R})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&a.jsx("button",{onClick:()=>{m(!w),c(!1),v()},className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent transition-colors",children:P?"浏览模式":"管理模式"}),!P&&x.current.size>0&&a.jsx("button",{className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent",onClick:()=>{x.current.forEach((j,W)=>S(W))},children:"关闭全部"}),e&&a.jsx("button",{onClick:e,className:"p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded transition-colors",title:"关闭",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mb-4 flex items-center justify-between",children:a.jsx("button",{type:"button",onClick:()=>{y(null),_({name:"",url:"",iconUrl:""}),c(j=>!j)},className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:h?"取消":"新增应用"})}),h&&a.jsxs("form",{onSubmit:j=>{var G,N,F;j.preventDefault();const W=((G=b.name)==null?void 0:G.trim())||"",D=((N=b.url)==null?void 0:N.trim())||"",X=((F=b.iconUrl)==null?void 0:F.trim())||void 0;W&&(g?p==null||p(g,{name:W,url:D,iconUrl:X}):u==null||u(W,D,X),c(!1),v())},className:"p-4 bg-muted rounded-lg space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),a.jsx("input",{value:b.name,onChange:j=>_({...b,name:j.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"例如:飞书"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"URL"}),a.jsx("input",{value:b.url,onChange:j=>_({...b,url:j.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://example.com"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"图标地址"}),a.jsx("input",{value:b.iconUrl,onChange:j=>_({...b,iconUrl:j.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://.../icon.png"})]}),a.jsxs("div",{className:"flex justify-end space-x-2",children:[a.jsx("button",{type:"button",onClick:()=>{c(!1),v(),y(null)},className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",children:"取消"}),a.jsx("button",{type:"submit",className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:g?"保存":"创建"})]})]}),a.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(j=>a.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center overflow-hidden shrink-0",children:j.iconUrl?a.jsx("img",{src:j.iconUrl,alt:j.name,className:"w-full h-full object-cover"}):a.jsx("span",{className:"text-white text-sm font-bold",children:j.name.charAt(0).toUpperCase()})}),a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-medium text-foreground",children:j.name}),j.url&&a.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:j.url})]})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{className:"px-2 py-1 text-xs rounded bg-background hover:bg-accent",onClick:()=>{c(!0),y(j.id),_({name:j.name||"",url:j.url||"",iconUrl:j.iconUrl||""})},children:"编辑"}),a.jsx("button",{className:"px-2 py-1 text-xs rounded bg-destructive text-destructive-foreground hover:opacity-90",onClick:()=>f==null?void 0:f(j.id),children:"删除"})]})]},j.id)),((l==null?void 0:l.length)??0)===0&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center",children:[a.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用,点击上方按钮添加。"})]})]})]}):a.jsxs("div",{className:"grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[l==null?void 0:l.map(j=>{const W=x.current.has(j.id);return a.jsxs("div",{className:"relative group/item",children:[a.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>I(j),title:j.url||"",children:[a.jsx("div",{className:`relative w-14 h-14 rounded-full flex items-center justify-center overflow-hidden transition-all ${W?"ring-2 ring-green-500 ring-offset-2 ring-offset-background scale-105":"bg-gradient-to-br from-blue-500/20 to-purple-500/20 group-hover/item:scale-105"}`,children:j.iconUrl?a.jsx("img",{src:j.iconUrl,alt:j.name,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:a.jsx("span",{className:"text-white text-lg font-bold",children:j.name.charAt(0).toUpperCase()})})}),a.jsx("div",{className:"text-xs font-medium text-foreground truncate max-w-full",children:j.name}),j.url&&a.jsx("div",{className:"text-[10px] text-muted-foreground truncate max-w-full",children:j.url})]}),W&&a.jsx("button",{onClick:D=>{D.stopPropagation(),S(j.id)},className:"absolute top-0 left-0 w-4 h-4 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover/item:opacity-100 transition-opacity z-10",title:"关闭",children:a.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},j.id)}),((l==null?void 0:l.length)??0)===0&&a.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-10 text-center",children:[a.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),a.jsx("button",{onClick:()=>m(!0),className:"text-sm text-blue-500 hover:text-blue-600 underline",children:"切换到管理模式以添加应用"})]})]})})]})},po=({className:r,apiBaseUrl:e,port:t,userId:n,projectId:s,showMcpManager:o=!0,showAiModelManager:i=!0,showSystemContextEditor:l=!0,showAgentManager:d=!0,onApplicationSelect:u})=>{const p=T.useMemo(()=>{if(e)return e;if(t)return`http://localhost:${t}/api`},[e,t]),f=T.useMemo(()=>{if(p)return new Xt(p)},[p]);return a.jsx(Rf,{userId:n,projectId:s,customApiClient:f,children:a.jsx(Ig,{className:r,showMcpManager:o,showAiModelManager:i,showSystemContextEditor:l,showAgentManager:d,onApplicationSelect:u})})},Ig=({className:r,showMcpManager:e,showAiModelManager:t,showSystemContextEditor:n,showAgentManager:s,onApplicationSelect:o})=>{const i=Pl(),{currentSession:l,messages:d,isLoading:u,isStreaming:p,hasMoreMessages:f,error:x,loadSessions:w,sendMessage:m,clearError:h,aiModelConfigs:c,selectedModelId:g,setSelectedModel:y,loadAiModelConfigs:b,agents:_,selectedAgentId:v,setSelectedAgent:C,loadAgents:S,abortCurrentConversation:I,loadMoreMessages:E}=i(),P=T.useRef(null),[R,j]=T.useState(!1),[W,D]=T.useState(!1),[X,G]=T.useState(!1),[N,F]=T.useState(!1),[z,$]=T.useState(!1),[O,U]=T.useState(!1);T.useEffect(()=>{(window.__standaloneChatInterfaceDidInit__??!1)||(window.__standaloneChatInterfaceDidInit__=!0,w(),b(),S())},[w,b,S]),T.useEffect(()=>{P.current&&P.current.scrollIntoView({behavior:"smooth"})},[d,p]);const V=async(k,q)=>{try{await m(k,q)}catch(A){console.error("Failed to send message:",A)}};return a.jsxs("div",{className:Me("flex flex-col h-screen bg-background text-foreground",r),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("button",{onClick:()=>j(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),l&&a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:l.title})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[o&&a.jsx("button",{onClick:()=>{console.log("[StandaloneChat] open ApplicationsPanel button clicked"),U(!0)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:a.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[a.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),a.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),e&&a.jsx("button",{onClick:()=>D(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP服务管理",children:a.jsxs("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}),t&&a.jsx("button",{onClick:()=>G(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI配置管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z"})})}),n&&a.jsx("button",{onClick:()=>F(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"System Prompt编辑器",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),s&&a.jsx("button",{onClick:()=>$(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12h6M9 16h6M6 8h12a2 2 0 012 2v8a2 2 0 01-2 2H6a2 2 0 01-2-2v-8a2 2 0 012-2z"})})}),a.jsx(fo,{})]})]}),x&&a.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:a.jsxs("div",{className:"flex items中心 justify-between",children:[a.jsx("p",{className:"text-sm text-destructive",children:x}),a.jsx("button",{onClick:h,className:"text-destructive hover:text-destructive/80 transition-colors",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),a.jsx("div",{className:"flex-1 flex overflow-hidden",children:a.jsxs("div",{className:"flex-1 overflow-hidden",children:[l?a.jsx(lo,{messages:d,isLoading:u,isStreaming:p,hasMore:f,onLoadMore:()=>l&&E(l.id)}):a.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:a.jsxs("div",{className:"text-center",children:[a.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 opacity-50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),a.jsx("p",{className:"text-lg mb-2",children:"欢迎使用AI聊天助手"}),a.jsx("p",{className:"text-sm",children:"点击左上角按钮创建新会话开始对话"})]})}),a.jsx("div",{ref:P})]})}),l&&a.jsx(co,{onSend:V,onStop:I,disabled:u||p,isStreaming:p,selectedModelId:g,availableModels:c,onModelChange:y,showModelSelector:!0,selectedAgentId:v,availableAgents:_,onAgentChange:C}),a.jsx(uo,{isOpen:R,onClose:()=>j(!1),store:i}),a.jsx(oc,{isOpen:O,onClose:()=>U(!1),title:"应用列表",layout:"modal",onApplicationSelect:o}),W&&a.jsx(ho,{onClose:()=>D(!1),store:i}),X&&a.jsx(mo,{onClose:()=>G(!1),store:i}),s&&z&&a.jsx(sc,{onClose:()=>$(!1),store:i}),N&&a.jsx(go,{onClose:()=>F(!1),store:i})]})};class Tg{constructor(e,t,n,s,o=!0,i=!0,l=!0,d=!0,u){J(this,"userId");J(this,"projectId");J(this,"configUrl");J(this,"apiClient");J(this,"store");J(this,"className");J(this,"showMcpManager");J(this,"showAiModelManager");J(this,"showSystemContextEditor");J(this,"showAgentManager");J(this,"onApplicationSelect");this.userId=e,this.projectId=t,this.configUrl=n||"/api",this.className=s,this.showMcpManager=o,this.showAiModelManager=i,this.showSystemContextEditor=l,this.showAgentManager=d,this.onApplicationSelect=u,console.log("🔧 AiChat Constructor - configUrl:",this.configUrl),console.log("🔧 AiChat Constructor - Module Controls:",{showMcpManager:this.showMcpManager,showAiModelManager:this.showAiModelManager,showSystemContextEditor:this.showSystemContextEditor,showAgentManager:this.showAgentManager,hasApplicationSelectCallback:!!this.onApplicationSelect}),this.apiClient=new Xt(this.configUrl),this.store=zr(this.apiClient,{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl})}render(){return T.createElement(Pg,{className:this.className,userId:this.userId,projectId:this.projectId,configUrl:this.configUrl,showMcpManager:this.showMcpManager,showAiModelManager:this.showAiModelManager,showSystemContextEditor:this.showSystemContextEditor,showAgentManager:this.showAgentManager,onApplicationSelect:this.onApplicationSelect})}getConfig(){return{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl,className:this.className,showMcpManager:this.showMcpManager,showAiModelManager:this.showAiModelManager,showSystemContextEditor:this.showSystemContextEditor,showAgentManager:this.showAgentManager,onApplicationSelect:this.onApplicationSelect}}updateConfig(e){e.userId&&(this.userId=e.userId),e.projectId&&(this.projectId=e.projectId),e.configUrl&&(this.configUrl=e.configUrl,this.apiClient=new Xt(this.configUrl),this.store=zr(this.apiClient,{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl})),e.className!==void 0&&(this.className=e.className),e.showMcpManager!==void 0&&(this.showMcpManager=e.showMcpManager),e.showAiModelManager!==void 0&&(this.showAiModelManager=e.showAiModelManager),e.showSystemContextEditor!==void 0&&(this.showSystemContextEditor=e.showSystemContextEditor),e.showAgentManager!==void 0&&(this.showAgentManager=e.showAgentManager),e.onApplicationSelect!==void 0&&(this.onApplicationSelect=e.onApplicationSelect)}getStore(){return this.store}getApiClient(){return this.apiClient}getSelectedApplication(){var s;const e=this.store.getState(),t=e.selectedApplicationId;if(console.log("[AiChat] getSelectedApplication called:",{id:t,applicationsCount:(s=e.applications)==null?void 0:s.length}),!t)return null;const n=e.applications.find(o=>o.id===t)||null;return console.log("[AiChat] getSelectedApplication result:",n),n}getSelectedApplicationUrl(){const e=this.getSelectedApplication();return e?e.url:null}subscribeSelectedApplication(e){console.log("[AiChat] subscribeSelectedApplication: 设置订阅"),console.log("[AiChat] store 对象:",this.store),console.log("[AiChat] store.subscribe 类型:",typeof this.store.subscribe);let t=this.store.getState().selectedApplicationId;console.log("[AiChat] 初始 previousId:",t);const n=this.store.subscribe(s=>{const o=s.selectedApplicationId;if(console.log("[AiChat] store.subscribe 被触发, currentId:",o,"previousId:",t),o!==t){console.log("[AiChat] selectedApplicationId 变化检测到:",{old:t,new:o}),t=o;const i=this.getSelectedApplication();console.log("[AiChat] 准备调用 listener,app:",i),e(i)}});return console.log("[AiChat] 首次调用 listener"),e(this.getSelectedApplication()),()=>{console.log("[AiChat] 取消订阅"),n()}}}const Pg=({className:r,userId:e,projectId:t,configUrl:n,showMcpManager:s,showAiModelManager:o,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d})=>a.jsx(po,{className:r,apiBaseUrl:n,userId:e,projectId:t,showMcpManager:s,showAiModelManager:o,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d}),Og=({className:r,onMessageSend:e,customRenderer:t})=>{const{currentSession:n,messages:s,isLoading:o,isStreaming:i,hasMoreMessages:l,error:d,loadSessions:u,loadMoreMessages:p,sendMessage:f,clearError:x,aiModelConfigs:w,selectedModelId:m,setSelectedModel:h,loadAiModelConfigs:c,agents:g,selectedAgentId:y,setSelectedAgent:b,loadAgents:_,abortCurrentConversation:v}=ft(),C=T.useRef(null),[S,I]=T.useState(!1),[E,P]=T.useState(!1),[R,j]=T.useState(!1),[W,D]=T.useState(!1),[X,G]=T.useState(!1),[N,F]=T.useState(!1);T.useEffect(()=>{(window.__chatInterfaceDidInit__??!1)||(window.__chatInterfaceDidInit__=!0,u(),c(),_())},[u,c,_]),T.useEffect(()=>{C.current&&C.current.scrollIntoView({behavior:"smooth"})},[s,i]);const z=async($,O)=>{try{await f($,O),e==null||e($,[])}catch(U){console.error("Failed to send message:",U)}};return a.jsxs("div",{className:Me("flex flex-col h-screen bg-background text-foreground",r),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("button",{onClick:()=>I(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),n&&a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:n.title})})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{onClick:()=>F(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:a.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[a.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),a.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),a.jsx("button",{onClick:()=>P(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP 服务器管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsx("button",{onClick:()=>G(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6M9 16h6M6 8h12a2 2 0 012 2v8a2 2 0 01-2 2H6a2 2 0 01-2-2v-8a2 2 0 012-2z"})})}),a.jsx("button",{onClick:()=>j(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI 模型管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsx("button",{onClick:()=>D(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"系统上下文设置",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsx(fo,{})]})]}),d&&a.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-destructive",children:d}),a.jsx("button",{onClick:x,className:"text-destructive hover:text-destructive/80 transition-colors",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),a.jsx("div",{className:"flex flex-1 overflow-hidden",children:a.jsxs("div",{className:"flex-1 overflow-hidden",children:[n?a.jsx(lo,{messages:s,isLoading:o,isStreaming:i,hasMore:l,onLoadMore:()=>n&&p(n.id),customRenderer:t}):a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h2",{className:"text-xl font-semibold text-muted-foreground mb-2",children:"欢迎使用 AI 聊天"}),a.jsx("p",{className:"text-muted-foreground mb-4",children:"点击左上角按钮选择会话,或创建新的会话开始对话"}),a.jsx("button",{onClick:()=>I(!0),className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"打开会话列表"})]})}),a.jsx("div",{ref:C})]})}),n&&a.jsx("div",{className:"border-t border-border",children:a.jsx(co,{onSend:z,onStop:v,disabled:o,isStreaming:i,placeholder:"输入消息...",showModelSelector:!0,selectedModelId:m,availableModels:w,onModelChange:h,selectedAgentId:y,availableAgents:g,onAgentChange:b})}),a.jsx(uo,{isOpen:S,onClose:()=>I(!1)}),E&&a.jsx(ho,{onClose:()=>P(!1)}),X&&a.jsx(sc,{onClose:()=>G(!1)}),R&&a.jsx(mo,{onClose:()=>j(!1)}),W&&a.jsx(go,{onClose:()=>D(!1)}),a.jsx(oc,{isOpen:N,onClose:()=>F(!1),title:"应用列表",layout:"modal"})]})};class Rg extends T.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:a.jsx("div",{className:"flex items-center justify-center h-full p-8",children:a.jsxs("div",{className:"text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 mx-auto bg-destructive/10 rounded-full flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Something went wrong"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),a.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 $g="1.0.0";exports.AiChat=Tg;exports.AiModelManager=mo;exports.AiServer=El;exports.ApiClient=Xt;exports.AppError=Zm;exports.AttachmentRenderer=Gl;exports.ChatIcon=tc;exports.ChatInterface=Og;exports.ChatService=Tl;exports.CheckIcon=ng;exports.ChevronDownIcon=ig;exports.CopyIcon=og;exports.DatabaseService=bs;exports.DotsVerticalIcon=Ql;exports.ErrorBoundary=Rg;exports.InputArea=co;exports.LoadingSpinner=Kl;exports.MarkdownRenderer=ot;exports.McpManager=ho;exports.MessageItem=Xl;exports.MessageList=lo;exports.MessageManager=Il;exports.PencilIcon=Zl;exports.PlayIcon=ag;exports.PlusIcon=Yl;exports.SessionList=uo;exports.StandaloneChatInterface=po;exports.SystemContextEditor=go;exports.ThemeToggle=fo;exports.ToolCallRenderer=ps;exports.TrashIcon=ec;exports.XIcon=sg;exports.apiClient=ne;exports.cleanHtmlContent=Wm;exports.cn=Me;exports.conversationsApi=Ar;exports.copyToClipboard=Xm;exports.debounce=zm;exports.deepClone=gs;exports.default=po;exports.downloadFile=Km;exports.formatDate=Fm;exports.formatDateTime=Um;exports.formatFileSize=Jl;exports.formatRelativeTime=Dm;exports.formatTime=zl;exports.generateId=Lm;exports.generateRandomColor=Gm;exports.getFileExtension=Vl;exports.getOS=Qm;exports.isImageFile=Vm;exports.isMobile=Ym;exports.isValidEmail=Hm;exports.isValidUrl=qm;exports.retry=eg;exports.storage=tg;exports.throttle=Jm;exports.truncateText=Bm;exports.useChatStore=ut;exports.useTheme=nc;exports.version=$g;
99
+ `;return C.forEach(I=>{const T=S[I];let $;typeof T=="string"?$=T.replace(/\n/g,"<br>").replace(/\|/g,"\\|"):Array.isArray(T)?$=`[${T.join(", ")}]`.replace(/\|/g,"\\|"):$=JSON.stringify(T).replace(/\|/g,"\\|"),_+=`| ${I} | ${$} |
100
+ `}),_})(),c=(()=>{if(!d)return null;if(i&&typeof i=="object")return i;if(typeof i=="string")try{const S=JSON.parse(i);if(S&&typeof S=="object")return S}catch{return null}return null})(),b=!!(c&&typeof c=="object"),x=S=>{if(S===null)return"null";if(Array.isArray(S)){if(S.length===0)return"array []";const C=S[0],_=x(C);return _==="object"?"object []":`${_}[]`}switch(typeof S){case"string":return"string";case"number":return Number.isInteger(S)?"integer":"number";case"boolean":return"boolean";case"object":return"object";default:return typeof S}},y=(S,C="",_="")=>{const I=[];if(S==null)return I;if(Array.isArray(S)){const T={path:_||C||"list",name:C||"list",type:x(S),value:S,children:S.map(($,F)=>{const k=`${_||C||"list"}[${F}]`,U=x($);return{path:k,name:`[${F}]`,type:U,value:$,children:U==="object"||Array.isArray($)?y($,`[${F}]`,k):[]}})};return I.push(T),I}return typeof S=="object"&&Object.keys(S).forEach(T=>{const $=S[T],F=_?`${_}.${T}`:T,k=x($),U=k==="object"||Array.isArray($)?y($,T,F):[];I.push({path:F,name:T,type:k,value:$,children:U})}),I},v=({data:S})=>{const C=Array.isArray(S)?y(S,"list","list"):y(S,"",""),[_,I]=O.useState(()=>new Set(C.filter(k=>k.children.length>0).map(k=>k.path))),T=k=>{I(U=>{const H=new Set(U);return H.has(k)?H.delete(k):H.add(k),H})},$=k=>{if(k===null)return"null";if(Array.isArray(k))return`数组(${k.length})`;if(typeof k=="object")return"对象";if(typeof k=="string")return k;try{return JSON.stringify(k)}catch{return String(k)}},F=(k,U)=>k.map(H=>{const Z=H.children&&H.children.length>0,P=_.has(H.path),N=Z?P?"▾":"▸":"",R=$(H.value);return a.jsxs(O.Fragment,{children:[a.jsxs("tr",{children:[a.jsxs("td",{style:{paddingLeft:U*16},children:[Z?a.jsx("button",{type:"button",onClick:()=>T(H.path),className:"mr-2 text-gray-600 dark:text-gray-300 hover:text-black dark:hover:text-white","aria-label":P?"收起":"展开",children:N}):a.jsx("span",{className:"mr-4"}),H.name]}),a.jsx("td",{style:{whiteSpace:"normal",wordBreak:"break-word"},children:R})]}),Z&&P&&F(H.children,U+1)]},H.path)});return a.jsx("div",{className:"border-l-4 border-green-400 dark:border-green-500 rounded-lg overflow-hidden bg-green-50/50 dark:bg-green-900/20 mb-2",children:a.jsx("div",{className:"markdown-renderer",children:a.jsxs("table",{children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"字段"}),a.jsx("th",{children:"值"})]})}),a.jsx("tbody",{children:F(C,0)})]})})})};return a.jsxs("div",{className:"tool-call-renderer tool-call-container",children:[a.jsxs("div",{className:"tool-header",children:[a.jsxs("span",{className:"tool-name",children:["@",r.name]}),l&&a.jsx("span",{className:"status-badge status-error",children:"错误"}),d&&!l&&a.jsx("span",{className:"status-badge status-success",children:"完成"}),!d&&!l&&a.jsx("span",{className:"status-badge status-pending",children:"等待中"}),(h||d||l)&&a.jsx("button",{onClick:()=>s(!n),className:"toggle-button",children:n?"收起详情":"查看详情"})]}),n&&a.jsxs("div",{className:"details-container",children:[h&&a.jsx("div",{children:m&&a.jsx("div",{className:"border-l-4 border-blue-400 dark:border-blue-500 rounded-lg overflow-hidden bg-blue-50/50 dark:bg-blue-900/20 mb-4",children:a.jsx(nt,{content:m})})}),d&&a.jsxs("div",{children:[a.jsx("div",{className:"details-title",children:"结果:"}),b?a.jsx(v,{data:c}):a.jsx(nt,{content:typeof i=="string"?i:JSON.stringify(i)})]}),l&&a.jsxs("div",{children:[a.jsx("div",{className:"details-title",children:"错误:"}),a.jsx("div",{className:"status-badge status-error",style:{display:"block",padding:"0.5rem"},children:r.error})]}),a.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 border-t border-gray-200 dark:border-gray-700 pt-2",children:["执行时间: ",(()=>{const S=new Date(r.createdAt);return isNaN(S.getTime())?"时间未知":S.toLocaleString()})()]})]})]})},eg=({message:r,isLast:e=!1,isStreaming:t=!1,onEdit:n,onDelete:s,allMessages:o=[],customRenderer:i})=>{var _,I,T,$,F,k,U,H,Z;console.log("🚀🚀🚀 MessageItem 组件被调用!消息ID:",r.id,"角色:",r.role),console.log("🚀🚀🚀 完整消息对象:",r);const[l,d]=O.useState(!1),[f,g]=O.useState(r.content),h=(P,N)=>{navigator.clipboard.writeText(P).then(()=>{console.log("代码已复制到剪贴板:",{code:P,language:N})}).catch(R=>{console.error("复制失败:",R)})},[p,w]=O.useState(!1),m=r.role==="user",u=r.role==="assistant",c=r.role==="system",b=r.role==="tool";if(b)return null;if(i!=null&&i.renderMessage)return a.jsx("div",{children:i.renderMessage(r)});const x=()=>{n&&f.trim()!==r.content&&n(r.id,f.trim()),d(!1)},y=()=>{g(r.content),d(!1)},v=async()=>{try{await navigator.clipboard.writeText(r.content)}catch(P){console.error("Failed to copy message:",P)}},S=((_=r.metadata)==null?void 0:_.attachments)||[],C=r.toolCalls||((I=r.metadata)==null?void 0:I.toolCalls)||[];return console.log("🔧 工具调用数据:",{顶层toolCalls:r.toolCalls,"metadata.toolCalls":(T=r.metadata)==null?void 0:T.toolCalls,最终toolCalls长度:C.length,消息ID:r.id,contentSegments:($=r.metadata)==null?void 0:$.contentSegments,contentSegments长度:((k=(F=r.metadata)==null?void 0:F.contentSegments)==null?void 0:k.length)||0}),a.jsxs("div",{className:ke("group relative rounded-lg transition-colors",!u&&"flex gap-3 px-4 py-4",u&&"px-4 py-2",m&&"bg-user-message",c&&"bg-muted border-l-4 border-primary",b&&"bg-blue-50 dark:bg-blue-950/20 border-l-4 border-blue-500","hover:bg-opacity-80"),onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),children:[!u&&a.jsx("div",{className:"flex-shrink-0",children:a.jsx("div",{className:ke("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium",m&&"bg-primary text-primary-foreground",c&&"bg-muted text-muted-foreground",b&&"bg-blue-500 text-white"),children:m?"U":b?"T":"S"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[!u&&a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("span",{className:"text-sm font-medium",children:m?"You":b?"Tool Result":"System"}),a.jsx("span",{className:"text-xs text-muted-foreground",children:Wl(r.createdAt)})]}),((U=r.metadata)==null?void 0:U.type)==="session_summary"&&a.jsxs("div",{className:"mb-3 border border-amber-300 dark:border-amber-600/50 bg-amber-50 dark:bg-amber-950/20 rounded-md p-3",children:[a.jsxs("div",{className:"text-xs text-amber-900 dark:text-amber-200 font-medium mb-1",children:["上下文已压缩为摘要",typeof((H=r.metadata)==null?void 0:H.keepLastN)=="number"?`(保留最近 ${r.metadata.keepLastN} 条)`:""]}),a.jsxs("details",{className:"group",children:[a.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground select-none",children:"查看摘要内容"}),a.jsx("div",{className:"mt-2 prose prose-sm max-w-none",children:a.jsx(nt,{content:(r.rawContent||((Z=r.metadata)==null?void 0:Z.summary)||"").toString(),isStreaming:!1,onApplyCode:()=>{}})})]})]}),S.length>0&&a.jsx("div",{className:"mb-3 space-y-2",children:S.map(P=>a.jsx(zl,{attachment:P,customRenderer:i==null?void 0:i.renderAttachment},P.id))}),l?a.jsxs("div",{className:"space-y-2",children:[a.jsx("textarea",{value:f,onChange:P=>g(P.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}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:x,className:"px-3 py-1 text-sm bg-primary text-primary-foreground rounded hover:bg-primary/90",children:"Save"}),a.jsx("button",{onClick:y,className:"px-3 py-1 text-sm bg-muted text-muted-foreground rounded hover:bg-muted/80",children:"Cancel"})]})]}):a.jsx("div",{className:"space-y-3",children:(()=>{var B;const P=((B=r.metadata)==null?void 0:B.contentSegments)||[],N=r.content&&r.content.trim().length>0,R=t&&e;return P.length>0?(console.log("🎨 使用分段渲染,分段数量:",P.length),console.log("🎨 分段详情:",P),a.jsx("div",{className:"space-y-0.5",children:P.map((q,D)=>{if(console.log(`🎨 渲染分段 ${D}:`,q),q.type==="text")return console.log(`🎨 渲染文本分段 ${D}:`,q.content),a.jsx("div",{className:"prose prose-sm max-w-none",children:a.jsx(nt,{content:q.content,isStreaming:R&&D===P.length-1,onApplyCode:h})},`segment-${D}`);if(q.type==="tool_call"){console.log(`🎨 渲染工具调用分段 ${D}:`,q);const A=C.find(j=>j.id===q.toolCallId);if(console.log(`🎨 查找工具调用 ${q.toolCallId}:`,A),A)return console.log("🎨 找到工具调用,开始渲染:",A),a.jsx("div",{children:a.jsx(hs,{toolCall:A,allMessages:o})},`tool-${A.id}`);console.log(`🎨 ❌ 未找到工具调用 ${q.toolCallId}`)}else if(q.type==="thinking")return console.log(`🎨 渲染思考分段 ${D}:`,q.content),a.jsxs("details",{className:"group border border-gray-200 dark:border-gray-700 rounded-md bg-muted px-3 py-2",children:[a.jsx("summary",{className:"cursor-pointer text-xs text-gray-500 dark:text-gray-400 select-none",children:"思考过程"}),a.jsx("div",{className:"mt-1",children:a.jsx(nt,{content:q.content||"",isStreaming:R&&D===P.length-1,onApplyCode:h,className:"thinking not-prose"})})]},`thinking-${D}`);return null})})):(console.log("🎨 使用传统渲染方式"),console.log("🎨 hasContent:",N),console.log("🎨 toolCalls.length:",C.length),a.jsxs("div",{className:"space-y-0.5",children:[N&&a.jsx("div",{className:"prose prose-sm max-w-none",children:a.jsx(nt,{content:r.content,isStreaming:R,onApplyCode:h})}),C.length>0&&a.jsxs("div",{className:"space-y-0.5",children:[a.jsx("div",{className:"text-sm text-muted-foreground font-medium",children:"工具调用:"}),C.map(q=>(console.log("🎨 传统方式渲染工具调用:",q),a.jsx("div",{children:a.jsx(hs,{toolCall:q,allMessages:o})},`tool-${q.id}`)))]})]}))})()}),r.tokensUsed&&a.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Tokens used: ",r.tokensUsed]})]}),p&&!l&&a.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:[a.jsx("button",{onClick:v,className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Copy message",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),m&&n&&a.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:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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&&a.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:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})})]})]})},Jl=O.memo(eg,(r,e)=>r.message.id===e.message.id&&r.message.content===e.message.content&&r.message.createdAt===e.message.createdAt&&r.isLast===e.isLast&&r.isStreaming===e.isStreaming&&JSON.stringify(r.message.metadata)===JSON.stringify(e.message.metadata)),Vl=({size:r="md",className:e})=>{const t={sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"};return a.jsx("div",{className:ke("animate-spin rounded-full border-2 border-current border-t-transparent",t[r],e),role:"status","aria-label":"Loading",children:a.jsx("span",{className:"sr-only",children:"Loading..."})})},oo=({messages:r,isLoading:e=!1,isStreaming:t=!1,hasMore:n=!1,onLoadMore:s,onMessageEdit:o,onMessageDelete:i,customRenderer:l})=>{const d=O.useRef(null),f=O.useRef(null),[g,h]=O.useState(!0),[p,w]=O.useState(!0),m=()=>{const x=d.current;return x?x.scrollHeight-x.scrollTop-x.clientHeight<=40:!0},u=(x=!0)=>{var y;(y=f.current)==null||y.scrollIntoView({behavior:x?"smooth":"auto"})};O.useEffect(()=>{t&&g&&u(!0)},[r,t,g]),O.useEffect(()=>{w(m())},[r,t]),O.useEffect(()=>{t&&p&&h(!0),t||h(!1)},[t,p]);const c=()=>{const x=m();w(x),x||h(!1)},b=()=>{u(!0),h(!0)};return r.length===0&&!e?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 mx-auto bg-muted rounded-full flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Start a conversation"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Send a message to begin your chat with AI"})]})]})}):a.jsxs("div",{className:"flex flex-col h-full relative",children:[a.jsxs("div",{ref:d,onScroll:c,className:"flex-1 overflow-y-auto px-4 py-6 space-y-1",style:{willChange:"scroll-position",transform:"translateZ(0)"},children:[n&&a.jsx("div",{className:"flex justify-center mb-2",children:a.jsx("button",{type:"button",onClick:s,className:"text-sm px-3 py-1 rounded border border-border text-foreground hover:bg-accent",children:"加载更多"})}),(r||[]).filter(x=>{var y;return!((y=x==null?void 0:x.metadata)!=null&&y.hidden)}).map((x,y,v)=>a.jsx(Jl,{message:x,isLast:y===v.length-1,isStreaming:t&&y===v.length-1,onEdit:o,onDelete:i,allMessages:r,customRenderer:l},x.id)),e&&a.jsx("div",{className:"flex justify-start",children:a.jsxs("div",{className:"flex items-center space-x-2 bg-muted px-4 py-3 rounded-lg max-w-xs",children:[a.jsx(Vl,{size:"sm"}),a.jsx("span",{className:"text-sm text-muted-foreground",children:"AI is thinking..."})]})}),a.jsx("div",{ref:f})]}),!p&&a.jsxs("button",{type:"button","aria-label":"回到底部",title:"回到底部",onClick:b,className:"absolute bottom-4 right-4 z-10 flex items-center gap-2 rounded-full bg-primary text-primary-foreground px-4 py-2 shadow-md hover:bg-primary/90",children:[a.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M12 5v12"}),a.jsx("path",{d:"M19 12l-7 7-7-7"})]}),a.jsx("span",{className:"text-sm",children:"回到底部"})]})]})},ao=({onSend:r,onStop:e,disabled:t=!1,isStreaming:n=!1,placeholder:s="Type your message...",maxLength:o=4e3,allowAttachments:i=!1,supportedFileTypes:l=["image/*","text/*","application/pdf"],showModelSelector:d=!1,selectedModelId:f=null,availableModels:g=[],onModelChange:h,selectedAgentId:p=null,availableAgents:w=[],onAgentChange:m})=>{const[u,c]=O.useState(""),[b,x]=O.useState([]),[y,v]=O.useState(!1),S=O.useRef(null),C=O.useRef(null);O.useEffect(()=>{console.log("InputArea - isStreaming 状态变化:",{isStreaming:n,disabled:t,onStop:!!e,timestamp:new Date().toISOString()})},[n,t,e]);const _=O.useCallback(()=>{const N=S.current;if(N){N.style.height="auto";const R=N.scrollHeight,B=200;N.style.height=`${Math.min(R,B)}px`}},[]),I=N=>{const R=N.target.value;R.length<=o&&(c(R),_())},T=N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),$())},$=()=>{const N=u.trim();if(!(!N&&b.length===0)&&!t){if(d&&!f&&!p){alert("请先选择一个模型或智能体");return}r(N,b),c(""),x([]),S.current&&(S.current.style.height="auto")}},F=N=>{const R=Array.from(N.target.files||[]);x(B=>[...B,...R]),C.current&&(C.current.value="")},k=N=>{x(R=>R.filter((B,q)=>q!==N))},U=N=>{N.preventDefault(),i&&!t&&v(!0)},H=N=>{N.preventDefault(),v(!1)},Z=N=>{if(N.preventDefault(),v(!1),!i||t)return;const R=Array.from(N.dataTransfer.files);x(B=>[...B,...R])},P=N=>{if(N===0)return"0 Bytes";const R=1024,B=["Bytes","KB","MB","GB"],q=Math.floor(Math.log(N)/Math.log(R));return parseFloat((N/Math.pow(R,q)).toFixed(2))+" "+B[q]};return a.jsxs("div",{className:"border-t bg-background p-4",children:[d&&a.jsx("div",{className:"mb-3",children:g.length>0||w.length>0?a.jsxs("select",{value:p?`agent:${p}`:f||"",onChange:N=>{const R=N.target.value;if(R.startsWith("agent:")){const B=R.replace("agent:","");m==null||m(B),h==null||h(null)}else h==null||h(R||null),m==null||m(null)},disabled:t,className:ke("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:[a.jsx("option",{value:"",children:"请选择模型或智能体..."}),w&&w.filter(N=>N.enabled).length>0&&a.jsx("optgroup",{label:"智能体",children:w.filter(N=>N.enabled).map(N=>a.jsxs("option",{value:`agent:${N.id}`,children:["[Agent] ",N.name]},N.id))}),g&&g.filter(N=>N.enabled).length>0&&a.jsx("optgroup",{label:"模型",children:g.filter(N=>N.enabled).map(N=>a.jsxs("option",{value:N.id,children:[N.name," (",N.model_name,")"]},N.id))})]}):a.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:"暂无可用模型或智能体,请先在右上角配置"})}),b.length>0&&a.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:b.map((N,R)=>a.jsxs("div",{className:"flex items-center gap-2 bg-muted px-3 py-2 rounded-lg text-sm",children:[a.jsx("svg",{className:"w-4 h-4 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),a.jsx("span",{className:"truncate max-w-32",children:N.name}),a.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",P(N.size),")"]}),a.jsx("button",{onClick:()=>k(R),className:"text-muted-foreground hover:text-destructive transition-colors",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},R))}),a.jsxs("div",{className:ke("relative flex items-end gap-2 p-3 border rounded-lg transition-colors","focus-within:border-primary",y&&"border-primary bg-primary/5",t&&"opacity-50 cursor-not-allowed"),onDragOver:U,onDragLeave:H,onDrop:Z,children:[i&&a.jsx("button",{onClick:()=>{var N;return(N=C.current)==null?void 0:N.click()},disabled:t,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:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsx("textarea",{ref:S,value:u,onChange:I,onKeyDown:T,placeholder:s,disabled:t,className:ke("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"}}),a.jsxs("div",{className:"flex-shrink-0 text-xs text-muted-foreground",children:[u.length,"/",o]}),n?a.jsx("button",{onClick:()=>{console.log("停止按钮被点击",{onStop:e,disabled:t}),e&&e()},disabled:!1,className:ke("flex-shrink-0 p-2 rounded-md transition-colors","bg-red-500 text-white hover:bg-red-600","disabled:opacity-50 disabled:cursor-not-allowed"),title:"停止生成",style:{backgroundColor:"#ef4444",color:"white"},children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 6h12v12H6z"})})}):a.jsx("button",{onClick:$,disabled:t||n||!u.trim()&&b.length===0,className:ke("flex-shrink-0 p-2 rounded-md transition-colors","disabled:opacity-50 disabled:cursor-not-allowed",(u.trim()||b.length>0)&&!t&&!n?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground"),title:d&&!f?"请先选择AI模型":"Send message",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"})})}),i&&a.jsx("input",{ref:C,type:"file",multiple:!0,accept:l.join(","),onChange:F,className:"hidden"})]}),y&&i&&a.jsx("div",{className:"absolute inset-0 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center",children:a.jsxs("div",{className:"text-center",children:[a.jsx("svg",{className:"w-8 h-8 mx-auto text-primary mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),a.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to attach"})]})})]})},Gl=({className:r="w-5 h-5"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Xl=({className:r="w-5 h-5"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),Kl=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),Yl=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),tg=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),rg=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),Ql=({className:r="w-5 h-5"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),ng=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),sg=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M14.828 14.828a4 4 0 01-5.656 0M9 10h1m4 0h1m-6 4h8m-9 4h10a1 1 0 001-1V7a1 1 0 00-1-1H7a1 1 0 00-1 1v10a1 1 0 001 1z"})}),og=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}),dr=({isOpen:r,title:e,message:t,confirmText:n="确认",cancelText:s="取消",onConfirm:o,onCancel:i,type:l="danger",verificationText:d,verificationLabel:f,verificationPlaceholder:g,verificationHint:h})=>{if(!r)return null;const[p,w]=O.useState("");O.useEffect(()=>{r&&w("")},[r,d]);const m=!!d,u=m&&p.trim()!==(d==null?void 0:d.trim()),c=()=>{switch(l){case"danger":return"bg-red-600 hover:bg-red-700 text-white";case"warning":return"bg-yellow-600 hover:bg-yellow-700 text-white";default:return"bg-blue-600 hover:bg-blue-700 text-white"}};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx("div",{className:"bg-card rounded-lg shadow-lg w-full max-w-sm border border-border animate-breathing-border",children:a.jsxs("div",{className:"p-6",children:[a.jsx("h3",{className:"text-lg font-medium text-foreground mb-2",children:e}),a.jsx("p",{className:"text-muted-foreground text-sm mb-6",children:t}),m&&a.jsxs("div",{className:"mb-6",children:[a.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-2",children:f||"请输入以下内容以继续操作"}),a.jsx("div",{className:"px-3 py-2 bg-muted rounded-md text-sm font-mono text-foreground border border-border mb-2",children:d}),a.jsx("input",{type:"text",value:p,onChange:b=>w(b.target.value),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:g||"输入上方关键字以确认",autoFocus:!0}),a.jsx("p",{className:"text-[12px] text-muted-foreground mt-2",children:h||"为了防止误删,需要您再次确认此操作。"})]}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx("button",{onClick:i,className:"flex-1 px-4 py-2 text-sm border border-border rounded-md hover:bg-accent transition-colors",children:s}),a.jsx("button",{onClick:o,disabled:u,className:`flex-1 px-4 py-2 text-sm rounded-md transition-colors ${c()} ${u?"opacity-50 cursor-not-allowed":""}`,children:n})]})]})})})},ur=()=>{const[r,e]=O.useState({isOpen:!1,title:"",message:"",confirmText:"确认",cancelText:"取消",type:"danger"}),t=O.useCallback(i=>{e({isOpen:!0,title:i.title,message:i.message,confirmText:i.confirmText||"确认",cancelText:i.cancelText||"取消",type:i.type||"danger",onConfirm:i.onConfirm,onCancel:i.onCancel,verificationText:i.verificationText,verificationLabel:i.verificationLabel,verificationPlaceholder:i.verificationPlaceholder,verificationHint:i.verificationHint})},[]),n=O.useCallback(()=>{e(i=>({...i,isOpen:!1}))},[]),s=O.useCallback(()=>{var i;(i=r.onConfirm)==null||i.call(r),n()},[r.onConfirm,n]),o=O.useCallback(()=>{var i;(i=r.onCancel)==null||i.call(r),n()},[r.onCancel,n]);return{dialogState:r,showConfirmDialog:t,hideConfirmDialog:n,handleConfirm:s,handleCancel:o}},ag=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")},io=({isOpen:r=!0,onClose:e,store:t,embedded:n=!1})=>{let s=null;try{s=dt()}catch{}const o=t?t():s;if(!o)throw new Error("SessionList must be used within a ChatStoreProvider or receive a store prop");const{sessions:i,currentSession:l,createSession:d,selectSession:f,deleteSession:g,updateSession:h}=o,p=n?"relative h-full bg-card shadow-lg breathing-border":"fixed left-0 top-0 h-full bg-card z-40 shadow-xl breathing-border",w="transition-all duration-300 ease-in-out",[m,u]=O.useState(null),[c,b]=O.useState(""),[x,y]=O.useState(!r),{dialogState:v,showConfirmDialog:S,handleConfirm:C,handleCancel:_}=ur(),I=()=>{y(!x)},T=async()=>{try{await d(),x&&y(!1)}catch(P){console.error("Failed to create session:",P)}},$=async P=>{try{await f(P)}catch(N){console.error("Failed to select session:",N)}},F=async P=>{const N=i.find(R=>R.id===P);S({title:"删除确认",message:`确定要删除会话 "${(N==null?void 0:N.title)||"Untitled"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{try{await g(P)}catch(R){console.error("Failed to delete session:",R)}}})},k=(P,N)=>{u(P),b(N)},U=async()=>{if(m&&c.trim())try{await h(m,{title:c.trim()}),u(null),b("")}catch(P){console.error("Failed to update session:",P)}},H=()=>{u(null),b("")},Z=P=>{P.key==="Enter"?U():P.key==="Escape"&&H()};return a.jsx("div",{className:`${p} ${w} ${x?"w-32":"w-80 sm:w-96"}`,children:a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:`flex ${x?"flex-col items-center justify-center p-2":"items-center justify-between p-4"} border-b border-border transition-all duration-300`,children:[!x&&a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"会话列表"}),a.jsxs("div",{className:`flex ${x?"flex-col space-y-2 items-center":"items-center space-x-2"}`,children:[a.jsx("button",{onClick:T,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"新建会话",children:a.jsx(Gl,{className:"w-5 h-5"})}),a.jsx("button",{onClick:I,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:x?"展开":"收起",children:x?a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})}):a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),e&&!x&&!n&&a.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto",children:i.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground",children:[a.jsx(Ql,{className:"w-12 h-12 mb-4 opacity-50"}),!x&&a.jsxs(a.Fragment,{children:[a.jsx("p",{className:"text-sm",children:"还没有会话"}),a.jsx("button",{onClick:T,className:"mt-2 px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"创建第一个会话"})]})]}):a.jsx("div",{className:"p-2 space-y-1",children:i.map(P=>a.jsxs("div",{className:`group relative flex items-center p-3 rounded-lg cursor-pointer transition-colors ${(l==null?void 0:l.id)===P.id?"bg-accent border border-border":"hover:bg-accent/50"}`,onClick:()=>$(P.id),children:[a.jsx("div",{className:"flex-1 min-w-0",children:m===P.id?a.jsx("input",{type:"text",value:c,onChange:N=>b(N.target.value),onBlur:U,onKeyDown:Z,className:"w-full px-2 py-1 text-sm bg-background border border-border rounded focus:outline-none focus:ring-2 focus:ring-ring",autoFocus:!0,onClick:N=>N.stopPropagation()}):a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:`text-sm font-medium text-foreground truncate ${x?"text-center w-full":""}`,title:P.title,children:x&&P.title.length>4?P.title.slice(0,4)+"...":P.title}),!x&&a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:ag(P.updatedAt)})]})}),m!==P.id&&!x&&a.jsxs("div",{className:"relative",children:[a.jsx("button",{className:"p-1 text-muted-foreground hover:text-foreground opacity-0 group-hover:opacity-100 transition-opacity",onClick:N=>{N.stopPropagation();const R=N.currentTarget.nextElementSibling;R&&R.classList.toggle("hidden")},children:a.jsx(Xl,{className:"w-4 h-4"})}),a.jsx("div",{className:"hidden absolute right-0 z-10 mt-1 w-32 bg-popover border border-border rounded-md shadow-lg",children:a.jsxs("div",{className:"py-1",children:[a.jsxs("button",{onClick:N=>{N.stopPropagation(),k(P.id,P.title);const R=N.currentTarget.closest(".absolute");R&&R.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-popover-foreground hover:bg-accent",children:[a.jsx(Kl,{className:"w-4 h-4 mr-2"}),"重命名"]}),a.jsxs("button",{onClick:N=>{N.stopPropagation(),F(P.id);const R=N.currentTarget.closest(".absolute");R&&R.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-destructive hover:bg-destructive/10",children:[a.jsx(Yl,{className:"w-4 h-4 mr-2"}),"删除"]})]})})]})]},P.id))})}),a.jsx(dr,{isOpen:v.isOpen,title:v.title,message:v.message,confirmText:v.confirmText,cancelText:v.cancelText,type:v.type,verificationText:v.verificationText,verificationLabel:v.verificationLabel,verificationPlaceholder:v.verificationPlaceholder,verificationHint:v.verificationHint,onConfirm:C,onCancel:_})]})})},Zl=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",Sa=r=>r==="system"?Zl():r,Fn=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")},Ca=()=>typeof window>"u"?"system":localStorage.getItem("theme")||"system",ig=r=>{typeof window>"u"||localStorage.setItem("theme",r)},ec=()=>{const[r,e]=O.useState(()=>Ca()),[t,n]=O.useState(()=>Sa(Ca())),s=i=>{e(i),ig(i);const l=Sa(i);n(l),Fn(l)},o=()=>{let i;switch(r){case"light":i="dark";break;case"dark":i="system";break;case"system":i="light";break;default:i="system"}s(i)};return O.useEffect(()=>{if(r!=="system")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),l=()=>{const d=Zl();n(d),Fn(d)};return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[r]),O.useEffect(()=>{Fn(t)},[t]),{theme:r,actualTheme:t,setTheme:s,toggleTheme:o}},lo=({className:r=""})=>{const{theme:e,toggleTheme:t}=ec(),n=()=>{switch(e){case"light":return a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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 a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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 a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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 a.jsx("button",{onClick:t,className:`p-2 hover:bg-muted rounded-lg transition-colors ${r}`,title:s(),"aria-label":s(),children:n()})},lg={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},cg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),ja=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),dg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),ug=({open:r,config:e,onClose:t})=>{const[n,s]=O.useState([]),[o,i]=O.useState(!1),[l,d]=O.useState(null),[f,g]=O.useState(null),[h,p]=O.useState(!1),[w,m]=O.useState({name:"",envJson:"",enabled:!1}),[u,c]=O.useState(null),[b,x]=O.useState({});if(O.useEffect(()=>{(async()=>{if(!(!r||!(e!=null&&e.id))){i(!0),d(null);try{const v=await ee.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[])}catch(v){d((v==null?void 0:v.message)||"获取配置档案失败")}finally{i(!1)}}})()},[r,e==null?void 0:e.id]),!r)return null;try{const y={id:e==null?void 0:e.id,name:e==null?void 0:e.name,type:e==null?void 0:e.type,command:e==null?void 0:e.command,cwd:e==null?void 0:e.cwd,args:e==null?void 0:e.args};typeof window<"u"}catch{}return a.jsxs("div",{className:"modal-container",children:[a.jsxs("div",{className:"modal-content w-full max-w-3xl max-h-[85vh] overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(cg,{}),a.jsxs("h3",{className:"text-lg font-semibold text-foreground",children:["配置档案 - ",e==null?void 0:e.name]})]}),a.jsx("button",{onClick:()=>t(),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(ja,{})})]}),a.jsxs("div",{className:"p-4 overflow-y-auto overflow-x-hidden",style:{maxHeight:"calc(85vh - 100px)"},children:[e&&a.jsxs("div",{className:"mb-4 p-3 rounded-md border border-border bg-muted/40",children:[a.jsx("div",{className:"text-sm font-medium mb-2 text-foreground",children:"基本信息"}),a.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-muted-foreground",children:[a.jsxs("div",{children:["协议类型:",a.jsx("span",{className:"ml-1 text-foreground",children:e.type==="http"?"HTTP":"Stdio"})]}),a.jsxs("div",{children:[e.type==="http"?"URL:":"命令:",a.jsx("span",{className:"ml-1 text-foreground break-all",children:e.command})]}),e.type==="stdio"&&e.cwd&&a.jsxs("div",{children:["cwd:",a.jsx("span",{className:"ml-1 text-foreground break-all",children:String(e.cwd)})]}),e.type==="stdio"&&a.jsxs("div",{className:"sm:col-span-2",children:["args:",a.jsx("span",{className:"ml-1 text-foreground break-all",children:(()=>{const y=e.args;if(!y)return"—";if(Array.isArray(y))return y.map(v=>String(v)).join(", ");if(typeof y=="string"){try{const v=JSON.parse(y);if(Array.isArray(v))return v.map(S=>String(S)).join(", ")}catch{}return y}return String(y)})()})]})]})]}),a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("span",{className:"text-sm text-muted-foreground",children:"已保存的配置档案"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{if(e!=null&&e.id){i(!0);try{const y=await ee.getMcpConfigProfiles(e.id);s(Array.isArray(y)?y:[])}finally{i(!1)}}},children:"刷新列表"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:async()=>{if(!(e!=null&&e.id))return;let y;try{const v=await ee.getMcpConfigResource(e.id),S=v&&v.config||{};S&&typeof S=="object"&&(y=S)}catch{}m({name:`配置_${new Date().toLocaleString("zh-CN")}`,envJson:"",enabled:!1}),x(y||{}),g(null),p(!0)},children:"新增配置档案"})]})]}),o?a.jsx("div",{className:"text-xs text-muted-foreground",children:"加载中..."}):l?a.jsx("div",{className:"text-xs text-destructive",children:l}):n.length===0?a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案,点击右上角“新增配置档案”。"}):a.jsx("div",{className:"space-y-2",children:n.map(y=>a.jsx("div",{className:"px-2 py-2 border border-border rounded-md",children:a.jsxs("div",{className:"flex items-center justify-between gap-2",children:[a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("div",{className:"text-sm text-foreground font-medium truncate",title:y.name,children:y.name}),y.enabled&&a.jsx("span",{className:"px-2 py-0.5 text-[10px] rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200",children:"已启用"})]}),a.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{if(e!=null&&e.id)try{await ee.activateMcpConfigProfile(e.id,y.id);const v=await ee.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[])}catch{}},children:"激活"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{g(y.id),m({name:y.name||"",envJson:(()=>{try{return JSON.stringify(y.env||{},null,2)}catch{return""}})(),enabled:!!y.enabled});const v=y.env||{},S={};Object.keys(v||{}).forEach(C=>{const _=v[C];if(typeof _=="string"){const I=_.trim();try{S[C]=JSON.parse(I)}catch{I.includes(",")?S[C]=I.split(",").map(T=>T.trim()).filter(Boolean):S[C]=I}}else S[C]=_}),x(S),p(!0)},children:"编辑"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-destructive text-destructive-foreground rounded-md hover:bg-destructive/80",onClick:async()=>{if(!(!(e!=null&&e.id)||!window.confirm(`确定删除配置档案 “${y.name}” 吗?`)))try{await ee.deleteMcpConfigProfile(e.id,y.id);const S=await ee.getMcpConfigProfiles(e.id);s(Array.isArray(S)?S:[])}catch(S){console.error("删除配置档案失败:",S)}},children:"删除"})]})]})},y.id))})]})]}),h&&a.jsxs("div",{className:"modal-container z-[100]",children:[a.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-sm",onClick:()=>{p(!1),c(null)}}),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:a.jsxs("div",{className:"modal-content w-full max-w-2xl transform overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(dg,{}),a.jsx("h3",{className:"text-base font-semibold text-foreground",children:f?"编辑配置档案":"新增配置档案"})]}),a.jsx("button",{onClick:()=>{p(!1),c(null)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(ja,{})})]}),a.jsxs("div",{className:"p-4",children:[u&&a.jsx("div",{className:"mb-2 text-xs text-destructive",children:u}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),a.jsx("input",{type:"text",value:w.name,onChange:y=>m({...w,name:y.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md"})]}),a.jsx("div",{children:b&&Object.keys(b).length>0&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"动态参数"}),a.jsx("div",{className:"grid grid-cols-1 gap-3",children:Object.keys(b).map(y=>{const v=b[y],S=typeof v,C=Array.isArray(v);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:y}),S==="boolean"?a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",checked:!!v,onChange:_=>x({...b,[y]:_.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("span",{className:"ml-2 text-xs",children:String(v)})]}):C?a.jsx("input",{type:"text",value:v.join(", "),onChange:_=>x({...b,[y]:_.target.value.split(",").map(I=>I.trim()).filter(Boolean)}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"}):S==="object"&&v!==null?a.jsx("textarea",{value:(()=>{try{return JSON.stringify(v,null,2)}catch{return String(v)}})(),onChange:_=>{try{const I=JSON.parse(_.target.value);x({...b,[y]:I})}catch{x({...b,[y]:_.target.value})}},rows:4,className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md font-mono text-xs"}):a.jsx("input",{type:S==="number"?"number":"text",value:v??"",onChange:_=>x({...b,[y]:S==="number"?Number(_.target.value):_.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},y)})})]})})]}),a.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:()=>{p(!1),c(null)},children:"取消"}),a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:async()=>{c(null);try{if(!(e!=null&&e.id))throw new Error("缺少配置ID");let y=null;if(b&&Object.keys(b).length>0)y=b;else{const C=(w.envJson||"").trim();if(C)try{const _=JSON.parse(C);_&&typeof _=="object"&&(y=_)}catch{throw new Error("env JSON 格式错误")}}let S=null;if(y&&typeof y=="object"){S={};for(const C of Object.keys(y)){const _=y[C];Array.isArray(_)?S[C]=_.join(","):typeof _=="boolean"||typeof _=="number"?S[C]=String(_):_==null?S[C]="":typeof _=="object"?S[C]=JSON.stringify(_):S[C]=String(_)}}if(f)if(await ee.updateMcpConfigProfile(e.id,f,{name:w.name,env:S,enabled:w.enabled})){const _=await ee.getMcpConfigProfiles(e.id);s(Array.isArray(_)?_:[]),p(!1),g(null)}else throw new Error("更新失败");else{const C=await ee.createMcpConfigProfile(e.id,{name:w.name,env:S,enabled:w.enabled});if(C&&(C.id||C.success)){const _=await ee.getMcpConfigProfiles(e.id);s(Array.isArray(_)?_:[]),p(!1)}else throw new Error("创建失败")}}catch(y){c((y==null?void 0:y.message)||"保存失败")}},children:"保存"})]})]})]})})]})]})},fg={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Aa=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),hg=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),mg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),gg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),pg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),co=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=dt()}catch{t=ct()}const{mcpConfigs:n,updateMcpConfig:s,deleteMcpConfig:o,loadMcpConfigs:i}=t,{dialogState:l,showConfirmDialog:d,handleConfirm:f,handleCancel:g}=ur(),[h,p]=O.useState(!1),[w,m]=O.useState(null),[u,c]=O.useState({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),[b,x]=O.useState(!1),[y,v]=O.useState(null),[S,C]=O.useState({}),[_,I]=O.useState([]),[T,$]=O.useState(""),[F,k]=O.useState(!1),[U,H]=O.useState(null);O.useEffect(()=>{const A="__mcpManagerInitAt__",j=window[A]||0,M=Date.now();typeof j=="number"&&M-j<1e3||(window[A]=M,i())},[i]);const Z=async A=>{H(A),k(!0);try{const j=await ee.getMcpConfigProfiles(A.id);I(Array.isArray(j)?j:[])}catch{console.error("加载配置档案失败")}finally{}},P=()=>{c({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),m(null),p(!1),C({}),I([]),$("")},N=async A=>{var M,L;if(A.preventDefault(),!u.name.trim()||!u.command.trim())return;const j={name:u.name.trim(),command:u.command.trim(),type:u.type,enabled:u.enabled,cwd:(M=u.cwd)!=null&&M.trim()?u.cwd.trim():void 0,args:(L=u.argsInput)!=null&&L.trim()?u.argsInput.split(",").map(z=>z.trim()).filter(Boolean):void 0,createdAt:new Date,updatedAt:new Date};await s(j),P()},R=async A=>{var M,L;if(A.preventDefault(),!w||!u.name.trim()||!u.command.trim())return;const j={...w,name:u.name.trim(),command:u.command.trim(),type:u.type,enabled:u.enabled,cwd:(M=u.cwd)!=null&&M.trim()?u.cwd.trim():void 0,args:(L=u.argsInput)!=null&&L.trim()?u.argsInput.split(",").map(z=>z.trim()).filter(Boolean):void 0,updatedAt:new Date};await s(j),P()},B=A=>{m(A);let j="";const M=A.args;if(Array.isArray(M))j=M.map(L=>String(L)).join(", ");else if(typeof M=="string"&&M.trim()!=="")try{const L=JSON.parse(M);Array.isArray(L)?j=L.map(z=>String(z)).join(", "):j=M}catch{j=M}c({name:A.name,command:A.command,type:A.type||"stdio",enabled:A.enabled,cwd:A.cwd||"",argsInput:j}),p(!0),C({}),v(null),x(!1)},q=async A=>{var L;const j=n.find(z=>z.id===A),M=((L=j==null?void 0:j.name)==null?void 0:L.trim())||"删除";d({title:"删除 MCP 服务器",message:`确定要删除服务器 "${(j==null?void 0:j.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",verificationText:M,verificationLabel:"请键入服务器名称以确认删除",verificationPlaceholder:`输入 "${M}"`,verificationHint:"删除后无法恢复,请再次确认操作。",onConfirm:()=>o(A)})},D=async A=>{const j={...A,enabled:!A.enabled,updatedAt:new Date};await s(j)};return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),a.jsxs("div",{className:"fixed right-0 top-0 h-full w-[520px] sm:w-[560px] bg-card z-50 shadow-xl breathing-border flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Aa,{}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"MCP 服务器管理"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx(hg,{})})]}),a.jsxs("div",{className:"p-4 flex-1 overflow-y-auto overflow-x-hidden",children:[!h&&a.jsxs("button",{onClick:()=>p(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx(mg,{}),a.jsx("span",{children:"添加 MCP 服务器"})]}),h&&a.jsxs("form",{onSubmit:w?R:N,className:"mb-6 p-4 bg-muted rounded-lg",children:[a.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:w?"编辑服务器":"添加新服务器"}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"服务器名称"}),a.jsx("input",{type:"text",value:u.name,onChange:A=>c({...u,name:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: File System",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"协议类型"}),a.jsxs("select",{value:u.type,onChange:A=>c({...u,type:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",children:[a.jsx("option",{value:"stdio",children:"Stdio (标准输入输出)"}),a.jsx("option",{value:"http",children:"HTTP (网络协议)"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:u.type==="http"?"URL地址":"命令"}),a.jsx("input",{type:"text",value:u.command,onChange:A=>c({...u,command:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:u.type==="http"?"https://api.example.com/mcp":"npx @modelcontextprotocol/server-filesystem /path/to/allowed/files",required:!0}),u.type==="stdio"&&a.jsx(a.Fragment,{})]}),u.type==="stdio"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"可执行地址(cwd)"}),a.jsx("input",{type:"text",value:u.cwd,onChange:A=>c({...u,cwd:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"/absolute/path/to/executable"}),a.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"为空则使用当前页面的工作目录"}),a.jsx("div",{className:"mt-2 flex gap-2",children:a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{var A,j;if(u.command.trim()){x(!0),v(null);try{const M=await ee.getMcpConfigResourceByCommand({type:u.type,command:u.command.trim(),args:(A=u.argsInput)!=null&&A.trim()?u.argsInput.split(",").map(L=>L.trim()).filter(Boolean):void 0,env:void 0,cwd:(j=u.cwd)!=null&&j.trim()?u.cwd.trim():void 0,alias:null});if(M&&M.success&&M.config){const L=M.config;if(C(L),w!=null&&w.id)try{const z=await ee.getMcpConfigProfiles(w.id);I(Array.isArray(z)?z:[])}catch{}}else v("无法获取服务器可配置参数")}catch(M){v((M==null?void 0:M.message)||"获取配置失败")}finally{x(!1)}}},children:b?"获取中…":"获取配置"})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"启动参数(args,逗号分隔)"}),a.jsx("input",{type:"text",value:u.argsInput,onChange:A=>c({...u,argsInput:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"--flag, value, --opt"}),a.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"将自动转换为参数数组"})]})]}),a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",id:"enabled",checked:u.enabled,onChange:A=>c({...u,enabled:A.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此服务器"})]}),u.type==="stdio"&&Object.keys(S).length>0&&a.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-foreground",children:"服务器可配置参数(动态解析)"}),b&&a.jsx("span",{className:"text-xs text-muted-foreground",children:"解析中…"})]}),y&&a.jsx("p",{className:"text-xs text-red-600 mb-2",children:y}),a.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[Object.keys(S).map(A=>{const j=S[A],M=typeof j,L=Array.isArray(j);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:A}),M==="boolean"?a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",checked:!!j,onChange:z=>C({...S,[A]:z.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("span",{className:"ml-2 text-xs",children:String(j)})]}):L?a.jsx("input",{type:"text",value:j.join(", "),onChange:z=>C({...S,[A]:z.target.value.split(",").map(Q=>Q.trim()).filter(Boolean)}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"}):a.jsx("input",{type:M==="number"?"number":"text",value:j??"",onChange:z=>C({...S,[A]:M==="number"?Number(z.target.value):z.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},A)}),(w==null?void 0:w.id)&&a.jsxs("div",{className:"mt-2 p-2 border border-dashed rounded-md",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"text",value:T,onChange:A=>$(A.target.value),className:"flex-1 px-2 py-1 border border-input bg-background text-foreground rounded-md",placeholder:"配置档案名称(例如:开发环境)"}),a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:async()=>{var A,j;if(w!=null&&w.id)try{await ee.createMcpConfigProfile(w.id,{name:T||`配置-${new Date().toLocaleString()}`,env:Object.keys(S).reduce((L,z)=>{const Q=S[z];return L[z]=typeof Q=="string"?Q:String(Q),L},{}),args:(A=u.argsInput)!=null&&A.trim()?u.argsInput.split(",").map(L=>L.trim()).filter(Boolean):void 0,cwd:(j=u.cwd)!=null&&j.trim()?u.cwd.trim():void 0,enabled:!1});const M=await ee.getMcpConfigProfiles(w.id);I(Array.isArray(M)?M:[]),$("")}catch(M){console.error("保存配置档案失败:",M),v("保存配置档案失败")}},children:"保存为配置档案"})]}),_.length>0&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:"text-xs text-muted-foreground",children:"已有配置档案:"}),_.map(A=>{const j=Array.isArray(A.args)?A.args.join(", "):"",M=A.env?Object.keys(A.env):[];return a.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"text-xs text-foreground font-medium",children:A.name}),A.enabled&&a.jsx("span",{className:"px-2 py-0.5 text-[10px] rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200",children:"已启用"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{try{await ee.activateMcpConfigProfile(w.id,A.id);const L=await ee.getMcpConfigProfiles(w.id);I(Array.isArray(L)?L:[])}catch{}},children:"激活"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{c(L=>({...L,argsInput:Array.isArray(A.args)?A.args.join(", "):L.argsInput,cwd:A.cwd??L.cwd})),C(A.env||{})},children:"应用到表单"})]})]}),a.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[a.jsxs("div",{className:"truncate",title:A.cwd||"未设置",children:[a.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),A.cwd||"未设置"]}),a.jsxs("div",{className:"truncate",title:j||"未设置",children:[a.jsx("span",{className:"text-muted-foreground",children:"args:"}),j||"未设置"]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-muted-foreground",children:["env(",M.length,"):"]}),M.length===0?"未设置":a.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:M.map(L=>a.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[a.jsx("span",{className:"text-muted-foreground shrink-0",children:L}),a.jsx("span",{className:"text-foreground truncate",title:String(A.env[L]),children:String(A.env[L])})]},L))})]})]})]},A.id)})]})]})]})]})]}),(w==null?void 0:w.id)&&!h&&a.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-foreground",children:"配置档案列表"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{try{const A=await ee.getMcpConfigProfiles(w.id);I(Array.isArray(A)?A:[])}catch{}},children:"刷新"})]}),_.length===0?a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案"}):a.jsx("div",{className:"space-y-2",children:_.map(A=>{const j=Array.isArray(A.args)?A.args.join(", "):"",M=A.env?Object.keys(A.env):[];return a.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"text-xs text-foreground font-medium",children:A.name}),A.enabled&&a.jsx("span",{className:"px-2 py-0.5 text-[10px] rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200",children:"已启用"})]}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{try{await ee.activateMcpConfigProfile(w.id,A.id);const L=await ee.getMcpConfigProfiles(w.id);I(Array.isArray(L)?L:[])}catch{}},children:"激活"})})]}),a.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),A.cwd||"未设置"]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"args:"}),j||"未设置"]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-muted-foreground",children:["env(",M.length,"):"]}),M.length===0?"未设置":a.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:M.map(L=>a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-muted-foreground",children:L}),a.jsx("span",{className:"text-foreground",children:String(A.env[L])})]},L))})]})]})]},A.id)})})]}),a.jsxs("div",{className:"flex space-x-3 mt-6",children:[a.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:w?"更新":"添加"}),a.jsx("button",{type:"button",onClick:P,className:"px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 focus:outline-none focus:ring-2 focus:ring-ring",children:"取消"})]})]}),a.jsx("div",{className:"space-y-3",children:n.length===0?a.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[a.jsx(Aa,{}),a.jsx("p",{className:"mt-2",children:"暂无 MCP 服务器配置"}),a.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个服务器"})]}):n.map(A=>a.jsxs("div",{className:"flex items-center justify-between gap-3 p-4 bg-card border border-border rounded-lg",children:[a.jsxs("div",{className:"flex items-center space-x-3 flex-1 min-w-0",children:[a.jsx("div",{className:`w-3 h-3 rounded-full ${A.enabled?"bg-green-500":"bg-gray-400"}`}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsxs("div",{className:"flex items-center space-x-2 min-w-0",children:[a.jsx("h4",{className:"font-medium text-foreground truncate",title:A.name,children:A.name}),a.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${A.type==="http"?"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200":"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"}`,children:A.type==="http"?"HTTP":"Stdio"})]}),a.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground truncate break-all font-mono",title:A.command,children:A.command}),typeof window<"u"&&fg&&!1,A.type==="stdio"&&a.jsxs("div",{className:"mt-1 space-y-0.5 min-w-0",children:[A.cwd&&a.jsxs("div",{className:"text-xs text-muted-foreground truncate",title:String(A.cwd),children:["cwd: ",a.jsx("span",{className:"text-foreground",children:String(A.cwd)})]}),a.jsx("div",{className:"text-xs text-muted-foreground truncate",title:(()=>{const j=A.args;let M=null,L=!1;if(Array.isArray(j))M=j.map(Q=>String(Q));else if(typeof j=="string"&&j.trim()!=="")try{const Q=JSON.parse(j);Array.isArray(Q)&&(M=Q.map(ae=>String(ae)),L=!0)}catch{}const z=Array.isArray(M)&&M.length>0?M.join(", "):typeof j=="string"&&!L?j:"—";return String(z)})(),children:(()=>{const j=A.args;let M=null,L=!1;if(Array.isArray(j))M=j.map(Q=>String(Q));else if(typeof j=="string"&&j.trim()!=="")try{const Q=JSON.parse(j);Array.isArray(Q)&&(M=Q.map(ae=>String(ae)),L=!0)}catch{}const z=Array.isArray(M)&&M.length>0?M.join(", "):typeof j=="string"&&!L?j:"—";return a.jsxs("span",{children:["参数(args):",a.jsx("span",{className:"text-foreground",children:z})]})})()})]})]})]}),a.jsxs("div",{className:"flex items-center space-x-2 shrink-0",children:[a.jsx("button",{onClick:()=>D(A),className:`px-3 py-1 text-xs rounded-full ${A.enabled?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-secondary text-secondary-foreground"}`,children:A.enabled?"已启用":"已禁用"}),a.jsx("button",{onClick:()=>Z(A),className:"p-2 text-muted-foreground hover:text-indigo-600 transition-colors",title:"查看配置档案",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 7.5l7.5 3 7.5-3M3 7.5V18l7.5 3 7.5-3V7.5M10.5 10.5V21"})})}),a.jsx("button",{onClick:()=>B(A),className:"p-2 text-muted-foreground hover:text-blue-600 transition-colors",title:"编辑",children:a.jsx(pg,{})}),a.jsx("button",{onClick:()=>q(A.id),className:"p-2 text-muted-foreground hover:text-red-600 transition-colors",title:"删除",children:a.jsx(gg,{})})]})]},A.id))})]})]}),a.jsx(ug,{open:F,config:U,onClose:()=>{k(!1),H(null)}}),a.jsx(dr,{isOpen:l.isOpen,title:l.title,message:l.message,confirmText:l.confirmText,cancelText:l.cancelText,type:l.type,verificationText:l.verificationText,verificationLabel:l.verificationLabel,verificationPlaceholder:l.verificationPlaceholder,verificationHint:l.verificationHint,onConfirm:f,onCancel:g})]})},ka=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),xg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),bg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),yg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),wg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),uo=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=dt()}catch{t=ct()}const{aiModelConfigs:n,loadAiModelConfigs:s,updateAiModelConfig:o,deleteAiModelConfig:i}=t,[l,d]=O.useState(!1),[f,g]=O.useState(null),[h,p]=O.useState({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),{dialogState:w,showConfirmDialog:m,handleConfirm:u,handleCancel:c}=ur();O.useEffect(()=>{const _="__aiModelManagerInitAt__",I=window[_]||0,T=Date.now();typeof I=="number"&&T-I<1e3||(window[_]=T,s())},[s]);const b=()=>{p({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),g(null),d(!1)},x=async _=>{if(_.preventDefault(),!h.name.trim()||!h.base_url.trim()||!h.api_key.trim()||!h.model_name.trim())return;const I={id:Math.random().toString(36).substr(2,9),name:h.name.trim(),base_url:h.base_url.trim(),api_key:h.api_key.trim(),model_name:h.model_name.trim(),enabled:h.enabled,createdAt:new Date,updatedAt:new Date};await o(I),b()},y=async _=>{if(_.preventDefault(),!f||!h.name.trim()||!h.base_url.trim()||!h.api_key.trim()||!h.model_name.trim())return;const I={...f,name:h.name.trim(),base_url:h.base_url.trim(),api_key:h.api_key.trim(),model_name:h.model_name.trim(),enabled:h.enabled,updatedAt:new Date};await o(I),b()},v=_=>{g(_),p({name:_.name,base_url:_.base_url,api_key:_.api_key,model_name:_.model_name,enabled:_.enabled}),d(!0)},S=async _=>{var $;const I=n.find(F=>F.id===_),T=(($=I==null?void 0:I.name)==null?void 0:$.trim())||"删除";m({title:"删除确认",message:`确定要删除AI模型配置 "${(I==null?void 0:I.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",verificationText:T,verificationLabel:"请输入下方关键字确认删除",verificationPlaceholder:`输入 "${T}"`,verificationHint:"删除后无法恢复,请谨慎操作。",onConfirm:async()=>{await i(_)}})},C=async _=>{const I={..._,enabled:!_.enabled,updatedAt:new Date};await o(I)};return a.jsxs("div",{className:"modal-container",children:[a.jsxs("div",{className:"modal-content w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(ka,{}),a.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"AI 模型管理"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(xg,{})})]}),a.jsxs("div",{className:"p-6 overflow-y-auto overflow-x-hidden max-h-[calc(80vh-120px)]",children:[!l&&a.jsxs("button",{onClick:()=>d(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx(bg,{}),a.jsx("span",{children:"添加 AI 模型"})]}),l&&a.jsxs("form",{onSubmit:f?y:x,className:"mb-6 p-4 bg-muted rounded-lg",children:[a.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:f?"编辑 AI 模型":"添加 AI 模型"}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),a.jsx("input",{type:"text",value:h.name,onChange:_=>p({...h,name:_.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: OpenAI GPT-4",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Base URL"}),a.jsx("input",{type:"url",value:h.base_url,onChange:_=>p({...h,base_url:_.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: https://api.openai.com/v1",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"API Key"}),a.jsx("input",{type:"password",value:h.api_key,onChange:_=>p({...h,api_key:_.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"输入API密钥",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"模型名称"}),a.jsx("input",{type:"text",value:h.model_name,onChange:_=>p({...h,model_name:_.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: gpt-4",required:!0})]}),a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",id:"enabled",checked:h.enabled,onChange:_=>p({...h,enabled:_.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此模型"})]})]}),a.jsxs("div",{className:"flex space-x-3 mt-6",children:[a.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:f?"更新":"添加"}),a.jsx("button",{type:"button",onClick:b,className:"px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 focus:outline-none focus:ring-2 focus:ring-ring",children:"取消"})]})]}),a.jsx("div",{className:"space-y-3",children:n.length===0?a.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[a.jsx(ka,{}),a.jsx("p",{className:"mt-2",children:"暂无 AI 模型配置"}),a.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个模型"})]}):n.map(_=>a.jsxs("div",{className:"flex items-center justify-between gap-3 p-4 bg-card border border-border rounded-lg hover:shadow-md transition-shadow",children:[a.jsxs("div",{className:"flex items-center space-x-3 flex-1 min-w-0",children:[a.jsx("div",{className:`w-3 h-3 rounded-full ${_.enabled?"bg-green-500":"bg-gray-400"}`}),a.jsxs("div",{className:"min-w-0 flex-1",children:[a.jsx("h4",{className:"font-medium text-foreground truncate",title:_.name,children:_.name}),a.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground truncate",title:`${_.base_url} - ${_.model_name}`,children:[_.base_url," - ",_.model_name]})]})]}),a.jsxs("div",{className:"flex items-center space-x-2 shrink-0",children:[a.jsx("button",{onClick:()=>C(_),className:`px-3 py-1 text-xs rounded-full transition-colors ${_.enabled?"bg-green-100 text-green-800 hover:bg-green-200 dark:bg-green-900 dark:text-green-200":"bg-secondary text-secondary-foreground hover:bg-secondary/80"}`,children:_.enabled?"已启用":"已禁用"}),a.jsx("button",{onClick:()=>v(_),className:"p-2 text-muted-foreground hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded transition-colors",title:"编辑",children:a.jsx(yg,{})}),a.jsx("button",{onClick:()=>S(_.id),className:"p-2 text-muted-foreground hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded transition-colors",title:"删除",children:a.jsx(wg,{})})]})]},_.id))})]})]}),a.jsx(dr,{isOpen:w.isOpen,title:w.title,message:w.message,confirmText:w.confirmText,cancelText:w.cancelText,type:w.type,verificationText:w.verificationText,verificationLabel:w.verificationLabel,verificationPlaceholder:w.verificationPlaceholder,verificationHint:w.verificationHint,onConfirm:u,onCancel:c})]})},Na=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),vg=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),_g=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),Sg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Cg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),jg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),Ag=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),fo=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=dt()}catch{t=ct()}const{systemContexts:n,activeSystemContext:s,loadSystemContexts:o,createSystemContext:i,updateSystemContext:l,deleteSystemContext:d,activateSystemContext:f}=t,[g,h]=O.useState("list"),[p,w]=O.useState(null),[m,u]=O.useState({name:"",content:""}),[c,b]=O.useState(!1),[x,y]=O.useState(!1),{dialogState:v,showConfirmDialog:S,handleConfirm:C,handleCancel:_}=ur();O.useEffect(()=>{const P="__systemContextEditorInitAt__",N=window[P]||0,R=Date.now();if(typeof N=="number"&&R-N<1e3)return;window[P]=R,(async()=>{b(!0);try{await o()}catch(q){console.error("Failed to load system contexts:",q)}finally{b(!1)}})()},[o]);const I=()=>{u({name:"",content:""}),w(null),h("create")},T=P=>{u({name:P.name,content:P.content}),w(P),h("edit")},$=async()=>{if(!m.name.trim()||!m.content.trim()){alert("请填写名称和内容");return}y(!0);try{g==="create"?await i(m.name,m.content):g==="edit"&&p&&await l(p.id,m.name,m.content),h("list")}catch(P){console.error("Failed to save system context:",P),alert("保存失败,请重试")}finally{y(!1)}},F=async P=>{var N,R;S({title:"删除确认",message:`确定要删除上下文 "${P.name}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",verificationText:((N=P.name)==null?void 0:N.trim())||"删除",verificationLabel:"请输入下方关键字确认删除",verificationPlaceholder:`输入 "${((R=P.name)==null?void 0:R.trim())||"删除"}"`,verificationHint:"为了防止误删,需要输入配置名称才能继续。",onConfirm:async()=>{try{await d(P.id)}catch(B){console.error("Failed to delete system context:",B),alert("删除失败,请重试")}}})},k=async P=>{try{await f(P.id),await o()}catch(N){console.error("Failed to activate system context:",N),alert("激活失败,请重试")}},U=P=>{P.ctrlKey&&P.key==="s"&&(P.preventDefault(),g!=="list"&&$())},H=()=>a.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[a.jsx("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:a.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:[a.jsx("strong",{children:"系统上下文"}),"将作为每次对话的系统提示词,支持 Markdown 格式。 您可以创建多个上下文配置,但同一时间只能激活一个。"]})}),a.jsx("div",{className:"flex-1 overflow-y-auto",children:c?a.jsx("div",{className:"flex items-center justify-center h-32",children:a.jsx("div",{className:"text-muted-foreground",children:"加载中..."})}):n.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-muted-foreground",children:[a.jsx(Na,{}),a.jsx("p",{className:"mt-2",children:"暂无系统上下文配置"}),a.jsx("p",{className:"text-sm",children:'点击"新建"按钮创建第一个配置'})]}):a.jsx("div",{className:"space-y-3",children:n.map(P=>a.jsx("div",{className:`p-4 border rounded-lg transition-colors ${P.isActive?"border-green-500 bg-green-50 dark:bg-green-900/20":"border-border bg-card"}`,children:a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("h3",{className:"font-medium text-foreground",children:P.name}),P.isActive&&a.jsxs("span",{className:"inline-flex items-center px-2 py-1 text-xs font-medium bg-green-100 text-green-800 rounded-full dark:bg-green-800 dark:text-green-100",children:[a.jsx(Ag,{}),a.jsx("span",{className:"ml-1",children:"已激活"})]})]}),a.jsxs("p",{className:"mt-1 text-sm text-muted-foreground line-clamp-2",children:[P.content.substring(0,100),P.content.length>100&&"..."]}),a.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["创建时间: ",new Date(P.createdAt).toLocaleString()]})]}),a.jsxs("div",{className:"flex items-center space-x-2 ml-4",children:[!P.isActive&&a.jsx("button",{onClick:()=>k(P),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"激活"}),a.jsx("button",{onClick:()=>T(P),className:"p-2 text-muted-foreground hover:text-blue-600 hover:bg-accent rounded transition-colors",children:a.jsx(Cg,{})}),a.jsx("button",{onClick:()=>F(P),className:"p-2 text-muted-foreground hover:text-red-600 hover:bg-accent rounded transition-colors",children:a.jsx(jg,{})})]})]})},P.id))})})]}),Z=()=>a.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[a.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:[a.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:g==="create"?"创建新的系统上下文配置":"编辑系统上下文配置"}),a.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300 mt-2",children:"提示:使用 Ctrl+S 快速保存"})]}),a.jsxs("div",{className:"flex-1 flex flex-col space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),a.jsx("input",{type:"text",value:m.name,onChange:P=>u({...m,name:P.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-lg focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如:编程助手、翻译专家、创意写作等"})]}),a.jsxs("div",{className:"flex-1 flex flex-col",children:[a.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[a.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Markdown 内容"}),a.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.content.length," 字符"]})]}),a.jsx("textarea",{value:m.content,onChange:P=>u({...m,content:P.target.value}),onKeyDown:U,className:"flex-1 w-full px-4 py-3 border border-input bg-background text-foreground rounded-lg focus:outline-none focus:ring-2 focus:ring-ring resize-none font-mono text-sm",placeholder:"请输入系统上下文内容,支持 Markdown 格式...\\n\\n例如:\\n# AI 助手角色设定\\n\\n你是一个专业的编程助手,具有以下特点:\\n- 提供准确、简洁的代码解决方案\\n- 遵循最佳实践和代码规范\\n- 耐心解答技术问题\\n\\n## 回答风格\\n- 使用中文回答\\n- 代码示例要完整可运行\\n- 提供必要的解释说明",spellCheck:!1})]}),a.jsxs("div",{className:"text-xs text-muted-foreground",children:[a.jsx("p",{children:"• 支持标准 Markdown 语法:标题、列表、代码块、链接等"}),a.jsx("p",{children:"• 内容将在每次对话开始时自动发送给 AI"}),a.jsx("p",{children:"• 留空则使用默认系统提示词"})]})]})]});return a.jsxs("div",{className:"modal-container",children:[a.jsxs("div",{className:"modal-content w-full max-w-4xl max-h-[90vh] overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Na,{}),a.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"系统上下文设置"})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[g==="list"?a.jsxs("button",{onClick:I,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 transition-colors",children:[a.jsx(Sg,{}),a.jsx("span",{children:"新建"})]}):a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:$,disabled:x,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:[a.jsx(_g,{}),a.jsx("span",{children:x?"保存中...":"保存"})]}),a.jsx("button",{onClick:()=>h("list"),className:"px-4 py-2 text-secondary-foreground border border-border rounded-md hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring transition-colors",children:"取消"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(vg,{})})]})]}),g==="list"?H():Z()]}),a.jsx(dr,{isOpen:v.isOpen,title:v.title,message:v.message,confirmText:v.confirmText,cancelText:v.cancelText,type:v.type,verificationText:v.verificationText,verificationLabel:v.verificationLabel,verificationPlaceholder:v.verificationPlaceholder,verificationHint:v.verificationHint,onConfirm:C,onCancel:_})]})},Ma=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6M9 16h6M6 8h12a2 2 0 012 2v8a2 2 0 01-2 2H6a2 2 0 01-2-2v-8a2 2 0 012-2z"})}),Ea=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),kg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Ng=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),tc=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=dt()}catch{t=ct()}const{aiModelConfigs:n,loadAiModelConfigs:s,mcpConfigs:o,loadMcpConfigs:i,systemContexts:l,loadSystemContexts:d}=t,{userId:f}=Of(),g=f||"custom_user_123",p=Rf()||ee,[w,m]=O.useState([]),[u,c]=O.useState(!1),[b,x]=O.useState(!1),[y,v]=O.useState(null),[S,C]=O.useState(null),[_,I]=O.useState({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),{dialogState:T,showConfirmDialog:$,handleConfirm:F,handleCancel:k}=ur(),U=async()=>{c(!0);try{await Promise.all([s(),i(),d(),t.loadAgents?t.loadAgents():Promise.resolve()]);const j=t.agents&&Array.isArray(t.agents)?t.agents:await p.getAgents(g),M=Array.isArray(j)?j:[];m(M)}catch(j){console.error("加载智能体失败",j)}finally{c(!1)}},H=async j=>{for(let L=0;L<3;L++)try{t.loadAgents&&await t.loadAgents();const z=await p.getAgents(g),Q=Array.isArray(z)?z:[];if(m(Q),j&&Array.isArray(Q)&&Q.some(ae=>ae.id===j)||!j)break;await new Promise(ae=>setTimeout(ae,250))}catch(z){console.warn("刷新智能体列表失败,重试中…",z),await new Promise(Q=>setTimeout(Q,250))}};O.useEffect(()=>{const j="__agentManagerInitAt__",M=window[j]||0,L=Date.now();typeof M=="number"&&L-M<1e3||(window[j]=L,U())},[]);const Z=()=>{I({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),x(!1),C(null)},P=async j=>{var M;if(j.preventDefault(),!(!_.name.trim()||!_.ai_model_config_id))try{const L=await p.createAgent({name:_.name.trim(),description:((M=_.description)==null?void 0:M.trim())||void 0,ai_model_config_id:_.ai_model_config_id,mcp_config_ids:_.mcp_config_ids,system_context_id:_.system_context_id,user_id:g,enabled:!0});L&&L.id&&m(z=>z.some(ae=>ae.id===L.id)?z.map(ae=>ae.id===L.id?{...ae,...L}:ae):[L,...z]),await H(L==null?void 0:L.id),Z()}catch(L){console.error("创建智能体失败",L),alert("创建失败,请重试")}},N=async j=>{if(j.preventDefault(),!!S)try{const M=await p.updateAgent(S.id,{name:_.name,description:_.description,ai_model_config_id:_.ai_model_config_id,mcp_config_ids:_.mcp_config_ids,system_context_id:_.system_context_id,enabled:!0});m(L=>L.map(z=>z.id===S.id?{...z,...M,name:_.name,description:_.description,ai_model_config_id:_.ai_model_config_id,mcp_config_ids:_.mcp_config_ids,system_context_id:_.system_context_id,enabled:!0}:z)),await H(S.id),Z()}catch(M){console.error("更新智能体失败",M),alert("更新失败,请重试")}},R=j=>{var z;const M=w.find(Q=>Q.id===j),L=((z=M==null?void 0:M.name)==null?void 0:z.trim())||"删除";$({title:"删除智能体",message:`确定要删除智能体 "${(M==null?void 0:M.name)||"未命名"}" 吗?此操作将无法撤销。`,confirmText:"永久删除",cancelText:"取消",type:"danger",verificationText:L,verificationLabel:"请输入智能体名称以确认删除",verificationPlaceholder:`输入 "${L}"`,verificationHint:"删除后该智能体将从所有应用中移除且无法恢复。",onConfirm:async()=>{try{await p.deleteAgent(j),m(Q=>Q.filter(ae=>ae.id!==j)),await H()}catch(Q){console.error("删除智能体失败",Q),alert("删除失败,请重试")}}})},B=j=>{C(j),x(!0),I({name:j.name,description:j.description||"",ai_model_config_id:j.ai_model_config_id,mcp_config_ids:Array.isArray(j.mcp_config_ids)?j.mcp_config_ids:[],system_context_id:j.system_context_id})},q=j=>{const M=n.find(L=>L.id===j);return M?`${M.name}(${M.model_name})`:j},D=j=>{if(!j)return"未选择";const M=l.find(L=>L.id===j);return M?M.name:j},A=j=>j.map(L=>{const z=o.find(Q=>Q.id===L);return z?z.name:L}).join(",");return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),a.jsxs("div",{className:"fixed right-0 top-0 h-full w-[520px] sm:w-[560px] bg-card z-50 shadow-xl breathing-border flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Ma,{}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"智能体管理"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx(Ea,{})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[!b&&a.jsxs("button",{onClick:()=>x(!0),className:"w-full p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx(kg,{}),a.jsx("span",{children:"新增智能体"})]}),b&&a.jsxs("form",{onSubmit:S?N:P,className:"p-4 bg-muted rounded-lg space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),a.jsx("input",{type:"text",value:_.name,onChange:j=>I({..._,name:j.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如:项目助理",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"描述"}),a.jsx("textarea",{value:_.description,onChange:j=>I({..._,description:j.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"智能体用途说明",rows:3})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择模型(单选)"}),a.jsxs("select",{value:_.ai_model_config_id,onChange:j=>I({..._,ai_model_config_id:j.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",required:!0,children:[a.jsx("option",{value:"",children:"请选择模型"}),n.map(j=>a.jsxs("option",{value:j.id,children:[j.name,"(",j.model_name,")"]},j.id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 MCP 配置(多选)"}),a.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 border rounded-md",children:o.map(j=>a.jsxs("label",{className:"flex items-center space-x-2",children:[a.jsx("input",{type:"checkbox",checked:_.mcp_config_ids.includes(j.id),onChange:M=>{const L=M.target.checked;I(z=>({...z,mcp_config_ids:L?[...z.mcp_config_ids,j.id]:z.mcp_config_ids.filter(Q=>Q!==j.id)}))}}),a.jsx("span",{children:j.name})]},j.id))})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择系统上下文"}),a.jsxs("select",{value:_.system_context_id||"",onChange:j=>I({..._,system_context_id:j.target.value||void 0}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",children:[a.jsx("option",{value:"",children:"不使用"}),l.map(j=>a.jsx("option",{value:j.id,children:j.name},j.id))]})]}),a.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[a.jsx("button",{type:"button",onClick:Z,className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"取消"}),a.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:"保存"})]})]}),a.jsx("div",{children:u?a.jsx("div",{className:"text-muted-foreground",children:"加载中..."}):w.length===0?a.jsx("div",{className:"text-muted-foreground",children:"暂无智能体配置"}):a.jsx("div",{className:"space-y-3",children:w.map(j=>a.jsxs("div",{className:"p-4 border rounded-lg flex items-start justify-between gap-3",children:[a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center space-x-2 min-w-0",children:[a.jsx("h3",{className:"font-medium text-foreground truncate",title:j.name,children:j.name}),!j.enabled&&a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-muted text-muted-foreground",children:"未启用"})]}),j.description&&a.jsx("p",{className:"mt-1 text-sm text-muted-foreground truncate",title:j.description,children:j.description}),a.jsxs("p",{className:"mt-2 text-xs text-muted-foreground truncate",title:q(j.ai_model_config_id),children:["模型:",q(j.ai_model_config_id)]}),a.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:D(j.system_context_id),children:["系统上下文:",D(j.system_context_id)]}),a.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:A(j.mcp_config_ids||[]),children:["MCP配置:",A(j.mcp_config_ids||[])]})]}),a.jsxs("div",{className:"flex items-center space-x-2 ml-4 shrink-0",children:[a.jsx("button",{onClick:()=>v(j),className:"px-3 py-1 text-sm bg-muted text-foreground rounded hover:bg-accent transition-colors",children:"详情"}),a.jsx("button",{onClick:()=>B(j),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"编辑"}),a.jsxs("button",{onClick:()=>R(j.id),className:"px-3 py-1 text-sm bg-destructive text-destructive-foreground rounded hover:bg-destructive/90 transition-colors flex items-center space-x-1",children:[a.jsx(Ng,{}),a.jsx("span",{children:"删除"})]})]})]},j.id))})})]}),y&&a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:()=>v(null)}),a.jsxs("div",{className:"relative bg-card border border-border rounded-lg shadow-xl w-[520px] p-6",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx(Ma,{}),a.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"智能体详情"})]}),a.jsx("button",{onClick:()=>v(null),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(Ea,{})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"名称:"}),y.name]}),y.description&&a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"描述:"}),y.description]}),a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"模型:"}),q(y.ai_model_config_id)]}),a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"系统上下文:"}),D(y.system_context_id)]}),a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"MCP配置:"}),A(y.mcp_config_ids||[])]}),Array.isArray(y.mcp_config_ids)&&y.mcp_config_ids.length>0&&a.jsx("div",{className:"mt-2 space-y-2",children:(y.mcp_config_ids||[]).map(j=>{var Q,ae;const M=(o||[]).find(be=>be.id===j);if(!M)return null;let L="—";const z=M.args;if(Array.isArray(z))L=z.map(be=>String(be)).join(", ");else if(typeof z=="string"&&z.trim()!=="")try{const be=JSON.parse(z);Array.isArray(be)?L=be.map(nc=>String(nc)).join(", "):L=z}catch{L=z}return a.jsxs("div",{className:"p-2 rounded border border-border",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium text-foreground",children:M.name}),a.jsx("span",{className:`px-1.5 py-0.5 text-xs rounded ${M.type==="http"?"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200":"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"}`,children:((ae=(Q=M.type)==null?void 0:Q.toUpperCase)==null?void 0:ae.call(Q))||M.type})]}),a.jsxs("div",{className:"mt-1 text-xs text-muted-foreground break-all",children:[M.type==="http"?"URL:":"命令:",a.jsx("span",{className:"text-foreground",children:M.command})]}),M.cwd&&a.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground break-all",children:["cwd:",a.jsx("span",{className:"text-foreground",children:String(M.cwd)})]}),M.type==="stdio"&&a.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground break-all",children:["args:",a.jsx("span",{className:"text-foreground",children:L})]})]},j)})}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:["创建时间:",y.created_at?new Date(y.created_at).toLocaleString():"-"]})]}),a.jsx("div",{className:"mt-4 flex justify-end space-x-2",children:a.jsx("button",{onClick:()=>v(null),className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"关闭"})})]})]})]}),a.jsx(dr,{isOpen:T.isOpen,title:T.title,message:T.message,confirmText:T.confirmText,cancelText:T.cancelText,type:T.type,verificationText:T.verificationText,verificationLabel:T.verificationLabel,verificationPlaceholder:T.verificationPlaceholder,verificationHint:T.verificationHint,onConfirm:F,onCancel:k})]})},rc=({isOpen:r,onClose:e,manageOnly:t=!1,title:n,layout:s="modal",onApplicationSelect:o})=>{let i;try{i=dt()}catch{i=ct()}const{applications:l,loadApplications:d,createApplication:f,updateApplication:g,deleteApplication:h}=i,p=O.useRef(new Map),[w,m]=O.useState(!!t),[u,c]=O.useState(!1),[b,x]=O.useState(null),[y,v]=O.useState({name:"",url:"",iconUrl:""});O.useEffect(()=>{try{console.log("[ApplicationsPanel] useEffect -> loadApplications"),d==null||d()}catch(k){console.error("[ApplicationsPanel] loadApplications error:",k)}},[d]);const S=()=>{x(null),v({name:"",url:"",iconUrl:""}),c(!1)},C=async k=>{k.preventDefault(),y.name.trim()&&(b?await(g==null?void 0:g(b,{name:y.name.trim(),url:y.url.trim(),iconUrl:y.iconUrl.trim()||void 0})):await(f==null?void 0:f(y.name.trim(),y.url.trim(),y.iconUrl.trim()||void 0)),S())},_=k=>{console.log("[ApplicationsPanel] closeAppWindow:",k);const U=p.current.get(k);U&&!U.closed&&U.close(),p.current.delete(k)},I=k=>{console.log("[ApplicationsPanel] handleAppClick - 应用被点击:",{id:k.id,name:k.name,url:k.url}),o?(console.log("[ApplicationsPanel] 调用 onApplicationSelect 回调"),o(k)):console.log("[ApplicationsPanel] ⚠️ 未提供 onApplicationSelect 回调"),e&&(console.log("[ApplicationsPanel] 关闭应用列表面板"),e())};if(!(s==="modal"?!!r:!0))return null;const $=t?!0:w,F=n??($?"应用管理":"应用列表");return s==="modal"?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:e}),a.jsxs("div",{className:"fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[90vw] max-w-4xl h-[85vh] bg-card z-50 shadow-xl breathing-border flex flex-col rounded-lg",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full bg-blue-500"}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:F})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&a.jsx("button",{onClick:()=>{m(!w),c(!1),S()},className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent transition-colors",children:$?"浏览模式":"管理模式"}),!$&&p.current.size>0&&a.jsx("button",{className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",onClick:()=>{p.current.forEach((k,U)=>_(U))},children:"关闭全部"}),a.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:$?a.jsxs("div",{className:"space-y-4",children:[!u&&a.jsxs("button",{type:"button",onClick:()=>c(!0),className:"w-full p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v12m6-6H6"})}),a.jsx("span",{children:"新增应用"})]}),u&&a.jsxs("form",{onSubmit:C,className:"p-4 bg-muted rounded-lg space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),a.jsx("input",{type:"text",value:y.name,onChange:k=>v({...y,name:k.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如:Jira、GitHub",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"URL"}),a.jsx("input",{type:"text",value:y.url,onChange:k=>v({...y,url:k.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"https://app.example.com"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"图标URL"}),a.jsx("input",{type:"text",value:y.iconUrl,onChange:k=>v({...y,iconUrl:k.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"https://app.example.com/icon.png"})]}),a.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[a.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-muted hover:bg-accent",onClick:S,children:"取消"}),a.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:b?"保存":"创建"})]})]}),a.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(k=>a.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center overflow-hidden shrink-0",children:k.iconUrl?a.jsx("img",{src:k.iconUrl,alt:k.name,className:"w-full h-full object-cover"}):a.jsx("span",{className:"text-white text-sm font-bold",children:k.name.charAt(0).toUpperCase()})}),a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-medium text-foreground",children:k.name}),k.url&&a.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:k.url})]})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{className:"px-2 py-1 text-xs bg-muted rounded hover:bg-accent",onClick:()=>{x(k.id),c(!0),v({name:k.name,url:k.url||"",iconUrl:k.iconUrl||""})},children:"编辑"}),a.jsx("button",{className:"px-2 py-1 text-xs bg-destructive text-destructive-foreground rounded hover:bg-destructive/90",onClick:()=>h==null?void 0:h(k.id),children:"删除"})]})]},k.id)),(l==null?void 0:l.length)===0&&a.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[a.jsx("svg",{className:"w-16 h-16 mx-auto mb-3 opacity-30",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm",children:"暂无应用,点击上方按钮添加"})]})]})]}):a.jsxs("div",{className:"grid grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-6",children:[l==null?void 0:l.map(k=>{const U=p.current.has(k.id);return a.jsxs("div",{className:"relative group/item",children:[a.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>I(k),title:k.url||"",children:[a.jsxs("div",{className:`relative w-16 h-16 rounded-full flex items-center justify-center overflow-hidden transition-all ${U?"ring-2 ring-green-500 ring-offset-2 ring-offset-background scale-110":"bg-gradient-to-br from-blue-500/20 to-purple-500/20 group-hover/item:scale-105"}`,children:[k.iconUrl?a.jsx("img",{src:k.iconUrl,alt:k.name,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:a.jsx("span",{className:"text-white text-xl font-bold",children:k.name.charAt(0).toUpperCase()})}),U&&a.jsx("div",{className:"absolute -top-1 -right-1 w-5 h-5 bg-green-500 rounded-full border-2 border-background flex items-center justify-center",children:a.jsx("div",{className:"w-2 h-2 bg-white rounded-full animate-pulse"})})]}),a.jsx("div",{className:"text-xs font-medium text-foreground text-center truncate w-full px-1",children:k.name})]}),U&&a.jsx("button",{onClick:H=>{H.stopPropagation(),_(k.id)},className:"absolute top-0 left-0 w-5 h-5 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover/item:opacity-100 transition-opacity z-10",title:"关闭",children:a.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},k.id)}),((l==null?void 0:l.length)??0)===0&&a.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-20 text-center",children:[a.jsx("svg",{className:"w-20 h-20 text-muted-foreground/30 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),a.jsx("button",{onClick:()=>m(!0),className:"text-sm text-blue-500 hover:text-blue-600 underline",children:"点击切换到管理模式添加应用"})]})]})})]})]}):a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-border bg-card/50",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-blue-500"}),a.jsx("span",{className:"text-sm font-medium text-foreground",children:F})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&a.jsx("button",{onClick:()=>{m(!w),c(!1),S()},className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent transition-colors",children:$?"浏览模式":"管理模式"}),!$&&p.current.size>0&&a.jsx("button",{className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent",onClick:()=>{p.current.forEach((k,U)=>_(U))},children:"关闭全部"}),e&&a.jsx("button",{onClick:e,className:"p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded transition-colors",title:"关闭",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:$?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mb-4 flex items-center justify-between",children:a.jsx("button",{type:"button",onClick:()=>{x(null),v({name:"",url:"",iconUrl:""}),c(k=>!k)},className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:u?"取消":"新增应用"})}),u&&a.jsxs("form",{onSubmit:k=>{var P,N,R;k.preventDefault();const U=((P=y.name)==null?void 0:P.trim())||"",H=((N=y.url)==null?void 0:N.trim())||"",Z=((R=y.iconUrl)==null?void 0:R.trim())||void 0;U&&(b?g==null||g(b,{name:U,url:H,iconUrl:Z}):f==null||f(U,H,Z),c(!1),S())},className:"p-4 bg-muted rounded-lg space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),a.jsx("input",{value:y.name,onChange:k=>v({...y,name:k.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"例如:飞书"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"URL"}),a.jsx("input",{value:y.url,onChange:k=>v({...y,url:k.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://example.com"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"图标地址"}),a.jsx("input",{value:y.iconUrl,onChange:k=>v({...y,iconUrl:k.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://.../icon.png"})]}),a.jsxs("div",{className:"flex justify-end space-x-2",children:[a.jsx("button",{type:"button",onClick:()=>{c(!1),S(),x(null)},className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",children:"取消"}),a.jsx("button",{type:"submit",className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:b?"保存":"创建"})]})]}),a.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(k=>a.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center overflow-hidden shrink-0",children:k.iconUrl?a.jsx("img",{src:k.iconUrl,alt:k.name,className:"w-full h-full object-cover"}):a.jsx("span",{className:"text-white text-sm font-bold",children:k.name.charAt(0).toUpperCase()})}),a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-medium text-foreground",children:k.name}),k.url&&a.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:k.url})]})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{className:"px-2 py-1 text-xs rounded bg-background hover:bg-accent",onClick:()=>{c(!0),x(k.id),v({name:k.name||"",url:k.url||"",iconUrl:k.iconUrl||""})},children:"编辑"}),a.jsx("button",{className:"px-2 py-1 text-xs rounded bg-destructive text-destructive-foreground hover:opacity-90",onClick:()=>h==null?void 0:h(k.id),children:"删除"})]})]},k.id)),((l==null?void 0:l.length)??0)===0&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center",children:[a.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用,点击上方按钮添加。"})]})]})]}):a.jsxs("div",{className:"grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[l==null?void 0:l.map(k=>{const U=p.current.has(k.id);return a.jsxs("div",{className:"relative group/item",children:[a.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>I(k),title:k.url||"",children:[a.jsx("div",{className:`relative w-14 h-14 rounded-full flex items-center justify-center overflow-hidden transition-all ${U?"ring-2 ring-green-500 ring-offset-2 ring-offset-background scale-105":"bg-gradient-to-br from-blue-500/20 to-purple-500/20 group-hover/item:scale-105"}`,children:k.iconUrl?a.jsx("img",{src:k.iconUrl,alt:k.name,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:a.jsx("span",{className:"text-white text-lg font-bold",children:k.name.charAt(0).toUpperCase()})})}),a.jsx("div",{className:"text-xs font-medium text-foreground truncate max-w-full",children:k.name}),k.url&&a.jsx("div",{className:"text-[10px] text-muted-foreground truncate max-w-full",children:k.url})]}),U&&a.jsx("button",{onClick:H=>{H.stopPropagation(),_(k.id)},className:"absolute top-0 left-0 w-4 h-4 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover/item:opacity-100 transition-opacity z-10",title:"关闭",children:a.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},k.id)}),((l==null?void 0:l.length)??0)===0&&a.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-10 text-center",children:[a.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),a.jsx("button",{onClick:()=>m(!0),className:"text-sm text-blue-500 hover:text-blue-600 underline",children:"切换到管理模式以添加应用"})]})]})})]})},ho=({className:r,apiBaseUrl:e,port:t,userId:n,projectId:s,showMcpManager:o=!0,showAiModelManager:i=!0,showSystemContextEditor:l=!0,showAgentManager:d=!0,onApplicationSelect:f})=>{const g=O.useMemo(()=>{if(e)return e;if(t)return`http://localhost:${t}/api`},[e,t]),h=O.useMemo(()=>{if(g)return new Vt(g)},[g]);return a.jsx(Tf,{userId:n,projectId:s,customApiClient:h,children:a.jsx(Mg,{className:r,showMcpManager:o,showAiModelManager:i,showSystemContextEditor:l,showAgentManager:d,onApplicationSelect:f})})},Mg=({className:r,showMcpManager:e,showAiModelManager:t,showSystemContextEditor:n,showAgentManager:s,onApplicationSelect:o})=>{const i=El(),{currentSession:l,messages:d,isLoading:f,isStreaming:g,hasMoreMessages:h,error:p,loadSessions:w,sendMessage:m,clearError:u,aiModelConfigs:c,selectedModelId:b,setSelectedModel:x,loadAiModelConfigs:y,agents:v,selectedAgentId:S,setSelectedAgent:C,loadAgents:_,abortCurrentConversation:I,loadMoreMessages:T}=i(),$=O.useRef(null),[F,k]=O.useState(!1),[U,H]=O.useState(!1),[Z,P]=O.useState(!1),[N,R]=O.useState(!1),[B,q]=O.useState(!1),[D,A]=O.useState(!1);O.useEffect(()=>{(window.__standaloneChatInterfaceDidInit__??!1)||(window.__standaloneChatInterfaceDidInit__=!0,w(),y(),_())},[w,y,_]),O.useEffect(()=>{$.current&&$.current.scrollIntoView({behavior:"smooth"})},[d,g]);const j=async(M,L)=>{try{await m(M,L)}catch(z){console.error("Failed to send message:",z)}};return a.jsxs("div",{className:ke("flex flex-col h-screen bg-background text-foreground",r),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("button",{onClick:()=>k(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),l&&a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:l.title})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[o&&a.jsx("button",{onClick:()=>{console.log("[StandaloneChat] open ApplicationsPanel button clicked"),A(!0)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:a.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[a.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),a.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),e&&a.jsx("button",{onClick:()=>H(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP服务管理",children:a.jsxs("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}),t&&a.jsx("button",{onClick:()=>P(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI配置管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z"})})}),n&&a.jsx("button",{onClick:()=>R(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"System Prompt编辑器",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),s&&a.jsx("button",{onClick:()=>q(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12h6M9 16h6M6 8h12a2 2 0 012 2v8a2 2 0 01-2 2H6a2 2 0 01-2-2v-8a2 2 0 012-2z"})})}),a.jsx(lo,{})]})]}),p&&a.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:a.jsxs("div",{className:"flex items中心 justify-between",children:[a.jsx("p",{className:"text-sm text-destructive",children:p}),a.jsx("button",{onClick:u,className:"text-destructive hover:text-destructive/80 transition-colors",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),a.jsx("div",{className:"flex-1 flex overflow-hidden",children:a.jsxs("div",{className:"flex-1 overflow-hidden",children:[l?a.jsx(oo,{messages:d,isLoading:f,isStreaming:g,hasMore:h,onLoadMore:()=>l&&T(l.id)}):a.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:a.jsxs("div",{className:"text-center",children:[a.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 opacity-50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})}),a.jsx("p",{className:"text-lg mb-2",children:"欢迎使用AI聊天助手"}),a.jsx("p",{className:"text-sm",children:"点击左上角按钮创建新会话开始对话"})]})}),a.jsx("div",{ref:$})]})}),l&&a.jsx(ao,{onSend:j,onStop:I,disabled:f||g,isStreaming:g,selectedModelId:b,availableModels:c,onModelChange:x,showModelSelector:!0,selectedAgentId:S,availableAgents:v,onAgentChange:C}),a.jsx(io,{isOpen:F,onClose:()=>k(!1),store:i}),a.jsx(rc,{isOpen:D,onClose:()=>A(!1),title:"应用列表",layout:"modal",onApplicationSelect:o}),U&&a.jsx(co,{onClose:()=>H(!1),store:i}),Z&&a.jsx(uo,{onClose:()=>P(!1),store:i}),s&&B&&a.jsx(tc,{onClose:()=>q(!1),store:i}),N&&a.jsx(fo,{onClose:()=>R(!1),store:i})]})};class Eg{constructor(e,t,n,s,o=!0,i=!0,l=!0,d=!0,f){W(this,"userId");W(this,"projectId");W(this,"configUrl");W(this,"apiClient");W(this,"store");W(this,"className");W(this,"showMcpManager");W(this,"showAiModelManager");W(this,"showSystemContextEditor");W(this,"showAgentManager");W(this,"onApplicationSelect");this.userId=e,this.projectId=t,this.configUrl=n||"/api",this.className=s,this.showMcpManager=o,this.showAiModelManager=i,this.showSystemContextEditor=l,this.showAgentManager=d,this.onApplicationSelect=f,console.log("🔧 AiChat Constructor - configUrl:",this.configUrl),console.log("🔧 AiChat Constructor - Module Controls:",{showMcpManager:this.showMcpManager,showAiModelManager:this.showAiModelManager,showSystemContextEditor:this.showSystemContextEditor,showAgentManager:this.showAgentManager,hasApplicationSelectCallback:!!this.onApplicationSelect}),this.apiClient=new Vt(this.configUrl),this.store=zr(this.apiClient,{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl})}render(){return O.createElement(Ig,{className:this.className,userId:this.userId,projectId:this.projectId,configUrl:this.configUrl,showMcpManager:this.showMcpManager,showAiModelManager:this.showAiModelManager,showSystemContextEditor:this.showSystemContextEditor,showAgentManager:this.showAgentManager,onApplicationSelect:this.onApplicationSelect})}getConfig(){return{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl,className:this.className,showMcpManager:this.showMcpManager,showAiModelManager:this.showAiModelManager,showSystemContextEditor:this.showSystemContextEditor,showAgentManager:this.showAgentManager,onApplicationSelect:this.onApplicationSelect}}updateConfig(e){e.userId&&(this.userId=e.userId),e.projectId&&(this.projectId=e.projectId),e.configUrl&&(this.configUrl=e.configUrl,this.apiClient=new Vt(this.configUrl),this.store=zr(this.apiClient,{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl})),e.className!==void 0&&(this.className=e.className),e.showMcpManager!==void 0&&(this.showMcpManager=e.showMcpManager),e.showAiModelManager!==void 0&&(this.showAiModelManager=e.showAiModelManager),e.showSystemContextEditor!==void 0&&(this.showSystemContextEditor=e.showSystemContextEditor),e.showAgentManager!==void 0&&(this.showAgentManager=e.showAgentManager),e.onApplicationSelect!==void 0&&(this.onApplicationSelect=e.onApplicationSelect)}getStore(){return this.store}getApiClient(){return this.apiClient}getSelectedApplication(){var s;const e=this.store.getState(),t=e.selectedApplicationId;if(console.log("[AiChat] getSelectedApplication called:",{id:t,applicationsCount:(s=e.applications)==null?void 0:s.length}),!t)return null;const n=e.applications.find(o=>o.id===t)||null;return console.log("[AiChat] getSelectedApplication result:",n),n}getSelectedApplicationUrl(){const e=this.getSelectedApplication();return e?e.url:null}subscribeSelectedApplication(e){console.log("[AiChat] subscribeSelectedApplication: 设置订阅"),console.log("[AiChat] store 对象:",this.store),console.log("[AiChat] store.subscribe 类型:",typeof this.store.subscribe);let t=this.store.getState().selectedApplicationId;console.log("[AiChat] 初始 previousId:",t);const n=this.store.subscribe(s=>{const o=s.selectedApplicationId;if(console.log("[AiChat] store.subscribe 被触发, currentId:",o,"previousId:",t),o!==t){console.log("[AiChat] selectedApplicationId 变化检测到:",{old:t,new:o}),t=o;const i=this.getSelectedApplication();console.log("[AiChat] 准备调用 listener,app:",i),e(i)}});return console.log("[AiChat] 首次调用 listener"),e(this.getSelectedApplication()),()=>{console.log("[AiChat] 取消订阅"),n()}}}const Ig=({className:r,userId:e,projectId:t,configUrl:n,showMcpManager:s,showAiModelManager:o,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d})=>a.jsx(ho,{className:r,apiBaseUrl:n,userId:e,projectId:t,showMcpManager:s,showAiModelManager:o,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d}),Pg=({className:r,onMessageSend:e,customRenderer:t})=>{const{currentSession:n,messages:s,isLoading:o,isStreaming:i,hasMoreMessages:l,error:d,loadSessions:f,loadMoreMessages:g,sendMessage:h,clearError:p,aiModelConfigs:w,selectedModelId:m,setSelectedModel:u,loadAiModelConfigs:c,agents:b,selectedAgentId:x,setSelectedAgent:y,loadAgents:v,abortCurrentConversation:S}=dt(),C=O.useRef(null),[_,I]=O.useState(!1),[T,$]=O.useState(!1),[F,k]=O.useState(!1),[U,H]=O.useState(!1),[Z,P]=O.useState(!1);O.useEffect(()=>{(window.__chatInterfaceDidInit__??!1)||(window.__chatInterfaceDidInit__=!0,f(),c(),v())},[f,c,v]),O.useEffect(()=>{C.current&&C.current.scrollIntoView({behavior:"smooth"})},[s,i]);const N=async(R,B)=>{try{await h(R,B),e==null||e(R,[])}catch(q){console.error("Failed to send message:",q)}};return a.jsxs("div",{className:ke("flex flex-col h-screen bg-background text-foreground",r),children:[d&&a.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-destructive",children:d}),a.jsx("button",{onClick:p,className:"text-destructive hover:text-destructive/80 transition-colors",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),a.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[a.jsx("div",{className:"flex flex-col h-full",children:a.jsx(io,{embedded:!0})}),a.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[n&&a.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[a.jsx("div",{className:"flex items-center space-x-3"}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx(lo,{}),a.jsx("button",{onClick:()=>P(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:a.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[a.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),a.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),a.jsx("button",{onClick:()=>I(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP 服务器管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsx("button",{onClick:()=>H(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6M9 16h6M6 8h12a2 2 0 012 2v8a2 2 0 01-2 2H6a2 2 0 01-2-2v-8a2 2 0 012-2z"})})}),a.jsx("button",{onClick:()=>$(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI 模型管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsx("button",{onClick:()=>k(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"系统上下文设置",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})})]})]}),n?a.jsxs(a.Fragment,{children:[a.jsxs("div",{className:"flex-1 overflow-auto",children:[a.jsx(oo,{messages:s,isLoading:o,isStreaming:i,hasMore:l,onLoadMore:()=>n&&g(n.id),customRenderer:t}),a.jsx("div",{ref:C})]}),a.jsx("div",{className:"border-t border-border",children:a.jsx(ao,{onSend:N,onStop:S,disabled:o,isStreaming:i,placeholder:"输入消息...",showModelSelector:!0,selectedModelId:m,availableModels:w,onModelChange:u,selectedAgentId:x,availableAgents:b,onAgentChange:y})})]}):a.jsx("div",{className:"flex-1 flex items-center justify-center",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h2",{className:"text-xl font-semibold text-muted-foreground mb-2",children:"欢迎使用 AI 聊天"}),a.jsx("p",{className:"text-muted-foreground mb-4",children:"从左侧会话列表选择会话,或创建新的会话开始对话"})]})})]})]}),_&&a.jsx(co,{onClose:()=>I(!1)}),U&&a.jsx(tc,{onClose:()=>H(!1)}),T&&a.jsx(uo,{onClose:()=>$(!1)}),F&&a.jsx(fo,{onClose:()=>k(!1)}),a.jsx(rc,{isOpen:Z,onClose:()=>P(!1),title:"应用列表",layout:"modal"})]})};class Tg extends O.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:a.jsx("div",{className:"flex items-center justify-center h-full p-8",children:a.jsxs("div",{className:"text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 mx-auto bg-destructive/10 rounded-full flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.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"})})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Something went wrong"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),a.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 Og="1.0.11";exports.AiChat=Eg;exports.AiModelManager=uo;exports.AiServer=kl;exports.ApiClient=Vt;exports.AppError=Ym;exports.AttachmentRenderer=zl;exports.ChatIcon=Ql;exports.ChatInterface=Pg;exports.ChatService=Ml;exports.CheckIcon=tg;exports.ChevronDownIcon=og;exports.CopyIcon=ng;exports.DatabaseService=ps;exports.DotsVerticalIcon=Xl;exports.ErrorBoundary=Tg;exports.InputArea=ao;exports.LoadingSpinner=Vl;exports.MarkdownRenderer=nt;exports.McpManager=co;exports.MessageItem=Jl;exports.MessageList=oo;exports.MessageManager=Nl;exports.PencilIcon=Kl;exports.PlayIcon=sg;exports.PlusIcon=Gl;exports.SessionList=io;exports.StandaloneChatInterface=ho;exports.SystemContextEditor=fo;exports.ThemeToggle=lo;exports.ToolCallRenderer=hs;exports.TrashIcon=Yl;exports.XIcon=rg;exports.apiClient=ee;exports.cleanHtmlContent=Um;exports.cn=ke;exports.conversationsApi=Ar;exports.copyToClipboard=Vm;exports.debounce=Hm;exports.deepClone=fs;exports.default=ho;exports.downloadFile=Gm;exports.formatDate=Lm;exports.formatDateTime=Dm;exports.formatFileSize=Hl;exports.formatRelativeTime=$m;exports.formatTime=Wl;exports.generateId=Rm;exports.generateRandomColor=Jm;exports.getFileExtension=ql;exports.getOS=Km;exports.isImageFile=zm;exports.isMobile=Xm;exports.isValidEmail=Bm;exports.isValidUrl=Wm;exports.retry=Qm;exports.storage=Zm;exports.throttle=qm;exports.truncateText=Fm;exports.useChatStore=ct;exports.useTheme=ec;exports.version=Og;
101
101
  //# sourceMappingURL=index.cjs.js.map