@leeoohoo/aichat 1.0.8-3 → 1.0.8-4

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 ic=Object.defineProperty;var lc=(r,e,t)=>e in r?ic(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var V=(r,e,t)=>lc(r,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("react/jsx-runtime"),P=require("react"),cc={},po=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:()=>u,subscribe:g=>(t.add(g),()=>t.delete(g)),destroy:()=>{(cc?"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},dc=r=>r?po(r):po;function uc(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Bn={exports:{}},yn={},fr={exports:{}},wn={};/**
1
+ "use strict";require('./index.css');var bc=Object.defineProperty;var yc=(r,e,t)=>e in r?bc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var V=(r,e,t)=>yc(r,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("react/jsx-runtime"),M=require("react"),wc={},Co=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:()=>u,subscribe:g=>(t.add(g),()=>t.delete(g)),destroy:()=>{(wc?"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},vc=r=>r?Co(r):Co;function _c(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Xn={exports:{}},kn={},yr={exports:{}},Nn={};/**
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 xo;function fc(){if(xo)return wn;xo=1;var r=P;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,a=r.useLayoutEffect,i=r.useDebugValue;function l(h,p){var w=p(),m=n({inst:{value:w,getSnapshot:p}}),f=m[0].inst,c=m[1];return a(function(){f.value=w,f.getSnapshot=p,d(f)&&c({inst:f})},[h,w,p]),s(function(){return d(f)&&c({inst:f}),h(function(){d(f)&&c({inst:f})})},[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 u(h,p){return p()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?u:l;return wn.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:g,wn}var vn={};/**
9
+ */var jo;function Sc(){if(jo)return Nn;jo=1;var r=M;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,a=r.useLayoutEffect,i=r.useDebugValue;function l(h,p){var w=p(),m=n({inst:{value:w,getSnapshot:p}}),f=m[0].inst,c=m[1];return a(function(){f.value=w,f.getSnapshot=p,d(f)&&c({inst:f})},[h,w,p]),s(function(){return d(f)&&c({inst:f}),h(function(){d(f)&&c({inst:f})})},[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 u(h,p){return p()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?u:l;return Nn.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:g,Nn}var Mn={};/**
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 hc(){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){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 f=m();if(!h){var c=m();a(f,c)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),h=!0)}c=i({inst:{value:f,getSnapshot:m}});var x=c[0].inst,b=c[1];return d(function(){x.value=f,x.getSnapshot=m,t(x)&&b({inst:x})},[w,f,m]),l(function(){return t(x)&&b({inst:x}),w(function(){t(x)&&b({inst:x})})},[w]),u(f),f}function t(w){var m=w.getSnapshot;w=w.value;try{var f=m();return!a(w,f)}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=P,a=typeof Object.is=="function"?Object.is:r,i=s.useState,l=s.useEffect,d=s.useLayoutEffect,u=s.useDebugValue,g=!1,h=!1,p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n:e;vn.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())}()),vn}var yo;function Ra(){return yo||(yo=1,process.env.NODE_ENV==="production"?fr.exports=fc():fr.exports=hc()),fr.exports}/**
17
+ */var Ao;function Cc(){return Ao||(Ao=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 f=m();if(!h){var c=m();a(f,c)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),h=!0)}c=i({inst:{value:f,getSnapshot:m}});var x=c[0].inst,b=c[1];return d(function(){x.value=f,x.getSnapshot=m,t(x)&&b({inst:x})},[w,f,m]),l(function(){return t(x)&&b({inst:x}),w(function(){t(x)&&b({inst:x})})},[w]),u(f),f}function t(w){var m=w.getSnapshot;w=w.value;try{var f=m();return!a(w,f)}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=M,a=typeof Object.is=="function"?Object.is:r,i=s.useState,l=s.useEffect,d=s.useLayoutEffect,u=s.useDebugValue,g=!1,h=!1,p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n:e;Mn.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())}()),Mn}var ko;function Ha(){return ko||(ko=1,process.env.NODE_ENV==="production"?yr.exports=Sc():yr.exports=Cc()),yr.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 wo;function mc(){if(wo)return yn;wo=1;var r=P,e=Ra();function t(u,g){return u===g&&(u!==0||1/u===1/g)||u!==u&&g!==g}var n=typeof Object.is=="function"?Object.is:t,s=e.useSyncExternalStore,a=r.useRef,i=r.useEffect,l=r.useMemo,d=r.useDebugValue;return yn.useSyncExternalStoreWithSelector=function(u,g,h,p,w){var m=a(null);if(m.current===null){var f={hasValue:!1,value:null};m.current=f}else f=m.current;m=l(function(){function x(j){if(!b){if(b=!0,y=j,j=p(j),w!==void 0&&f.hasValue){var v=f.value;if(w(v,j))return _=v}return _=j}if(v=_,n(y,j))return v;var I=p(j);return w!==void 0&&w(v,I)?(y=j,v):(y=j,_=I)}var b=!1,y,_,S=h===void 0?null:h;return[function(){return x(g())},S===null?void 0:function(){return x(S())}]},[g,h,p,w]);var c=s(u,m[0],m[1]);return i(function(){f.hasValue=!0,f.value=c},[c]),d(c),c},yn}var _n={};/**
25
+ */var No;function jc(){if(No)return kn;No=1;var r=M,e=Ha();function t(u,g){return u===g&&(u!==0||1/u===1/g)||u!==u&&g!==g}var n=typeof Object.is=="function"?Object.is:t,s=e.useSyncExternalStore,a=r.useRef,i=r.useEffect,l=r.useMemo,d=r.useDebugValue;return kn.useSyncExternalStoreWithSelector=function(u,g,h,p,w){var m=a(null);if(m.current===null){var f={hasValue:!1,value:null};m.current=f}else f=m.current;m=l(function(){function x(j){if(!b){if(b=!0,y=j,j=p(j),w!==void 0&&f.hasValue){var v=f.value;if(w(v,j))return _=v}return _=j}if(v=_,n(y,j))return v;var I=p(j);return w!==void 0&&w(v,I)?(y=j,v):(y=j,_=I)}var b=!1,y,_,S=h===void 0?null:h;return[function(){return x(g())},S===null?void 0:function(){return x(S())}]},[g,h,p,w]);var c=s(u,m[0],m[1]);return i(function(){f.hasValue=!0,f.value=c},[c]),d(c),c},kn}var En={};/**
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 vo;function gc(){return vo||(vo=1,process.env.NODE_ENV!=="production"&&function(){function r(u,g){return u===g&&(u!==0||1/u===1/g)||u!==u&&g!==g}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=P,t=Ra(),n=typeof Object.is=="function"?Object.is:r,s=t.useSyncExternalStore,a=e.useRef,i=e.useEffect,l=e.useMemo,d=e.useDebugValue;_n.useSyncExternalStoreWithSelector=function(u,g,h,p,w){var m=a(null);if(m.current===null){var f={hasValue:!1,value:null};m.current=f}else f=m.current;m=l(function(){function x(j){if(!b){if(b=!0,y=j,j=p(j),w!==void 0&&f.hasValue){var v=f.value;if(w(v,j))return _=v}return _=j}if(v=_,n(y,j))return v;var I=p(j);return w!==void 0&&w(v,I)?(y=j,v):(y=j,_=I)}var b=!1,y,_,S=h===void 0?null:h;return[function(){return x(g())},S===null?void 0:function(){return x(S())}]},[g,h,p,w]);var c=s(u,m[0],m[1]);return i(function(){f.hasValue=!0,f.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())}()),_n}process.env.NODE_ENV==="production"?Bn.exports=mc():Bn.exports=gc();var pc=Bn.exports;const xc=uc(pc),$a={},{useDebugValue:bc}=P,{useSyncExternalStoreWithSelector:yc}=xc;let _o=!1;const wc=r=>r;function vc(r,e=wc,t){($a?"production":void 0)!=="production"&&t&&!_o&&(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"),_o=!0);const n=yc(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return bc(n),n}const _c=r=>{($a?"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"?dc(r):r,t=(n,s)=>vc(e,n,s);return Object.assign(t,e),t},Sc=r=>_c;var La=Symbol.for("immer-nothing"),So=Symbol.for("immer-draftable"),Ae=Symbol.for("immer-state"),Cc=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=Cc[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?Da(r)||Array.isArray(r)||!!r[So]||!!((e=r.constructor)!=null&&e[So])||Yt(r)||Kr(r):!1}var jc=Object.prototype.constructor.toString();function Da(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)===jc}function Dr(r,e){Xr(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function Xr(r){const e=r[Ae];return e?e.type_:Array.isArray(r)?1:Yt(r)?2:Kr(r)?3:0}function Wn(r,e){return Xr(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function Fa(r,e,t){const n=Xr(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function Ac(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function Yt(r){return r instanceof Map}function Kr(r){return r instanceof Set}function Qe(r){return r.copy_||r.base_}function Hn(r,e){if(Yt(r))return new Map(r);if(Kr(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);const t=Da(r);if(e===!0||e==="class_only"&&!t){const n=Object.getOwnPropertyDescriptors(r);delete n[Ae];let s=Reflect.ownKeys(n);for(let a=0;a<s.length;a++){const i=s[a],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 ps(r,e=!1){return Yr(r)||St(r)||!ot(r)||(Xr(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=>ps(t,!0))),r}function hr(){we(2)}function Yr(r){return Object.isFrozen(r)}var kc={};function at(r){const e=kc[r];return e||we(0,r),e}var qt;function Ua(){return qt}function Nc(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Co(r,e){e&&(at("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function qn(r){zn(r),r.drafts_.forEach(Mc),r.drafts_=null}function zn(r){r===qt&&(qt=r.parent_)}function jo(r){return qt=Nc(qt,r)}function Mc(r){const e=r[Ae];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function Ao(r,e){e.unfinalizedDrafts_=e.drafts_.length;const t=e.drafts_[0];return r!==void 0&&r!==t?(t[Ae].modified_&&(qn(e),we(4)),ot(r)&&(r=Fr(e,r),e.parent_||Ur(e,r)),e.patches_&&at("Patches").generateReplacementPatches_(t[Ae].base_,r,e.patches_,e.inversePatches_)):r=Fr(e,t,[]),qn(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==La?r:void 0}function Fr(r,e,t){if(Yr(e))return e;const n=e[Ae];if(!n)return Dr(e,(s,a)=>ko(r,n,e,s,a,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return Ur(r,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const s=n.copy_;let a=s,i=!1;n.type_===3&&(a=new Set(s),s.clear(),i=!0),Dr(a,(l,d)=>ko(r,n,s,l,d,t,i)),Ur(r,s,!1),t&&r.patches_&&at("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function ko(r,e,t,n,s,a,i){if(process.env.NODE_ENV!=="production"&&s===t&&we(5),St(s)){const l=a&&e&&e.type_!==3&&!Wn(e.assigned_,n)?a.concat(n):void 0,d=Fr(r,s,l);if(Fa(t,n,d),St(d))r.canAutoFreeze_=!1;else return}else i&&t.add(s);if(ot(s)&&!Yr(s)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;Fr(r,s),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&(Yt(t)?t.has(n):Object.prototype.propertyIsEnumerable.call(t,n))&&Ur(r,s)}}function Ur(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&ps(e,t)}function Ec(r,e){const t=Array.isArray(r),n={type_:t?1:0,scope_:e?e.scope_:Ua(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=n,a=xs;t&&(s=[n],a=zt);const{revoke:i,proxy:l}=Proxy.revocable(s,a);return n.draft_=l,n.revoke_=i,l}var xs={get(r,e){if(e===Ae)return r;const t=Qe(r);if(!Wn(t,e))return Ic(r,t,e);const n=t[e];return r.finalized_||!ot(n)?n:n===Sn(r.base_,e)?(Cn(r),r.copy_[e]=Vn(n,r)):n},has(r,e){return e in Qe(r)},ownKeys(r){return Reflect.ownKeys(Qe(r))},set(r,e,t){const n=Ba(Qe(r),e);if(n!=null&&n.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){const s=Sn(Qe(r),e),a=s==null?void 0:s[Ae];if(a&&a.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(Ac(t,s)&&(t!==void 0||Wn(r.base_,e)))return!0;Cn(r),Jn(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 Sn(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,Cn(r),Jn(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={};Dr(xs,(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),xs.set.call(this,r[0],e,t,r[0])};function Sn(r,e){const t=r[Ae];return(t?Qe(t):r)[e]}function Ic(r,e,t){var s;const n=Ba(e,t);return n?"value"in n?n.value:(s=n.get)==null?void 0:s.call(r.draft_):void 0}function Ba(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 Jn(r){r.modified_||(r.modified_=!0,r.parent_&&Jn(r.parent_))}function Cn(r){r.copy_||(r.copy_=Hn(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Tc=class{constructor(r){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if(typeof e=="function"&&typeof t!="function"){const a=t;t=e;const i=this;return function(d=a,...u){return i.produce(d,g=>t.call(this,g,...u))}}typeof t!="function"&&we(6),n!==void 0&&typeof n!="function"&&we(7);let s;if(ot(e)){const a=jo(this),i=Vn(e,void 0);let l=!0;try{s=t(i),l=!1}finally{l?qn(a):zn(a)}return Co(a,n),Ao(s,a)}else if(!e||typeof e!="object"){if(s=t(e),s===void 0&&(s=e),s===La&&(s=void 0),this.autoFreeze_&&ps(s,!0),n){const a=[],i=[];at("Patches").generateReplacementPatches_(e,s,a,i),n(a,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=Pc(r));const e=jo(this),t=Vn(r,void 0);return t[Ae].isManual_=!0,zn(e),t}finishDraft(r,e){const t=r&&r[Ae];(!t||!t.isManual_)&&we(9);const{scope_:n}=t;return Co(n,e),Ao(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 Vn(r,e){const t=Yt(r)?at("MapSet").proxyMap_(r,e):Kr(r)?at("MapSet").proxySet_(r,e):Ec(r,e);return(e?e.scope_:Ua()).drafts_.push(t),t}function Pc(r){return St(r)||we(10,r),Wa(r)}function Wa(r){if(!ot(r)||Yr(r))return r;const e=r[Ae];let t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=Hn(r,e.scope_.immer_.useStrictShallowCopy_)}else t=Hn(r,!0);return Dr(t,(n,s)=>{Fa(t,n,Wa(s))}),e&&(e.finalized_=!1),t}var Oc=new Tc,Rc=Oc.produce;const $c=r=>(e,t,n)=>(n.setState=(s,a,...i)=>{const l=typeof s=="function"?Rc(s):s;return e(l,a,...i)},r(n.setState,t,n)),Lc=$c,Dc={};function Fc(r,e){let t;try{t=r()}catch{return}return{getItem:s=>{var a;const i=d=>d===null?null:JSON.parse(d,void 0),l=(a=t.getItem(s))!=null?a:null;return l instanceof Promise?l.then(i):i(l)},setItem:(s,a)=>t.setItem(s,JSON.stringify(a,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)}}}},Uc=(r,e)=>(t,n,s)=>{let a={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:c=>c,version:0,merge:(c,x)=>({...x,...c}),...e},i=!1;const l=new Set,d=new Set;let u;try{u=a.getStorage()}catch{}if(!u)return r((...c)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),t(...c)},n,s);const g=Jt(a.serialize),h=()=>{const c=a.partialize({...n()});let x;const b=g({state:c,version:a.version}).then(y=>u.setItem(a.name,y)).catch(y=>{x=y});if(x)throw x;return b},p=s.setState;s.setState=(c,x)=>{p(c,x),h()};const w=r((...c)=>{t(...c),h()},n,s);let m;const f=()=>{var c;if(!u)return;i=!1,l.forEach(b=>b(n()));const x=((c=a.onRehydrateStorage)==null?void 0:c.call(a,n()))||void 0;return Jt(u.getItem.bind(u))(a.name).then(b=>{if(b)return a.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==a.version){if(a.migrate)return a.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var y;return m=a.merge(b,(y=n())!=null?y:w),t(m,!0),h()}).then(()=>{x==null||x(m,void 0),i=!0,d.forEach(b=>b(m))}).catch(b=>{x==null||x(void 0,b)})};return s.persist={setOptions:c=>{a={...a,...c},c.getStorage&&(u=c.getStorage())},clearStorage:()=>{u==null||u.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>f(),hasHydrated:()=>i,onHydrate:c=>(l.add(c),()=>{l.delete(c)}),onFinishHydration:c=>(d.add(c),()=>{d.delete(c)})},f(),m||w},Bc=(r,e)=>(t,n,s)=>{let a={storage:Fc(()=>localStorage),partialize:f=>f,version:0,merge:(f,c)=>({...c,...f}),...e},i=!1;const l=new Set,d=new Set;let u=a.storage;if(!u)return r((...f)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),t(...f)},n,s);const g=()=>{const f=a.partialize({...n()});return u.setItem(a.name,{state:f,version:a.version})},h=s.setState;s.setState=(f,c)=>{h(f,c),g()};const p=r((...f)=>{t(...f),g()},n,s);s.getInitialState=()=>p;let w;const m=()=>{var f,c;if(!u)return;i=!1,l.forEach(b=>{var y;return b((y=n())!=null?y:p)});const x=((c=a.onRehydrateStorage)==null?void 0:c.call(a,(f=n())!=null?f:p))||void 0;return Jt(u.getItem.bind(u))(a.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==a.version){if(a.migrate)return[!0,a.migrate(b.state,b.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,b.state];return[!1,void 0]}).then(b=>{var y;const[_,S]=b;if(w=a.merge(S,(y=n())!=null?y:p),t(w,!0),_)return g()}).then(()=>{x==null||x(w,void 0),w=n(),i=!0,d.forEach(b=>b(w))}).catch(b=>{x==null||x(void 0,b)})};return s.persist={setOptions:f=>{a={...a,...f},f.storage&&(u=f.storage)},clearStorage:()=>{u==null||u.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>m(),hasHydrated:()=>i,onHydrate:f=>(l.add(f),()=>{l.delete(f)}),onFinishHydration:f=>(d.add(f),()=>{d.delete(f)})},a.skipHydration||m(),w||p},Wc=(r,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((Dc?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),Uc(r,e)):Bc(r,e),Hc=Wc,qc="/api";class Vt{constructor(e=qc){V(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 a=await fetch(n,s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);const i=await a.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(a){throw console.error(`API request failed: ${e}`,a),a}}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 getSessionMcpServers(e){return this.request(`/sessions/${e}/mcp-servers`)}async addSessionMcpServer(e,t){return this.request(`/sessions/${e}/mcp-servers`,{method:"POST",body:JSON.stringify(t)})}async deleteSessionMcpServer(e,t){return this.request(`/sessions/${e}/mcp-servers/${t}`,{method:"DELETE"})}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 a=`${this.baseUrl}/agent_v2/chat/stream`,i=await fetch(a,{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 streamChatBySession(e,t,n,s){const a=`${this.baseUrl}/agent_v2/chat/stream/session`,i=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:e,content:t,user_id:n,...s?{ai_model_config: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 streamAgentChat(e,t,n,s){const a=`${this.baseUrl}/agents/chat/stream`,i=await fetch(a,{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 te=new Vt,kr={getDetails:r=>te.getConversationDetails(r),getAssistant:r=>te.getAssistant(r),getMcpServers:r=>te.getMcpServers(r),saveMessage:(r,e)=>te.saveMessage(r,e),getMessages:(r,e)=>te.getMessages(r,e),addMessage:(r,e)=>te.addMessage(r,e)};class bs{constructor(e,t,n=te){V(this,"userId");V(this,"projectId");V(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,metadata:e.metadata??void 0},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:n.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:t.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:n.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 a;const t={id:crypto.randomUUID(),session_id:e.sessionId,role:e.role,content:e.content,summary:e.rawContent,tool_calls:(a=e.metadata)!=null&&a.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(f=>{let c;if(f.metadata)try{c=typeof f.metadata=="string"?JSON.parse(f.metadata):f.metadata}catch(b){console.warn("Failed to parse message metadata:",b),c={}}let x;if(f.toolCalls)try{x=typeof f.toolCalls=="string"?JSON.parse(f.toolCalls):f.toolCalls}catch(b){console.warn("Failed to parse top-level toolCalls:",b)}return{id:f.id,sessionId:f.session_id,role:f.role,content:f.content,summary:f.summary,toolCallId:f.tool_call_id,reasoning:f.reasoning,metadata:c,topLevelToolCalls:x,createdAt:new Date(f.created_at),originalMessage:f}}),l=new Map;i.forEach(f=>{var c;if(f.role==="tool"&&f.toolCallId){const x=((c=f.metadata)==null?void 0:c.isError)||!1;l.set(f.toolCallId,{content:f.content,error:x?f.content:void 0})}});const d=i.map(f=>{var _,S;let c;const x=f.topLevelToolCalls||((_=f.metadata)==null?void 0:_.toolCalls);f.role==="assistant"&&x&&Array.isArray(x)&&(console.log("[Database] 处理工具调用:",{messageId:f.id,sourceToolCalls:x}),c=x.map(j=>{if(j.function){let v={};try{v=typeof j.function.arguments=="string"?JSON.parse(j.function.arguments):j.function.arguments}catch(T){console.warn("Failed to parse tool call arguments:",T),v={}}const I=l.get(j.id);return{id:j.id||`tool_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,messageId:f.id,name:j.function.name,arguments:v,result:(I==null?void 0:I.content)||void 0,error:(I==null?void 0:I.error)||void 0,createdAt:f.createdAt}}return null}).filter(Boolean));const b=[],y=typeof f.reasoning=="string"&&f.reasoning.trim().length>0;return f.role==="assistant"&&y&&b.push({type:"thinking",content:f.reasoning}),typeof f.content=="string"&&f.content.trim().length>0&&b.push({type:"text",content:f.content}),c&&Array.isArray(c)&&c.length>0&&c.forEach(j=>{b.push({type:"tool_call",toolCallId:j.id})}),{id:f.id,sessionId:f.sessionId,role:f.role,content:f.content,rawContent:f.summary,tokensUsed:void 0,status:"completed",createdAt:f.createdAt,updatedAt:void 0,toolCallId:f.toolCallId,metadata:{...f.metadata,toolCalls:c,contentSegments:b.length>0?b:(S=f.metadata)==null?void 0:S.contentSegments}}}),u=new Set;for(let f=0;f<d.length;f++){const c=d[f];if(((g=c==null?void 0:c.metadata)==null?void 0:g.type)==="session_summary"){const x=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 b=-1;for(let y=f+1;y<d.length;y++)if(((p=d[y])==null?void 0:p.role)==="assistant"){b=y;break}if(b===-1){for(let y=f-1;y>=0;y--)if(((w=d[y])==null?void 0:w.role)==="assistant"){b=y;break}}if(b!==-1){const y=d[b],_=`【上下文摘要】
34
- `,S=(((m=y.metadata)==null?void 0:m.contentSegments)||[]).slice(),j=S.length-1;j>=0&&S[j].type==="thinking"&&String(S[j].content||"").startsWith(_)?S[j].content=_+String(x||""):S.push({type:"thinking",content:_+String(x||"")}),y.metadata=y.metadata||{},y.metadata.contentSegments=S,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 Gn="RFC3986",Xn={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},zc="RFC1738",Jc=Array.isArray,Pe=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),jn=1024,Vc=(r,e,t,n,s)=>{if(r.length===0)return r;let a=r;if(typeof r=="symbol"?a=Symbol.prototype.toString.call(r):typeof r!="string"&&(a=String(r)),t==="iso-8859-1")return escape(a).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<a.length;l+=jn){const d=a.length>=jn?a.slice(l,l+jn):a,u=[];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===zc&&(h===40||h===41)){u[u.length]=d.charAt(g);continue}if(h<128){u[u.length]=Pe[h];continue}if(h<2048){u[u.length]=Pe[192|h>>6]+Pe[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=Pe[224|h>>12]+Pe[128|h>>6&63]+Pe[128|h&63];continue}g+=1,h=65536+((h&1023)<<10|d.charCodeAt(g)&1023),u[u.length]=Pe[240|h>>18]+Pe[128|h>>12&63]+Pe[128|h>>6&63]+Pe[128|h&63]}i+=u.join("")}return i};function Gc(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function No(r,e){if(Jc(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const Xc=Object.prototype.hasOwnProperty,Ha={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Re=Array.isArray,Kc=Array.prototype.push,qa=function(r,e){Kc.apply(r,Re(e)?e:[e])},Yc=Date.prototype.toISOString,ce={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Vc,encodeValuesOnly:!1,format:Gn,formatter:Xn[Gn],indices:!1,serializeDate(r){return Yc.call(r)},skipNulls:!1,strictNullHandling:!1};function Qc(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const An={};function za(r,e,t,n,s,a,i,l,d,u,g,h,p,w,m,f,c,x){let b=r,y=x,_=0,S=!1;for(;(y=y.get(An))!==void 0&&!S;){const R=y.get(r);if(_+=1,typeof R<"u"){if(R===_)throw new RangeError("Cyclic object value");S=!0}typeof y.get(An)>"u"&&(_=0)}if(typeof u=="function"?b=u(e,b):b instanceof Date?b=p==null?void 0:p(b):t==="comma"&&Re(b)&&(b=No(b,function(R){return R instanceof Date?p==null?void 0:p(R):R})),b===null){if(a)return d&&!f?d(e,ce.encoder,c,"key",w):e;b=""}if(Qc(b)||Gc(b)){if(d){const R=f?e:d(e,ce.encoder,c,"key",w);return[(m==null?void 0:m(R))+"="+(m==null?void 0:m(d(b,ce.encoder,c,"value",w)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(b)))]}const j=[];if(typeof b>"u")return j;let v;if(t==="comma"&&Re(b))f&&d&&(b=No(b,d)),v=[{value:b.length>0?b.join(",")||null:void 0}];else if(Re(u))v=u;else{const R=Object.keys(b);v=g?R.sort(g):R}const I=l?String(e).replace(/\./g,"%2E"):String(e),T=n&&Re(b)&&b.length===1?I+"[]":I;if(s&&Re(b)&&b.length===0)return T+"[]";for(let R=0;R<v.length;++R){const D=v[R],C=typeof D=="object"&&typeof D.value<"u"?D.value:b[D];if(i&&C===null)continue;const B=h&&l?D.replace(/\./g,"%2E"):D,W=Re(b)?typeof t=="function"?t(T,B):T:T+(h?"."+B:"["+B+"]");x.set(r,_);const H=new WeakMap;H.set(An,x),qa(j,za(C,W,t,n,s,a,i,l,t==="comma"&&f&&Re(b)?null:d,u,g,h,p,w,m,f,c,H))}return j}function Zc(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=Gn;if(typeof r.format<"u"){if(!Xc.call(Xn,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=Xn[t];let s=ce.filter;(typeof r.filter=="function"||Re(r.filter))&&(s=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in Ha?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=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:a,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 ed(r,e={}){let t=r;const n=Zc(e);let s,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):Re(n.filter)&&(a=n.filter,s=a);const i=[];if(typeof t!="object"||t===null)return"";const l=Ha[n.arrayFormat],d=l==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const u=new WeakMap;for(let p=0;p<s.length;++p){const w=s[p];n.skipNulls&&t[w]===null||qa(i,za(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 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 Mo=!1,Wt,Ja,Va,Kn,Ga,Xa,Ka,Ya,Qa;function td(r,e={auto:!1}){if(Mo)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}'\``);Mo=e.auto,Wt=r.kind,Ja=r.fetch,Va=r.FormData,Kn=r.File,Ga=r.ReadableStream,Xa=r.getMultipartRequestOptions,Ka=r.getDefaultAgent,Ya=r.fileFromPath,Qa=r.isFsReadStream}class rd{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function nd({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,a;try{t=fetch,n=Request,s=Response,a=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:a,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 rd(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 Za=()=>{Wt||td(nd(),{auto:!0})};Za();class X extends Error{}class ge extends X{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 a=t;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.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 Qr({message:n,cause:Qn(t)});const a=t==null?void 0:t.error;return e===400?new ei(e,a,n,s):e===401?new ti(e,a,n,s):e===403?new ri(e,a,n,s):e===404?new ni(e,a,n,s):e===409?new si(e,a,n,s):e===422?new oi(e,a,n,s):e===429?new ai(e,a,n,s):e>=500?new ii(e,a,n,s):new ge(e,a,n,s)}}class Ne extends ge{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Qr extends ge{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ys extends Qr{constructor({message:e}={}){super({message:e??"Request timed out."})}}class ei extends ge{}class ti extends ge{}class ri extends ge{}class ni extends ge{}class si extends ge{}class oi extends ge{}class ai extends ge{}class ii extends ge{}class li extends X{constructor(){super("Could not parse response content as the length limit was reached")}}class ci extends X{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 Zr{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 a;for(;(a=sd(this.buffer,Ye(this,Ce,"f")))!=null;){if(a.carriage&&Ye(this,Ce,"f")==null){mr(this,Ce,a.index,"f");continue}if(Ye(this,Ce,"f")!=null&&(a.index!==Ye(this,Ce,"f")+1||a.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?a.preceding-1:a.preceding,l=this.decodeText(this.buffer.slice(0,i));s.push(l),this.buffer=this.buffer.slice(a.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 X(`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 X(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new X("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
35
- `):[]}}Ce=new WeakMap;Zr.NEWLINE_CHARS=new Set([`
36
- `,"\r"]);Zr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function sd(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 od(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 di(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 a=!1;try{for await(const i of ad(e,t))if(!a){if(i.data.startsWith("[DONE]")){a=!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,xi(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}}}a=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{a||t.abort()}}return new Le(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){const i=new Zr,l=di(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*a(){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(a,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=n.next();e.push(i),t.push(i)}return a.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 Ga({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:a,done:i}=await t.next();if(i)return s.close();const l=n.encode(JSON.stringify(a)+`
37
- `);s.enqueue(l)}catch(a){s.error(a)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}}async function*ad(r,e){if(!r.body)throw e.abort(),new X("Attempted to iterate over a response with no body");const t=new ld,n=new Zr,s=di(r.body);for await(const a of id(s))for(const i of n.decode(a)){const l=t.decode(i);l&&(yield l)}for(const a of n.flush()){const i=t.decode(a);i&&(yield i)}}async function*id(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 a;for(;(a=od(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class ld{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 a={event:this.event,data:this.data.join(`
38
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=cd(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function cd(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}const ui=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",fi=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&en(r),en=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",dd=r=>fi(r)||ui(r)||Qa(r);async function hi(r,e,t){var s;if(r=await r,fi(r))return r;if(ui(r)){const a=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");const i=en(a)?[await a.arrayBuffer()]:[a];return new Kn(i,e,t)}const n=await ud(r);if(e||(e=hd(r)??"unknown_file"),!(t!=null&&t.type)){const a=(s=n[0])==null?void 0:s.type;typeof a=="string"&&(t={...t,type:a})}return new Kn(n,e,t)}async function ud(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(en(r))e.push(await r.arrayBuffer());else if(md(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: ${fd(r)}`);return e}function fd(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function hd(r){var e;return kn(r.name)||kn(r.filename)||((e=kn(r.path))==null?void 0:e.split(/[\\/]/).pop())}const kn=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},md=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Eo=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody",it=async r=>{const e=await gd(r.body);return Xa(e,r)},gd=async r=>{const e=new Va;return await Promise.all(Object.entries(r||{}).map(([t,n])=>Yn(e,t,n))),e},Yn=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(dd(t)){const n=await hi(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>Yn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>Yn(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 pd=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},xd=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;Za();async function mi(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),gi(l,e)}const a=await e.text();return Ge("response",e.status,e.url,e.headers,a),a}function gi(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 tn extends Promise{constructor(e,t=mi){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new tn(this.responsePromise,async t=>gi(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 bd{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:a}){this.baseURL=e,this.maxRetries=Nn("maxRetries",t),this.timeout=Nn("timeout",n),this.httpAgent=s,this.fetch=a??Ja}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Sd(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${kd()}`}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 a=s&&en(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:a}}))}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 f;const n={...e},{method:s,path:a,query:i,headers:l={}}=n,d=ArrayBuffer.isView(n.body)||n.__binaryRequest&&typeof n.body=="string"?n.body:Eo(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,u=this.calculateContentLength(d),g=this.buildURL(a,i);"timeout"in n&&Nn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const h=n.httpAgent??this.httpAgent??Ka(g),p=n.timeout+1e3;typeof((f=h==null?void 0:h.options)==null?void 0:f.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:u,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 a={};n&&(a["content-length"]=n);const i=this.defaultHeaders(e);return Oo(a,i),Oo(a,t),Eo(e.body)&&Wt!=="node"&&delete a["content-type"],xr(i,"x-stainless-retry-count")===void 0&&xr(t,"x-stainless-retry-count")===void 0&&(a["x-stainless-retry-count"]=String(s)),xr(i,"x-stainless-timeout")===void 0&&xr(t,"x-stainless-timeout")===void 0&&e.timeout&&(a["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(a,t),a}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 tn(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:a,url:i,timeout:l}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(a,{url:i,options:n}),Ge("request",i,n,a.headers),(h=n.signal)!=null&&h.aborted)throw new Ne;const d=new AbortController,u=await this.fetchWithTimeout(i,a,l,d).catch(Qn);if(u instanceof Error){if((p=n.signal)!=null&&p.aborted)throw new Ne;if(t)return this.retryRequest(n,t);throw u.name==="AbortError"?new ys:new Qr({cause:u})}const g=xi(u.headers);if(!u.ok){if(t&&this.shouldRetry(u)){const b=`retrying, ${t} attempts remaining`;return Ge(`response (error; ${b})`,u.status,i,g),this.retryRequest(n,t,g)}const w=await u.text().catch(b=>Qn(b).message),m=Cd(w),f=m?void 0:w;throw Ge(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,u.status,i,g,f),this.makeStatusError(u.status,m,f,g)}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=Ad(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return bi(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 X(`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:a,...i}=t||{};a&&a.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 a=n==null?void 0:n["retry-after-ms"];if(a){const l=parseFloat(a);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 a=t-e,i=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return i*l*1e3}getUserAgent(){return`${this.constructor.name}/JS ${pt}`}}class pi{constructor(e,t,n,s){gr.set(this,void 0),pd(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 X("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,a]of n)e.url.searchParams.set(s,a);t.query=void 0,t.path=e.url.toString()}return await xd(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 tn{constructor(e,t,n){super(t,async s=>new n(e,s.response,await mi(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const xi=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),wd={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},ae=r=>typeof r=="object"&&r!==null&&!bi(r)&&Object.keys(r).every(e=>yi(wd,e)),vd=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":pt,"X-Stainless-OS":To(Deno.build.os),"X-Stainless-Arch":Io(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":To(process.platform),"X-Stainless-Arch":Io(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const r=_d();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 _d(){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,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const Io=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",To=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 Po;const Sd=()=>Po??(Po=vd()),Cd=r=>{try{return JSON.parse(r)}catch{return}},jd=/^[a-z][a-z0-9+.-]*:/i,Ad=r=>jd.test(r),Qt=r=>new Promise(e=>setTimeout(e,r)),Nn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new X(`${r} must be an integer`);if(e<0)throw new X(`${r} must be a positive integer`);return e},Qn=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,a;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(a=(s=(n=Deno.env)==null?void 0:n.get)==null?void 0:s.call(n,r))==null?void 0:a.trim()};function bi(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 Oo(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 Ro=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)Ro.has(l.toLowerCase())&&(i.headers[l]="REDACTED");return i}let a=null;for(const i in s)Ro.has(i.toLowerCase())&&(a??(a={...s}),a[i]="REDACTED");return a??s});console.log(`OpenAI:DEBUG:${r}`,...n)}}const kd=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Nd=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Md=r=>typeof(r==null?void 0:r.get)=="function",xr=(r,e)=>{var n;const t=e.toLowerCase();if(Md(r)){const s=((n=e[0])==null?void 0:n.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(a,i,l)=>i+l.toUpperCase());for(const a of[e,t,e.toUpperCase(),s]){const i=r.get(a);if(i)return i}}for(const[s,a]of Object.entries(r))if(s.toLowerCase()===t)return Array.isArray(a)?(a.length<=1||console.warn(`Received ${a.length} entries for the ${e} header, using the first entry.`),a[0]):a},Ed=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 Mn(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}class rn extends pi{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 pi{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 K{constructor(e){this._client=e}}let wi=class extends K{list(e,t={},n){return ae(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Id,{query:t,...n})}},nn=class extends K{constructor(){super(...arguments),this.messages=new wi(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 ae(e)?this.list({},e):this._client.getAPIList("/chat/completions",sn,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class sn extends de{}class Id extends de{}nn.ChatCompletionsPage=sn;nn.Messages=wi;let on=class extends K{constructor(){super(...arguments),this.completions=new nn(this._client)}};on.Completions=nn;on.ChatCompletionsPage=sn;class vi extends K{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 _i extends K{create(e,t){return this._client.post("/audio/transcriptions",it({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Si extends K{create(e,t){return this._client.post("/audio/translations",it({body:e,...t,__metadata:{model:e.model}}))}}class Zt extends K{constructor(){super(...arguments),this.transcriptions=new _i(this._client),this.translations=new Si(this._client),this.speech=new vi(this._client)}}Zt.Transcriptions=_i;Zt.Translations=Si;Zt.Speech=vi;class ws extends K{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 ae(e)?this.list({},e):this._client.getAPIList("/batches",vs,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class vs extends de{}ws.BatchesPage=vs;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},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)},Zn,Nr,Mr,$t,Lt,Er,Dt,Ue,Ft,Br,Wr,xt,Ci;class _s{constructor(){Zn.add(this),this.controller=new AbortController,Nr.set(this,void 0),Mr.set(this,()=>{}),$t.set(this,()=>{}),Lt.set(this,void 0),Er.set(this,()=>{}),Dt.set(this,()=>{}),Ue.set(this,{}),Ft.set(this,!1),Br.set(this,!1),Wr.set(this,!1),xt.set(this,!1),Me(this,Nr,new Promise((e,t)=>{Me(this,Mr,e,"f"),Me(this,$t,t,"f")}),"f"),Me(this,Lt,new Promise((e,t)=>{Me(this,Er,e,"f"),Me(this,Dt,t,"f")}),"f"),oe(this,Nr,"f").catch(()=>{}),oe(this,Lt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},oe(this,Zn,"m",Ci).bind(this))},0)}_connected(){this.ended||(oe(this,Mr,"f").call(this),this._emit("connect"))}get ended(){return oe(this,Ft,"f")}get errored(){return oe(this,Br,"f")}get aborted(){return oe(this,Wr,"f")}abort(){this.controller.abort()}on(e,t){return(oe(this,Ue,"f")[e]||(oe(this,Ue,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=oe(this,Ue,"f")[e];if(!n)return this;const s=n.findIndex(a=>a.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(oe(this,Ue,"f")[e]||(oe(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 oe(this,Lt,"f")}_emit(e,...t){if(oe(this,Ft,"f"))return;e==="end"&&(Me(this,Ft,!0,"f"),oe(this,Er,"f").call(this));const n=oe(this,Ue,"f")[e];if(n&&(oe(this,Ue,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!oe(this,xt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),oe(this,$t,"f").call(this,s),oe(this,Dt,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!oe(this,xt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),oe(this,$t,"f").call(this,s),oe(this,Dt,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Nr=new WeakMap,Mr=new WeakMap,$t=new WeakMap,Lt=new WeakMap,Er=new WeakMap,Dt=new WeakMap,Ue=new WeakMap,Ft=new WeakMap,Br=new WeakMap,Wr=new WeakMap,xt=new WeakMap,Zn=new WeakSet,Ci=function(e){if(Me(this,Br,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Ne),e instanceof Ne)return Me(this,Wr,!0,"f"),this._emit("abort",e);if(e instanceof X)return this._emit("error",e);if(e instanceof Error){const t=new X(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new X(String(e)))};var G=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,es,$e,Ir,Ee,tt,bt,et,Hr,je,Tr,Pr,Ht,Ut,Bt,$o,Lo,Do,Fo,Uo,Bo,Wo;class Ie extends _s{constructor(){super(...arguments),me.add(this),es.set(this,[]),$e.set(this,{}),Ir.set(this,{}),Ee.set(this,void 0),tt.set(this,void 0),bt.set(this,void 0),et.set(this,void 0),Hr.set(this,void 0),je.set(this,void 0),Tr.set(this,void 0),Pr.set(this,void 0),Ht.set(this,void 0)}[(es=new WeakMap,$e=new WeakMap,Ir=new WeakMap,Ee=new WeakMap,tt=new WeakMap,bt=new WeakMap,et=new WeakMap,Hr=new WeakMap,je=new WeakMap,Tr=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 a=t.shift();a?a.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 a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,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 a;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)G(this,me,"m",Ut).call(this,i);if((a=s.controller.signal)!=null&&a.aborted)throw new Ne;return this._addRun(G(this,me,"m",Bt).call(this))}toReadableStream(){return new Le(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,a){const i=new Ie;return i._run(()=>i._runToolAssistantStream(e,t,n,s,{...a,headers:{...a==null?void 0:a.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,n,s,a){var u;const i=a==null?void 0:a.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,{...a,signal:this.controller.signal});this._connected();for await(const g of d)G(this,me,"m",Ut).call(this,g);if((u=d.controller.signal)!=null&&u.aborted)throw new Ne;return this._addRun(G(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 a=new Ie;return a._run(()=>a._runAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return G(this,Tr,"f")}currentRun(){return G(this,Pr,"f")}currentMessageSnapshot(){return G(this,Ee,"f")}currentRunStepSnapshot(){return G(this,Ht,"f")}async finalRunSteps(){return await this.done(),Object.values(G(this,$e,"f"))}async finalMessages(){return await this.done(),Object.values(G(this,Ir,"f"))}async finalRun(){if(await this.done(),!G(this,tt,"f"))throw Error("Final run was not received.");return G(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 a={...t,stream:!0},i=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(const d of i)G(this,me,"m",Ut).call(this,d);if((l=i.controller.signal)!=null&&l.aborted)throw new Ne;return this._addRun(G(this,me,"m",Bt).call(this))}async _createAssistantStream(e,t,n,s){var d;const a=s==null?void 0:s.signal;a&&(a.aborted&&this.controller.abort(),a.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)G(this,me,"m",Ut).call(this,u);if((d=l.controller.signal)!=null&&d.aborted)throw new Ne;return this._addRun(G(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 a=e[n];if(a==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(Mn(a)&&Mn(s))a=this.accumulateDelta(a,s);else if(Array.isArray(a)&&Array.isArray(s)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...s);continue}for(const i of s){if(!Mn(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=a[l];d==null?a.push(i):a[l]=this.accumulateDelta(d,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${a}`);e[n]=a}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,a){return await this._createToolAssistantStream(n,e,t,s,a)}}Ut=function(e){if(!this.ended)switch(Se(this,Tr,e,"f"),G(this,me,"m",Do).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":G(this,me,"m",Wo).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":G(this,me,"m",Lo).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":G(this,me,"m",$o).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 X("stream has ended, this shouldn't happen");if(!G(this,tt,"f"))throw Error("Final run has not been received");return G(this,tt,"f")},$o=function(e){const[t,n]=G(this,me,"m",Uo).call(this,e,G(this,Ee,"f"));Se(this,Ee,t,"f"),G(this,Ir,"f")[t.id]=t;for(const s of n){const a=t.content[s.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.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 a=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=G(this,bt,"f")){if(G(this,et,"f"))switch(G(this,et,"f").type){case"text":this._emit("textDone",G(this,et,"f").text,G(this,Ee,"f"));break;case"image_file":this._emit("imageFileDone",G(this,et,"f").image_file,G(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(G(this,bt,"f")!==void 0){const s=e.data.content[G(this,bt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,G(this,Ee,"f"));break;case"text":this._emit("textDone",s.text,G(this,Ee,"f"));break}}G(this,Ee,"f")&&this._emit("messageDone",e.data),Se(this,Ee,void 0,"f")}},Lo=function(e){const t=G(this,me,"m",Fo).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 a of n.step_details.tool_calls)a.index==G(this,Hr,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(G(this,je,"f")&&this._emit("toolCallDone",G(this,je,"f")),Se(this,Hr,a.index,"f"),Se(this,je,t.step_details.tool_calls[a.index],"f"),G(this,je,"f")&&this._emit("toolCallCreated",G(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"&&G(this,je,"f")&&(this._emit("toolCallDone",G(this,je,"f")),Se(this,je,void 0,"f")),this._emit("runStepDone",e.data,t);break}},Do=function(e){G(this,es,"f").push(e),this._emit("event",e)},Fo=function(e){switch(e.event){case"thread.run.step.created":return G(this,$e,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=G(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);G(this,$e,"f")[e.data.id]=s}return G(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":G(this,$e,"f")[e.data.id]=e.data;break}if(G(this,$e,"f")[e.data.id])return G(this,$e,"f")[e.data.id];throw new Error("No snapshot available")},Uo=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 a of s.delta.content)if(a.index in t.content){let i=t.content[a.index];t.content[a.index]=G(this,me,"m",Bo).call(this,a,i)}else t.content[a.index]=a,n.push(a);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")},Bo=function(e,t){return Ie.accumulateDelta(t,e)},Wo=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"),G(this,je,"f")&&(this._emit("toolCallDone",G(this,je,"f")),Se(this,je,void 0,"f"));break}};class Ss extends K{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 ae(e)?this.list({},e):this._client.getAPIList("/assistants",Cs,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Cs extends de{}Ss.AssistantsPage=Cs;function Ho(r){return typeof r.parse=="function"}const yt=r=>(r==null?void 0:r.role)==="assistant",ji=r=>(r==null?void 0:r.role)==="function",Ai=r=>(r==null?void 0:r.role)==="tool";function js(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 Td(r,e){return!e||!ki(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:As(r,e)}function As(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new li;if(n.finish_reason==="content_filter")throw new ci;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(a=>Od(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Pd(e,n.message.content):null}}});return{...r,choices:t}}function Pd(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 Od(r,e){var n;const t=(n=r.tools)==null?void 0:n.find(s=>{var a;return((a=s.function)==null?void 0:a.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 Rd(r,e){var n;if(!r)return!1;const t=(n=r.tools)==null?void 0:n.find(s=>{var a;return((a=s.function)==null?void 0:a.name)===e.function.name});return er(t)||(t==null?void 0:t.function.strict)||!1}function ki(r){var e;return js(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>er(t)||t.type==="function"&&t.function.strict===!0))??!1}function $d(r){for(const e of r??[]){if(e.type!=="function")throw new X(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new X(`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,ts,qr,rs,ns,ss,Ni,os;const qo=10;class Mi extends _s{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),(ji(e)||Ai(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 X("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),ye(this,pe,"m",ts).call(this)}async finalMessage(){return await this.done(),ye(this,pe,"m",qr).call(this)}async finalFunctionCall(){return await this.done(),ye(this,pe,"m",rs).call(this)}async finalFunctionCallResult(){return await this.done(),ye(this,pe,"m",ns).call(this)}async totalUsage(){return await this.done(),ye(this,pe,"m",ss).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",qr).call(this);t&&this._emit("finalMessage",t);const n=ye(this,pe,"m",ts).call(this);n&&this._emit("finalContent",n);const s=ye(this,pe,"m",rs).call(this);s&&this._emit("finalFunctionCall",s);const a=ye(this,pe,"m",ns).call(this);a!=null&&this._emit("finalFunctionCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",ye(this,pe,"m",ss).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",Ni).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(As(a,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:a="auto",stream:i,...l}=t,d=typeof a!="string"&&(a==null?void 0:a.name),{maxChatCompletions:u=qo}=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<u;++w){const f=(p=(await this._createChatCompletion(e,{...l,function_call:a,functions:h,messages:[...this.messages]},n)).choices[0])==null?void 0:p.message;if(!f)throw new X("missing message in ChatCompletion response");if(!f.function_call)return;const{name:c,arguments:x}=f.function_call,b=g[c];if(b){if(d&&d!==c){const j=`Invalid function_call: ${JSON.stringify(c)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,name:c,content:j});continue}}else{const j=`Invalid function_call: ${JSON.stringify(c)}. Available options are: ${h.map(v=>JSON.stringify(v.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:c,content:j});continue}let y;try{y=Ho(b)?await b.parse(x):x}catch(j){this._addMessage({role:s,name:c,content:j instanceof Error?j.message:String(j)});continue}const _=await b.function(y,this),S=ye(this,pe,"m",os).call(this,_);if(this._addMessage({role:s,name:c,content:S}),d)return}}async _runTools(e,t,n){var w,m,f;const s="tool",{tool_choice:a="auto",stream:i,...l}=t,d=typeof a!="string"&&((w=a==null?void 0:a.function)==null?void 0:w.name),{maxChatCompletions:u=qo}=n||{},g=t.tools.map(c=>{if(er(c)){if(!c.$callback)throw new X("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<u;++c){const b=(m=(await this._createChatCompletion(e,{...l,tool_choice:a,tools:p,messages:[...this.messages]},n)).choices[0])==null?void 0:m.message;if(!b)throw new X("missing message in ChatCompletion response");if(!((f=b.tool_calls)!=null&&f.length))return;for(const y of b.tool_calls){if(y.type!=="function")continue;const _=y.id,{name:S,arguments:j}=y.function,v=h[S];if(v){if(d&&d!==S){const D=`Invalid tool_call: ${JSON.stringify(S)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,tool_call_id:_,content:D});continue}}else{const D=`Invalid tool_call: ${JSON.stringify(S)}. Available options are: ${Object.keys(h).map(C=>JSON.stringify(C)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:_,content:D});continue}let I;try{I=Ho(v)?await v.parse(j):j}catch(D){const C=D instanceof Error?D.message:String(D);this._addMessage({role:s,tool_call_id:_,content:C});continue}const T=await v.function(I,this),R=ye(this,pe,"m",os).call(this,T);if(this._addMessage({role:s,tool_call_id:_,content:R}),d)return}}}}pe=new WeakSet,ts=function(){return ye(this,pe,"m",qr).call(this).content??null},qr=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(yt(t)){const{function_call:n,...s}=t,a={...s,content:t.content??null,refusal:t.refusal??null};return n&&(a.function_call=n),a}}throw new X("stream ended without producing a ChatCompletionMessage with role=assistant")},rs=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}},ns=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(ji(t)&&t.content!=null||Ai(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(a=>a.type==="function"&&a.id===t.tool_call_id))}))return t.content}},ss=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},Ni=function(e){if(e.n!=null&&e.n>1)throw new X("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},os=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Gt extends Mi{static runFunctions(e,t,n){const s=new Gt,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,a)),s}static runTools(e,t,n){const s=new Gt,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}_addMessage(e,t=!0){super._addMessage(e,t),yt(e)&&e.content&&this._emit("content",e.content)}}const Ei=1,Ii=2,Ti=4,Pi=8,Oi=16,Ri=32,$i=64,Li=128,Di=256,Fi=Li|Di,Ui=Oi|Ri|Fi|$i,Bi=Ei|Ii|Ui,Wi=Ti|Pi,Ld=Bi|Wi,ue={STR:Ei,NUM:Ii,ARR:Ti,OBJ:Pi,NULL:Oi,BOOL:Ri,NAN:$i,INFINITY:Li,MINUS_INFINITY:Di,INF:Fi,SPECIAL:Ui,ATOM:Bi,COLLECTION:Wi,ALL:Ld};class Dd extends Error{}class Fd extends Error{}function Ud(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 Bd(r.trim(),e)}const Bd=(r,e)=>{const t=r.length;let n=0;const s=p=>{throw new Dd(`${p} at position ${n}`)},a=p=>{throw new Fd(`${p} at position ${n}`)},i=()=>(h(),n>=t&&s("Unexpected end of input"),r[n]==='"'?l():r[n]==="{"?d():r[n]==="["?u():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){a(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},u=()=>{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{}a(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){a(String(m))}}},h=()=>{for(;n<t&&`
39
- \r `.includes(r[n]);)n++};return i()},zo=r=>Ud(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},ne=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,En,br,In,Tn,Pn,yr,On,Jo;class Xt extends Mi{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 ne(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())),ne(this,le,"m",En).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of a)ne(this,le,"m",In).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new Ne;return this._addChatCompletion(ne(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())),ne(this,le,"m",En).call(this),this._connected();const s=Le.fromReadableStream(e,this.controller);let a;for await(const l of s)a&&a!==l.id&&this._addChatCompletion(ne(this,le,"m",yr).call(this)),ne(this,le,"m",In).call(this,l),a=l.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Ne;return this._addChatCompletion(ne(this,le,"m",yr).call(this))}[(De=new WeakMap,ft=new WeakMap,We=new WeakMap,le=new WeakSet,En=function(){this.ended||ut(this,We,void 0,"f")},br=function(t){let n=ne(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},ne(this,ft,"f")[t.index]=n,n)},In=function(t){var s,a,i,l,d,u,g,h,p,w,m,f,c,x,b;if(this.ended)return;const n=ne(this,le,"m",Jo).call(this,t);this._emit("chunk",t,n);for(const y of t.choices){const _=n.choices[y.index];y.delta.content!=null&&((s=_.message)==null?void 0:s.role)==="assistant"&&((a=_.message)!=null&&a.content)&&(this._emit("content",y.delta.content,_.message.content),this._emit("content.delta",{delta:y.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),y.delta.refusal!=null&&((i=_.message)==null?void 0:i.role)==="assistant"&&((l=_.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:y.delta.refusal,snapshot:_.message.refusal}),((d=y.logprobs)==null?void 0:d.content)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(g=y.logprobs)==null?void 0:g.content,snapshot:((h=_.logprobs)==null?void 0:h.content)??[]}),((p=y.logprobs)==null?void 0:p.refusal)!=null&&((w=_.message)==null?void 0:w.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(m=y.logprobs)==null?void 0:m.refusal,snapshot:((f=_.logprobs)==null?void 0:f.refusal)??[]});const S=ne(this,le,"m",br).call(this,_);_.finish_reason&&(ne(this,le,"m",Pn).call(this,_),S.current_tool_call_index!=null&&ne(this,le,"m",Tn).call(this,_,S.current_tool_call_index));for(const j of y.delta.tool_calls??[])S.current_tool_call_index!==j.index&&(ne(this,le,"m",Pn).call(this,_),S.current_tool_call_index!=null&&ne(this,le,"m",Tn).call(this,_,S.current_tool_call_index)),S.current_tool_call_index=j.index;for(const j of y.delta.tool_calls??[]){const v=(c=_.message.tool_calls)==null?void 0:c[j.index];v!=null&&v.type&&((v==null?void 0:v.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(x=v.function)==null?void 0:x.name,index:j.index,arguments:v.function.arguments,parsed_arguments:v.function.parsed_arguments,arguments_delta:((b=j.function)==null?void 0:b.arguments)??""}):(v==null||v.type,void 0))}}},Tn=function(t,n){var i,l,d;if(ne(this,le,"m",br).call(this,t).done_tool_calls.has(n))return;const a=(i=t.message.tool_calls)==null?void 0:i[n];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const u=(d=(l=ne(this,De,"f"))==null?void 0:l.tools)==null?void 0:d.find(g=>g.type==="function"&&g.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:er(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Pn=function(t){var s,a;const n=ne(this,le,"m",br).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=ne(this,le,"m",On).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})),(a=t.logprobs)!=null&&a.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 X("stream has ended, this shouldn't happen");const t=ne(this,We,"f");if(!t)throw new X("request ended without sending any chunks");return ut(this,We,void 0,"f"),ut(this,ft,[],"f"),Wd(t,ne(this,De,"f"))},On=function(){var n;const t=(n=ne(this,De,"f"))==null?void 0:n.response_format;return js(t)?t:null},Jo=function(t){var n,s,a,i;let l=ne(this,We,"f");const{choices:d,...u}=t;l?Object.assign(l,u):l=ut(this,We,{...u,choices:[]},"f");for(const{delta:g,finish_reason:h,index:p,logprobs:w=null,...m}of t.choices){let f=l.choices[p];if(f||(f=l.choices[p]={finish_reason:h,index:p,message:{},logprobs:w,...m}),w)if(!f.logprobs)f.logprobs=Object.assign({},w);else{const{content:j,refusal:v,...I}=w;Object.assign(f.logprobs,I),j&&((n=f.logprobs).content??(n.content=[]),f.logprobs.content.push(...j)),v&&((s=f.logprobs).refusal??(s.refusal=[]),f.logprobs.refusal.push(...v))}if(h&&(f.finish_reason=h,ne(this,De,"f")&&ki(ne(this,De,"f")))){if(h==="length")throw new li;if(h==="content_filter")throw new ci}if(Object.assign(f,m),!g)continue;const{content:c,refusal:x,function_call:b,role:y,tool_calls:_,...S}=g;if(Object.assign(f.message,S),x&&(f.message.refusal=(f.message.refusal||"")+x),y&&(f.message.role=y),b&&(f.message.function_call?(b.name&&(f.message.function_call.name=b.name),b.arguments&&((a=f.message.function_call).arguments??(a.arguments=""),f.message.function_call.arguments+=b.arguments)):f.message.function_call=b),c&&(f.message.content=(f.message.content||"")+c,!f.message.refusal&&ne(this,le,"m",On).call(this)&&(f.message.parsed=zo(f.message.content))),_){f.message.tool_calls||(f.message.tool_calls=[]);for(const{index:j,id:v,type:I,function:T,...R}of _){const D=(i=f.message.tool_calls)[j]??(i[j]={});Object.assign(D,R),v&&(D.id=v),I&&(D.type=I),T&&(D.function??(D.function={name:T.name??"",arguments:""})),T!=null&&T.name&&(D.function.name=T.name),T!=null&&T.arguments&&(D.function.arguments+=T.arguments,Rd(ne(this,De,"f"),D)&&(D.function.parsed_arguments=zo(D.function.arguments)))}}}return l},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",s=>{const a=t.shift();a?a.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 a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,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 Wd(r,e){const{id:t,choices:n,created:s,model:a,system_fingerprint:i,...l}=r,d={...l,id:t,choices:n.map(({message:u,finish_reason:g,index:h,logprobs:p,...w})=>{if(!g)throw new X(`missing finish_reason for choice ${h}`);const{content:m=null,function_call:f,tool_calls:c,...x}=u,b=u.role;if(!b)throw new X(`missing role for choice ${h}`);if(f){const{arguments:y,name:_}=f;if(y==null)throw new X(`missing function_call.arguments for choice ${h}`);if(!_)throw new X(`missing function_call.name for choice ${h}`);return{...w,message:{content:m,function_call:{arguments:y,name:_},role:b,refusal:u.refusal??null},finish_reason:g,index:h,logprobs:p}}return c?{...w,index:h,finish_reason:g,logprobs:p,message:{...x,role:b,content:m,refusal:u.refusal??null,tool_calls:c.map((y,_)=>{const{function:S,type:j,id:v,...I}=y,{arguments:T,name:R,...D}=S||{};if(v==null)throw new X(`missing choices[${h}].tool_calls[${_}].id
40
- ${wr(r)}`);if(j==null)throw new X(`missing choices[${h}].tool_calls[${_}].type
41
- ${wr(r)}`);if(R==null)throw new X(`missing choices[${h}].tool_calls[${_}].function.name
42
- ${wr(r)}`);if(T==null)throw new X(`missing choices[${h}].tool_calls[${_}].function.arguments
43
- ${wr(r)}`);return{...I,id:v,type:j,function:{...D,name:R,arguments:T}}})}}:{...w,message:{...x,content:m,role:b,refusal:u.refusal??null},finish_reason:g,index:h,logprobs:p}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Td(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),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,a)),s}static runTools(e,t,n){const s=new wt(t),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}}let Hi=class extends K{parse(e,t){return $d(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(n=>As(n,e))}runFunctions(e,t){return e.stream?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 as extends K{constructor(){super(...arguments),this.completions=new Hi(this._client)}}(function(r){r.Completions=Hi})(as||(as={}));class qi extends K{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class zi extends K{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 an extends K{constructor(){super(...arguments),this.sessions=new qi(this._client),this.transcriptionSessions=new zi(this._client)}}an.Sessions=qi;an.TranscriptionSessions=zi;class ks extends K{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 ae(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Ns,{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 Ns extends de{}ks.MessagesPage=Ns;class Ms extends K{retrieve(e,t,n,s={},a){return ae(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...a,headers:{"OpenAI-Beta":"assistants=v2",...a==null?void 0:a.headers}})}list(e,t,n={},s){return ae(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Es,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}}class Es extends de{}Ms.RunStepsPage=Es;let tr=class extends K{constructor(){super(...arguments),this.steps=new Ms(this._client)}create(e,t,n){const{include:s,...a}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:a,...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 ae(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Is,{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:a,response:i}=await this.retrieve(e,t,{...n,headers:{...n==null?void 0:n.headers,...s}}).withResponse();switch(a.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 Qt(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}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 a=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,a.id,s)}submitToolOutputsStream(e,t,n,s){return Ie.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class Is extends de{}tr.RunsPage=Is;tr.Steps=Ms;tr.RunStepsPage=Es;class jt extends K{constructor(){super(...arguments),this.runs=new tr(this._client),this.messages=new ks(this._client)}create(e={},t){return ae(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=Is;jt.Messages=ks;jt.MessagesPage=Ns;class At extends K{constructor(){super(...arguments),this.realtime=new an(this._client),this.chat=new as(this._client),this.assistants=new Ss(this._client),this.threads=new jt(this._client)}}At.Realtime=an;At.Assistants=Ss;At.AssistantsPage=Cs;At.Threads=jt;class Ji extends K{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Vi extends K{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 ln=class extends K{constructor(){super(...arguments),this.content=new Vi(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 ae(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Ts,{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 Ts extends de{}ln.FileListResponsesPage=Ts;ln.Content=Vi;class rr extends K{constructor(){super(...arguments),this.files=new ln(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 ae(e)?this.list({},e):this._client.getAPIList("/containers",Ps,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}}class Ps extends de{}rr.ContainerListResponsesPage=Ps;rr.Files=ln;rr.FileListResponsesPage=Ts;class Gi extends K{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 a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?a:(Ge("response","Decoding base64 embeddings to float32 array"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const d=l.embedding;l.embedding=Ed(d)}),i)))}}class Os extends K{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return ae(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Rs,{query:n,...s})}}class Rs extends de{}Os.OutputItemListResponsesPage=Rs;class nr extends K{constructor(){super(...arguments),this.outputItems=new Os(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 ae(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,$s,{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 $s extends de{}nr.RunListResponsesPage=$s;nr.OutputItems=Os;nr.OutputItemListResponsesPage=Rs;class sr extends K{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 ae(e)?this.list({},e):this._client.getAPIList("/evals",Ls,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class Ls extends de{}sr.EvalListResponsesPage=Ls;sr.Runs=nr;sr.RunListResponsesPage=$s;let Ds=class extends K{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 ae(e)?this.list({},e):this._client.getAPIList("/files",Fs,{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"]),a=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()-a>n)throw new ys({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class Fs extends de{}Ds.FileObjectsPage=Fs;class Xi extends K{}let Ki=class extends K{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 Us extends K{constructor(){super(...arguments),this.graders=new Ki(this._client)}}Us.Graders=Ki;class Bs extends K{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Ws,{body:t,method:"post",...n})}retrieve(e,t={},n){return ae(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}del(e,t,n){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,n)}}class Ws extends rn{}Bs.PermissionCreateResponsesPage=Ws;let cn=class extends K{constructor(){super(...arguments),this.permissions=new Bs(this._client)}};cn.Permissions=Bs;cn.PermissionCreateResponsesPage=Ws;class Hs extends K{list(e,t={},n){return ae(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,qs,{query:t,...n})}}class qs extends de{}Hs.FineTuningJobCheckpointsPage=qs;class kt extends K{constructor(){super(...arguments),this.checkpoints=new Hs(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return ae(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",zs,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return ae(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Js,{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 zs extends de{}class Js extends de{}kt.FineTuningJobsPage=zs;kt.FineTuningJobEventsPage=Js;kt.Checkpoints=Hs;kt.FineTuningJobCheckpointsPage=qs;class Xe extends K{constructor(){super(...arguments),this.methods=new Xi(this._client),this.jobs=new kt(this._client),this.checkpoints=new cn(this._client),this.alpha=new Us(this._client)}}Xe.Methods=Xi;Xe.Jobs=kt;Xe.FineTuningJobsPage=zs;Xe.FineTuningJobEventsPage=Js;Xe.Checkpoints=cn;Xe.Alpha=Us;class Yi extends K{}class Vs extends K{constructor(){super(...arguments),this.graderModels=new Yi(this._client)}}Vs.GraderModels=Yi;class Qi extends K{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 Gs extends K{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Xs,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Xs extends rn{}Gs.ModelsPage=Xs;class Zi extends K{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Hd(r,e){return!e||!zd(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)}:el(r,e)}function el(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Gd(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:qd(e,i.text)}:i);return{...s,content:a}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||tl(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const s of n.output)if(s.type==="message"){for(const a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function qd(r,e){var t,n,s,a;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)?((a=r.text)==null?void 0:a.format).$parseRaw(e):JSON.parse(e)}function zd(r){var e;return!!js((e=r.text)==null?void 0:e.format)}function Jd(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function Vd(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function Gd(r,e){const t=Vd(r.tools??[],e.name);return{...e,...e,parsed_arguments:Jd(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function tl(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 rl extends K{list(e,t={},n){return ae(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Kd,{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,Vo,Go,Xo,Ko;class Ks extends _s{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 Ks(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",Vo).call(this);let a,i=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const d of a)He(this,mt,"m",Go).call(this,d,i);if((l=a.controller.signal)!=null&&l.aborted)throw new Ne;return He(this,mt,"m",Xo).call(this)}[(vr=new WeakMap,qe=new WeakMap,_r=new WeakMap,mt=new WeakSet,Vo=function(){this.ended||ht(this,qe,void 0,"f")},Go=function(t,n){if(this.ended)return;const s=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},a=He(this,mt,"m",Ko).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const i=a.output[t.output_index];if(!i)throw new X(`missing output at index ${t.output_index}`);if(i.type==="message"){const l=i.content[t.content_index];if(!l)throw new X(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new X(`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=a.output[t.output_index];if(!i)throw new X(`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}},Xo=function(){if(this.ended)throw new X("stream has ended, this shouldn't happen");const t=He(this,qe,"f");if(!t)throw new X("request ended without sending any events");ht(this,qe,void 0,"f");const n=Xd(t,He(this,vr,"f"));return ht(this,_r,n,"f"),n},Ko=function(t){let n=He(this,qe,"f");if(!n){if(t.type!=="response.created")throw new X(`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 X(`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 X(`missing output at index ${t.output_index}`);if(s.type==="message"){const a=s.content[t.content_index];if(!a)throw new X(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new X(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const s=n.output[t.output_index];if(!s)throw new X(`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 a=t.shift();a?a.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 a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,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 X("stream ended without producing a ChatCompletion");return e}}function Xd(r,e){return Hd(r,e)}class Ys extends K{constructor(){super(...arguments),this.inputItems=new rl(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"&&tl(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=>el(n,e))}stream(e,t){return Ks.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 Kd extends de{}Ys.InputItems=rl;class nl extends K{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,it({body:t,...n}))}}class Qs extends K{constructor(){super(...arguments),this.parts=new nl(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}Qs.Parts=nl;const Yd=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 dn extends K{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 ae(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,un,{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 a=await this.retrieve(e,t,{...n,headers:s}).withResponse(),i=a.data;switch(i.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const d=a.response.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(l=u)}}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`,Zs,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class un extends de{}class Zs extends rn{}dn.VectorStoreFilesPage=un;dn.FileContentResponsesPage=Zs;class sl extends K{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 ae(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,un,{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:a,response:i}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(a.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 Qt(l);break;case"failed":case"cancelled":case"completed":return a}}}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 a=(s==null?void 0:s.maxConcurrency)??5,i=Math.min(a,t.length),l=this._client,d=t.values(),u=[...n];async function g(p){for(let w of p){const m=await l.files.create({file:w,purpose:"assistants"},s);u.push(m.id)}}const h=Array(i).fill(d).map(g);return await Yd(h),await this.createAndPoll(e,{file_ids:u})}}class Ke extends K{constructor(){super(...arguments),this.files=new dn(this._client),this.fileBatches=new sl(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 ae(e)?this.list({},e):this._client.getAPIList("/vector_stores",eo,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,to,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class eo extends de{}class to extends rn{}Ke.VectorStoresPage=eo;Ke.VectorStoreSearchResponsesPage=to;Ke.Files=dn;Ke.VectorStoreFilesPage=un;Ke.FileContentResponsesPage=Zs;Ke.FileBatches=sl;var ol;class Y extends bd{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,...a}={}){if(t===void 0)throw new X("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,...a,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&Nd())throw new X(`It looks like you're running in a browser-like environment.
33
+ */var Mo;function Ac(){return Mo||(Mo=1,process.env.NODE_ENV!=="production"&&function(){function r(u,g){return u===g&&(u!==0||1/u===1/g)||u!==u&&g!==g}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=M,t=Ha(),n=typeof Object.is=="function"?Object.is:r,s=t.useSyncExternalStore,a=e.useRef,i=e.useEffect,l=e.useMemo,d=e.useDebugValue;En.useSyncExternalStoreWithSelector=function(u,g,h,p,w){var m=a(null);if(m.current===null){var f={hasValue:!1,value:null};m.current=f}else f=m.current;m=l(function(){function x(j){if(!b){if(b=!0,y=j,j=p(j),w!==void 0&&f.hasValue){var v=f.value;if(w(v,j))return _=v}return _=j}if(v=_,n(y,j))return v;var I=p(j);return w!==void 0&&w(v,I)?(y=j,v):(y=j,_=I)}var b=!1,y,_,S=h===void 0?null:h;return[function(){return x(g())},S===null?void 0:function(){return x(S())}]},[g,h,p,w]);var c=s(u,m[0],m[1]);return i(function(){f.hasValue=!0,f.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())}()),En}process.env.NODE_ENV==="production"?Xn.exports=jc():Xn.exports=Ac();var kc=Xn.exports;const Nc=_c(kc),qa={},{useDebugValue:Mc}=M,{useSyncExternalStoreWithSelector:Ec}=Nc;let Eo=!1;const Ic=r=>r;function Pc(r,e=Ic,t){(qa?"production":void 0)!=="production"&&t&&!Eo&&(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"),Eo=!0);const n=Ec(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return Mc(n),n}const Tc=r=>{(qa?"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"?vc(r):r,t=(n,s)=>Pc(e,n,s);return Object.assign(t,e),t},Oc=r=>Tc;var za=Symbol.for("immer-nothing"),Io=Symbol.for("immer-draftable"),ke=Symbol.for("immer-state"),Rc=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=Rc[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 At=Object.getPrototypeOf;function kt(r){return!!r&&!!r[ke]}function dt(r){var e;return r?Ja(r)||Array.isArray(r)||!!r[Io]||!!((e=r.constructor)!=null&&e[Io])||sr(r)||nn(r):!1}var $c=Object.prototype.constructor.toString();function Ja(r){if(!r||typeof r!="object")return!1;const e=At(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 zr(r,e){rn(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function rn(r){const e=r[ke];return e?e.type_:Array.isArray(r)?1:sr(r)?2:nn(r)?3:0}function Kn(r,e){return rn(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function Va(r,e,t){const n=rn(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function Lc(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function sr(r){return r instanceof Map}function nn(r){return r instanceof Set}function nt(r){return r.copy_||r.base_}function Yn(r,e){if(sr(r))return new Map(r);if(nn(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);const t=Ja(r);if(e===!0||e==="class_only"&&!t){const n=Object.getOwnPropertyDescriptors(r);delete n[ke];let s=Reflect.ownKeys(n);for(let a=0;a<s.length;a++){const i=s[a],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(At(r),n)}else{const n=At(r);if(n!==null&&t)return{...r};const s=Object.create(n);return Object.assign(s,r)}}function Cs(r,e=!1){return sn(r)||kt(r)||!dt(r)||(rn(r)>1&&Object.defineProperties(r,{set:{value:wr},add:{value:wr},clear:{value:wr},delete:{value:wr}}),Object.freeze(r),e&&Object.values(r).forEach(t=>Cs(t,!0))),r}function wr(){we(2)}function sn(r){return Object.isFrozen(r)}var Dc={};function ut(r){const e=Dc[r];return e||we(0,r),e}var Yt;function Ga(){return Yt}function Fc(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Po(r,e){e&&(ut("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function Qn(r){Zn(r),r.drafts_.forEach(Uc),r.drafts_=null}function Zn(r){r===Yt&&(Yt=r.parent_)}function To(r){return Yt=Fc(Yt,r)}function Uc(r){const e=r[ke];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function Oo(r,e){e.unfinalizedDrafts_=e.drafts_.length;const t=e.drafts_[0];return r!==void 0&&r!==t?(t[ke].modified_&&(Qn(e),we(4)),dt(r)&&(r=Jr(e,r),e.parent_||Vr(e,r)),e.patches_&&ut("Patches").generateReplacementPatches_(t[ke].base_,r,e.patches_,e.inversePatches_)):r=Jr(e,t,[]),Qn(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==za?r:void 0}function Jr(r,e,t){if(sn(e))return e;const n=e[ke];if(!n)return zr(e,(s,a)=>Ro(r,n,e,s,a,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return Vr(r,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const s=n.copy_;let a=s,i=!1;n.type_===3&&(a=new Set(s),s.clear(),i=!0),zr(a,(l,d)=>Ro(r,n,s,l,d,t,i)),Vr(r,s,!1),t&&r.patches_&&ut("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function Ro(r,e,t,n,s,a,i){if(process.env.NODE_ENV!=="production"&&s===t&&we(5),kt(s)){const l=a&&e&&e.type_!==3&&!Kn(e.assigned_,n)?a.concat(n):void 0,d=Jr(r,s,l);if(Va(t,n,d),kt(d))r.canAutoFreeze_=!1;else return}else i&&t.add(s);if(dt(s)&&!sn(s)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;Jr(r,s),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&(sr(t)?t.has(n):Object.prototype.propertyIsEnumerable.call(t,n))&&Vr(r,s)}}function Vr(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&Cs(e,t)}function Bc(r,e){const t=Array.isArray(r),n={type_:t?1:0,scope_:e?e.scope_:Ga(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=n,a=js;t&&(s=[n],a=Qt);const{revoke:i,proxy:l}=Proxy.revocable(s,a);return n.draft_=l,n.revoke_=i,l}var js={get(r,e){if(e===ke)return r;const t=nt(r);if(!Kn(t,e))return Wc(r,t,e);const n=t[e];return r.finalized_||!dt(n)?n:n===In(r.base_,e)?(Pn(r),r.copy_[e]=ts(n,r)):n},has(r,e){return e in nt(r)},ownKeys(r){return Reflect.ownKeys(nt(r))},set(r,e,t){const n=Xa(nt(r),e);if(n!=null&&n.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){const s=In(nt(r),e),a=s==null?void 0:s[ke];if(a&&a.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(Lc(t,s)&&(t!==void 0||Kn(r.base_,e)))return!0;Pn(r),es(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 In(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,Pn(r),es(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){const t=nt(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 At(r.base_)},setPrototypeOf(){we(12)}},Qt={};zr(js,(r,e)=>{Qt[r]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});Qt.deleteProperty=function(r,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&we(13),Qt.set.call(this,r,e,void 0)};Qt.set=function(r,e,t){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&we(14),js.set.call(this,r[0],e,t,r[0])};function In(r,e){const t=r[ke];return(t?nt(t):r)[e]}function Wc(r,e,t){var s;const n=Xa(e,t);return n?"value"in n?n.value:(s=n.get)==null?void 0:s.call(r.draft_):void 0}function Xa(r,e){if(!(e in r))return;let t=At(r);for(;t;){const n=Object.getOwnPropertyDescriptor(t,e);if(n)return n;t=At(t)}}function es(r){r.modified_||(r.modified_=!0,r.parent_&&es(r.parent_))}function Pn(r){r.copy_||(r.copy_=Yn(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Hc=class{constructor(r){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if(typeof e=="function"&&typeof t!="function"){const a=t;t=e;const i=this;return function(d=a,...u){return i.produce(d,g=>t.call(this,g,...u))}}typeof t!="function"&&we(6),n!==void 0&&typeof n!="function"&&we(7);let s;if(dt(e)){const a=To(this),i=ts(e,void 0);let l=!0;try{s=t(i),l=!1}finally{l?Qn(a):Zn(a)}return Po(a,n),Oo(s,a)}else if(!e||typeof e!="object"){if(s=t(e),s===void 0&&(s=e),s===za&&(s=void 0),this.autoFreeze_&&Cs(s,!0),n){const a=[],i=[];ut("Patches").generateReplacementPatches_(e,s,a,i),n(a,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){dt(r)||we(8),kt(r)&&(r=qc(r));const e=To(this),t=ts(r,void 0);return t[ke].isManual_=!0,Zn(e),t}finishDraft(r,e){const t=r&&r[ke];(!t||!t.isManual_)&&we(9);const{scope_:n}=t;return Po(n,e),Oo(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=ut("Patches").applyPatches_;return kt(r)?n(r,e):this.produce(r,s=>n(s,e))}};function ts(r,e){const t=sr(r)?ut("MapSet").proxyMap_(r,e):nn(r)?ut("MapSet").proxySet_(r,e):Bc(r,e);return(e?e.scope_:Ga()).drafts_.push(t),t}function qc(r){return kt(r)||we(10,r),Ka(r)}function Ka(r){if(!dt(r)||sn(r))return r;const e=r[ke];let t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=Yn(r,e.scope_.immer_.useStrictShallowCopy_)}else t=Yn(r,!0);return zr(t,(n,s)=>{Va(t,n,Ka(s))}),e&&(e.finalized_=!1),t}var zc=new Hc,Jc=zc.produce;const Vc=r=>(e,t,n)=>(n.setState=(s,a,...i)=>{const l=typeof s=="function"?Jc(s):s;return e(l,a,...i)},r(n.setState,t,n)),Gc=Vc,Xc={};function Kc(r,e){let t;try{t=r()}catch{return}return{getItem:s=>{var a;const i=d=>d===null?null:JSON.parse(d,void 0),l=(a=t.getItem(s))!=null?a:null;return l instanceof Promise?l.then(i):i(l)},setItem:(s,a)=>t.setItem(s,JSON.stringify(a,void 0)),removeItem:s=>t.removeItem(s)}}const Zt=r=>e=>{try{const t=r(e);return t instanceof Promise?t:{then(n){return Zt(n)(t)},catch(n){return this}}}catch(t){return{then(n){return this},catch(n){return Zt(n)(t)}}}},Yc=(r,e)=>(t,n,s)=>{let a={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:c=>c,version:0,merge:(c,x)=>({...x,...c}),...e},i=!1;const l=new Set,d=new Set;let u;try{u=a.getStorage()}catch{}if(!u)return r((...c)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),t(...c)},n,s);const g=Zt(a.serialize),h=()=>{const c=a.partialize({...n()});let x;const b=g({state:c,version:a.version}).then(y=>u.setItem(a.name,y)).catch(y=>{x=y});if(x)throw x;return b},p=s.setState;s.setState=(c,x)=>{p(c,x),h()};const w=r((...c)=>{t(...c),h()},n,s);let m;const f=()=>{var c;if(!u)return;i=!1,l.forEach(b=>b(n()));const x=((c=a.onRehydrateStorage)==null?void 0:c.call(a,n()))||void 0;return Zt(u.getItem.bind(u))(a.name).then(b=>{if(b)return a.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==a.version){if(a.migrate)return a.migrate(b.state,b.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return b.state}).then(b=>{var y;return m=a.merge(b,(y=n())!=null?y:w),t(m,!0),h()}).then(()=>{x==null||x(m,void 0),i=!0,d.forEach(b=>b(m))}).catch(b=>{x==null||x(void 0,b)})};return s.persist={setOptions:c=>{a={...a,...c},c.getStorage&&(u=c.getStorage())},clearStorage:()=>{u==null||u.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>f(),hasHydrated:()=>i,onHydrate:c=>(l.add(c),()=>{l.delete(c)}),onFinishHydration:c=>(d.add(c),()=>{d.delete(c)})},f(),m||w},Qc=(r,e)=>(t,n,s)=>{let a={storage:Kc(()=>localStorage),partialize:f=>f,version:0,merge:(f,c)=>({...c,...f}),...e},i=!1;const l=new Set,d=new Set;let u=a.storage;if(!u)return r((...f)=>{console.warn(`[zustand persist middleware] Unable to update item '${a.name}', the given storage is currently unavailable.`),t(...f)},n,s);const g=()=>{const f=a.partialize({...n()});return u.setItem(a.name,{state:f,version:a.version})},h=s.setState;s.setState=(f,c)=>{h(f,c),g()};const p=r((...f)=>{t(...f),g()},n,s);s.getInitialState=()=>p;let w;const m=()=>{var f,c;if(!u)return;i=!1,l.forEach(b=>{var y;return b((y=n())!=null?y:p)});const x=((c=a.onRehydrateStorage)==null?void 0:c.call(a,(f=n())!=null?f:p))||void 0;return Zt(u.getItem.bind(u))(a.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==a.version){if(a.migrate)return[!0,a.migrate(b.state,b.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,b.state];return[!1,void 0]}).then(b=>{var y;const[_,S]=b;if(w=a.merge(S,(y=n())!=null?y:p),t(w,!0),_)return g()}).then(()=>{x==null||x(w,void 0),w=n(),i=!0,d.forEach(b=>b(w))}).catch(b=>{x==null||x(void 0,b)})};return s.persist={setOptions:f=>{a={...a,...f},f.storage&&(u=f.storage)},clearStorage:()=>{u==null||u.removeItem(a.name)},getOptions:()=>a,rehydrate:()=>m(),hasHydrated:()=>i,onHydrate:f=>(l.add(f),()=>{l.delete(f)}),onFinishHydration:f=>(d.add(f),()=>{d.delete(f)})},a.skipHydration||m(),w||p},Zc=(r,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((Xc?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),Yc(r,e)):Qc(r,e),ed=Zc,td="/api";class er{constructor(e=td){V(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 a=await fetch(n,s);if(!a.ok)throw new Error(`HTTP error! status: ${a.status}`);const i=await a.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(a){throw console.error(`API request failed: ${e}`,a),a}}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 getSessionMcpServers(e){return this.request(`/sessions/${e}/mcp-servers`)}async addSessionMcpServer(e,t){return this.request(`/sessions/${e}/mcp-servers`,{method:"POST",body:JSON.stringify(t)})}async deleteSessionMcpServer(e,t){return this.request(`/sessions/${e}/mcp-servers/${t}`,{method:"DELETE"})}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 a=`${this.baseUrl}/agent_v2/chat/stream`,i=await fetch(a,{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 streamChatBySession(e,t,n,s){const a=`${this.baseUrl}/agent_v2/chat/stream/session`,i=await fetch(a,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:e,content:t,user_id:n,...s?{ai_model_config: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 streamAgentChat(e,t,n,s){const a=`${this.baseUrl}/agents/chat/stream`,i=await fetch(a,{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 te=new er,Or={getDetails:r=>te.getConversationDetails(r),getAssistant:r=>te.getAssistant(r),getMcpServers:r=>te.getMcpServers(r),saveMessage:(r,e)=>te.saveMessage(r,e),getMessages:(r,e)=>te.getMessages(r,e),addMessage:(r,e)=>te.addMessage(r,e)};class As{constructor(e,t,n=te){V(this,"userId");V(this,"projectId");V(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,metadata:e.metadata??void 0},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:n.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:t.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:n.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 a;const t={id:crypto.randomUUID(),session_id:e.sessionId,role:e.role,content:e.content,summary:e.rawContent,tool_calls:(a=e.metadata)!=null&&a.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(f=>{let c;if(f.metadata)try{c=typeof f.metadata=="string"?JSON.parse(f.metadata):f.metadata}catch(b){console.warn("Failed to parse message metadata:",b),c={}}let x;if(f.toolCalls)try{x=typeof f.toolCalls=="string"?JSON.parse(f.toolCalls):f.toolCalls}catch(b){console.warn("Failed to parse top-level toolCalls:",b)}return{id:f.id,sessionId:f.session_id,role:f.role,content:f.content,summary:f.summary,toolCallId:f.tool_call_id,reasoning:f.reasoning,metadata:c,topLevelToolCalls:x,createdAt:new Date(f.created_at),originalMessage:f}}),l=new Map;i.forEach(f=>{var c;if(f.role==="tool"&&f.toolCallId){const x=((c=f.metadata)==null?void 0:c.isError)||!1;l.set(f.toolCallId,{content:f.content,error:x?f.content:void 0})}});const d=i.map(f=>{var _,S;let c;const x=f.topLevelToolCalls||((_=f.metadata)==null?void 0:_.toolCalls);f.role==="assistant"&&x&&Array.isArray(x)&&(console.log("[Database] 处理工具调用:",{messageId:f.id,sourceToolCalls:x}),c=x.map(j=>{if(j.function){let v={};try{v=typeof j.function.arguments=="string"?JSON.parse(j.function.arguments):j.function.arguments}catch(P){console.warn("Failed to parse tool call arguments:",P),v={}}const I=l.get(j.id);return{id:j.id||`tool_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,messageId:f.id,name:j.function.name,arguments:v,result:(I==null?void 0:I.content)||void 0,error:(I==null?void 0:I.error)||void 0,createdAt:f.createdAt}}return null}).filter(Boolean));const b=[],y=typeof f.reasoning=="string"&&f.reasoning.trim().length>0;return f.role==="assistant"&&y&&b.push({type:"thinking",content:f.reasoning}),typeof f.content=="string"&&f.content.trim().length>0&&b.push({type:"text",content:f.content}),c&&Array.isArray(c)&&c.length>0&&c.forEach(j=>{b.push({type:"tool_call",toolCallId:j.id})}),{id:f.id,sessionId:f.sessionId,role:f.role,content:f.content,rawContent:f.summary,tokensUsed:void 0,status:"completed",createdAt:f.createdAt,updatedAt:void 0,toolCallId:f.toolCallId,metadata:{...f.metadata,toolCalls:c,contentSegments:b.length>0?b:(S=f.metadata)==null?void 0:S.contentSegments}}}),u=new Set;for(let f=0;f<d.length;f++){const c=d[f];if(((g=c==null?void 0:c.metadata)==null?void 0:g.type)==="session_summary"){const x=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 b=-1;for(let y=f+1;y<d.length;y++)if(((p=d[y])==null?void 0:p.role)==="assistant"){b=y;break}if(b===-1){for(let y=f-1;y>=0;y--)if(((w=d[y])==null?void 0:w.role)==="assistant"){b=y;break}}if(b!==-1){const y=d[b],_=`【上下文摘要】
34
+ `,S=(((m=y.metadata)==null?void 0:m.contentSegments)||[]).slice(),j=S.length-1;j>=0&&S[j].type==="thinking"&&String(S[j].content||"").startsWith(_)?S[j].content=_+String(x||""):S.push({type:"thinking",content:_+String(x||"")}),y.metadata=y.metadata||{},y.metadata.contentSegments=S,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 rs="RFC3986",ns={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},rd="RFC1738",nd=Array.isArray,Oe=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),Tn=1024,sd=(r,e,t,n,s)=>{if(r.length===0)return r;let a=r;if(typeof r=="symbol"?a=Symbol.prototype.toString.call(r):typeof r!="string"&&(a=String(r)),t==="iso-8859-1")return escape(a).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<a.length;l+=Tn){const d=a.length>=Tn?a.slice(l,l+Tn):a,u=[];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===rd&&(h===40||h===41)){u[u.length]=d.charAt(g);continue}if(h<128){u[u.length]=Oe[h];continue}if(h<2048){u[u.length]=Oe[192|h>>6]+Oe[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=Oe[224|h>>12]+Oe[128|h>>6&63]+Oe[128|h&63];continue}g+=1,h=65536+((h&1023)<<10|d.charCodeAt(g)&1023),u[u.length]=Oe[240|h>>18]+Oe[128|h>>12&63]+Oe[128|h>>6&63]+Oe[128|h&63]}i+=u.join("")}return i};function od(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function $o(r,e){if(nd(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const ad=Object.prototype.hasOwnProperty,Ya={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},$e=Array.isArray,id=Array.prototype.push,Qa=function(r,e){id.apply(r,$e(e)?e:[e])},ld=Date.prototype.toISOString,de={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:sd,encodeValuesOnly:!1,format:rs,formatter:ns[rs],indices:!1,serializeDate(r){return ld.call(r)},skipNulls:!1,strictNullHandling:!1};function cd(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const On={};function Za(r,e,t,n,s,a,i,l,d,u,g,h,p,w,m,f,c,x){let b=r,y=x,_=0,S=!1;for(;(y=y.get(On))!==void 0&&!S;){const T=y.get(r);if(_+=1,typeof T<"u"){if(T===_)throw new RangeError("Cyclic object value");S=!0}typeof y.get(On)>"u"&&(_=0)}if(typeof u=="function"?b=u(e,b):b instanceof Date?b=p==null?void 0:p(b):t==="comma"&&$e(b)&&(b=$o(b,function(T){return T instanceof Date?p==null?void 0:p(T):T})),b===null){if(a)return d&&!f?d(e,de.encoder,c,"key",w):e;b=""}if(cd(b)||od(b)){if(d){const T=f?e:d(e,de.encoder,c,"key",w);return[(m==null?void 0:m(T))+"="+(m==null?void 0:m(d(b,de.encoder,c,"value",w)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(b)))]}const j=[];if(typeof b>"u")return j;let v;if(t==="comma"&&$e(b))f&&d&&(b=$o(b,d)),v=[{value:b.length>0?b.join(",")||null:void 0}];else if($e(u))v=u;else{const T=Object.keys(b);v=g?T.sort(g):T}const I=l?String(e).replace(/\./g,"%2E"):String(e),P=n&&$e(b)&&b.length===1?I+"[]":I;if(s&&$e(b)&&b.length===0)return P+"[]";for(let T=0;T<v.length;++T){const L=v[T],C=typeof L=="object"&&typeof L.value<"u"?L.value:b[L];if(i&&C===null)continue;const W=h&&l?L.replace(/\./g,"%2E"):L,B=$e(b)?typeof t=="function"?t(P,W):P:P+(h?"."+W:"["+W+"]");x.set(r,_);const z=new WeakMap;z.set(On,x),Qa(j,Za(C,B,t,n,s,a,i,l,t==="comma"&&f&&$e(b)?null:d,u,g,h,p,w,m,f,c,z))}return j}function dd(r=de){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||de.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=rs;if(typeof r.format<"u"){if(!ad.call(ns,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=ns[t];let s=de.filter;(typeof r.filter=="function"||$e(r.filter))&&(s=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in Ya?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=de.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:de.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:de.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:de.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:de.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?de.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:de.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:de.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:de.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:de.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:de.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:de.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:de.strictNullHandling}}function ud(r,e={}){let t=r;const n=dd(e);let s,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):$e(n.filter)&&(a=n.filter,s=a);const i=[];if(typeof t!="object"||t===null)return"";const l=Ya[n.arrayFormat],d=l==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const u=new WeakMap;for(let p=0;p<s.length;++p){const w=s[p];n.skipNulls&&t[w]===null||Qa(i,Za(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 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 wt="4.104.0";let Lo=!1,Xt,ei,ti,ss,ri,ni,si,oi,ai;function fd(r,e={auto:!1}){if(Lo)throw new Error(`you must \`import 'openai/shims/${r.kind}'\` before importing anything else from openai`);if(Xt)throw new Error(`can't \`import 'openai/shims/${r.kind}'\` after \`import 'openai/shims/${Xt}'\``);Lo=e.auto,Xt=r.kind,ei=r.fetch,ti=r.FormData,ss=r.File,ri=r.ReadableStream,ni=r.getMultipartRequestOptions,si=r.getDefaultAgent,oi=r.fileFromPath,ai=r.isFsReadStream}class hd{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function md({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,a;try{t=fetch,n=Request,s=Response,a=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:a,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 hd(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 ii=()=>{Xt||fd(md(),{auto:!0})};ii();class X extends Error{}class pe extends X{constructor(e,t,n,s){super(`${pe.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 a=t;this.code=a==null?void 0:a.code,this.param=a==null?void 0:a.param,this.type=a==null?void 0:a.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 on({message:n,cause:as(t)});const a=t==null?void 0:t.error;return e===400?new li(e,a,n,s):e===401?new ci(e,a,n,s):e===403?new di(e,a,n,s):e===404?new ui(e,a,n,s):e===409?new fi(e,a,n,s):e===422?new hi(e,a,n,s):e===429?new mi(e,a,n,s):e>=500?new gi(e,a,n,s):new pe(e,a,n,s)}}class Ne extends pe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class on extends pe{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ks extends on{constructor({message:e}={}){super({message:e??"Request timed out."})}}class li extends pe{}class ci extends pe{}class di extends pe{}class ui extends pe{}class fi extends pe{}class hi extends pe{}class mi extends pe{}class gi extends pe{}class pi extends X{constructor(){super("Could not parse response content as the length limit was reached")}}class xi extends X{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var vr=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},rt=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;class an{constructor(){je.set(this,void 0),this.buffer=new Uint8Array,vr(this,je,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 a;for(;(a=gd(this.buffer,rt(this,je,"f")))!=null;){if(a.carriage&&rt(this,je,"f")==null){vr(this,je,a.index,"f");continue}if(rt(this,je,"f")!=null&&(a.index!==rt(this,je,"f")+1||a.carriage)){s.push(this.decodeText(this.buffer.slice(0,rt(this,je,"f")-1))),this.buffer=this.buffer.slice(rt(this,je,"f")),vr(this,je,null,"f");continue}const i=rt(this,je,"f")!==null?a.preceding-1:a.preceding,l=this.decodeText(this.buffer.slice(0,i));s.push(l),this.buffer=this.buffer.slice(a.index),vr(this,je,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 X(`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 X(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new X("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
35
+ `):[]}}je=new WeakMap;an.NEWLINE_CHARS=new Set([`
36
+ `,"\r"]);an.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function gd(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 pd(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 bi(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 De{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 a=!1;try{for await(const i of xd(e,t))if(!a){if(i.data.startsWith("[DONE]")){a=!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 pe(void 0,l.error,void 0,ji(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 pe(void 0,l.error,l.message,void 0);yield{event:i.event,data:l}}}a=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{a||t.abort()}}return new De(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){const i=new an,l=bi(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*a(){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 De(a,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=n.next();e.push(i),t.push(i)}return a.shift()}});return[new De(()=>s(e),this.controller),new De(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new ri({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:a,done:i}=await t.next();if(i)return s.close();const l=n.encode(JSON.stringify(a)+`
37
+ `);s.enqueue(l)}catch(a){s.error(a)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}}async function*xd(r,e){if(!r.body)throw e.abort(),new X("Attempted to iterate over a response with no body");const t=new yd,n=new an,s=bi(r.body);for await(const a of bd(s))for(const i of n.decode(a)){const l=t.decode(i);l&&(yield l)}for(const a of n.flush()){const i=t.decode(a);i&&(yield i)}}async function*bd(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 a;for(;(a=pd(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class yd{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 a={event:this.event,data:this.data.join(`
38
+ `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=wd(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function wd(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}const yi=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",wi=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&ln(r),ln=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",vd=r=>wi(r)||yi(r)||ai(r);async function vi(r,e,t){var s;if(r=await r,wi(r))return r;if(yi(r)){const a=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");const i=ln(a)?[await a.arrayBuffer()]:[a];return new ss(i,e,t)}const n=await _d(r);if(e||(e=Cd(r)??"unknown_file"),!(t!=null&&t.type)){const a=(s=n[0])==null?void 0:s.type;typeof a=="string"&&(t={...t,type:a})}return new ss(n,e,t)}async function _d(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(ln(r))e.push(await r.arrayBuffer());else if(jd(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: ${Sd(r)}`);return e}function Sd(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Cd(r){var e;return Rn(r.name)||Rn(r.filename)||((e=Rn(r.path))==null?void 0:e.split(/[\\/]/).pop())}const Rn=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},jd=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Do=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody",ft=async r=>{const e=await Ad(r.body);return ni(e,r)},Ad=async r=>{const e=new ti;return await Promise.all(Object.entries(r||{}).map(([t,n])=>os(e,t,n))),e},os=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(vd(t)){const n=await vi(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>os(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>os(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 kd=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},Nd=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)},_r;ii();async function _i(r){var i;const{response:e}=r;if(r.options.stream)return Qe("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):De.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 Qe("response",e.status,e.url,e.headers,l),Si(l,e)}const a=await e.text();return Qe("response",e.status,e.url,e.headers,a),a}function Si(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 cn extends Promise{constructor(e,t=_i){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new cn(this.responsePromise,async t=>Si(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 Md{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:a}){this.baseURL=e,this.maxRetries=$n("maxRetries",t),this.timeout=$n("timeout",n),this.httpAgent=s,this.fetch=a??ei}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Od(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Dd()}`}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 a=s&&ln(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:a}}))}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 f;const n={...e},{method:s,path:a,query:i,headers:l={}}=n,d=ArrayBuffer.isView(n.body)||n.__binaryRequest&&typeof n.body=="string"?n.body:Do(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,u=this.calculateContentLength(d),g=this.buildURL(a,i);"timeout"in n&&$n("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const h=n.httpAgent??this.httpAgent??si(g),p=n.timeout+1e3;typeof((f=h==null?void 0:h.options)==null?void 0:f.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:u,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 a={};n&&(a["content-length"]=n);const i=this.defaultHeaders(e);return Wo(a,i),Wo(a,t),Do(e.body)&&Xt!=="node"&&delete a["content-type"],Cr(i,"x-stainless-retry-count")===void 0&&Cr(t,"x-stainless-retry-count")===void 0&&(a["x-stainless-retry-count"]=String(s)),Cr(i,"x-stainless-timeout")===void 0&&Cr(t,"x-stainless-timeout")===void 0&&e.timeout&&(a["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(a,t),a}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 pe.generate(e,t,n,s)}request(e,t=null){return new cn(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:a,url:i,timeout:l}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(a,{url:i,options:n}),Qe("request",i,n,a.headers),(h=n.signal)!=null&&h.aborted)throw new Ne;const d=new AbortController,u=await this.fetchWithTimeout(i,a,l,d).catch(as);if(u instanceof Error){if((p=n.signal)!=null&&p.aborted)throw new Ne;if(t)return this.retryRequest(n,t);throw u.name==="AbortError"?new ks:new on({cause:u})}const g=ji(u.headers);if(!u.ok){if(t&&this.shouldRetry(u)){const b=`retrying, ${t} attempts remaining`;return Qe(`response (error; ${b})`,u.status,i,g),this.retryRequest(n,t,g)}const w=await u.text().catch(b=>as(b).message),m=Rd(w),f=m?void 0:w;throw Qe(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,u.status,i,g,f),this.makeStatusError(u.status,m,f,g)}return{response:u,options:n,controller:d}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new Ed(this,n,e)}buildURL(e,t){const n=Ld(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Ai(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 X(`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:a,...i}=t||{};a&&a.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 a=n==null?void 0:n["retry-after-ms"];if(a){const l=parseFloat(a);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 or(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,i=Math.min(.5*Math.pow(2,a),8),l=1-Math.random()*.25;return i*l*1e3}getUserAgent(){return`${this.constructor.name}/JS ${wt}`}}class Ci{constructor(e,t,n,s){_r.set(this,void 0),kd(this,_r,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 X("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,a]of n)e.url.searchParams.set(s,a);t.query=void 0,t.path=e.url.toString()}return await Nd(this,_r,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(_r=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Ed extends cn{constructor(e,t,n){super(t,async s=>new n(e,s.response,await _i(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const ji=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),Id={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},ie=r=>typeof r=="object"&&r!==null&&!Ai(r)&&Object.keys(r).every(e=>ki(Id,e)),Pd=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":wt,"X-Stainless-OS":Uo(Deno.build.os),"X-Stainless-Arch":Fo(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((e=Deno.version)==null?void 0:e.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":wt,"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":wt,"X-Stainless-OS":Uo(process.platform),"X-Stainless-Arch":Fo(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const r=Td();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":wt,"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":wt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Td(){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,a=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const Fo=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Uo=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown");let Bo;const Od=()=>Bo??(Bo=Pd()),Rd=r=>{try{return JSON.parse(r)}catch{return}},$d=/^[a-z][a-z0-9+.-]*:/i,Ld=r=>$d.test(r),or=r=>new Promise(e=>setTimeout(e,r)),$n=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new X(`${r} must be an integer`);if(e<0)throw new X(`${r} must be a positive integer`);return e},as=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)},Sr=r=>{var e,t,n,s,a;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(a=(s=(n=Deno.env)==null?void 0:n.get)==null?void 0:s.call(n,r))==null?void 0:a.trim()};function Ai(r){if(!r)return!0;for(const e in r)return!1;return!0}function ki(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Wo(r,e){for(const t in e){if(!ki(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 Ho=new Set(["authorization","api-key"]);function Qe(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)Ho.has(l.toLowerCase())&&(i.headers[l]="REDACTED");return i}let a=null;for(const i in s)Ho.has(i.toLowerCase())&&(a??(a={...s}),a[i]="REDACTED");return a??s});console.log(`OpenAI:DEBUG:${r}`,...n)}}const Dd=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Fd=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Ud=r=>typeof(r==null?void 0:r.get)=="function",Cr=(r,e)=>{var n;const t=e.toLowerCase();if(Ud(r)){const s=((n=e[0])==null?void 0:n.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(a,i,l)=>i+l.toUpperCase());for(const a of[e,t,e.toUpperCase(),s]){const i=r.get(a);if(i)return i}}for(const[s,a]of Object.entries(r))if(s.toLowerCase()===t)return Array.isArray(a)?(a.length<=1||console.warn(`Received ${a.length} entries for the ${e} header, using the first entry.`),a[0]):a},Bd=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 Ln(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}class dn extends Ci{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 ue extends Ci{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 K{constructor(e){this._client=e}}let Ni=class extends K{list(e,t={},n){return ie(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Wd,{query:t,...n})}},un=class extends K{constructor(){super(...arguments),this.messages=new Ni(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 ie(e)?this.list({},e):this._client.getAPIList("/chat/completions",fn,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class fn extends ue{}class Wd extends ue{}un.ChatCompletionsPage=fn;un.Messages=Ni;let hn=class extends K{constructor(){super(...arguments),this.completions=new un(this._client)}};hn.Completions=un;hn.ChatCompletionsPage=fn;class Mi extends K{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 Ei extends K{create(e,t){return this._client.post("/audio/transcriptions",ft({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Ii extends K{create(e,t){return this._client.post("/audio/translations",ft({body:e,...t,__metadata:{model:e.model}}))}}class ar extends K{constructor(){super(...arguments),this.transcriptions=new Ei(this._client),this.translations=new Ii(this._client),this.speech=new Mi(this._client)}}ar.Transcriptions=Ei;ar.Translations=Ii;ar.Speech=Mi;class Ns extends K{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 ie(e)?this.list({},e):this._client.getAPIList("/batches",Ms,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class Ms extends ue{}Ns.BatchesPage=Ms;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},ae=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)},is,Rr,$r,Ht,qt,Lr,zt,We,Jt,Gr,Xr,vt,Pi;class Es{constructor(){is.add(this),this.controller=new AbortController,Rr.set(this,void 0),$r.set(this,()=>{}),Ht.set(this,()=>{}),qt.set(this,void 0),Lr.set(this,()=>{}),zt.set(this,()=>{}),We.set(this,{}),Jt.set(this,!1),Gr.set(this,!1),Xr.set(this,!1),vt.set(this,!1),Me(this,Rr,new Promise((e,t)=>{Me(this,$r,e,"f"),Me(this,Ht,t,"f")}),"f"),Me(this,qt,new Promise((e,t)=>{Me(this,Lr,e,"f"),Me(this,zt,t,"f")}),"f"),ae(this,Rr,"f").catch(()=>{}),ae(this,qt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},ae(this,is,"m",Pi).bind(this))},0)}_connected(){this.ended||(ae(this,$r,"f").call(this),this._emit("connect"))}get ended(){return ae(this,Jt,"f")}get errored(){return ae(this,Gr,"f")}get aborted(){return ae(this,Xr,"f")}abort(){this.controller.abort()}on(e,t){return(ae(this,We,"f")[e]||(ae(this,We,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=ae(this,We,"f")[e];if(!n)return this;const s=n.findIndex(a=>a.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(ae(this,We,"f")[e]||(ae(this,We,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Me(this,vt,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){Me(this,vt,!0,"f"),await ae(this,qt,"f")}_emit(e,...t){if(ae(this,Jt,"f"))return;e==="end"&&(Me(this,Jt,!0,"f"),ae(this,Lr,"f").call(this));const n=ae(this,We,"f")[e];if(n&&(ae(this,We,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!ae(this,vt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),ae(this,Ht,"f").call(this,s),ae(this,zt,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!ae(this,vt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),ae(this,Ht,"f").call(this,s),ae(this,zt,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Rr=new WeakMap,$r=new WeakMap,Ht=new WeakMap,qt=new WeakMap,Lr=new WeakMap,zt=new WeakMap,We=new WeakMap,Jt=new WeakMap,Gr=new WeakMap,Xr=new WeakMap,vt=new WeakMap,is=new WeakSet,Pi=function(e){if(Me(this,Gr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Ne),e instanceof Ne)return Me(this,Xr,!0,"f"),this._emit("abort",e);if(e instanceof X)return this._emit("error",e);if(e instanceof Error){const t=new X(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new X(String(e)))};var G=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=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},ge,ls,Le,Dr,Ee,at,_t,ot,Kr,Ae,Fr,Ur,Kt,Vt,Gt,qo,zo,Jo,Vo,Go,Xo,Ko;class Ie extends Es{constructor(){super(...arguments),ge.add(this),ls.set(this,[]),Le.set(this,{}),Dr.set(this,{}),Ee.set(this,void 0),at.set(this,void 0),_t.set(this,void 0),ot.set(this,void 0),Kr.set(this,void 0),Ae.set(this,void 0),Fr.set(this,void 0),Ur.set(this,void 0),Kt.set(this,void 0)}[(ls=new WeakMap,Le=new WeakMap,Dr=new WeakMap,Ee=new WeakMap,at=new WeakMap,_t=new WeakMap,ot=new WeakMap,Kr=new WeakMap,Ae=new WeakMap,Fr=new WeakMap,Ur=new WeakMap,Kt=new WeakMap,ge=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const a=t.shift();a?a.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 a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,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 a;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=De.fromReadableStream(e,this.controller);for await(const i of s)G(this,ge,"m",Vt).call(this,i);if((a=s.controller.signal)!=null&&a.aborted)throw new Ne;return this._addRun(G(this,ge,"m",Gt).call(this))}toReadableStream(){return new De(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,a){const i=new Ie;return i._run(()=>i._runToolAssistantStream(e,t,n,s,{...a,headers:{...a==null?void 0:a.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,n,s,a){var u;const i=a==null?void 0:a.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,{...a,signal:this.controller.signal});this._connected();for await(const g of d)G(this,ge,"m",Vt).call(this,g);if((u=d.controller.signal)!=null&&u.aborted)throw new Ne;return this._addRun(G(this,ge,"m",Gt).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 a=new Ie;return a._run(()=>a._runAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return G(this,Fr,"f")}currentRun(){return G(this,Ur,"f")}currentMessageSnapshot(){return G(this,Ee,"f")}currentRunStepSnapshot(){return G(this,Kt,"f")}async finalRunSteps(){return await this.done(),Object.values(G(this,Le,"f"))}async finalMessages(){return await this.done(),Object.values(G(this,Dr,"f"))}async finalRun(){if(await this.done(),!G(this,at,"f"))throw Error("Final run was not received.");return G(this,at,"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 a={...t,stream:!0},i=await e.createAndRun(a,{...n,signal:this.controller.signal});this._connected();for await(const d of i)G(this,ge,"m",Vt).call(this,d);if((l=i.controller.signal)!=null&&l.aborted)throw new Ne;return this._addRun(G(this,ge,"m",Gt).call(this))}async _createAssistantStream(e,t,n,s){var d;const a=s==null?void 0:s.signal;a&&(a.aborted&&this.controller.abort(),a.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)G(this,ge,"m",Vt).call(this,u);if((d=l.controller.signal)!=null&&d.aborted)throw new Ne;return this._addRun(G(this,ge,"m",Gt).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let a=e[n];if(a==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(Ln(a)&&Ln(s))a=this.accumulateDelta(a,s);else if(Array.isArray(a)&&Array.isArray(s)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...s);continue}for(const i of s){if(!Ln(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=a[l];d==null?a.push(i):a[l]=this.accumulateDelta(d,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${a}`);e[n]=a}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,a){return await this._createToolAssistantStream(n,e,t,s,a)}}Vt=function(e){if(!this.ended)switch(Ce(this,Fr,e,"f"),G(this,ge,"m",Jo).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":G(this,ge,"m",Ko).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":G(this,ge,"m",zo).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":G(this,ge,"m",qo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Gt=function(){if(this.ended)throw new X("stream has ended, this shouldn't happen");if(!G(this,at,"f"))throw Error("Final run has not been received");return G(this,at,"f")},qo=function(e){const[t,n]=G(this,ge,"m",Go).call(this,e,G(this,Ee,"f"));Ce(this,Ee,t,"f"),G(this,Dr,"f")[t.id]=t;for(const s of n){const a=t.content[s.index];(a==null?void 0:a.type)=="text"&&this._emit("textCreated",a.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 a=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=G(this,_t,"f")){if(G(this,ot,"f"))switch(G(this,ot,"f").type){case"text":this._emit("textDone",G(this,ot,"f").text,G(this,Ee,"f"));break;case"image_file":this._emit("imageFileDone",G(this,ot,"f").image_file,G(this,Ee,"f"));break}Ce(this,_t,s.index,"f")}Ce(this,ot,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(G(this,_t,"f")!==void 0){const s=e.data.content[G(this,_t,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,G(this,Ee,"f"));break;case"text":this._emit("textDone",s.text,G(this,Ee,"f"));break}}G(this,Ee,"f")&&this._emit("messageDone",e.data),Ce(this,Ee,void 0,"f")}},zo=function(e){const t=G(this,ge,"m",Vo).call(this,e);switch(Ce(this,Kt,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 a of n.step_details.tool_calls)a.index==G(this,Kr,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(G(this,Ae,"f")&&this._emit("toolCallDone",G(this,Ae,"f")),Ce(this,Kr,a.index,"f"),Ce(this,Ae,t.step_details.tool_calls[a.index],"f"),G(this,Ae,"f")&&this._emit("toolCallCreated",G(this,Ae,"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":Ce(this,Kt,void 0,"f"),e.data.step_details.type=="tool_calls"&&G(this,Ae,"f")&&(this._emit("toolCallDone",G(this,Ae,"f")),Ce(this,Ae,void 0,"f")),this._emit("runStepDone",e.data,t);break}},Jo=function(e){G(this,ls,"f").push(e),this._emit("event",e)},Vo=function(e){switch(e.event){case"thread.run.step.created":return G(this,Le,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=G(this,Le,"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);G(this,Le,"f")[e.data.id]=s}return G(this,Le,"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":G(this,Le,"f")[e.data.id]=e.data;break}if(G(this,Le,"f")[e.data.id])return G(this,Le,"f")[e.data.id];throw new Error("No snapshot available")},Go=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 a of s.delta.content)if(a.index in t.content){let i=t.content[a.index];t.content[a.index]=G(this,ge,"m",Xo).call(this,a,i)}else t.content[a.index]=a,n.push(a);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")},Xo=function(e,t){return Ie.accumulateDelta(t,e)},Ko=function(e){switch(Ce(this,Ur,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":Ce(this,at,e.data,"f"),G(this,Ae,"f")&&(this._emit("toolCallDone",G(this,Ae,"f")),Ce(this,Ae,void 0,"f"));break}};class Is extends K{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 ie(e)?this.list({},e):this._client.getAPIList("/assistants",Ps,{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 Ps extends ue{}Is.AssistantsPage=Ps;function Yo(r){return typeof r.parse=="function"}const St=r=>(r==null?void 0:r.role)==="assistant",Ti=r=>(r==null?void 0:r.role)==="function",Oi=r=>(r==null?void 0:r.role)==="tool";function Ts(r){return(r==null?void 0:r.$brand)==="auto-parseable-response-format"}function ir(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function Hd(r,e){return!e||!Ri(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}}))}:Os(r,e)}function Os(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new pi;if(n.finish_reason==="content_filter")throw new xi;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(a=>zd(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?qd(e,n.message.content):null}}});return{...r,choices:t}}function qd(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 zd(r,e){var n;const t=(n=r.tools)==null?void 0:n.find(s=>{var a;return((a=s.function)==null?void 0:a.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:ir(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function Jd(r,e){var n;if(!r)return!1;const t=(n=r.tools)==null?void 0:n.find(s=>{var a;return((a=s.function)==null?void 0:a.name)===e.function.name});return ir(t)||(t==null?void 0:t.function.strict)||!1}function Ri(r){var e;return Ts(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>ir(t)||t.type==="function"&&t.function.strict===!0))??!1}function Vd(r){for(const e of r??[]){if(e.type!=="function")throw new X(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new X(`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)},xe,cs,Yr,ds,us,fs,$i,hs;const Qo=10;class Li extends Es{constructor(){super(...arguments),xe.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),(Ti(e)||Oi(e))&&e.content)this._emit("functionCallResult",e.content);else if(St(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(St(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 X("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),ye(this,xe,"m",cs).call(this)}async finalMessage(){return await this.done(),ye(this,xe,"m",Yr).call(this)}async finalFunctionCall(){return await this.done(),ye(this,xe,"m",ds).call(this)}async finalFunctionCallResult(){return await this.done(),ye(this,xe,"m",us).call(this)}async totalUsage(){return await this.done(),ye(this,xe,"m",fs).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=ye(this,xe,"m",Yr).call(this);t&&this._emit("finalMessage",t);const n=ye(this,xe,"m",cs).call(this);n&&this._emit("finalContent",n);const s=ye(this,xe,"m",ds).call(this);s&&this._emit("finalFunctionCall",s);const a=ye(this,xe,"m",us).call(this);a!=null&&this._emit("finalFunctionCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",ye(this,xe,"m",fs).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,xe,"m",$i).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Os(a,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:a="auto",stream:i,...l}=t,d=typeof a!="string"&&(a==null?void 0:a.name),{maxChatCompletions:u=Qo}=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<u;++w){const f=(p=(await this._createChatCompletion(e,{...l,function_call:a,functions:h,messages:[...this.messages]},n)).choices[0])==null?void 0:p.message;if(!f)throw new X("missing message in ChatCompletion response");if(!f.function_call)return;const{name:c,arguments:x}=f.function_call,b=g[c];if(b){if(d&&d!==c){const j=`Invalid function_call: ${JSON.stringify(c)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,name:c,content:j});continue}}else{const j=`Invalid function_call: ${JSON.stringify(c)}. Available options are: ${h.map(v=>JSON.stringify(v.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:c,content:j});continue}let y;try{y=Yo(b)?await b.parse(x):x}catch(j){this._addMessage({role:s,name:c,content:j instanceof Error?j.message:String(j)});continue}const _=await b.function(y,this),S=ye(this,xe,"m",hs).call(this,_);if(this._addMessage({role:s,name:c,content:S}),d)return}}async _runTools(e,t,n){var w,m,f;const s="tool",{tool_choice:a="auto",stream:i,...l}=t,d=typeof a!="string"&&((w=a==null?void 0:a.function)==null?void 0:w.name),{maxChatCompletions:u=Qo}=n||{},g=t.tools.map(c=>{if(ir(c)){if(!c.$callback)throw new X("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<u;++c){const b=(m=(await this._createChatCompletion(e,{...l,tool_choice:a,tools:p,messages:[...this.messages]},n)).choices[0])==null?void 0:m.message;if(!b)throw new X("missing message in ChatCompletion response");if(!((f=b.tool_calls)!=null&&f.length))return;for(const y of b.tool_calls){if(y.type!=="function")continue;const _=y.id,{name:S,arguments:j}=y.function,v=h[S];if(v){if(d&&d!==S){const L=`Invalid tool_call: ${JSON.stringify(S)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,tool_call_id:_,content:L});continue}}else{const L=`Invalid tool_call: ${JSON.stringify(S)}. Available options are: ${Object.keys(h).map(C=>JSON.stringify(C)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:_,content:L});continue}let I;try{I=Yo(v)?await v.parse(j):j}catch(L){const C=L instanceof Error?L.message:String(L);this._addMessage({role:s,tool_call_id:_,content:C});continue}const P=await v.function(I,this),T=ye(this,xe,"m",hs).call(this,P);if(this._addMessage({role:s,tool_call_id:_,content:T}),d)return}}}}xe=new WeakSet,cs=function(){return ye(this,xe,"m",Yr).call(this).content??null},Yr=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(St(t)){const{function_call:n,...s}=t,a={...s,content:t.content??null,refusal:t.refusal??null};return n&&(a.function_call=n),a}}throw new X("stream ended without producing a ChatCompletionMessage with role=assistant")},ds=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const s=this.messages[n];if(St(s)&&(s!=null&&s.function_call))return s.function_call;if(St(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},us=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ti(t)&&t.content!=null||Oi(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(a=>a.type==="function"&&a.id===t.tool_call_id))}))return t.content}},fs=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},$i=function(e){if(e.n!=null&&e.n>1)throw new X("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},hs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class tr extends Li{static runFunctions(e,t,n){const s=new tr,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,a)),s}static runTools(e,t,n){const s=new tr,a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}_addMessage(e,t=!0){super._addMessage(e,t),St(e)&&e.content&&this._emit("content",e.content)}}const Di=1,Fi=2,Ui=4,Bi=8,Wi=16,Hi=32,qi=64,zi=128,Ji=256,Vi=zi|Ji,Gi=Wi|Hi|Vi|qi,Xi=Di|Fi|Gi,Ki=Ui|Bi,Gd=Xi|Ki,fe={STR:Di,NUM:Fi,ARR:Ui,OBJ:Bi,NULL:Wi,BOOL:Hi,NAN:qi,INFINITY:zi,MINUS_INFINITY:Ji,INF:Vi,SPECIAL:Gi,ATOM:Xi,COLLECTION:Ki,ALL:Gd};class Xd extends Error{}class Kd extends Error{}function Yd(r,e=fe.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Qd(r.trim(),e)}const Qd=(r,e)=>{const t=r.length;let n=0;const s=p=>{throw new Xd(`${p} at position ${n}`)},a=p=>{throw new Kd(`${p} at position ${n}`)},i=()=>(h(),n>=t&&s("Unexpected end of input"),r[n]==='"'?l():r[n]==="{"?d():r[n]==="["?u():r.substring(n,n+4)==="null"||fe.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||fe.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||fe.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||fe.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||fe.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||fe.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){a(String(m))}else if(fe.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&&fe.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(fe.OBJ&e)return p;throw m}h(),r[n]===","&&n++}}catch{if(fe.OBJ&e)return p;s("Expected '}' at end of object")}return n++,p},u=()=>{n++;const p=[];try{for(;r[n]!=="]";)p.push(i()),h(),r[n]===","&&n++}catch{if(fe.ARR&e)return p;s("Expected ']' at end of array")}return n++,p},g=()=>{if(n===0){r==="-"&&fe.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(w){if(fe.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}a(String(w))}}const p=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(fe.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(p,n))}catch{r.substring(p,n)==="-"&&fe.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(p,r.lastIndexOf("e")))}catch(m){a(String(m))}}},h=()=>{for(;n<t&&`
39
+ \r `.includes(r[n]);)n++};return i()},Zo=r=>Yd(r,fe.ALL^fe.NUM);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},ne=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,Ue,pt,Je,Dn,jr,Fn,Un,Bn,Ar,Wn,ea;class rr extends Li{constructor(e){super(),ce.add(this),Ue.set(this,void 0),pt.set(this,void 0),Je.set(this,void 0),gt(this,Ue,e,"f"),gt(this,pt,[],"f")}get currentChatCompletionSnapshot(){return ne(this,Je,"f")}static fromReadableStream(e){const t=new rr(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new rr(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())),ne(this,ce,"m",Dn).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of a)ne(this,ce,"m",Fn).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new Ne;return this._addChatCompletion(ne(this,ce,"m",Ar).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())),ne(this,ce,"m",Dn).call(this),this._connected();const s=De.fromReadableStream(e,this.controller);let a;for await(const l of s)a&&a!==l.id&&this._addChatCompletion(ne(this,ce,"m",Ar).call(this)),ne(this,ce,"m",Fn).call(this,l),a=l.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Ne;return this._addChatCompletion(ne(this,ce,"m",Ar).call(this))}[(Ue=new WeakMap,pt=new WeakMap,Je=new WeakMap,ce=new WeakSet,Dn=function(){this.ended||gt(this,Je,void 0,"f")},jr=function(t){let n=ne(this,pt,"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},ne(this,pt,"f")[t.index]=n,n)},Fn=function(t){var s,a,i,l,d,u,g,h,p,w,m,f,c,x,b;if(this.ended)return;const n=ne(this,ce,"m",ea).call(this,t);this._emit("chunk",t,n);for(const y of t.choices){const _=n.choices[y.index];y.delta.content!=null&&((s=_.message)==null?void 0:s.role)==="assistant"&&((a=_.message)!=null&&a.content)&&(this._emit("content",y.delta.content,_.message.content),this._emit("content.delta",{delta:y.delta.content,snapshot:_.message.content,parsed:_.message.parsed})),y.delta.refusal!=null&&((i=_.message)==null?void 0:i.role)==="assistant"&&((l=_.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:y.delta.refusal,snapshot:_.message.refusal}),((d=y.logprobs)==null?void 0:d.content)!=null&&((u=_.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(g=y.logprobs)==null?void 0:g.content,snapshot:((h=_.logprobs)==null?void 0:h.content)??[]}),((p=y.logprobs)==null?void 0:p.refusal)!=null&&((w=_.message)==null?void 0:w.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(m=y.logprobs)==null?void 0:m.refusal,snapshot:((f=_.logprobs)==null?void 0:f.refusal)??[]});const S=ne(this,ce,"m",jr).call(this,_);_.finish_reason&&(ne(this,ce,"m",Bn).call(this,_),S.current_tool_call_index!=null&&ne(this,ce,"m",Un).call(this,_,S.current_tool_call_index));for(const j of y.delta.tool_calls??[])S.current_tool_call_index!==j.index&&(ne(this,ce,"m",Bn).call(this,_),S.current_tool_call_index!=null&&ne(this,ce,"m",Un).call(this,_,S.current_tool_call_index)),S.current_tool_call_index=j.index;for(const j of y.delta.tool_calls??[]){const v=(c=_.message.tool_calls)==null?void 0:c[j.index];v!=null&&v.type&&((v==null?void 0:v.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(x=v.function)==null?void 0:x.name,index:j.index,arguments:v.function.arguments,parsed_arguments:v.function.parsed_arguments,arguments_delta:((b=j.function)==null?void 0:b.arguments)??""}):(v==null||v.type,void 0))}}},Un=function(t,n){var i,l,d;if(ne(this,ce,"m",jr).call(this,t).done_tool_calls.has(n))return;const a=(i=t.message.tool_calls)==null?void 0:i[n];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const u=(d=(l=ne(this,Ue,"f"))==null?void 0:l.tools)==null?void 0:d.find(g=>g.type==="function"&&g.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:n,arguments:a.function.arguments,parsed_arguments:ir(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},Bn=function(t){var s,a;const n=ne(this,ce,"m",jr).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=ne(this,ce,"m",Wn).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})),(a=t.logprobs)!=null&&a.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Ar=function(){if(this.ended)throw new X("stream has ended, this shouldn't happen");const t=ne(this,Je,"f");if(!t)throw new X("request ended without sending any chunks");return gt(this,Je,void 0,"f"),gt(this,pt,[],"f"),Zd(t,ne(this,Ue,"f"))},Wn=function(){var n;const t=(n=ne(this,Ue,"f"))==null?void 0:n.response_format;return Ts(t)?t:null},ea=function(t){var n,s,a,i;let l=ne(this,Je,"f");const{choices:d,...u}=t;l?Object.assign(l,u):l=gt(this,Je,{...u,choices:[]},"f");for(const{delta:g,finish_reason:h,index:p,logprobs:w=null,...m}of t.choices){let f=l.choices[p];if(f||(f=l.choices[p]={finish_reason:h,index:p,message:{},logprobs:w,...m}),w)if(!f.logprobs)f.logprobs=Object.assign({},w);else{const{content:j,refusal:v,...I}=w;Object.assign(f.logprobs,I),j&&((n=f.logprobs).content??(n.content=[]),f.logprobs.content.push(...j)),v&&((s=f.logprobs).refusal??(s.refusal=[]),f.logprobs.refusal.push(...v))}if(h&&(f.finish_reason=h,ne(this,Ue,"f")&&Ri(ne(this,Ue,"f")))){if(h==="length")throw new pi;if(h==="content_filter")throw new xi}if(Object.assign(f,m),!g)continue;const{content:c,refusal:x,function_call:b,role:y,tool_calls:_,...S}=g;if(Object.assign(f.message,S),x&&(f.message.refusal=(f.message.refusal||"")+x),y&&(f.message.role=y),b&&(f.message.function_call?(b.name&&(f.message.function_call.name=b.name),b.arguments&&((a=f.message.function_call).arguments??(a.arguments=""),f.message.function_call.arguments+=b.arguments)):f.message.function_call=b),c&&(f.message.content=(f.message.content||"")+c,!f.message.refusal&&ne(this,ce,"m",Wn).call(this)&&(f.message.parsed=Zo(f.message.content))),_){f.message.tool_calls||(f.message.tool_calls=[]);for(const{index:j,id:v,type:I,function:P,...T}of _){const L=(i=f.message.tool_calls)[j]??(i[j]={});Object.assign(L,T),v&&(L.id=v),I&&(L.type=I),P&&(L.function??(L.function={name:P.name??"",arguments:""})),P!=null&&P.name&&(L.function.name=P.name),P!=null&&P.arguments&&(L.function.arguments+=P.arguments,Jd(ne(this,Ue,"f"),L)&&(L.function.parsed_arguments=Zo(L.function.arguments)))}}}return l},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",s=>{const a=t.shift();a?a.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 a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new De(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Zd(r,e){const{id:t,choices:n,created:s,model:a,system_fingerprint:i,...l}=r,d={...l,id:t,choices:n.map(({message:u,finish_reason:g,index:h,logprobs:p,...w})=>{if(!g)throw new X(`missing finish_reason for choice ${h}`);const{content:m=null,function_call:f,tool_calls:c,...x}=u,b=u.role;if(!b)throw new X(`missing role for choice ${h}`);if(f){const{arguments:y,name:_}=f;if(y==null)throw new X(`missing function_call.arguments for choice ${h}`);if(!_)throw new X(`missing function_call.name for choice ${h}`);return{...w,message:{content:m,function_call:{arguments:y,name:_},role:b,refusal:u.refusal??null},finish_reason:g,index:h,logprobs:p}}return c?{...w,index:h,finish_reason:g,logprobs:p,message:{...x,role:b,content:m,refusal:u.refusal??null,tool_calls:c.map((y,_)=>{const{function:S,type:j,id:v,...I}=y,{arguments:P,name:T,...L}=S||{};if(v==null)throw new X(`missing choices[${h}].tool_calls[${_}].id
40
+ ${kr(r)}`);if(j==null)throw new X(`missing choices[${h}].tool_calls[${_}].type
41
+ ${kr(r)}`);if(T==null)throw new X(`missing choices[${h}].tool_calls[${_}].function.name
42
+ ${kr(r)}`);if(P==null)throw new X(`missing choices[${h}].tool_calls[${_}].function.arguments
43
+ ${kr(r)}`);return{...I,id:v,type:j,function:{...L,name:T,arguments:P}}})}}:{...w,message:{...x,content:m,role:b,refusal:u.refusal??null},finish_reason:g,index:h,logprobs:p}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Hd(d,e)}function kr(r){return JSON.stringify(r)}class Ct extends rr{static fromReadableStream(e){const t=new Ct(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new Ct(null),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,a)),s}static runTools(e,t,n){const s=new Ct(t),a={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}}let Yi=class extends K{parse(e,t){return Vd(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=>Os(n,e))}runFunctions(e,t){return e.stream?Ct.runFunctions(this._client,e,t):tr.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?Ct.runTools(this._client,e,t):tr.runTools(this._client,e,t)}stream(e,t){return rr.createChatCompletion(this._client,e,t)}};class ms extends K{constructor(){super(...arguments),this.completions=new Yi(this._client)}}(function(r){r.Completions=Yi})(ms||(ms={}));class Qi extends K{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Zi extends K{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 mn extends K{constructor(){super(...arguments),this.sessions=new Qi(this._client),this.transcriptionSessions=new Zi(this._client)}}mn.Sessions=Qi;mn.TranscriptionSessions=Zi;class Rs extends K{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 ie(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,$s,{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 $s extends ue{}Rs.MessagesPage=$s;class Ls extends K{retrieve(e,t,n,s={},a){return ie(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...a,headers:{"OpenAI-Beta":"assistants=v2",...a==null?void 0:a.headers}})}list(e,t,n={},s){return ie(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Ds,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}}class Ds extends ue{}Ls.RunStepsPage=Ds;let lr=class extends K{constructor(){super(...arguments),this.steps=new Ls(this._client)}create(e,t,n){const{include:s,...a}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:a,...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 ie(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Fs,{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:a,response:i}=await this.retrieve(e,t,{...n,headers:{...n==null?void 0:n.headers,...s}}).withResponse();switch(a.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 or(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}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 a=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,a.id,s)}submitToolOutputsStream(e,t,n,s){return Ie.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class Fs extends ue{}lr.RunsPage=Fs;lr.Steps=Ls;lr.RunStepsPage=Ds;class Mt extends K{constructor(){super(...arguments),this.runs=new lr(this._client),this.messages=new Rs(this._client)}create(e={},t){return ie(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)}}Mt.Runs=lr;Mt.RunsPage=Fs;Mt.Messages=Rs;Mt.MessagesPage=$s;class Et extends K{constructor(){super(...arguments),this.realtime=new mn(this._client),this.chat=new ms(this._client),this.assistants=new Is(this._client),this.threads=new Mt(this._client)}}Et.Realtime=mn;Et.Assistants=Is;Et.AssistantsPage=Ps;Et.Threads=Mt;class el extends K{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class tl extends K{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 gn=class extends K{constructor(){super(...arguments),this.content=new tl(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,ft({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return ie(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Us,{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 Us extends ue{}gn.FileListResponsesPage=Us;gn.Content=tl;class cr extends K{constructor(){super(...arguments),this.files=new gn(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 ie(e)?this.list({},e):this._client.getAPIList("/containers",Bs,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}}class Bs extends ue{}cr.ContainerListResponsesPage=Bs;cr.Files=gn;cr.FileListResponsesPage=Us;class rl extends K{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&Qe("Request","User defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?a:(Qe("response","Decoding base64 embeddings to float32 array"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const d=l.embedding;l.embedding=Bd(d)}),i)))}}class Ws extends K{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return ie(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Hs,{query:n,...s})}}class Hs extends ue{}Ws.OutputItemListResponsesPage=Hs;class dr extends K{constructor(){super(...arguments),this.outputItems=new Ws(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 ie(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,qs,{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 qs extends ue{}dr.RunListResponsesPage=qs;dr.OutputItems=Ws;dr.OutputItemListResponsesPage=Hs;class ur extends K{constructor(){super(...arguments),this.runs=new dr(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 ie(e)?this.list({},e):this._client.getAPIList("/evals",zs,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class zs extends ue{}ur.EvalListResponsesPage=zs;ur.Runs=dr;ur.RunListResponsesPage=qs;let Js=class extends K{create(e,t){return this._client.post("/files",ft({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return ie(e)?this.list({},e):this._client.getAPIList("/files",Vs,{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"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await or(t),i=await this.retrieve(e),Date.now()-a>n)throw new ks({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class Vs extends ue{}Js.FileObjectsPage=Vs;class nl extends K{}let sl=class extends K{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 Gs extends K{constructor(){super(...arguments),this.graders=new sl(this._client)}}Gs.Graders=sl;class Xs extends K{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Ks,{body:t,method:"post",...n})}retrieve(e,t={},n){return ie(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 Ks extends dn{}Xs.PermissionCreateResponsesPage=Ks;let pn=class extends K{constructor(){super(...arguments),this.permissions=new Xs(this._client)}};pn.Permissions=Xs;pn.PermissionCreateResponsesPage=Ks;class Ys extends K{list(e,t={},n){return ie(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,Qs,{query:t,...n})}}class Qs extends ue{}Ys.FineTuningJobCheckpointsPage=Qs;class It extends K{constructor(){super(...arguments),this.checkpoints=new Ys(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 ie(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",Zs,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return ie(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,eo,{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 Zs extends ue{}class eo extends ue{}It.FineTuningJobsPage=Zs;It.FineTuningJobEventsPage=eo;It.Checkpoints=Ys;It.FineTuningJobCheckpointsPage=Qs;class Ze extends K{constructor(){super(...arguments),this.methods=new nl(this._client),this.jobs=new It(this._client),this.checkpoints=new pn(this._client),this.alpha=new Gs(this._client)}}Ze.Methods=nl;Ze.Jobs=It;Ze.FineTuningJobsPage=Zs;Ze.FineTuningJobEventsPage=eo;Ze.Checkpoints=pn;Ze.Alpha=Gs;class ol extends K{}class to extends K{constructor(){super(...arguments),this.graderModels=new ol(this._client)}}to.GraderModels=ol;class al extends K{createVariation(e,t){return this._client.post("/images/variations",ft({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",ft({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class ro extends K{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",no,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class no extends dn{}ro.ModelsPage=no;class il extends K{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function eu(r,e){return!e||!ru(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)}:ll(r,e)}function ll(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:ou(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:tu(e,i.text)}:i);return{...s,content:a}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||cl(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const s of n.output)if(s.type==="message"){for(const a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),n}function tu(r,e){var t,n,s,a;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)?((a=r.text)==null?void 0:a.format).$parseRaw(e):JSON.parse(e)}function ru(r){var e;return!!Ts((e=r.text)==null?void 0:e.format)}function nu(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function su(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function ou(r,e){const t=su(r.tools??[],e.name);return{...e,...e,parsed_arguments:nu(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function cl(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 dl extends K{list(e,t={},n){return ie(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,iu,{query:t,...n})}}var xt=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},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)},bt,Nr,Ge,Mr,ta,ra,na,sa;class so extends Es{constructor(e){super(),bt.add(this),Nr.set(this,void 0),Ge.set(this,void 0),Mr.set(this,void 0),xt(this,Nr,e,"f")}static createResponse(e,t,n){const s=new so(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())),Ve(this,bt,"m",ta).call(this);let a,i=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const d of a)Ve(this,bt,"m",ra).call(this,d,i);if((l=a.controller.signal)!=null&&l.aborted)throw new Ne;return Ve(this,bt,"m",na).call(this)}[(Nr=new WeakMap,Ge=new WeakMap,Mr=new WeakMap,bt=new WeakSet,ta=function(){this.ended||xt(this,Ge,void 0,"f")},ra=function(t,n){if(this.ended)return;const s=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},a=Ve(this,bt,"m",sa).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const i=a.output[t.output_index];if(!i)throw new X(`missing output at index ${t.output_index}`);if(i.type==="message"){const l=i.content[t.content_index];if(!l)throw new X(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new X(`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=a.output[t.output_index];if(!i)throw new X(`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}},na=function(){if(this.ended)throw new X("stream has ended, this shouldn't happen");const t=Ve(this,Ge,"f");if(!t)throw new X("request ended without sending any events");xt(this,Ge,void 0,"f");const n=au(t,Ve(this,Nr,"f"));return xt(this,Mr,n,"f"),n},sa=function(t){let n=Ve(this,Ge,"f");if(!n){if(t.type!=="response.created")throw new X(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=xt(this,Ge,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 X(`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 X(`missing output at index ${t.output_index}`);if(s.type==="message"){const a=s.content[t.content_index];if(!a)throw new X(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new X(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const s=n.output[t.output_index];if(!s)throw new X(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{xt(this,Ge,t.response,"f");break}}return n},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const a=t.shift();a?a.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 a of t)a.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=Ve(this,Mr,"f");if(!e)throw new X("stream ended without producing a ChatCompletion");return e}}function au(r,e){return eu(r,e)}class oo extends K{constructor(){super(...arguments),this.inputItems=new dl(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"&&cl(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=>ll(n,e))}stream(e,t){return so.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 iu extends ue{}oo.InputItems=dl;class ul extends K{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,ft({body:t,...n}))}}class ao extends K{constructor(){super(...arguments),this.parts=new ul(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})}}ao.Parts=ul;const lu=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 xn extends K{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 ie(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,bn,{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 a=await this.retrieve(e,t,{...n,headers:s}).withResponse(),i=a.data;switch(i.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const d=a.response.headers.get("openai-poll-after-ms");if(d){const u=parseInt(d);isNaN(u)||(l=u)}}await or(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`,io,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class bn extends ue{}class io extends dn{}xn.VectorStoreFilesPage=bn;xn.FileContentResponsesPage=io;class fl extends K{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 ie(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,bn,{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:a,response:i}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(a.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 or(l);break;case"failed":case"cancelled":case"completed":return a}}}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 a=(s==null?void 0:s.maxConcurrency)??5,i=Math.min(a,t.length),l=this._client,d=t.values(),u=[...n];async function g(p){for(let w of p){const m=await l.files.create({file:w,purpose:"assistants"},s);u.push(m.id)}}const h=Array(i).fill(d).map(g);return await lu(h),await this.createAndPoll(e,{file_ids:u})}}class et extends K{constructor(){super(...arguments),this.files=new xn(this._client),this.fileBatches=new fl(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 ie(e)?this.list({},e):this._client.getAPIList("/vector_stores",lo,{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`,co,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class lo extends ue{}class co extends dn{}et.VectorStoresPage=lo;et.VectorStoreSearchResponsesPage=co;et.Files=xn;et.VectorStoreFilesPage=bn;et.FileContentResponsesPage=io;et.FileBatches=fl;var hl;class Y extends Md{constructor({baseURL:e=Sr("OPENAI_BASE_URL"),apiKey:t=Sr("OPENAI_API_KEY"),organization:n=Sr("OPENAI_ORG_ID")??null,project:s=Sr("OPENAI_PROJECT_ID")??null,...a}={}){if(t===void 0)throw new X("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,...a,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&Fd())throw new X(`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 Ji(this),this.chat=new on(this),this.embeddings=new Gi(this),this.files=new Ds(this),this.images=new Qi(this),this.audio=new Zt(this),this.moderations=new Zi(this),this.models=new Gs(this),this.fineTuning=new Xe(this),this.graders=new Vs(this),this.vectorStores=new Ke(this),this.beta=new At(this),this.batches=new ws(this),this.uploads=new Qs(this),this.responses=new Ys(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 ed(e,{arrayFormat:"brackets"})}}ol=Y;Y.OpenAI=ol;Y.DEFAULT_TIMEOUT=6e5;Y.OpenAIError=X;Y.APIError=ge;Y.APIConnectionError=Qr;Y.APIConnectionTimeoutError=ys;Y.APIUserAbortError=Ne;Y.NotFoundError=ni;Y.ConflictError=si;Y.RateLimitError=ai;Y.BadRequestError=ei;Y.AuthenticationError=ti;Y.InternalServerError=ii;Y.PermissionDeniedError=ri;Y.UnprocessableEntityError=oi;Y.toFile=hi;Y.fileFromPath=Ya;Y.Completions=Ji;Y.Chat=on;Y.ChatCompletionsPage=sn;Y.Embeddings=Gi;Y.Files=Ds;Y.FileObjectsPage=Fs;Y.Images=Qi;Y.Audio=Zt;Y.Moderations=Zi;Y.Models=Gs;Y.ModelsPage=Xs;Y.FineTuning=Xe;Y.Graders=Vs;Y.VectorStores=Ke;Y.VectorStoresPage=eo;Y.VectorStoreSearchResponsesPage=to;Y.Beta=At;Y.Batches=ws;Y.BatchesPage=vs;Y.Uploads=Qs;Y.Responses=Ys;Y.Evals=sr;Y.EvalListResponsesPage=Ls;Y.Containers=rr;Y.ContainerListResponsesPage=Ps;class al{constructor(e,t,n,s,a,i,l){V(this,"messages");V(this,"tools");V(this,"callback");V(this,"modelConfig");V(this,"configUrl");V(this,"abortController");V(this,"isAborted");V(this,"sessionId");this.messages=e,this.tools=t,this.callback=s,this.modelConfig=a,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 Y({apiKey:this.modelConfig.api_key,baseURL:this.configUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{"x-target-url":this.modelConfig.base_url}}),s=this.buildPayLoad(),a=await n.chat.completions.create({...s,stream:!0},{signal:this.abortController.signal});return await this.handleOpenAIStreamResponse(a,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,a;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")||(a=i.message)!=null&&a.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 el(this),this.chat=new hn(this),this.embeddings=new rl(this),this.files=new Js(this),this.images=new al(this),this.audio=new ar(this),this.moderations=new il(this),this.models=new ro(this),this.fineTuning=new Ze(this),this.graders=new to(this),this.vectorStores=new et(this),this.beta=new Et(this),this.batches=new Ns(this),this.uploads=new ao(this),this.responses=new oo(this),this.evals=new ur(this),this.containers=new cr(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 ud(e,{arrayFormat:"brackets"})}}hl=Y;Y.OpenAI=hl;Y.DEFAULT_TIMEOUT=6e5;Y.OpenAIError=X;Y.APIError=pe;Y.APIConnectionError=on;Y.APIConnectionTimeoutError=ks;Y.APIUserAbortError=Ne;Y.NotFoundError=ui;Y.ConflictError=fi;Y.RateLimitError=mi;Y.BadRequestError=li;Y.AuthenticationError=ci;Y.InternalServerError=gi;Y.PermissionDeniedError=di;Y.UnprocessableEntityError=hi;Y.toFile=vi;Y.fileFromPath=oi;Y.Completions=el;Y.Chat=hn;Y.ChatCompletionsPage=fn;Y.Embeddings=rl;Y.Files=Js;Y.FileObjectsPage=Vs;Y.Images=al;Y.Audio=ar;Y.Moderations=il;Y.Models=ro;Y.ModelsPage=no;Y.FineTuning=Ze;Y.Graders=to;Y.VectorStores=et;Y.VectorStoresPage=lo;Y.VectorStoreSearchResponsesPage=co;Y.Beta=Et;Y.Batches=Ns;Y.BatchesPage=Ms;Y.Uploads=ao;Y.Responses=oo;Y.Evals=ur;Y.EvalListResponsesPage=zs;Y.Containers=cr;Y.ContainerListResponsesPage=Bs;class ml{constructor(e,t,n,s,a,i,l){V(this,"messages");V(this,"tools");V(this,"callback");V(this,"modelConfig");V(this,"configUrl");V(this,"abortController");V(this,"isAborted");V(this,"sessionId");this.messages=e,this.tools=t,this.callback=s,this.modelConfig=a,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 Y({apiKey:this.modelConfig.api_key,baseURL:this.configUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{"x-target-url":this.modelConfig.base_url}}),s=this.buildPayLoad(),a=await n.chat.completions.create({...s,stream:!0},{signal:this.abortController.signal});return await this.handleOpenAIStreamResponse(a,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,a;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")||(a=i.message)!=null&&a.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 a=t.tool_calls||t.function_calls||[];a.length>0&&(console.log("Converting tool calls for assistant message:",a),s.tool_calls=a.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 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 g={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:",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 Qd{constructor(e,t,n,s,a,i="/api"){V(this,"messageManager");V(this,"modelConfig");V(this,"conversationId");V(this,"callback");V(this,"sessionId");V(this,"configUrl");this.messageManager=e,this.modelConfig=t,this.conversationId=n,this.callback=s,this.sessionId=a||n,this.configUrl=i}async processToolResult(e,t){const n=e;debugger;const s=(n.content||"").length,a=s>1e3;let i=n.content||"";if(a)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:a?i:void 0,status:"completed",createdAt:new Date,metadata:{tool_call_id:n.tool_call_id,tool_name:n.tool_name,is_summarized:a,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:a}}}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 a=t.tool_calls||t.function_calls||[];a.length>0&&(console.log("Converting tool calls for assistant message:",a),s.tool_calls=a.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 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 g={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:",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 cu{constructor(e,t,n,s,a,i="/api"){V(this,"messageManager");V(this,"modelConfig");V(this,"conversationId");V(this,"callback");V(this,"sessionId");V(this,"configUrl");this.messageManager=e,this.modelConfig=t,this.conversationId=n,this.callback=s,this.sessionId=a||n,this.configUrl=i}async processToolResult(e,t){const n=e;debugger;const s=(n.content||"").length,a=s>1e3;let i=n.content||"";if(a)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:a?i:void 0,status:"completed",createdAt:new Date,metadata:{tool_call_id:n.tool_call_id,tool_name:n.tool_name,is_summarized:a,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:a}}}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 al(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 Yo{constructor(e,t,n,s,a,i,l,d,u,g){V(this,"messages");V(this,"conversationId");V(this,"tools");V(this,"modelConfig");V(this,"callBack");V(this,"mcpToolExecute");V(this,"configUrl");V(this,"isAborted");V(this,"currentAiRequestHandler");V(this,"toolResultProcessor");V(this,"sessionId");this.messages=e,this.conversationId=t,this.tools=n,this.modelConfig=s,this.callBack=a,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 Qd(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 a=[];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"})}a.push(g)}else{console.log(`Using regular execution for tool: ${d}`);const g=await this.mcpToolExecute.execute([l]);a.push(...g)}}if(this.isAborted){console.log("AiClient: Aborted after tool execution");return}const i=await this.toolResultProcessor.processToolResult(a[0],this.conversationId);debugger;if(this.messages.push(i),this.callBack("tool_result",a),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 al(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 il(r,e){return function(){return r.apply(e,arguments)}}const{toString:Zd}=Object.prototype,{getPrototypeOf:ro}=Object,{iterator:fn,toStringTag:ll}=Symbol,hn=(r=>e=>{const t=Zd.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Te=r=>(r=r.toLowerCase(),e=>hn(e)===r),mn=r=>e=>typeof e===r,{isArray:Nt}=Array,Ct=mn("undefined");function or(r){return r!==null&&!Ct(r)&&r.constructor!==null&&!Ct(r.constructor)&&ve(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const cl=Te("ArrayBuffer");function eu(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&cl(r.buffer),e}const tu=mn("string"),ve=mn("function"),dl=mn("number"),ar=r=>r!==null&&typeof r=="object",ru=r=>r===!0||r===!1,Or=r=>{if(hn(r)!=="object")return!1;const e=ro(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(ll in r)&&!(fn in r)},nu=r=>{if(!ar(r)||or(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},su=Te("Date"),ou=Te("File"),au=Te("Blob"),iu=Te("FileList"),lu=r=>ar(r)&&ve(r.pipe),cu=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||ve(r.append)&&((e=hn(r))==="formdata"||e==="object"&&ve(r.toString)&&r.toString()==="[object FormData]"))},du=Te("URLSearchParams"),[uu,fu,hu,mu]=["ReadableStream","Request","Response","Headers"].map(Te),gu=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 a=t?Object.getOwnPropertyNames(r):Object.keys(r),i=a.length;let l;for(n=0;n<i;n++)l=a[n],e.call(null,r[l],l,r)}}function ul(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,fl=r=>!Ct(r)&&r!==rt;function is(){const{caseless:r,skipUndefined:e}=fl(this)&&this||{},t={},n=(s,a)=>{const i=r&&ul(t,a)||a;Or(t[i])&&Or(s)?t[i]=is(t[i],s):Or(s)?t[i]=is({},s):Nt(s)?t[i]=s.slice():(!e||!Ct(s))&&(t[i]=s)};for(let s=0,a=arguments.length;s<a;s++)arguments[s]&&ir(arguments[s],n);return t}const pu=(r,e,t,{allOwnKeys:n}={})=>(ir(e,(s,a)=>{t&&ve(s)?r[a]=il(s,t):r[a]=s},{allOwnKeys:n}),r),xu=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),bu=(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,a,i;const l={};if(e=e||{},r==null)return e;do{for(s=Object.getOwnPropertyNames(r),a=s.length;a-- >0;)i=s[a],(!n||n(i,r,e))&&!l[i]&&(e[i]=r[i],l[i]=!0);r=t!==!1&&ro(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},wu=(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},vu=r=>{if(!r)return null;if(Nt(r))return r;let e=r.length;if(!dl(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},_u=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&ro(Uint8Array)),Su=(r,e)=>{const n=(r&&r[fn]).call(r);let s;for(;(s=n.next())&&!s.done;){const a=s.value;e.call(r,a[0],a[1])}},Cu=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},ju=Te("HTMLFormElement"),Au=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,s){return n.toUpperCase()+s}),Qo=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),ku=Te("RegExp"),hl=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};ir(t,(s,a)=>{let i;(i=e(s,a,r))!==!1&&(n[a]=i||s)}),Object.defineProperties(r,n)},Nu=r=>{hl(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+"'")})}})},Mu=(r,e)=>{const t={},n=s=>{s.forEach(a=>{t[a]=!0})};return Nt(r)?n(r):n(String(r).split(e)),t},Eu=()=>{},Iu=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function Tu(r){return!!(r&&ve(r.append)&&r[ll]==="FormData"&&r[fn])}const Pu=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 a=Nt(n)?[]:{};return ir(n,(i,l)=>{const d=t(i,s+1);!Ct(d)&&(a[l]=d)}),e[s]=void 0,a}}return n};return t(r,0)},Ou=Te("AsyncFunction"),Ru=r=>r&&(ar(r)||ve(r))&&ve(r.then)&&ve(r.catch),ml=((r,e)=>r?setImmediate:e?((t,n)=>(rt.addEventListener("message",({source:s,data:a})=>{s===rt&&a===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)),$u=typeof queueMicrotask<"u"?queueMicrotask.bind(rt):typeof process<"u"&&process.nextTick||ml,Lu=r=>r!=null&&ve(r[fn]),E={isArray:Nt,isArrayBuffer:cl,isBuffer:or,isFormData:cu,isArrayBufferView:eu,isString:tu,isNumber:dl,isBoolean:ru,isObject:ar,isPlainObject:Or,isEmptyObject:nu,isReadableStream:uu,isRequest:fu,isResponse:hu,isHeaders:mu,isUndefined:Ct,isDate:su,isFile:ou,isBlob:au,isRegExp:ku,isFunction:ve,isStream:lu,isURLSearchParams:du,isTypedArray:_u,isFileList:iu,forEach:ir,merge:is,extend:pu,trim:gu,stripBOM:xu,inherits:bu,toFlatObject:yu,kindOf:hn,kindOfTest:Te,endsWith:wu,toArray:vu,forEachEntry:Su,matchAll:Cu,isHTMLForm:ju,hasOwnProperty:Qo,hasOwnProp:Qo,reduceDescriptors:hl,freezeMethods:Nu,toObjectSet:Mu,toCamelCase:Au,noop:Eu,toFiniteNumber:Iu,findKey:ul,global:rt,isContextDefined:fl,isSpecCompliantForm:Tu,toJSONObject:Pu,isAsyncFn:Ou,isThenable:Ru,setImmediate:ml,asap:$u,isIterable:Lu};function Q(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(Q,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 gl=Q.prototype,pl={};["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=>{pl[r]={value:r}});Object.defineProperties(Q,pl);Object.defineProperty(gl,"isAxiosError",{value:!0});Q.from=(r,e,t,n,s,a)=>{const i=Object.create(gl);E.toFlatObject(r,i,function(g){return g!==Error.prototype},u=>u!=="isAxiosError");const l=r&&r.message?r.message:"Error",d=e==null&&r?r.code:e;return Q.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",a&&Object.assign(i,a),i};const Du=null;function ls(r){return E.isPlainObject(r)||E.isArray(r)}function xl(r){return E.endsWith(r,"[]")?r.slice(0,-2):r}function Zo(r,e,t){return r?r.concat(e).map(function(s,a){return s=xl(s),!t&&a?"["+s+"]":s}).join(t?".":""):e}function Fu(r){return E.isArray(r)&&!r.some(ls)}const Uu=E.toFlatObject(E,{},null,function(e){return/^is[A-Z]/.test(e)});function gn(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(f,c){return!E.isUndefined(c[f])});const n=t.metaTokens,s=t.visitor||g,a=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 u(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 Q("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,f,c){let x=m;if(m&&!c&&typeof m=="object"){if(E.endsWith(f,"{}"))f=n?f:f.slice(0,-2),m=JSON.stringify(m);else if(E.isArray(m)&&Fu(m)||(E.isFileList(m)||E.endsWith(f,"[]"))&&(x=E.toArray(m)))return f=xl(f),x.forEach(function(y,_){!(E.isUndefined(y)||y===null)&&e.append(i===!0?Zo([f],_,a):i===null?f:f+"[]",u(y))}),!1}return ls(m)?!0:(e.append(Zo(c,f,a),u(m)),!1)}const h=[],p=Object.assign(Uu,{defaultVisitor:g,convertValue:u,isVisitable:ls});function w(m,f){if(!E.isUndefined(m)){if(h.indexOf(m)!==-1)throw Error("Circular reference detected in "+f.join("."));h.push(m),E.forEach(m,function(x,b){(!(E.isUndefined(x)||x===null)&&s.call(e,x,E.isString(b)?b.trim():b,f,p))===!0&&w(x,f?f.concat(b):[b])}),h.pop()}}if(!E.isObject(r))throw new TypeError("data must be an object");return w(r),e}function ea(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function no(r,e){this._pairs=[],r&&gn(r,this,e)}const bl=no.prototype;bl.append=function(e,t){this._pairs.push([e,t])};bl.toString=function(e){const t=e?function(n){return e.call(this,n,ea)}:ea;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function Bu(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||Bu;E.isFunction(t)&&(t={serialize:t});const s=t&&t.serialize;let a;if(s?a=s(e,t):a=E.isURLSearchParams(e)?e.toString():new no(e,t).toString(n),a){const i=r.indexOf("#");i!==-1&&(r=r.slice(0,i)),r+=(r.indexOf("?")===-1?"?":"&")+a}return r}class ta{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 wl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Wu=typeof URLSearchParams<"u"?URLSearchParams:no,Hu=typeof FormData<"u"?FormData:null,qu=typeof Blob<"u"?Blob:null,zu={isBrowser:!0,classes:{URLSearchParams:Wu,FormData:Hu,Blob:qu},protocols:["http","https","file","blob","url","data"]},so=typeof window<"u"&&typeof document<"u",cs=typeof navigator=="object"&&navigator||void 0,Ju=so&&(!cs||["ReactNative","NativeScript","NS"].indexOf(cs.product)<0),Vu=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Gu=so&&window.location.href||"http://localhost",Xu=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:so,hasStandardBrowserEnv:Ju,hasStandardBrowserWebWorkerEnv:Vu,navigator:cs,origin:Gu},Symbol.toStringTag,{value:"Module"})),xe={...Xu,...zu};function Ku(r,e){return gn(r,new xe.classes.URLSearchParams,{visitor:function(t,n,s,a){return xe.isNode&&E.isBuffer(t)?(this.append(n,t.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...e})}function Yu(r){return E.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Qu(r){const e={},t=Object.keys(r);let n;const s=t.length;let a;for(n=0;n<s;n++)a=t[n],e[a]=r[a];return e}function vl(r){function e(t,n,s,a){let i=t[a++];if(i==="__proto__")return!0;const l=Number.isFinite(+i),d=a>=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],a)&&E.isArray(s[i])&&(s[i]=Qu(s[i])),!l)}if(E.isFormData(r)&&E.isFunction(r.entries)){const t={};return E.forEachEntry(r,(n,s)=>{e(Yu(n),s,t,0)}),t}return null}function Zu(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:wl,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",s=n.indexOf("application/json")>-1,a=E.isObject(e);if(a&&E.isHTMLForm(e)&&(e=new FormData(e)),E.isFormData(e))return s?JSON.stringify(vl(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(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Ku(e,this.formSerializer).toString();if((l=E.isFileList(e))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return gn(l?{"files[]":e}:e,d&&new d,this.formSerializer)}}return a||s?(t.setContentType("application/json",!1),Zu(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"?Q.from(l,Q.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 ef=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"]),tf=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]&&ef[t])&&(t==="set-cookie"?e[t]?e[t].push(n):e[t]=[n]:e[t]=e[t]?e[t]+", "+n:n)}),e},ra=Symbol("internals");function It(r){return r&&String(r).trim().toLowerCase()}function Rr(r){return r===!1||r==null?r:E.isArray(r)?r.map(Rr):String(r)}function rf(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 nf=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function Rn(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 sf(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function of(r,e){const t=E.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(r,n+t,{value:function(s,a,i){return this[n].call(this,e,s,a,i)},configurable:!0})})}let _e=class{constructor(e){e&&this.set(e)}set(e,t,n){const s=this;function a(l,d,u){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||u===!0||u===void 0&&s[h]!==!1)&&(s[h||d]=Rr(l))}const i=(l,d)=>E.forEach(l,(u,g)=>a(u,g,d));if(E.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(E.isString(e)&&(e=e.trim())&&!nf(e))i(tf(e),t);else if(E.isObject(e)&&E.isIterable(e)){let l={},d,u;for(const g of e){if(!E.isArray(g))throw TypeError("Object iterator must return a key-value pair");l[u=g[0]]=(d=l[u])?E.isArray(d)?[...d,g[1]]:[d,g[1]]:g[1]}i(l,t)}else e!=null&&a(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 rf(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||Rn(this,this[n],n,t)))}return!1}delete(e,t){const n=this;let s=!1;function a(i){if(i=It(i),i){const l=E.findKey(n,i);l&&(!t||Rn(n,n[l],l,t))&&(delete n[l],s=!0)}}return E.isArray(e)?e.forEach(a):a(e),s}clear(e){const t=Object.keys(this);let n=t.length,s=!1;for(;n--;){const a=t[n];(!e||Rn(this,this[a],a,e,!0))&&(delete this[a],s=!0)}return s}normalize(e){const t=this,n={};return E.forEach(this,(s,a)=>{const i=E.findKey(n,a);if(i){t[i]=Rr(s),delete t[a];return}const l=e?sf(a):String(a).trim();l!==a&&delete t[a],t[l]=Rr(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[ra]=this[ra]={accessors:{}}).accessors,s=this.prototype;function a(i){const l=It(i);n[l]||(of(s,i),n[l]=!0)}return E.isArray(e)?e.forEach(a):a(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 $n(r,e){const t=this||lr,n=e||t,s=_e.from(n.headers);let a=n.data;return E.forEach(r,function(l){a=l.call(t,a,s.normalize(),e?e.status:void 0)}),s.normalize(),a}function _l(r){return!!(r&&r.__CANCEL__)}function Mt(r,e,t){Q.call(this,r??"canceled",Q.ERR_CANCELED,e,t),this.name="CanceledError"}E.inherits(Mt,Q,{__CANCEL__:!0});function Sl(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new Q("Request failed with status code "+t.status,[Q.ERR_BAD_REQUEST,Q.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function af(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function lf(r,e){r=r||10;const t=new Array(r),n=new Array(r);let s=0,a=0,i;return e=e!==void 0?e:1e3,function(d){const u=Date.now(),g=n[a];i||(i=u),t[s]=d,n[s]=u;let h=a,p=0;for(;h!==s;)p+=t[h++],h=h%r;if(s=(s+1)%r,s===a&&(a=(a+1)%r),u-i<e)return;const w=g&&u-g;return w?Math.round(p*1e3/w):void 0}}function cf(r,e){let t=0,n=1e3/e,s,a;const i=(u,g=Date.now())=>{t=g,s=null,a&&(clearTimeout(a),a=null),r(...u)};return[(...u)=>{const g=Date.now(),h=g-t;h>=n?i(u,g):(s=u,a||(a=setTimeout(()=>{a=null,i(s)},n-h)))},()=>s&&i(s)]}const zr=(r,e,t=3)=>{let n=0;const s=lf(50,250);return cf(a=>{const i=a.loaded,l=a.lengthComputable?a.total:void 0,d=i-n,u=s(d),g=i<=l;n=i;const h={loaded:i,total:l,progress:l?i/l:void 0,bytes:d,rate:u||void 0,estimated:u&&l&&g?(l-i)/u:void 0,event:a,lengthComputable:l!=null,[e?"download":"upload"]:!0};r(h)},t)},na=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},sa=r=>(...e)=>E.asap(()=>r(...e)),df=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,uf=xe.hasStandardBrowserEnv?{write(r,e,t,n,s,a){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),a===!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 ff(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function hf(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function Cl(r,e,t){let n=!ff(e);return r&&(n||t==!1)?hf(r,e):e}const oa=r=>r instanceof _e?{...r}:r;function lt(r,e){e=e||{};const t={};function n(u,g,h,p){return E.isPlainObject(u)&&E.isPlainObject(g)?E.merge.call({caseless:p},u,g):E.isPlainObject(g)?E.merge({},g):E.isArray(g)?g.slice():g}function s(u,g,h,p){if(E.isUndefined(g)){if(!E.isUndefined(u))return n(void 0,u,h,p)}else return n(u,g,h,p)}function a(u,g){if(!E.isUndefined(g))return n(void 0,g)}function i(u,g){if(E.isUndefined(g)){if(!E.isUndefined(u))return n(void 0,u)}else return n(void 0,g)}function l(u,g,h){if(h in e)return n(u,g);if(h in r)return n(void 0,u)}const d={url:a,method:a,data:a,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,g,h)=>s(oa(u),oa(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 jl=r=>{const e=lt({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:a,headers:i,auth:l}=e;if(e.headers=i=_e.from(i),e.url=yl(Cl(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(),u=["content-type","content-length"];Object.entries(d).forEach(([g,h])=>{u.includes(g.toLowerCase())&&i.set(g,h)})}}if(xe.hasStandardBrowserEnv&&(n&&E.isFunction(n)&&(n=n(e)),n||n!==!1&&df(e.url))){const d=s&&a&&uf.read(a);d&&i.set(s,d)}return e},mf=typeof XMLHttpRequest<"u",gf=mf&&function(r){return new Promise(function(t,n){const s=jl(r);let a=s.data;const i=_e.from(s.headers).normalize();let{responseType:l,onUploadProgress:d,onDownloadProgress:u}=s,g,h,p,w,m;function f(){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 x(){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};Sl(function(v){t(v),f()},function(v){n(v),f()},S),c=null}"onloadend"in c?c.onloadend=x:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(x)},c.onabort=function(){c&&(n(new Q("Request aborted",Q.ECONNABORTED,r,c)),c=null)},c.onerror=function(_){const S=_&&_.message?_.message:"Network Error",j=new Q(S,Q.ERR_NETWORK,r,c);j.event=_||null,n(j),c=null},c.ontimeout=function(){let _=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const S=s.transitional||wl;s.timeoutErrorMessage&&(_=s.timeoutErrorMessage),n(new Q(_,S.clarifyTimeoutError?Q.ETIMEDOUT:Q.ECONNABORTED,r,c)),c=null},a===void 0&&i.setContentType(null),"setRequestHeader"in c&&E.forEach(i.toJSON(),function(_,S){c.setRequestHeader(S,_)}),E.isUndefined(s.withCredentials)||(c.withCredentials=!!s.withCredentials),l&&l!=="json"&&(c.responseType=s.responseType),u&&([p,m]=zr(u,!0),c.addEventListener("progress",p)),d&&c.upload&&([h,w]=zr(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 b=af(s.url);if(b&&xe.protocols.indexOf(b)===-1){n(new Q("Unsupported protocol "+b+":",Q.ERR_BAD_REQUEST,r));return}c.send(a||null)})},pf=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let n=new AbortController,s;const a=function(u){if(!s){s=!0,l();const g=u instanceof Error?u:this.reason;n.abort(g instanceof Q?g:new Mt(g instanceof Error?g.message:g))}};let i=e&&setTimeout(()=>{i=null,a(new Q(`timeout ${e} of ms exceeded`,Q.ETIMEDOUT))},e);const l=()=>{r&&(i&&clearTimeout(i),i=null,r.forEach(u=>{u.unsubscribe?u.unsubscribe(a):u.removeEventListener("abort",a)}),r=null)};r.forEach(u=>u.addEventListener("abort",a));const{signal:d}=n;return d.unsubscribe=()=>E.asap(l),d}},xf=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},bf=async function*(r,e){for await(const t of yf(r))yield*xf(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()}},aa=(r,e,t,n)=>{const s=bf(r,e);let a=0,i,l=d=>{i||(i=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:u,value:g}=await s.next();if(u){l(),d.close();return}let h=g.byteLength;if(t){let p=a+=h;t(p)}d.enqueue(new Uint8Array(g))}catch(u){throw l(u),u}},cancel(d){return l(d),s.return()}},{highWaterMark:2})},ia=64*1024,{isFunction:Sr}=E,wf=(({Request:r,Response:e})=>({Request:r,Response:e}))(E.global),{ReadableStream:la,TextEncoder:ca}=E.global,da=(r,...e)=>{try{return!!r(...e)}catch{return!1}},vf=r=>{r=E.merge.call({skipUndefined:!0},wf,r);const{fetch:e,Request:t,Response:n}=r,s=e?Sr(e):typeof fetch=="function",a=Sr(t),i=Sr(n);if(!s)return!1;const l=s&&Sr(la),d=s&&(typeof ca=="function"?(m=>f=>m.encode(f))(new ca):async m=>new Uint8Array(await new t(m).arrayBuffer())),u=a&&l&&da(()=>{let m=!1;const f=new t(xe.origin,{body:new la,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!f}),g=i&&l&&da(()=>E.isReadableStream(new n("").body)),h={stream:g&&(m=>m.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!h[m]&&(h[m]=(f,c)=>{let x=f&&f[m];if(x)return x.call(f);throw new Q(`Response type '${m}' is not supported`,Q.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,f)=>{const c=E.toFiniteNumber(m.getContentLength());return c??p(f)};return async m=>{let{url:f,method:c,data:x,signal:b,cancelToken:y,timeout:_,onDownloadProgress:S,onUploadProgress:j,responseType:v,headers:I,withCredentials:T="same-origin",fetchOptions:R}=jl(m),D=e||fetch;v=v?(v+"").toLowerCase():"text";let C=pf([b,y&&y.toAbortSignal()],_),B=null;const W=C&&C.unsubscribe&&(()=>{C.unsubscribe()});let H;try{if(j&&u&&c!=="get"&&c!=="head"&&(H=await w(I,x))!==0){let F=new t(f,{method:"POST",body:x,duplex:"half"}),k;if(E.isFormData(x)&&(k=F.headers.get("content-type"))&&I.setContentType(k),F.body){const[A,M]=na(H,zr(sa(j)));x=aa(F.body,ia,A,M)}}E.isString(T)||(T=T?"include":"omit");const O=a&&"credentials"in t.prototype,N={...R,signal:C,method:c.toUpperCase(),headers:I.normalize().toJSON(),body:x,duplex:"half",credentials:O?T:void 0};B=a&&new t(f,N);let U=await(a?D(B,R):D(f,N));const z=g&&(v==="stream"||v==="response");if(g&&(S||z&&W)){const F={};["status","statusText","headers"].forEach(L=>{F[L]=U[L]});const k=E.toFiniteNumber(U.headers.get("content-length")),[A,M]=S&&na(k,zr(sa(S),!0))||[];U=new n(aa(U.body,ia,A,()=>{M&&M(),W&&W()}),F)}v=v||"text";let J=await h[E.findKey(h,v)||"text"](U,m);return!z&&W&&W(),await new Promise((F,k)=>{Sl(F,k,{data:J,headers:_e.from(U.headers),status:U.status,statusText:U.statusText,config:m,request:B})})}catch(O){throw W&&W(),O&&O.name==="TypeError"&&/Load failed|fetch/i.test(O.message)?Object.assign(new Q("Network Error",Q.ERR_NETWORK,m,B),{cause:O.cause||O}):Q.from(O,O&&O.code,m,B)}}},_f=new Map,Al=r=>{let e=r?r.env:{};const{fetch:t,Request:n,Response:s}=e,a=[n,s,t];let i=a.length,l=i,d,u,g=_f;for(;l--;)d=a[l],u=g.get(d),u===void 0&&g.set(d,u=l?new Map:vf(e)),g=u;return u};Al();const ds={http:Du,xhr:gf,fetch:{get:Al}};E.forEach(ds,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const ua=r=>`- ${r}`,Sf=r=>E.isFunction(r)||r===null||r===!1,kl={getAdapter:(r,e)=>{r=E.isArray(r)?r:[r];const{length:t}=r;let n,s;const a={};for(let i=0;i<t;i++){n=r[i];let l;if(s=n,!Sf(n)&&(s=ds[(l=String(n)).toLowerCase()],s===void 0))throw new Q(`Unknown adapter '${l}'`);if(s&&(E.isFunction(s)||(s=s.get(e))))break;a[l||"#"+i]=s}if(!s){const i=Object.entries(a).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(ua).join(`
64
- `):" "+ua(i[0]):"as no adapter specified";throw new Q("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return s},adapters:ds};function Ln(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Mt(null,r)}function fa(r){return Ln(r),r.headers=_e.from(r.headers),r.data=$n.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),kl.getAdapter(r.adapter||lr.adapter,r)(r).then(function(n){return Ln(r),n.data=$n.call(r,r.transformResponse,n),n.headers=_e.from(n.headers),n},function(n){return _l(n)||(Ln(r),n&&n.response&&(n.response.data=$n.call(r,r.transformResponse,n.response),n.response.headers=_e.from(n.response.headers))),Promise.reject(n)})}const Nl="1.12.2",pn={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{pn[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});const ha={};pn.transitional=function(e,t,n){function s(a,i){return"[Axios v"+Nl+"] Transitional option '"+a+"'"+i+(n?". "+n:"")}return(a,i,l)=>{if(e===!1)throw new Q(s(i," has been removed"+(t?" in "+t:"")),Q.ERR_DEPRECATED);return t&&!ha[i]&&(ha[i]=!0,console.warn(s(i," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(a,i,l):!0}};pn.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Cf(r,e,t){if(typeof r!="object")throw new Q("options must be an object",Q.ERR_BAD_OPTION_VALUE);const n=Object.keys(r);let s=n.length;for(;s-- >0;){const a=n[s],i=e[a];if(i){const l=r[a],d=l===void 0||i(l,a,r);if(d!==!0)throw new Q("option "+a+" must be "+d,Q.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new Q("Unknown option "+a,Q.ERR_BAD_OPTION)}}const $r={assertOptions:Cf,validators:pn},Oe=$r.validators;let st=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ta,response:new ta}}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 a=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?a&&!String(n.stack).endsWith(a.replace(/^.+\n.+\n/,""))&&(n.stack+=`
65
- `+a):n.stack=a}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:a}=t;n!==void 0&&$r.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}:$r.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),$r.assertOptions(t,{baseUrl:Oe.spelling("baseURL"),withXsrfToken:Oe.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=a&&E.merge(a.common,a[t.method]);a&&E.forEach(["delete","get","head","post","put","patch","common"],m=>{delete a[m]}),t.headers=_e.concat(i,a);const l=[];let d=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(t)===!1||(d=d&&f.synchronous,l.unshift(f.fulfilled,f.rejected))});const u=[];this.interceptors.response.forEach(function(f){u.push(f.fulfilled,f.rejected)});let g,h=0,p;if(!d){const m=[fa.bind(this),void 0];for(m.unshift(...l),m.push(...u),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++],f=l[h++];try{w=m(w)}catch(c){f.call(this,c);break}}try{g=fa.call(this,w)}catch(m){return Promise.reject(m)}for(h=0,p=u.length;h<p;)g=g.then(u[h++],u[h++]);return g}getUri(e){e=lt(this.defaults,e);const t=Cl(e.baseURL,e.url,e.allowAbsoluteUrls);return yl(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(a,i,l){return this.request(lt(l||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:a,data:i}))}}st.prototype[e]=t(),st.prototype[e+"Form"]=t(!0)});let jf=class Ml{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(a){t=a});const n=this;this.promise.then(s=>{if(!n._listeners)return;let a=n._listeners.length;for(;a-- >0;)n._listeners[a](s);n._listeners=null}),this.promise.then=s=>{let a;const i=new Promise(l=>{n.subscribe(l),a=l}).then(s);return i.cancel=function(){n.unsubscribe(a)},i},e(function(a,i,l){n.reason||(n.reason=new Mt(a,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 Ml(function(s){e=s}),cancel:e}}};function Af(r){return function(t){return r.apply(null,t)}}function kf(r){return E.isObject(r)&&r.isAxiosError===!0}const us={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(us).forEach(([r,e])=>{us[e]=r});function El(r){const e=new st(r),t=il(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 El(lt(r,s))},t}const ie=El(lr);ie.Axios=st;ie.CanceledError=Mt;ie.CancelToken=jf;ie.isCancel=_l;ie.VERSION=Nl;ie.toFormData=gn;ie.AxiosError=Q;ie.Cancel=ie.CanceledError;ie.all=function(e){return Promise.all(e)};ie.spread=Af;ie.isAxiosError=kf;ie.mergeConfig=lt;ie.AxiosHeaders=_e;ie.formToJSON=r=>vl(E.isHTMLForm(r)?new FormData(r):r);ie.getAdapter=kl.getAdapter;ie.HttpStatusCode=us;ie.default=ie;const{Axios:ep,AxiosError:tp,CanceledError:rp,isCancel:np,CancelToken:sp,VERSION:op,all:ap,Cancel:ip,isAxiosError:lp,spread:cp,toFormData:dp,AxiosHeaders:up,HttpStatusCode:fp,formToJSON:hp,getAdapter:mp,mergeConfig:gp}=ie,ma=ie.create({timeout:3e4,headers:{"Content-Type":"application/json"}});class Nf{constructor(e){V(this,"mcpServers");V(this,"tools");V(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(a,i)=>{var l,d,u,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 f=this.toolSupportsStreaming(h);if(console.log("开始调用工具:",f),f)await this.callMcpToolStream(m.serverUrl,m.originalName,w,t,()=>{n(),a()},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(),a()}}catch(h){if(h.message==="Stream aborted by user"||h.name==="AbortError"){console.log(`Tool ${((u=e.function)==null?void 0:u.name)||e.name} stream aborted by user`),a();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,a,i,l,d;console.log("开始调用工具,但是没有用流式的方式");const t=[];for(const u of e)try{const g=((n=u.function)==null?void 0:n.name)||u.name,h=((s=u.function)==null?void 0:s.arguments)||u.arguments||{};if(!g)throw new Error("Tool name is required");let p=h;if(typeof h=="string")try{p=JSON.parse(h)}catch(f){console.warn("Failed to parse tool arguments:",f),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:u.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 ${((a=u.function)==null?void 0:a.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}:`,g),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: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,a,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 g=u.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:f,value:c}=await g.read();if(f)break;w=Date.now(),p+=h.decode(c,{stream:!0});const x=this.parseSSEEvents(p);p=x.remaining;for(const b of x.parsed)if(await this.handleSSEEvent(b,s,a,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(`
59
+ ${e}`,status:"completed",createdAt:new Date}];let s="";return await new ml(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 oa{constructor(e,t,n,s,a,i,l,d,u,g){V(this,"messages");V(this,"conversationId");V(this,"tools");V(this,"modelConfig");V(this,"callBack");V(this,"mcpToolExecute");V(this,"configUrl");V(this,"isAborted");V(this,"currentAiRequestHandler");V(this,"toolResultProcessor");V(this,"sessionId");this.messages=e,this.conversationId=t,this.tools=n,this.modelConfig=s,this.callBack=a,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 cu(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 a=[];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"})}a.push(g)}else{console.log(`Using regular execution for tool: ${d}`);const g=await this.mcpToolExecute.execute([l]);a.push(...g)}}if(this.isAborted){console.log("AiClient: Aborted after tool execution");return}const i=await this.toolResultProcessor.processToolResult(a[0],this.conversationId);debugger;if(this.messages.push(i),this.callBack("tool_result",a),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 ml(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 gl(r,e){return function(){return r.apply(e,arguments)}}const{toString:du}=Object.prototype,{getPrototypeOf:uo}=Object,{iterator:yn,toStringTag:pl}=Symbol,wn=(r=>e=>{const t=du.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Pe=r=>(r=r.toLowerCase(),e=>wn(e)===r),vn=r=>e=>typeof e===r,{isArray:Pt}=Array,Nt=vn("undefined");function fr(r){return r!==null&&!Nt(r)&&r.constructor!==null&&!Nt(r.constructor)&&_e(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const xl=Pe("ArrayBuffer");function uu(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&xl(r.buffer),e}const fu=vn("string"),_e=vn("function"),bl=vn("number"),hr=r=>r!==null&&typeof r=="object",hu=r=>r===!0||r===!1,Br=r=>{if(wn(r)!=="object")return!1;const e=uo(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(pl in r)&&!(yn in r)},mu=r=>{if(!hr(r)||fr(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},gu=Pe("Date"),pu=Pe("File"),xu=Pe("Blob"),bu=Pe("FileList"),yu=r=>hr(r)&&_e(r.pipe),wu=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||_e(r.append)&&((e=wn(r))==="formdata"||e==="object"&&_e(r.toString)&&r.toString()==="[object FormData]"))},vu=Pe("URLSearchParams"),[_u,Su,Cu,ju]=["ReadableStream","Request","Response","Headers"].map(Pe),Au=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function mr(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let n,s;if(typeof r!="object"&&(r=[r]),Pt(r))for(n=0,s=r.length;n<s;n++)e.call(null,r[n],n,r);else{if(fr(r))return;const a=t?Object.getOwnPropertyNames(r):Object.keys(r),i=a.length;let l;for(n=0;n<i;n++)l=a[n],e.call(null,r[l],l,r)}}function yl(r,e){if(fr(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 it=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,wl=r=>!Nt(r)&&r!==it;function gs(){const{caseless:r,skipUndefined:e}=wl(this)&&this||{},t={},n=(s,a)=>{const i=r&&yl(t,a)||a;Br(t[i])&&Br(s)?t[i]=gs(t[i],s):Br(s)?t[i]=gs({},s):Pt(s)?t[i]=s.slice():(!e||!Nt(s))&&(t[i]=s)};for(let s=0,a=arguments.length;s<a;s++)arguments[s]&&mr(arguments[s],n);return t}const ku=(r,e,t,{allOwnKeys:n}={})=>(mr(e,(s,a)=>{t&&_e(s)?r[a]=gl(s,t):r[a]=s},{allOwnKeys:n}),r),Nu=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),Mu=(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)},Eu=(r,e,t,n)=>{let s,a,i;const l={};if(e=e||{},r==null)return e;do{for(s=Object.getOwnPropertyNames(r),a=s.length;a-- >0;)i=s[a],(!n||n(i,r,e))&&!l[i]&&(e[i]=r[i],l[i]=!0);r=t!==!1&&uo(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},Iu=(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},Pu=r=>{if(!r)return null;if(Pt(r))return r;let e=r.length;if(!bl(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},Tu=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&uo(Uint8Array)),Ou=(r,e)=>{const n=(r&&r[yn]).call(r);let s;for(;(s=n.next())&&!s.done;){const a=s.value;e.call(r,a[0],a[1])}},Ru=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},$u=Pe("HTMLFormElement"),Lu=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,s){return n.toUpperCase()+s}),aa=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),Du=Pe("RegExp"),vl=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};mr(t,(s,a)=>{let i;(i=e(s,a,r))!==!1&&(n[a]=i||s)}),Object.defineProperties(r,n)},Fu=r=>{vl(r,(e,t)=>{if(_e(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=r[t];if(_e(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+"'")})}})},Uu=(r,e)=>{const t={},n=s=>{s.forEach(a=>{t[a]=!0})};return Pt(r)?n(r):n(String(r).split(e)),t},Bu=()=>{},Wu=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function Hu(r){return!!(r&&_e(r.append)&&r[pl]==="FormData"&&r[yn])}const qu=r=>{const e=new Array(10),t=(n,s)=>{if(hr(n)){if(e.indexOf(n)>=0)return;if(fr(n))return n;if(!("toJSON"in n)){e[s]=n;const a=Pt(n)?[]:{};return mr(n,(i,l)=>{const d=t(i,s+1);!Nt(d)&&(a[l]=d)}),e[s]=void 0,a}}return n};return t(r,0)},zu=Pe("AsyncFunction"),Ju=r=>r&&(hr(r)||_e(r))&&_e(r.then)&&_e(r.catch),_l=((r,e)=>r?setImmediate:e?((t,n)=>(it.addEventListener("message",({source:s,data:a})=>{s===it&&a===t&&n.length&&n.shift()()},!1),s=>{n.push(s),it.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",_e(it.postMessage)),Vu=typeof queueMicrotask<"u"?queueMicrotask.bind(it):typeof process<"u"&&process.nextTick||_l,Gu=r=>r!=null&&_e(r[yn]),E={isArray:Pt,isArrayBuffer:xl,isBuffer:fr,isFormData:wu,isArrayBufferView:uu,isString:fu,isNumber:bl,isBoolean:hu,isObject:hr,isPlainObject:Br,isEmptyObject:mu,isReadableStream:_u,isRequest:Su,isResponse:Cu,isHeaders:ju,isUndefined:Nt,isDate:gu,isFile:pu,isBlob:xu,isRegExp:Du,isFunction:_e,isStream:yu,isURLSearchParams:vu,isTypedArray:Tu,isFileList:bu,forEach:mr,merge:gs,extend:ku,trim:Au,stripBOM:Nu,inherits:Mu,toFlatObject:Eu,kindOf:wn,kindOfTest:Pe,endsWith:Iu,toArray:Pu,forEachEntry:Ou,matchAll:Ru,isHTMLForm:$u,hasOwnProperty:aa,hasOwnProp:aa,reduceDescriptors:vl,freezeMethods:Fu,toObjectSet:Uu,toCamelCase:Lu,noop:Bu,toFiniteNumber:Wu,findKey:yl,global:it,isContextDefined:wl,isSpecCompliantForm:Hu,toJSONObject:qu,isAsyncFn:zu,isThenable:Ju,setImmediate:_l,asap:Vu,isIterable:Gu};function Z(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(Z,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 Sl=Z.prototype,Cl={};["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=>{Cl[r]={value:r}});Object.defineProperties(Z,Cl);Object.defineProperty(Sl,"isAxiosError",{value:!0});Z.from=(r,e,t,n,s,a)=>{const i=Object.create(Sl);E.toFlatObject(r,i,function(g){return g!==Error.prototype},u=>u!=="isAxiosError");const l=r&&r.message?r.message:"Error",d=e==null&&r?r.code:e;return Z.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",a&&Object.assign(i,a),i};const Xu=null;function ps(r){return E.isPlainObject(r)||E.isArray(r)}function jl(r){return E.endsWith(r,"[]")?r.slice(0,-2):r}function ia(r,e,t){return r?r.concat(e).map(function(s,a){return s=jl(s),!t&&a?"["+s+"]":s}).join(t?".":""):e}function Ku(r){return E.isArray(r)&&!r.some(ps)}const Yu=E.toFlatObject(E,{},null,function(e){return/^is[A-Z]/.test(e)});function _n(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(f,c){return!E.isUndefined(c[f])});const n=t.metaTokens,s=t.visitor||g,a=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 u(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 Z("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,f,c){let x=m;if(m&&!c&&typeof m=="object"){if(E.endsWith(f,"{}"))f=n?f:f.slice(0,-2),m=JSON.stringify(m);else if(E.isArray(m)&&Ku(m)||(E.isFileList(m)||E.endsWith(f,"[]"))&&(x=E.toArray(m)))return f=jl(f),x.forEach(function(y,_){!(E.isUndefined(y)||y===null)&&e.append(i===!0?ia([f],_,a):i===null?f:f+"[]",u(y))}),!1}return ps(m)?!0:(e.append(ia(c,f,a),u(m)),!1)}const h=[],p=Object.assign(Yu,{defaultVisitor:g,convertValue:u,isVisitable:ps});function w(m,f){if(!E.isUndefined(m)){if(h.indexOf(m)!==-1)throw Error("Circular reference detected in "+f.join("."));h.push(m),E.forEach(m,function(x,b){(!(E.isUndefined(x)||x===null)&&s.call(e,x,E.isString(b)?b.trim():b,f,p))===!0&&w(x,f?f.concat(b):[b])}),h.pop()}}if(!E.isObject(r))throw new TypeError("data must be an object");return w(r),e}function la(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function fo(r,e){this._pairs=[],r&&_n(r,this,e)}const Al=fo.prototype;Al.append=function(e,t){this._pairs.push([e,t])};Al.toString=function(e){const t=e?function(n){return e.call(this,n,la)}:la;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function Qu(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function kl(r,e,t){if(!e)return r;const n=t&&t.encode||Qu;E.isFunction(t)&&(t={serialize:t});const s=t&&t.serialize;let a;if(s?a=s(e,t):a=E.isURLSearchParams(e)?e.toString():new fo(e,t).toString(n),a){const i=r.indexOf("#");i!==-1&&(r=r.slice(0,i)),r+=(r.indexOf("?")===-1?"?":"&")+a}return r}class ca{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 Nl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Zu=typeof URLSearchParams<"u"?URLSearchParams:fo,ef=typeof FormData<"u"?FormData:null,tf=typeof Blob<"u"?Blob:null,rf={isBrowser:!0,classes:{URLSearchParams:Zu,FormData:ef,Blob:tf},protocols:["http","https","file","blob","url","data"]},ho=typeof window<"u"&&typeof document<"u",xs=typeof navigator=="object"&&navigator||void 0,nf=ho&&(!xs||["ReactNative","NativeScript","NS"].indexOf(xs.product)<0),sf=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",of=ho&&window.location.href||"http://localhost",af=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:ho,hasStandardBrowserEnv:nf,hasStandardBrowserWebWorkerEnv:sf,navigator:xs,origin:of},Symbol.toStringTag,{value:"Module"})),be={...af,...rf};function lf(r,e){return _n(r,new be.classes.URLSearchParams,{visitor:function(t,n,s,a){return be.isNode&&E.isBuffer(t)?(this.append(n,t.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...e})}function cf(r){return E.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function df(r){const e={},t=Object.keys(r);let n;const s=t.length;let a;for(n=0;n<s;n++)a=t[n],e[a]=r[a];return e}function Ml(r){function e(t,n,s,a){let i=t[a++];if(i==="__proto__")return!0;const l=Number.isFinite(+i),d=a>=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],a)&&E.isArray(s[i])&&(s[i]=df(s[i])),!l)}if(E.isFormData(r)&&E.isFunction(r.entries)){const t={};return E.forEachEntry(r,(n,s)=>{e(cf(n),s,t,0)}),t}return null}function uf(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 gr={transitional:Nl,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",s=n.indexOf("application/json")>-1,a=E.isObject(e);if(a&&E.isHTMLForm(e)&&(e=new FormData(e)),E.isFormData(e))return s?JSON.stringify(Ml(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(a){if(n.indexOf("application/x-www-form-urlencoded")>-1)return lf(e,this.formSerializer).toString();if((l=E.isFileList(e))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return _n(l?{"files[]":e}:e,d&&new d,this.formSerializer)}}return a||s?(t.setContentType("application/json",!1),uf(e)):e}],transformResponse:[function(e){const t=this.transitional||gr.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"?Z.from(l,Z.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:be.classes.FormData,Blob:be.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=>{gr.headers[r]={}});const ff=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"]),hf=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]&&ff[t])&&(t==="set-cookie"?e[t]?e[t].push(n):e[t]=[n]:e[t]=e[t]?e[t]+", "+n:n)}),e},da=Symbol("internals");function Dt(r){return r&&String(r).trim().toLowerCase()}function Wr(r){return r===!1||r==null?r:E.isArray(r)?r.map(Wr):String(r)}function mf(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 gf=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function Hn(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 pf(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function xf(r,e){const t=E.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(r,n+t,{value:function(s,a,i){return this[n].call(this,e,s,a,i)},configurable:!0})})}let Se=class{constructor(e){e&&this.set(e)}set(e,t,n){const s=this;function a(l,d,u){const g=Dt(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||u===!0||u===void 0&&s[h]!==!1)&&(s[h||d]=Wr(l))}const i=(l,d)=>E.forEach(l,(u,g)=>a(u,g,d));if(E.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(E.isString(e)&&(e=e.trim())&&!gf(e))i(hf(e),t);else if(E.isObject(e)&&E.isIterable(e)){let l={},d,u;for(const g of e){if(!E.isArray(g))throw TypeError("Object iterator must return a key-value pair");l[u=g[0]]=(d=l[u])?E.isArray(d)?[...d,g[1]]:[d,g[1]]:g[1]}i(l,t)}else e!=null&&a(t,e,n);return this}get(e,t){if(e=Dt(e),e){const n=E.findKey(this,e);if(n){const s=this[n];if(!t)return s;if(t===!0)return mf(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=Dt(e),e){const n=E.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||Hn(this,this[n],n,t)))}return!1}delete(e,t){const n=this;let s=!1;function a(i){if(i=Dt(i),i){const l=E.findKey(n,i);l&&(!t||Hn(n,n[l],l,t))&&(delete n[l],s=!0)}}return E.isArray(e)?e.forEach(a):a(e),s}clear(e){const t=Object.keys(this);let n=t.length,s=!1;for(;n--;){const a=t[n];(!e||Hn(this,this[a],a,e,!0))&&(delete this[a],s=!0)}return s}normalize(e){const t=this,n={};return E.forEach(this,(s,a)=>{const i=E.findKey(n,a);if(i){t[i]=Wr(s),delete t[a];return}const l=e?pf(a):String(a).trim();l!==a&&delete t[a],t[l]=Wr(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[da]=this[da]={accessors:{}}).accessors,s=this.prototype;function a(i){const l=Dt(i);n[l]||(xf(s,i),n[l]=!0)}return E.isArray(e)?e.forEach(a):a(e),this}};Se.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);E.reduceDescriptors(Se.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(n){this[t]=n}}});E.freezeMethods(Se);function qn(r,e){const t=this||gr,n=e||t,s=Se.from(n.headers);let a=n.data;return E.forEach(r,function(l){a=l.call(t,a,s.normalize(),e?e.status:void 0)}),s.normalize(),a}function El(r){return!!(r&&r.__CANCEL__)}function Tt(r,e,t){Z.call(this,r??"canceled",Z.ERR_CANCELED,e,t),this.name="CanceledError"}E.inherits(Tt,Z,{__CANCEL__:!0});function Il(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new Z("Request failed with status code "+t.status,[Z.ERR_BAD_REQUEST,Z.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function bf(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function yf(r,e){r=r||10;const t=new Array(r),n=new Array(r);let s=0,a=0,i;return e=e!==void 0?e:1e3,function(d){const u=Date.now(),g=n[a];i||(i=u),t[s]=d,n[s]=u;let h=a,p=0;for(;h!==s;)p+=t[h++],h=h%r;if(s=(s+1)%r,s===a&&(a=(a+1)%r),u-i<e)return;const w=g&&u-g;return w?Math.round(p*1e3/w):void 0}}function wf(r,e){let t=0,n=1e3/e,s,a;const i=(u,g=Date.now())=>{t=g,s=null,a&&(clearTimeout(a),a=null),r(...u)};return[(...u)=>{const g=Date.now(),h=g-t;h>=n?i(u,g):(s=u,a||(a=setTimeout(()=>{a=null,i(s)},n-h)))},()=>s&&i(s)]}const Qr=(r,e,t=3)=>{let n=0;const s=yf(50,250);return wf(a=>{const i=a.loaded,l=a.lengthComputable?a.total:void 0,d=i-n,u=s(d),g=i<=l;n=i;const h={loaded:i,total:l,progress:l?i/l:void 0,bytes:d,rate:u||void 0,estimated:u&&l&&g?(l-i)/u:void 0,event:a,lengthComputable:l!=null,[e?"download":"upload"]:!0};r(h)},t)},ua=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},fa=r=>(...e)=>E.asap(()=>r(...e)),vf=be.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,be.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(be.origin),be.navigator&&/(msie|trident)/i.test(be.navigator.userAgent)):()=>!0,_f=be.hasStandardBrowserEnv?{write(r,e,t,n,s,a){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),a===!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 Sf(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function Cf(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function Pl(r,e,t){let n=!Sf(e);return r&&(n||t==!1)?Cf(r,e):e}const ha=r=>r instanceof Se?{...r}:r;function ht(r,e){e=e||{};const t={};function n(u,g,h,p){return E.isPlainObject(u)&&E.isPlainObject(g)?E.merge.call({caseless:p},u,g):E.isPlainObject(g)?E.merge({},g):E.isArray(g)?g.slice():g}function s(u,g,h,p){if(E.isUndefined(g)){if(!E.isUndefined(u))return n(void 0,u,h,p)}else return n(u,g,h,p)}function a(u,g){if(!E.isUndefined(g))return n(void 0,g)}function i(u,g){if(E.isUndefined(g)){if(!E.isUndefined(u))return n(void 0,u)}else return n(void 0,g)}function l(u,g,h){if(h in e)return n(u,g);if(h in r)return n(void 0,u)}const d={url:a,method:a,data:a,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,g,h)=>s(ha(u),ha(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 Tl=r=>{const e=ht({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:a,headers:i,auth:l}=e;if(e.headers=i=Se.from(i),e.url=kl(Pl(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(be.hasStandardBrowserEnv||be.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(E.isFunction(t.getHeaders)){const d=t.getHeaders(),u=["content-type","content-length"];Object.entries(d).forEach(([g,h])=>{u.includes(g.toLowerCase())&&i.set(g,h)})}}if(be.hasStandardBrowserEnv&&(n&&E.isFunction(n)&&(n=n(e)),n||n!==!1&&vf(e.url))){const d=s&&a&&_f.read(a);d&&i.set(s,d)}return e},jf=typeof XMLHttpRequest<"u",Af=jf&&function(r){return new Promise(function(t,n){const s=Tl(r);let a=s.data;const i=Se.from(s.headers).normalize();let{responseType:l,onUploadProgress:d,onDownloadProgress:u}=s,g,h,p,w,m;function f(){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 x(){if(!c)return;const y=Se.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};Il(function(v){t(v),f()},function(v){n(v),f()},S),c=null}"onloadend"in c?c.onloadend=x:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(x)},c.onabort=function(){c&&(n(new Z("Request aborted",Z.ECONNABORTED,r,c)),c=null)},c.onerror=function(_){const S=_&&_.message?_.message:"Network Error",j=new Z(S,Z.ERR_NETWORK,r,c);j.event=_||null,n(j),c=null},c.ontimeout=function(){let _=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const S=s.transitional||Nl;s.timeoutErrorMessage&&(_=s.timeoutErrorMessage),n(new Z(_,S.clarifyTimeoutError?Z.ETIMEDOUT:Z.ECONNABORTED,r,c)),c=null},a===void 0&&i.setContentType(null),"setRequestHeader"in c&&E.forEach(i.toJSON(),function(_,S){c.setRequestHeader(S,_)}),E.isUndefined(s.withCredentials)||(c.withCredentials=!!s.withCredentials),l&&l!=="json"&&(c.responseType=s.responseType),u&&([p,m]=Qr(u,!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 Tt(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 b=bf(s.url);if(b&&be.protocols.indexOf(b)===-1){n(new Z("Unsupported protocol "+b+":",Z.ERR_BAD_REQUEST,r));return}c.send(a||null)})},kf=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let n=new AbortController,s;const a=function(u){if(!s){s=!0,l();const g=u instanceof Error?u:this.reason;n.abort(g instanceof Z?g:new Tt(g instanceof Error?g.message:g))}};let i=e&&setTimeout(()=>{i=null,a(new Z(`timeout ${e} of ms exceeded`,Z.ETIMEDOUT))},e);const l=()=>{r&&(i&&clearTimeout(i),i=null,r.forEach(u=>{u.unsubscribe?u.unsubscribe(a):u.removeEventListener("abort",a)}),r=null)};r.forEach(u=>u.addEventListener("abort",a));const{signal:d}=n;return d.unsubscribe=()=>E.asap(l),d}},Nf=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},Mf=async function*(r,e){for await(const t of Ef(r))yield*Nf(t,e)},Ef=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()}},ma=(r,e,t,n)=>{const s=Mf(r,e);let a=0,i,l=d=>{i||(i=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:u,value:g}=await s.next();if(u){l(),d.close();return}let h=g.byteLength;if(t){let p=a+=h;t(p)}d.enqueue(new Uint8Array(g))}catch(u){throw l(u),u}},cancel(d){return l(d),s.return()}},{highWaterMark:2})},ga=64*1024,{isFunction:Er}=E,If=(({Request:r,Response:e})=>({Request:r,Response:e}))(E.global),{ReadableStream:pa,TextEncoder:xa}=E.global,ba=(r,...e)=>{try{return!!r(...e)}catch{return!1}},Pf=r=>{r=E.merge.call({skipUndefined:!0},If,r);const{fetch:e,Request:t,Response:n}=r,s=e?Er(e):typeof fetch=="function",a=Er(t),i=Er(n);if(!s)return!1;const l=s&&Er(pa),d=s&&(typeof xa=="function"?(m=>f=>m.encode(f))(new xa):async m=>new Uint8Array(await new t(m).arrayBuffer())),u=a&&l&&ba(()=>{let m=!1;const f=new t(be.origin,{body:new pa,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!f}),g=i&&l&&ba(()=>E.isReadableStream(new n("").body)),h={stream:g&&(m=>m.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(m=>{!h[m]&&(h[m]=(f,c)=>{let x=f&&f[m];if(x)return x.call(f);throw new Z(`Response type '${m}' is not supported`,Z.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(be.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,f)=>{const c=E.toFiniteNumber(m.getContentLength());return c??p(f)};return async m=>{let{url:f,method:c,data:x,signal:b,cancelToken:y,timeout:_,onDownloadProgress:S,onUploadProgress:j,responseType:v,headers:I,withCredentials:P="same-origin",fetchOptions:T}=Tl(m),L=e||fetch;v=v?(v+"").toLowerCase():"text";let C=kf([b,y&&y.toAbortSignal()],_),W=null;const B=C&&C.unsubscribe&&(()=>{C.unsubscribe()});let z;try{if(j&&u&&c!=="get"&&c!=="head"&&(z=await w(I,x))!==0){let F=new t(f,{method:"POST",body:x,duplex:"half"}),k;if(E.isFormData(x)&&(k=F.headers.get("content-type"))&&I.setContentType(k),F.body){const[A,N]=ua(z,Qr(fa(j)));x=ma(F.body,ga,A,N)}}E.isString(P)||(P=P?"include":"omit");const O=a&&"credentials"in t.prototype,U={...T,signal:C,method:c.toUpperCase(),headers:I.normalize().toJSON(),body:x,duplex:"half",credentials:O?P:void 0};W=a&&new t(f,U);let J=await(a?L(W,T):L(f,U));const $=g&&(v==="stream"||v==="response");if(g&&(S||$&&B)){const F={};["status","statusText","headers"].forEach(D=>{F[D]=J[D]});const k=E.toFiniteNumber(J.headers.get("content-length")),[A,N]=S&&ua(k,Qr(fa(S),!0))||[];J=new n(ma(J.body,ga,A,()=>{N&&N(),B&&B()}),F)}v=v||"text";let H=await h[E.findKey(h,v)||"text"](J,m);return!$&&B&&B(),await new Promise((F,k)=>{Il(F,k,{data:H,headers:Se.from(J.headers),status:J.status,statusText:J.statusText,config:m,request:W})})}catch(O){throw B&&B(),O&&O.name==="TypeError"&&/Load failed|fetch/i.test(O.message)?Object.assign(new Z("Network Error",Z.ERR_NETWORK,m,W),{cause:O.cause||O}):Z.from(O,O&&O.code,m,W)}}},Tf=new Map,Ol=r=>{let e=r?r.env:{};const{fetch:t,Request:n,Response:s}=e,a=[n,s,t];let i=a.length,l=i,d,u,g=Tf;for(;l--;)d=a[l],u=g.get(d),u===void 0&&g.set(d,u=l?new Map:Pf(e)),g=u;return u};Ol();const bs={http:Xu,xhr:Af,fetch:{get:Ol}};E.forEach(bs,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const ya=r=>`- ${r}`,Of=r=>E.isFunction(r)||r===null||r===!1,Rl={getAdapter:(r,e)=>{r=E.isArray(r)?r:[r];const{length:t}=r;let n,s;const a={};for(let i=0;i<t;i++){n=r[i];let l;if(s=n,!Of(n)&&(s=bs[(l=String(n)).toLowerCase()],s===void 0))throw new Z(`Unknown adapter '${l}'`);if(s&&(E.isFunction(s)||(s=s.get(e))))break;a[l||"#"+i]=s}if(!s){const i=Object.entries(a).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(ya).join(`
64
+ `):" "+ya(i[0]):"as no adapter specified";throw new Z("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return s},adapters:bs};function zn(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Tt(null,r)}function wa(r){return zn(r),r.headers=Se.from(r.headers),r.data=qn.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),Rl.getAdapter(r.adapter||gr.adapter,r)(r).then(function(n){return zn(r),n.data=qn.call(r,r.transformResponse,n),n.headers=Se.from(n.headers),n},function(n){return El(n)||(zn(r),n&&n.response&&(n.response.data=qn.call(r,r.transformResponse,n.response),n.response.headers=Se.from(n.response.headers))),Promise.reject(n)})}const $l="1.12.2",Sn={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{Sn[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});const va={};Sn.transitional=function(e,t,n){function s(a,i){return"[Axios v"+$l+"] Transitional option '"+a+"'"+i+(n?". "+n:"")}return(a,i,l)=>{if(e===!1)throw new Z(s(i," has been removed"+(t?" in "+t:"")),Z.ERR_DEPRECATED);return t&&!va[i]&&(va[i]=!0,console.warn(s(i," has been deprecated since v"+t+" and will be removed in the near future"))),e?e(a,i,l):!0}};Sn.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Rf(r,e,t){if(typeof r!="object")throw new Z("options must be an object",Z.ERR_BAD_OPTION_VALUE);const n=Object.keys(r);let s=n.length;for(;s-- >0;){const a=n[s],i=e[a];if(i){const l=r[a],d=l===void 0||i(l,a,r);if(d!==!0)throw new Z("option "+a+" must be "+d,Z.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new Z("Unknown option "+a,Z.ERR_BAD_OPTION)}}const Hr={assertOptions:Rf,validators:Sn},Re=Hr.validators;let ct=class{constructor(e){this.defaults=e||{},this.interceptors={request:new ca,response:new ca}}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 a=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?a&&!String(n.stack).endsWith(a.replace(/^.+\n.+\n/,""))&&(n.stack+=`
65
+ `+a):n.stack=a}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=ht(this.defaults,t);const{transitional:n,paramsSerializer:s,headers:a}=t;n!==void 0&&Hr.assertOptions(n,{silentJSONParsing:Re.transitional(Re.boolean),forcedJSONParsing:Re.transitional(Re.boolean),clarifyTimeoutError:Re.transitional(Re.boolean)},!1),s!=null&&(E.isFunction(s)?t.paramsSerializer={serialize:s}:Hr.assertOptions(s,{encode:Re.function,serialize:Re.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Hr.assertOptions(t,{baseUrl:Re.spelling("baseURL"),withXsrfToken:Re.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=a&&E.merge(a.common,a[t.method]);a&&E.forEach(["delete","get","head","post","put","patch","common"],m=>{delete a[m]}),t.headers=Se.concat(i,a);const l=[];let d=!0;this.interceptors.request.forEach(function(f){typeof f.runWhen=="function"&&f.runWhen(t)===!1||(d=d&&f.synchronous,l.unshift(f.fulfilled,f.rejected))});const u=[];this.interceptors.response.forEach(function(f){u.push(f.fulfilled,f.rejected)});let g,h=0,p;if(!d){const m=[wa.bind(this),void 0];for(m.unshift(...l),m.push(...u),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++],f=l[h++];try{w=m(w)}catch(c){f.call(this,c);break}}try{g=wa.call(this,w)}catch(m){return Promise.reject(m)}for(h=0,p=u.length;h<p;)g=g.then(u[h++],u[h++]);return g}getUri(e){e=ht(this.defaults,e);const t=Pl(e.baseURL,e.url,e.allowAbsoluteUrls);return kl(t,e.params,e.paramsSerializer)}};E.forEach(["delete","get","head","options"],function(e){ct.prototype[e]=function(t,n){return this.request(ht(n||{},{method:e,url:t,data:(n||{}).data}))}});E.forEach(["post","put","patch"],function(e){function t(n){return function(a,i,l){return this.request(ht(l||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:a,data:i}))}}ct.prototype[e]=t(),ct.prototype[e+"Form"]=t(!0)});let $f=class Ll{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(a){t=a});const n=this;this.promise.then(s=>{if(!n._listeners)return;let a=n._listeners.length;for(;a-- >0;)n._listeners[a](s);n._listeners=null}),this.promise.then=s=>{let a;const i=new Promise(l=>{n.subscribe(l),a=l}).then(s);return i.cancel=function(){n.unsubscribe(a)},i},e(function(a,i,l){n.reason||(n.reason=new Tt(a,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 Ll(function(s){e=s}),cancel:e}}};function Lf(r){return function(t){return r.apply(null,t)}}function Df(r){return E.isObject(r)&&r.isAxiosError===!0}const ys={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(ys).forEach(([r,e])=>{ys[e]=r});function Dl(r){const e=new ct(r),t=gl(ct.prototype.request,e);return E.extend(t,ct.prototype,e,{allOwnKeys:!0}),E.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return Dl(ht(r,s))},t}const le=Dl(gr);le.Axios=ct;le.CanceledError=Tt;le.CancelToken=$f;le.isCancel=El;le.VERSION=$l;le.toFormData=_n;le.AxiosError=Z;le.Cancel=le.CanceledError;le.all=function(e){return Promise.all(e)};le.spread=Lf;le.isAxiosError=Df;le.mergeConfig=ht;le.AxiosHeaders=Se;le.formToJSON=r=>Ml(E.isHTMLForm(r)?new FormData(r):r);le.getAdapter=Rl.getAdapter;le.HttpStatusCode=ys;le.default=le;const{Axios:hp,AxiosError:mp,CanceledError:gp,isCancel:pp,CancelToken:xp,VERSION:bp,all:yp,Cancel:wp,isAxiosError:vp,spread:_p,toFormData:Sp,AxiosHeaders:Cp,HttpStatusCode:jp,formToJSON:Ap,getAdapter:kp,mergeConfig:Np}=le,_a=le.create({timeout:3e4,headers:{"Content-Type":"application/json"}});class Ff{constructor(e){V(this,"mcpServers");V(this,"tools");V(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(a,i)=>{var l,d,u,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 f=this.toolSupportsStreaming(h);if(console.log("开始调用工具:",f),f)await this.callMcpToolStream(m.serverUrl,m.originalName,w,t,()=>{n(),a()},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(),a()}}catch(h){if(h.message==="Stream aborted by user"||h.name==="AbortError"){console.log(`Tool ${((u=e.function)==null?void 0:u.name)||e.name} stream aborted by user`),a();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,a,i,l,d;console.log("开始调用工具,但是没有用流式的方式");const t=[];for(const u of e)try{const g=((n=u.function)==null?void 0:n.name)||u.name,h=((s=u.function)==null?void 0:s.arguments)||u.arguments||{};if(!g)throw new Error("Tool name is required");let p=h;if(typeof h=="string")try{p=JSON.parse(h)}catch(f){console.warn("Failed to parse tool arguments:",f),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:u.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 ${((a=u.function)==null?void 0:a.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}:`,g),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: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,a,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 g=u.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:f,value:c}=await g.read();if(f)break;w=Date.now(),p+=h.decode(c,{stream:!0});const x=this.parseSSEEvents(p);p=x.remaining;for(const b of x.parsed)if(await this.handleSSEEvent(b,s,a,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
66
  `);let s={},a=0;for(;a<n.length;){const d=n[a].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}a++}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 a=JSON.parse(e.data);switch(e.event){case"start":return console.log("Stream started:",a),!1;case"data":if(console.log("Stream data:",a),a.choices&&a.choices.length>0){const i=a.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 a.chunk&&t(a.chunk);return!1;case"end":return console.log("Stream completed:",a),n(),!0;case"error":return console.error("Stream error:",a),s(new Error(a.error||"Stream error")),!0;default:return console.warn("Unknown SSE event:",e.event,a),!1}}catch(a){return console.error("Failed to parse SSE event:",a),s(new Error(a.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||{}}},a=`${e}`;console.log("MCP Tool Call URL:",a);const i=await ma.post(a,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 a=await ma.post(s,n);if(a.data.error)throw new Error(`MCP tools/list failed: ${a.data.error.message}`);const l=(((e=a.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 Il{constructor(e,t,n,s=null,a,i){V(this,"conversationId");V(this,"userId");V(this,"conversation");V(this,"mcpServers");V(this,"messages");V(this,"tools");V(this,"mcpToolsExecute");V(this,"modelConfig");V(this,"currentThread");V(this,"isAborted");V(this,"messageManager");V(this,"configUrl");V(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=a||"/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 kr.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 te.getMcpConfigs(this.userId);console.log("mcpResponse",n);const a=(Array.isArray(n)?n:[]).filter(i=>i.enabled);this.mcpServers=a.map((i,l)=>({id:i.id||`mcp-server-${l}`,name:i.name,url:i.command,config:i.config||{}})),this.mcpToolsExecute=new Nf(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 kr.getMessages(this.conversationId,{limit:2})).data.messages||[]).sort((w,m)=>{const f=new Date(w.created_at||w.timestamp||0),c=new Date(m.created_at||m.timestamp||0),x=isNaN(f.getTime())?0:f.getTime(),b=isNaN(c.getTime())?0:c.getTime();return x-b});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 a=JSON.parse(e.data);switch(e.event){case"start":return console.log("Stream started:",a),!1;case"data":if(console.log("Stream data:",a),a.choices&&a.choices.length>0){const i=a.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 a.chunk&&t(a.chunk);return!1;case"end":return console.log("Stream completed:",a),n(),!0;case"error":return console.error("Stream error:",a),s(new Error(a.error||"Stream error")),!0;default:return console.warn("Unknown SSE event:",e.event,a),!1}}catch(a){return console.error("Failed to parse SSE event:",a),s(new Error(a.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||{}}},a=`${e}`;console.log("MCP Tool Call URL:",a);const i=await _a.post(a,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 a=await _a.post(s,n);if(a.data.error)throw new Error(`MCP tools/list failed: ${a.data.error.message}`);const l=(((e=a.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 Fl{constructor(e,t,n,s=null,a,i){V(this,"conversationId");V(this,"userId");V(this,"conversation");V(this,"mcpServers");V(this,"messages");V(this,"tools");V(this,"mcpToolsExecute");V(this,"modelConfig");V(this,"currentThread");V(this,"isAborted");V(this,"messageManager");V(this,"configUrl");V(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=a||"/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 Or.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 te.getMcpConfigs(this.userId);console.log("mcpResponse",n);const a=(Array.isArray(n)?n:[]).filter(i=>i.enabled);this.mcpServers=a.map((i,l)=>({id:i.id||`mcp-server-${l}`,name:i.name,url:i.command,config:i.config||{}})),this.mcpToolsExecute=new Ff(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 Or.getMessages(this.conversationId,{limit:2})).data.messages||[]).sort((w,m)=>{const f=new Date(w.created_at||w.timestamp||0),c=new Date(m.created_at||m.timestamp||0),x=isNaN(f.getTime())?0:f.getTime(),b=isNaN(c.getTime())?0:c.getTime();return x-b});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)}`,g=new AbortController,h=new Yo(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:u,aiClient:h,abortController:g,isRunning:!0,startTime:Date.now()};this.currentThread=p,console.log(`AiServer: Created request thread ${u}`);try{if(this.isAborted||!p.isRunning){console.log(`AiServer: Thread ${u} was aborted before start`);return}await h.start(),console.log(`AiServer: Thread ${u} completed successfully`)}catch(w){if(this.isAborted||!p.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,a=new Yo(this.messages,this.conversationId,[],this.modelConfig,(l,d)=>this.callback(l,d),null,this.messageManager,this.configUrl,s,this.sessionId),i={id:n,aiClient:a,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 a.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 kr.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 Tl{constructor(e){V(this,"pendingSaves",new Set);V(this,"savedMessages",new Map);V(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(a=>setTimeout(a,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 a=this.savedMessages.get(t);if(a)return a}this.pendingSaves.add(t);try{const a=await this.databaseService.createMessage(e);return this.savedMessages.set(t,a),a}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(a=>setTimeout(a,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 Mf 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 Pl{constructor(e,t,n,s){V(this,"currentAiClient",null);V(this,"currentSessionId",null);V(this,"dbService");V(this,"messageManager");V(this,"userId");V(this,"configUrl");this.userId=e,this.dbService=new Mf(e,t),this.messageManager=n,this.configUrl=s||"/api",console.log("🔧 ChatService Constructor - configUrl:",this.configUrl)}async sendMessage(e,t,n=[],s={},a){var i,l,d,u,g;try{if(this.currentSessionId=e,!await this.dbService.getSession(e))throw new Error("Session not found");let p;if(a)p=a;else{const f=await this.getChatConfig();p={model_name:f.model,temperature:f.temperature,max_tokens:16e3,api_key:f.apiKey,base_url:f.baseUrl}}const w=new Il(e,this.userId,this.messageManager,p,this.configUrl,e);let m=3;for(;m>0;)try{await w.init();break}catch(f){if(m--,m===0)throw new Error(`AI服务初始化失败: ${f instanceof Error?f.message:"未知错误"}`);await new Promise(c=>setTimeout(c,1e3))}w.callback=(f,c)=>{var x,b,y,_,S,j,v,I;try{switch(f){case"chunk":const T=typeof c=="string"?c:c.content||c.accumulated||"";(x=s.onChunk)==null||x.call(s,{type:"text",content:T,accumulated:T});break;case"summary_chunk":const R=typeof c=="string"?c:c.content||c.accumulated||"";(b=s.onChunk)==null||b.call(s,{type:"text",content:R,accumulated:R});break;case"tool_call":(y=s.onToolCall)==null||y.call(s,c);break;case"tool_result":(_=s.onToolResult)==null||_.call(s,c);break;case"tool_stream_chunk":(S=s.onToolStreamChunk)==null||S.call(s,c);break;case"complete":debugger;break;case"conversation_complete":(j=s.onComplete)==null||j.call(s,c);break;case"error":const D=c instanceof Error?c.message:typeof c=="string"?c:"AI响应出错";(v=s.onError)==null||v.call(s,new Error(D));break;default:console.warn("Unknown AI response type:",f)}}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),(u=s.onError)==null||u.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 Ef({set:r,get:e,client:t,getUserIdParam:n}){return async function(a,i=[]){var b;const{currentSessionId:l,selectedModelId:d,aiModelConfigs:u,chatConfig:g,isLoading:h,isStreaming:p,activeSystemContext:w,selectedAgentId:m,agents:f}=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,x=null;if(m){if(x=f.find(y=>y.id===m),!x||x.enabled===!1)throw new Error("选择的智能体不可用")}else if(d){if(c=u.find(y=>y.id===d),!c||!c.enabled)throw new Error("选择的模型不可用")}else throw new Error("请先选择一个模型或智能体");try{const y=new Date,_={id:`temp_user_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:l,role:"user",content:a,status:"completed",createdAt:y,metadata:{...i.length>0?{attachments:i}:{},model:x?`[Agent] ${x.name}`:c.model_name,...c?{modelConfig:{id:c.id,name:c.name,base_url:c.base_url,model_name:c.model_name}}:{}}};r(D=>{D.messages.push(_),D.isLoading=!0,D.isStreaming=!0});const S=new Date(y.getTime()+1),j={id:`temp_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:l,role:"assistant",content:"",status:"streaming",createdAt:S,metadata:{model:x?`[Agent] ${x.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(D=>{D.messages.push(j),D.streamingMessageId=j.id});const v=x?{session_id:l,message:a,agent_id:x.id,system_context:(w==null?void 0:w.content)||g.systemPrompt||"",attachments:i||[]}:{session_id:l,message:a,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:",v);const I=x?await t.streamAgentChat(l,a,x.id,n()):await t.streamChatBySession(l,a,n(),{id:c.id});if(!I)throw new Error("No response received");const T=I.getReader(),R=new TextDecoder;try{for(;;){const{done:D,value:C}=await T.read();if(D){console.log("✅ 流式响应完成");break}const W=R.decode(C,{stream:!0}).split(`
71
- `);for(const H of W)if(H.trim()!==""&&H.startsWith("data: ")){const O=H.slice(6);if(O==="[DONE]"){console.log("✅ 收到完成信号");break}try{const N=JSON.parse(O);if(typeof N=="string"&&N==="[DONE]"){console.log("✅ 收到完成信号");break}if(N.type==="chunk")N.content&&r(U=>{const z=U.messages.find(J=>J.id===j.id);if(z&&z.metadata){const J=typeof N.content=="string"?N.content:typeof N=="string"?N:N.content||"",F=z.metadata.currentSegmentIndex||0,k=z.metadata.contentSegments||[];k[F]&&k[F].type==="text"?k[F].content+=J:(k.push({content:J,type:"text"}),z.metadata.currentSegmentIndex=k.length-1),z.content=k.filter(A=>A.type==="text").map(A=>A.content).join("")}});else if(N.type==="thinking")N.content&&r(U=>{const z=U.messages.find(J=>J.id===j.id);if(z&&z.metadata){const J=typeof N.content=="string"?N.content:typeof N=="string"?N:N.content||"",F=z.metadata.contentSegments||[],k=F.length-1;k>=0&&F[k].type==="thinking"?(F[k].content+=J,z.metadata.currentSegmentIndex=k):(F.push({content:J,type:"thinking"}),z.metadata.currentSegmentIndex=F.length-1),z.content=F.filter(A=>A.type==="text").map(A=>A.content).join("")}});else if(N.type==="context_summarized"||N.type==="context_summarized_start"||N.type==="context_summarized_stream"||N.type==="context_summarized_end"){const U=N.data||{},z="【上下文摘要】\\n";r(J=>{const F=J.messages.find(M=>M.id===j.id);if(!F||!F.metadata)return;const k=F.metadata.contentSegments||[],A=()=>{const M=k.length-1;return M>=0&&k[M].type==="thinking"&&String(k[M].content||"").startsWith(z)?M:(k.push({content:z,type:"thinking"}),F.metadata.contentSegments=k,F.metadata.currentSegmentIndex=k.length-1,k.length-1)};if(N.type==="context_summarized_start")A();else if(N.type==="context_summarized_stream"){const M=A(),L=U.content||U.chunk||U.data||"";k[M].content+=String(L),F.metadata.currentSegmentIndex=M}else if(N.type==="context_summarized_end"||N.type==="context_summarized"){const M=A(),L=typeof U.full_summary=="string"&&U.full_summary.length>0?U.full_summary:U.summary_preview||"";k[M].content=z+String(L),F.metadata.contentSegments=k,F.metadata.currentSegmentIndex=M}F.updatedAt=new Date})}else if(N.type==="content")r(U=>{const z=U.messages.find(J=>J.id===j.id);if(z&&z.metadata){const J=typeof N.content=="string"?N.content:typeof N=="string"?N:N.content||"",F=z.metadata.currentSegmentIndex||0,k=z.metadata.contentSegments||[];k[F]&&k[F].type==="text"?k[F].content+=J:(k.push({content:J,type:"text"}),z.metadata.currentSegmentIndex=k.length-1),z.content=k.filter(A=>A.type==="text").map(A=>A.content).join("")}});else if(N.type==="tools_start"){console.log("🔧 收到工具调用:",N.data),console.log("🔧 工具调用数据类型:",typeof N.data,"是否为数组:",Array.isArray(N.data));const U=F=>{var A,M,L;console.log("🔧 [DEBUG] 原始工具调用数据:",F),console.log("🔧 [DEBUG] tc.function:",F.function),console.log("🔧 [DEBUG] tc.function?.name:",(A=F.function)==null?void 0:A.name),console.log("🔧 [DEBUG] tc.name:",F.name);const k={id:F.id||F.tool_call_id||`tool_${Date.now()}_${Math.random()}`,messageId:j.id,name:((M=F.function)==null?void 0:M.name)||F.name||"unknown_tool",arguments:((L=F.function)==null?void 0:L.arguments)||F.arguments||"{}",result:F.result||"",error:F.error||void 0,createdAt:F.createdAt||F.created_at||new Date};return console.log("🔧 [DEBUG] 转换后的工具调用:",k),k};console.log("🔧 [DEBUG] tools_start 原始数据:",N.data);const z=N.data.tool_calls||N.data,J=Array.isArray(z)?z:[z];console.log("🔧 [DEBUG] 提取的工具调用数组:",J),r(F=>{const k=F.messages.findIndex(A=>A.id===j.id);if(console.log("🔧 查找消息索引:",k,"消息ID:",j.id),k!==-1){const A=F.messages[k];console.log("🔧 找到消息,当前metadata:",A.metadata),A.metadata||(A.metadata={}),A.metadata.toolCalls||(A.metadata.toolCalls=[]);const M=A.metadata.contentSegments||[];console.log("🔧 处理工具调用数组,长度:",J.length),J.forEach(L=>{const $=U(L);console.log("🔧 添加转换后的工具调用:",$),A.metadata.toolCalls.push($),M.push({content:"",type:"tool_call",toolCallId:$.id})}),M.push({content:"",type:"text"}),A.metadata.currentSegmentIndex=M.length-1,console.log("🔧 更新后的toolCalls:",A.metadata.toolCalls)}else console.log("🔧 ❌ 未找到对应的消息")})}else if(N.type==="tools_end"){console.log("🔧 收到工具结果:",N.data),console.log("🔧 工具结果数据类型:",typeof N.data);const U=Array.isArray(N.data)?N.data:[N.data];r(z=>{const J=z.messages.findIndex(F=>F.id===j.id);if(J!==-1){const F=z.messages[J];F.metadata&&F.metadata.toolCalls&&(U.forEach(k=>{var L,$,q,ee;const A=k.tool_call_id||k.id||k.toolCallId;if(!A){console.warn("⚠️ 工具结果缺少工具调用ID:",k);return}console.log("🔍 查找工具调用:",A,"在消息中:",($=(L=F.metadata)==null?void 0:L.toolCalls)==null?void 0:$.map(be=>be.id));const M=F.metadata.toolCalls.find(be=>be.id===A);if(M){console.log("✅ 找到工具调用,更新最终结果:",M.id);const be=k.result||k.content||k.output||"";k.success===!1||k.is_error===!0?(M.error=k.error||be||"工具执行失败",console.log("❌ 工具执行失败:",{id:M.id,name:k.name||M.name,error:M.error,success:k.success,is_error:k.is_error})):((!M.result||M.result.trim()==="")&&(M.result=be),M.error&&delete M.error,console.log("✅ 工具执行成功,最终结果已更新:",{id:M.id,name:k.name||M.name,resultLength:M.result.length,success:k.success,is_stream:k.is_stream}))}else console.log("❌ 未找到对应的工具调用:",A),console.log("📋 当前可用的工具调用ID:",(ee=(q=F.metadata)==null?void 0:q.toolCalls)==null?void 0:ee.map(be=>be.id))}),F.updatedAt=new Date)}})}else if(N.type==="tools_stream"){console.log("🔧 收到工具流式数据:",N.data);const U=N.data;r(z=>{const J=z.messages.findIndex(F=>F.id===j.id);if(J!==-1){const F=z.messages[J];if(F.metadata&&F.metadata.toolCalls){const k=U.toolCallId||U.tool_call_id||U.id;if(!k){console.warn("⚠️ 工具流式数据缺少工具调用ID:",U);return}console.log("🔍 查找工具调用进行流式更新:",k);const A=F.metadata.toolCalls.find(M=>M.id===k);if(A){const M=U.content||U.chunk||U.data||"";U.is_error||!U.success?(A.error=M||"工具执行出错",console.log("❌ 工具流式执行出错:",{id:A.id,error:A.error,success:U.success,is_error:U.is_error})):(A.result=(A.result||"")+M,console.log("🔧 工具流式数据已更新:",{id:A.id,name:U.name,chunkLength:M.length,totalLength:A.result.length,success:U.success,is_stream:U.is_stream})),F.updatedAt=new Date}}}})}else{if(N.type==="error")throw new Error(N.message||((b=N.data)==null?void 0:b.message)||"Stream error");if(N.type==="cancelled"){console.log("⚠️ 流式会话已被取消");break}else if(N.type==="done"){console.log("✅ 收到完成信号");break}}}catch(N){console.warn("解析流式数据失败:",N,"data:",O)}}}}finally{T.releaseLock(),r(D=>{D.isLoading=!1,D.isStreaming=!1,D.streamingMessageId=null})}console.log("✅ 消息发送完成")}catch(y){throw console.error("❌ 发送消息失败:",y),r(_=>{const S=_.messages.findIndex(j=>{var v;return(v=j.id)==null?void 0:v.startsWith("temp_")});S!==-1&&_.messages.splice(S,1),_.isLoading=!1,_.isStreaming=!1,_.streamingMessageId=null,_.error=y instanceof Error?y.message:"Failed to send message"}),y}}}function If({set:r,get:e,client:t,getUserIdParam:n}){const s=a=>({id:a.id,name:a.name,url:a.url,iconUrl:a.icon_url??void 0,createdAt:new Date(a.created_at),updatedAt:new Date(a.updated_at??a.created_at)});return{loadApplications:async()=>{try{console.log("[Store] loadApplications: start");const a=n(),l=(await t.getApplications(a)||[]).map(s);r(d=>{d.applications=l}),console.log("[Store] loadApplications: loaded",l.length,"items")}catch(a){console.error("Failed to load applications:",a),r(i=>{i.applications=[]})}},createApplication:async(a,i,l)=>{try{const d=await t.createApplication({name:a,url:i,icon_url:l??null,user_id:n()}),u=s(d);r(g=>{g.applications=[u,...g.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(a,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(a,l),u=s(d);r(g=>{g.applications=g.applications.map(h=>h.id===a?u: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 a=>{try{await t.deleteApplication(a),r(i=>{i.applications=i.applications.filter(l=>l.id!==a),i.mcpConfigs=i.mcpConfigs.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==a):[]})),i.systemContexts=i.systemContexts.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==a):[]})),i.agents=i.agents.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==a):[]}))})}catch(i){console.error("Failed to delete application:",i),r(l=>{l.error=i instanceof Error?i.message:"Failed to delete application"})}},setSelectedApplication:a=>{console.log("[Store] setSelectedApplication:",a);const i=e().selectedApplicationId;console.log("[Store] setSelectedApplication - before:",{oldId:i,newId:a}),r(d=>({...d,selectedApplicationId:a}));const l=e().selectedApplicationId;console.log("[Store] setSelectedApplication - after:",{oldId:i,newId:l})},setMcpAppAssociation:(a,i)=>{r(l=>{l.mcpConfigs=l.mcpConfigs.map(d=>d.id===a?{...d,app_ids:Array.isArray(i)?i:[]}:d)})},setSystemContextAppAssociation:(a,i)=>{r(l=>{l.systemContexts=l.systemContexts.map(d=>d.id===a?{...d,app_ids:Array.isArray(i)?i:[]}:d)});try{(async()=>await t.updateSystemContext(a,{name:void 0,content:void 0,app_ids:Array.isArray(i)?i:[]}))()}catch{}},setAgentAppAssociation:(a,i)=>{r(l=>{l.agents=l.agents.map(d=>d.id===a?{...d,app_ids:Array.isArray(i)?i:[]}:d)});try{(async()=>await t.updateAgent(a,{app_ids:Array.isArray(i)?i:[]}))()}catch{}}}}function Tf({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(a=>{a.error=s instanceof Error?s.message:"Failed to load AI model configs"})}},updateAiModelConfig:async s=>{try{const a=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:a};l==="update"?await t.updateAiModelConfig(s.id,d):await t.createAiModelConfig(d),await e().loadAiModelConfigs()}catch(a){console.error("Failed to update AI model config:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to update AI model config"})}},deleteAiModelConfig:async s=>{try{await t.deleteAiModelConfig(s),r(a=>{a.aiModelConfigs=a.aiModelConfigs.filter(i=>i.id!==s)})}catch(a){console.error("Failed to delete AI model config:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to delete AI model config"})}},setSelectedModel:s=>{var l,d;const i=e().currentSessionId||null;r(u=>{var g,h;if(u.selectedModelId=s,s&&(u.selectedAgentId=null),u.currentSession&&u.currentSessionId){const p=u.currentSession.metadata;let w={};try{const f=typeof p=="string"?p?JSON.parse(p):{}:p&&typeof p=="object"?p:{};w=f&&typeof f=="object"&&!Array.isArray(f)?{...f}:{}}catch{w={}}s?w.ai_model_config_id=s:delete w.ai_model_config_id,u.currentSession.metadata=w;const m=((h=(g=u.sessions)==null?void 0:g.findIndex)==null?void 0:h.call(g,f=>f.id===u.currentSessionId))??-1;m!==-1&&u.sessions[m]&&(u.sessions[m]={...u.sessions[m],metadata:w})}}),i&&((d=(l=e()).updateSessionConfig)==null||d.call(l,i,{modelId:s}).catch(u=>{console.error("Failed to persist session model selection:",u)}))}}}function Pf({set:r,get:e,client:t,getUserIdParam:n}){return{loadMcpConfigs:async()=>{var s;try{const a=n(),i=await t.getMcpConfigs(a);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(a){console.error("Failed to load MCP configs:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to load MCP configs"})}},updateMcpConfig:async s=>{try{const a=n();console.log("🔍 updateMcpConfig 调用:",{userId:a,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:a,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:a,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(g=>g.id===l?{...g,app_ids:d}:g)}),await e().loadMcpConfigs(),i}catch(a){return console.error("Failed to update MCP config:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to update MCP config"}),null}},deleteMcpConfig:async s=>{try{await t.deleteMcpConfig(s),r(a=>{a.mcpConfigs=a.mcpConfigs.filter(i=>i.id!==s)})}catch(a){console.error("Failed to delete MCP config:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to delete MCP config"})}}}}function Of({set:r}){return{updateChatConfig:async e=>{r(t=>{t.chatConfig={...t.chatConfig,...e}})}}}function Jr(r,e){const t=r||te,n=e==null?void 0:e.userId,s=e==null?void 0:e.projectId,a=e==null?void 0:e.configUrl,i=n||"default-user",l=s||"default-project",d=a||"/api",u=()=>i,g=()=>({userId:i,projectId:l}),h=new bs(i,l,t),p=new Tl(h),w=new Pl(i,l,p,d);return console.log("chatService:",w),Sc()(Lc(Hc((m,f)=>({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:x}=g();console.log("🔍 loadSessions 调用 client.getSessions",{userId:c,projectId:x,customUserId:n,customProjectId:s});const b=await t.getSessions(c,x);console.log("🔍 loadSessions 返回结果:",b),m(_=>{_.sessions=b,_.isLoading=!1});const y=f();if(b.length>0&&!y.currentSessionId){const _=localStorage.getItem(`lastSessionId_${c}_${x}`);let S=null;_&&(S=b.find(j=>j.id===_)),S||(S=[...b].sort((j,v)=>new Date(v.createdAt).getTime()-new Date(j.createdAt).getTime())[0]),S&&(console.log("🔍 自动选择会话:",S.id),setTimeout(()=>{f().selectSession(S.id)},0))}console.log("🔍 loadSessions 完成")}catch(c){console.error("🔍 loadSessions 错误:",c),m(x=>{x.error=c instanceof Error?c.message:"Failed to load sessions",x.isLoading=!1})}},createSession:async(c="New Chat")=>{try{const{userId:x,projectId:b}=g(),y=typeof c=="string"?{title:c}:c||{},_=y.title||"New Chat",S=y.modelId??f().selectedModelId??null,j=Array.isArray(y.mcpConfigIds)?y.mcpConfigIds:[],v=Array.isArray(y.promptIds)?y.promptIds:[];console.log("🔍 createSession 使用参数:",{userId:x,projectId:b,title:_}),console.log("🔍 createSession 自定义参数:",{customUserId:n,customProjectId:s}),console.log("🔍 createSession 最终使用的参数:",{userId:x,projectId:b,isCustomUserId:!!n,isCustomProjectId:!!s});const I=crypto.randomUUID(),T={id:I,title:_,user_id:x,project_id:b},R={...S?{ai_model_config_id:S}:{},...v.length>0?{prompt_ids:v}:{}};Object.keys(R).length>0&&(T.metadata=R);const D=await t.createSession(T);if(console.log("✅ createSession API调用成功:",D),j.length>0){const B=f().mcpConfigs||[];for(const W of j){const H=B.find(N=>N.id===W),O=H?`${H.name}_${String(W).slice(0,8)}`:`mcp_${String(W).slice(0,8)}`;try{await t.addSessionMcpServer(I,{mcp_server_name:O,mcp_config_id:W})}catch(N){console.warn("Failed to add session MCP server:",{sessionId:I,mcpConfigId:W,e:N})}}}const C={id:D.id,title:D.title,createdAt:new Date(D.created_at),updatedAt:new Date(D.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:D.metadata||null};return m(B=>{B.sessions.unshift(C),B.currentSessionId=C.id,B.currentSession=C,B.messages=[],B.selectedModelId=S,B.selectedAgentId=null,B.error=null}),localStorage.setItem(`lastSessionId_${x}_${b}`,C.id),console.log("🔍 保存新创建的会话ID到 localStorage:",C.id),C.id}catch(x){throw console.error("❌ createSession 失败:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to create session"}),x}},getSessionMcpConfigIds:async c=>{try{if(!c)return[];const x=await t.getSessionMcpServers(c);return Array.from(new Set((x||[]).map(y=>y.mcp_config_id).filter(y=>typeof y=="string"&&y.trim()!=="")))}catch(x){return console.error("Failed to load session MCP config ids:",x),[]}},updateSessionConfig:async(c,x)=>{try{if(!c)return;const b=f(),y=b.sessions.find(v=>v.id===c)||(b.currentSessionId===c?b.currentSession:null),_=y==null?void 0:y.metadata;let S={};try{const v=typeof _=="string"?_?JSON.parse(_):{}:_&&typeof _=="object"?_:{};S=v&&typeof v=="object"&&!Array.isArray(v)?{...v}:{}}catch{S={}}if(x.modelId!==void 0&&(x.modelId?S.ai_model_config_id=x.modelId:delete S.ai_model_config_id),x.promptIds!==void 0){const v=Array.isArray(x.promptIds)?x.promptIds.map(I=>String(I)).filter(Boolean):[];v.length>0?S.prompt_ids=v:delete S.prompt_ids}const j={};if(x.title!==void 0&&(j.title=x.title),j.metadata=S,await f().updateSession(c,j),b.currentSessionId===c&&x.modelId!==void 0&&m(v=>{v.selectedModelId=x.modelId||null,v.selectedAgentId=null}),x.mcpConfigIds!==void 0){const v=Array.from(new Set((Array.isArray(x.mcpConfigIds)?x.mcpConfigIds:[]).map(C=>String(C)).filter(Boolean))),I=await t.getSessionMcpServers(c),T=Array.from(new Set((I||[]).map(C=>C.mcp_config_id).filter(C=>typeof C=="string"&&C.trim()!==""))),R=T.filter(C=>!v.includes(C)),D=v.filter(C=>!T.includes(C));for(const C of R)try{await t.deleteSessionMcpServer(c,C)}catch(B){console.warn("Failed to delete session MCP server:",{sessionId:c,id:C,e:B})}if(D.length>0){const C=f().mcpConfigs||[];for(const B of D){const W=C.find(O=>O.id===B),H=W?`${W.name}_${String(B).slice(0,8)}`:`mcp_${String(B).slice(0,8)}`;try{await t.addSessionMcpServer(c,{mcp_server_name:H,mcp_config_id:B})}catch(O){console.warn("Failed to add session MCP server:",{sessionId:c,id:B,e:O})}}}}}catch(b){throw console.error("Failed to update session config:",b),m(y=>{y.error=b instanceof Error?b.message:"Failed to update session config"}),b}},selectSession:async c=>{try{m(_=>{_.isLoading=!0,_.error=null});const x=await h.getSession(c),b=await h.getSessionMessages(c,{limit:10,offset:0});let y=null;try{const _=x==null?void 0:x.metadata,S=typeof _=="string"?_?JSON.parse(_):{}:_&&typeof _=="object"?_:{};y=S.ai_model_config_id||S.model_id||S.modelId||null}catch{y=null}if(m(_=>{_.currentSessionId=c,_.currentSession=x,_.messages=b,_.selectedModelId=y,_.selectedAgentId=null,_.isLoading=!1,_.hasMoreMessages=b.length===10,x||(_.error="Session not found")}),x){const{userId:_,projectId:S}=g();localStorage.setItem(`lastSessionId_${_}_${S}`,c),console.log("🔍 保存会话ID到 localStorage:",c)}}catch(x){console.error("Failed to select session:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to select session",b.isLoading=!1})}},updateSession:async(c,x)=>{try{const b=await h.updateSession(c,x);m(y=>{const _=y.sessions.findIndex(S=>S.id===c);_!==-1&&b&&(y.sessions[_]=b),y.currentSessionId===c&&(y.currentSession=b)})}catch(b){console.error("Failed to update session:",b),m(y=>{y.error=b instanceof Error?b.message:"Failed to update session"})}},deleteSession:async c=>{try{await h.deleteSession(c),m(x=>{x.sessions=x.sessions.filter(b=>b.id!==c),x.currentSessionId===c&&(x.currentSessionId=null,x.currentSession=null,x.messages=[])})}catch(x){console.error("Failed to delete session:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to delete session"})}},loadMessages:async c=>{try{m(b=>{b.isLoading=!0,b.error=null});const x=await h.getSessionMessages(c,{limit:10,offset:0});m(b=>{b.messages=x,b.isLoading=!1,b.hasMoreMessages=x.length===10})}catch(x){console.error("Failed to load messages:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to load messages",b.isLoading=!1})}},loadMoreMessages:async c=>{try{const b=f().messages.length,y=await h.getSessionMessages(c,{limit:10,offset:b});m(_=>{const S=new Set(_.messages.map(v=>v.id)),j=y.filter(v=>!S.has(v.id));_.messages=[...j,..._.messages],_.hasMoreMessages=y.length===10})}catch(x){console.error("Failed to load more messages:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to load more messages"})}},sendMessage:Ef({set:m,get:f,client:t,getUserIdParam:u}),updateMessage:async(c,x)=>{try{const b=await h.updateMessage(c,x);m(y=>{const _=y.messages.findIndex(S=>S.id===c);_!==-1&&b&&(y.messages[_]=b)})}catch(b){console.error("Failed to update message:",b),m(y=>{y.error=b instanceof Error?b.message:"Failed to update message"})}},deleteMessage:async c=>{try{await h.deleteMessage(c),m(x=>{x.messages=x.messages.filter(b=>b.id!==c)})}catch(x){console.error("Failed to delete message:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to delete message"})}},startStreaming:c=>{m(x=>{x.isStreaming=!0,x.streamingMessageId=c})},updateStreamingMessage:c=>{m(x=>{if(x.streamingMessageId){const b=x.messages.findIndex(y=>y.id===x.streamingMessageId);b!==-1&&(x.messages[b].content=c)}})},stopStreaming:()=>{m(c=>{c.isStreaming=!1,c.streamingMessageId=null})},abortCurrentConversation:async()=>{const{currentSessionId:c}=f();if(c)try{await t.stopChat(c),console.log("✅ 成功停止当前对话")}catch(x){console.error("❌ 停止对话失败:",x)}m(x=>{x.isStreaming=!1,x.streamingMessageId=null,x.isLoading=!1})},toggleSidebar:()=>{m(c=>{c.sidebarOpen=!c.sidebarOpen})},setTheme:c=>{m(x=>{x.theme=c})},...Of({set:m}),...Pf({set:m,get:f,client:t,getUserIdParam:u}),...If({set:m,get:f,client:t,getUserIdParam:u}),...Tf({set:m,get:f,client:t,getUserIdParam:u}),loadAgents:async()=>{var c;try{const x=await t.getAgents(u());console.log("🔍 [后端返回] loadAgents 返回的数据:",x),console.log("🔍 [后端返回] 第一个智能体的 app_ids:",(c=x==null?void 0:x[0])==null?void 0:c.app_ids),m(b=>{b.agents=x||[]})}catch(x){console.error("Failed to load agents:",x),m(b=>{b.agents=[],b.error=x instanceof Error?x.message:"Failed to load agents"})}},setSelectedAgent:c=>{m(x=>{x.selectedAgentId=c,c&&(x.selectedModelId=null)})},loadSystemContexts:async()=>{try{const c=await t.getSystemContexts(u()),x=await t.getActiveSystemContext(u());m(b=>{const y=(c||[]).map(_=>({..._,isActive:!1}));if(x&&x.context){const _=x.context,S=y.findIndex(j=>j.id===_.id);S!==-1?(y[S].isActive=!0,b.activeSystemContext={...y[S]}):b.activeSystemContext=null}else b.activeSystemContext=null;b.systemContexts=y})}catch(c){console.error("Failed to load system contexts:",c),m(x=>{x.systemContexts=[],x.activeSystemContext=null})}},createSystemContext:async(c,x,b)=>{try{const y=await t.createSystemContext({name:c,content:x,user_id:u(),app_ids:Array.isArray(b)?b:void 0});return m(_=>{_.systemContexts.push(y)}),y}catch(y){return console.error("Failed to create system context:",y),m(_=>{_.error=y instanceof Error?y.message:"Failed to create system context"}),null}},updateSystemContext:async(c,x,b,y)=>{try{const _=await t.updateSystemContext(c,{name:x,content:b,app_ids:Array.isArray(y)?y:void 0});return m(S=>{const j=S.systemContexts.findIndex(v=>v.id===c);j!==-1&&(S.systemContexts[j]=_)}),_}catch(_){return console.error("Failed to update system context:",_),m(S=>{S.error=_ instanceof Error?_.message:"Failed to update system context"}),null}},deleteSystemContext:async c=>{try{await t.deleteSystemContext(c),m(x=>{var b;x.systemContexts=x.systemContexts.filter(y=>y.id!==c),((b=x.activeSystemContext)==null?void 0:b.id)===c&&(x.activeSystemContext=null)})}catch(x){console.error("Failed to delete system context:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to delete system context"})}},activateSystemContext:async c=>{try{await t.activateSystemContext(c,u()),m(x=>{const b=x.systemContexts.find(y=>y.id===c);b&&(x.systemContexts.forEach(y=>{y.isActive=y.id===c}),x.activeSystemContext={...b,isActive:!0})})}catch(x){console.error("Failed to activate system context:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to activate system context"})}},setError:c=>{m(x=>{x.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=Jr();function Rf(r,e,t){return Jr(t,{userId:r,projectId:e})}const xn=P.createContext(null),$f=({children:r,userId:e,projectId:t,customApiClient:n})=>{const s=P.useMemo(()=>e||t||n?(console.log("🏪 创建自定义store:",{userId:e,projectId:t,hasCustomApiClient:!!n}),Rf(e||"default-user",t||"default-project",n)):(console.log("🏪 使用默认store"),ct),[e,t,n]);return o.jsx(xn.Provider,{value:{store:s,userId:e,projectId:t,apiClient:n},children:r})},Ol=()=>{const r=P.useContext(xn);if(!r)throw new Error("useChatStoreContext must be used within a ChatStoreProvider");return r.store},dt=()=>Ol()(),Lf=()=>{const r=P.useContext(xn);return r?{userId:r.userId,projectId:r.projectId}:{userId:void 0,projectId:void 0}},Df=()=>{const r=P.useContext(xn);return r==null?void 0:r.apiClient},nt=({content:r,isStreaming:e=!1,className:t="",onApplyCode:n})=>{const[s,a]=P.useState(new Set),i=P.useCallback(async h=>{try{await navigator.clipboard.writeText(h)}catch(p){console.error("Failed to copy code:",p)}},[]),l=P.useCallback(h=>{a(p=>{const w=new Set(p);return w.has(h)?w.delete(h):w.add(h),w})},[]),d=P.useMemo(()=>h=>{if(!h)return"";let p=h;const w=/\$\$([\s\S]*?)\$\$/g;p=p.replace(w,(_,S)=>`<div class="math-block">${S.trim()}</div>`);const m=/\$([^$]+)\$/g;p=p.replace(m,(_,S)=>`<span class="math-inline">${S}</span>`);const f=/\|(.+)\|\n\|[-\s|:]+\|\n((?:\|.+\|\n?)*)/g;if(p=p.replace(f,(_,S,j)=>{const v=S.split("|").map(R=>R.trim()).filter(R=>R),I=j.trim().split(`
72
- `).map(R=>R.split("|").map(D=>D.trim()).filter(D=>D));let T="<table>";return v.length>0&&(T+="<thead><tr>",v.forEach(R=>{T+=`<th>${R}</th>`}),T+="</tr></thead>"),I.length>0&&(T+="<tbody>",I.forEach(R=>{R.length>0&&(T+="<tr>",R.forEach(D=>{T+=`<td>${D}</td>`}),T+="</tr>")}),T+="</tbody>"),T+="</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 u=`thread_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,g=new AbortController,h=new oa(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:u,aiClient:h,abortController:g,isRunning:!0,startTime:Date.now()};this.currentThread=p,console.log(`AiServer: Created request thread ${u}`);try{if(this.isAborted||!p.isRunning){console.log(`AiServer: Thread ${u} was aborted before start`);return}await h.start(),console.log(`AiServer: Thread ${u} completed successfully`)}catch(w){if(this.isAborted||!p.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,a=new oa(this.messages,this.conversationId,[],this.modelConfig,(l,d)=>this.callback(l,d),null,this.messageManager,this.configUrl,s,this.sessionId),i={id:n,aiClient:a,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 a.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 Or.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 Ul{constructor(e){V(this,"pendingSaves",new Set);V(this,"savedMessages",new Map);V(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(a=>setTimeout(a,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 a=this.savedMessages.get(t);if(a)return a}this.pendingSaves.add(t);try{const a=await this.databaseService.createMessage(e);return this.savedMessages.set(t,a),a}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(a=>setTimeout(a,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 Uf extends As{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 Bl{constructor(e,t,n,s){V(this,"currentAiClient",null);V(this,"currentSessionId",null);V(this,"dbService");V(this,"messageManager");V(this,"userId");V(this,"configUrl");this.userId=e,this.dbService=new Uf(e,t),this.messageManager=n,this.configUrl=s||"/api",console.log("🔧 ChatService Constructor - configUrl:",this.configUrl)}async sendMessage(e,t,n=[],s={},a){var i,l,d,u,g;try{if(this.currentSessionId=e,!await this.dbService.getSession(e))throw new Error("Session not found");let p;if(a)p=a;else{const f=await this.getChatConfig();p={model_name:f.model,temperature:f.temperature,max_tokens:16e3,api_key:f.apiKey,base_url:f.baseUrl}}const w=new Fl(e,this.userId,this.messageManager,p,this.configUrl,e);let m=3;for(;m>0;)try{await w.init();break}catch(f){if(m--,m===0)throw new Error(`AI服务初始化失败: ${f instanceof Error?f.message:"未知错误"}`);await new Promise(c=>setTimeout(c,1e3))}w.callback=(f,c)=>{var x,b,y,_,S,j,v,I;try{switch(f){case"chunk":const P=typeof c=="string"?c:c.content||c.accumulated||"";(x=s.onChunk)==null||x.call(s,{type:"text",content:P,accumulated:P});break;case"summary_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"tool_call":(y=s.onToolCall)==null||y.call(s,c);break;case"tool_result":(_=s.onToolResult)==null||_.call(s,c);break;case"tool_stream_chunk":(S=s.onToolStreamChunk)==null||S.call(s,c);break;case"complete":debugger;break;case"conversation_complete":(j=s.onComplete)==null||j.call(s,c);break;case"error":const L=c instanceof Error?c.message:typeof c=="string"?c:"AI响应出错";(v=s.onError)==null||v.call(s,new Error(L));break;default:console.warn("Unknown AI response type:",f)}}catch(P){console.error("Callback error:",P),(I=s.onError)==null||I.call(s,new Error(`处理AI响应时出错: ${P instanceof Error?P.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),(u=s.onError)==null||u.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 Bf({set:r,get:e,client:t,getUserIdParam:n}){return async function(a,i=[]){var b;const{currentSessionId:l,selectedModelId:d,aiModelConfigs:u,chatConfig:g,isLoading:h,isStreaming:p,activeSystemContext:w,selectedAgentId:m,agents:f}=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,x=null;if(m){if(x=f.find(y=>y.id===m),!x||x.enabled===!1)throw new Error("选择的智能体不可用")}else if(d){if(c=u.find(y=>y.id===d),!c||!c.enabled)throw new Error("选择的模型不可用")}else throw new Error("请先选择一个模型或智能体");try{const y=new Date,_={id:`temp_user_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:l,role:"user",content:a,status:"completed",createdAt:y,metadata:{...i.length>0?{attachments:i}:{},model:x?`[Agent] ${x.name}`:c.model_name,...c?{modelConfig:{id:c.id,name:c.name,base_url:c.base_url,model_name:c.model_name}}:{}}};r(L=>{L.messages.push(_),L.isLoading=!0,L.isStreaming=!0});const S=new Date(y.getTime()+1),j={id:`temp_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:l,role:"assistant",content:"",status:"streaming",createdAt:S,metadata:{model:x?`[Agent] ${x.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(L=>{L.messages.push(j),L.streamingMessageId=j.id});const v=x?{session_id:l,message:a,agent_id:x.id,system_context:(w==null?void 0:w.content)||g.systemPrompt||"",attachments:i||[]}:{session_id:l,message:a,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:",v);const I=x?await t.streamAgentChat(l,a,x.id,n()):await t.streamChatBySession(l,a,n(),{id:c.id});if(!I)throw new Error("No response received");const P=I.getReader(),T=new TextDecoder;try{for(;;){const{done:L,value:C}=await P.read();if(L){console.log("✅ 流式响应完成");break}const B=T.decode(C,{stream:!0}).split(`
71
+ `);for(const z of B)if(z.trim()!==""&&z.startsWith("data: ")){const O=z.slice(6);if(O==="[DONE]"){console.log("✅ 收到完成信号");break}try{const U=JSON.parse(O);if(typeof U=="string"&&U==="[DONE]"){console.log("✅ 收到完成信号");break}if(U.type==="chunk")U.content&&r(J=>{const $=J.messages.find(H=>H.id===j.id);if($&&$.metadata){const H=typeof U.content=="string"?U.content:typeof U=="string"?U:U.content||"",F=$.metadata.currentSegmentIndex||0,k=$.metadata.contentSegments||[];k[F]&&k[F].type==="text"?k[F].content+=H:(k.push({content:H,type:"text"}),$.metadata.currentSegmentIndex=k.length-1),$.content=k.filter(A=>A.type==="text").map(A=>A.content).join("")}});else if(U.type==="thinking")U.content&&r(J=>{const $=J.messages.find(H=>H.id===j.id);if($&&$.metadata){const H=typeof U.content=="string"?U.content:typeof U=="string"?U:U.content||"",F=$.metadata.contentSegments||[],k=F.length-1;k>=0&&F[k].type==="thinking"?(F[k].content+=H,$.metadata.currentSegmentIndex=k):(F.push({content:H,type:"thinking"}),$.metadata.currentSegmentIndex=F.length-1),$.content=F.filter(A=>A.type==="text").map(A=>A.content).join("")}});else if(U.type==="context_summarized"||U.type==="context_summarized_start"||U.type==="context_summarized_stream"||U.type==="context_summarized_end"){const J=U.data||{},$="【上下文摘要】\\n";r(H=>{const F=H.messages.find(N=>N.id===j.id);if(!F||!F.metadata)return;const k=F.metadata.contentSegments||[],A=()=>{const N=k.length-1;return N>=0&&k[N].type==="thinking"&&String(k[N].content||"").startsWith($)?N:(k.push({content:$,type:"thinking"}),F.metadata.contentSegments=k,F.metadata.currentSegmentIndex=k.length-1,k.length-1)};if(U.type==="context_summarized_start")A();else if(U.type==="context_summarized_stream"){const N=A(),D=J.content||J.chunk||J.data||"";k[N].content+=String(D),F.metadata.currentSegmentIndex=N}else if(U.type==="context_summarized_end"||U.type==="context_summarized"){const N=A(),D=typeof J.full_summary=="string"&&J.full_summary.length>0?J.full_summary:J.summary_preview||"";k[N].content=$+String(D),F.metadata.contentSegments=k,F.metadata.currentSegmentIndex=N}F.updatedAt=new Date})}else if(U.type==="content")r(J=>{const $=J.messages.find(H=>H.id===j.id);if($&&$.metadata){const H=typeof U.content=="string"?U.content:typeof U=="string"?U:U.content||"",F=$.metadata.currentSegmentIndex||0,k=$.metadata.contentSegments||[];k[F]&&k[F].type==="text"?k[F].content+=H:(k.push({content:H,type:"text"}),$.metadata.currentSegmentIndex=k.length-1),$.content=k.filter(A=>A.type==="text").map(A=>A.content).join("")}});else if(U.type==="tools_start"){console.log("🔧 收到工具调用:",U.data),console.log("🔧 工具调用数据类型:",typeof U.data,"是否为数组:",Array.isArray(U.data));const J=F=>{var A,N,D;console.log("🔧 [DEBUG] 原始工具调用数据:",F),console.log("🔧 [DEBUG] tc.function:",F.function),console.log("🔧 [DEBUG] tc.function?.name:",(A=F.function)==null?void 0:A.name),console.log("🔧 [DEBUG] tc.name:",F.name);const k={id:F.id||F.tool_call_id||`tool_${Date.now()}_${Math.random()}`,messageId:j.id,name:((N=F.function)==null?void 0:N.name)||F.name||"unknown_tool",arguments:((D=F.function)==null?void 0:D.arguments)||F.arguments||"{}",result:F.result||"",error:F.error||void 0,createdAt:F.createdAt||F.created_at||new Date};return console.log("🔧 [DEBUG] 转换后的工具调用:",k),k};console.log("🔧 [DEBUG] tools_start 原始数据:",U.data);const $=U.data.tool_calls||U.data,H=Array.isArray($)?$:[$];console.log("🔧 [DEBUG] 提取的工具调用数组:",H),r(F=>{const k=F.messages.findIndex(A=>A.id===j.id);if(console.log("🔧 查找消息索引:",k,"消息ID:",j.id),k!==-1){const A=F.messages[k];console.log("🔧 找到消息,当前metadata:",A.metadata),A.metadata||(A.metadata={}),A.metadata.toolCalls||(A.metadata.toolCalls=[]);const N=A.metadata.contentSegments||[];console.log("🔧 处理工具调用数组,长度:",H.length),H.forEach(D=>{const R=J(D);console.log("🔧 添加转换后的工具调用:",R),A.metadata.toolCalls.push(R),N.push({content:"",type:"tool_call",toolCallId:R.id})}),N.push({content:"",type:"text"}),A.metadata.currentSegmentIndex=N.length-1,console.log("🔧 更新后的toolCalls:",A.metadata.toolCalls)}else console.log("🔧 ❌ 未找到对应的消息")})}else if(U.type==="tools_end"){console.log("🔧 收到工具结果:",U.data),console.log("🔧 工具结果数据类型:",typeof U.data);const J=Array.isArray(U.data)?U.data:[U.data];r($=>{const H=$.messages.findIndex(F=>F.id===j.id);if(H!==-1){const F=$.messages[H];F.metadata&&F.metadata.toolCalls&&(J.forEach(k=>{var D,R,q,Q;const A=k.tool_call_id||k.id||k.toolCallId;if(!A){console.warn("⚠️ 工具结果缺少工具调用ID:",k);return}console.log("🔍 查找工具调用:",A,"在消息中:",(R=(D=F.metadata)==null?void 0:D.toolCalls)==null?void 0:R.map(se=>se.id));const N=F.metadata.toolCalls.find(se=>se.id===A);if(N){console.log("✅ 找到工具调用,更新最终结果:",N.id);const se=k.result||k.content||k.output||"";k.success===!1||k.is_error===!0?(N.error=k.error||se||"工具执行失败",console.log("❌ 工具执行失败:",{id:N.id,name:k.name||N.name,error:N.error,success:k.success,is_error:k.is_error})):((!N.result||N.result.trim()==="")&&(N.result=se),N.error&&delete N.error,console.log("✅ 工具执行成功,最终结果已更新:",{id:N.id,name:k.name||N.name,resultLength:N.result.length,success:k.success,is_stream:k.is_stream}))}else console.log("❌ 未找到对应的工具调用:",A),console.log("📋 当前可用的工具调用ID:",(Q=(q=F.metadata)==null?void 0:q.toolCalls)==null?void 0:Q.map(se=>se.id))}),F.updatedAt=new Date)}})}else if(U.type==="tools_stream"){console.log("🔧 收到工具流式数据:",U.data);const J=U.data;r($=>{const H=$.messages.findIndex(F=>F.id===j.id);if(H!==-1){const F=$.messages[H];if(F.metadata&&F.metadata.toolCalls){const k=J.toolCallId||J.tool_call_id||J.id;if(!k){console.warn("⚠️ 工具流式数据缺少工具调用ID:",J);return}console.log("🔍 查找工具调用进行流式更新:",k);const A=F.metadata.toolCalls.find(N=>N.id===k);if(A){const N=J.content||J.chunk||J.data||"";J.is_error||!J.success?(A.error=N||"工具执行出错",console.log("❌ 工具流式执行出错:",{id:A.id,error:A.error,success:J.success,is_error:J.is_error})):(A.result=(A.result||"")+N,console.log("🔧 工具流式数据已更新:",{id:A.id,name:J.name,chunkLength:N.length,totalLength:A.result.length,success:J.success,is_stream:J.is_stream})),F.updatedAt=new Date}}}})}else{if(U.type==="error")throw new Error(U.message||((b=U.data)==null?void 0:b.message)||"Stream error");if(U.type==="cancelled"){console.log("⚠️ 流式会话已被取消");break}else if(U.type==="done"){console.log("✅ 收到完成信号");break}}}catch(U){console.warn("解析流式数据失败:",U,"data:",O)}}}}finally{P.releaseLock(),r(L=>{L.isLoading=!1,L.isStreaming=!1,L.streamingMessageId=null})}console.log("✅ 消息发送完成")}catch(y){throw console.error("❌ 发送消息失败:",y),r(_=>{const S=_.messages.findIndex(j=>{var v;return(v=j.id)==null?void 0:v.startsWith("temp_")});S!==-1&&_.messages.splice(S,1),_.isLoading=!1,_.isStreaming=!1,_.streamingMessageId=null,_.error=y instanceof Error?y.message:"Failed to send message"}),y}}}function Wf({set:r,get:e,client:t,getUserIdParam:n}){const s=a=>({id:a.id,name:a.name,url:a.url,iconUrl:a.icon_url??void 0,createdAt:new Date(a.created_at),updatedAt:new Date(a.updated_at??a.created_at)});return{loadApplications:async()=>{try{console.log("[Store] loadApplications: start");const a=n(),l=(await t.getApplications(a)||[]).map(s);r(d=>{d.applications=l}),console.log("[Store] loadApplications: loaded",l.length,"items")}catch(a){console.error("Failed to load applications:",a),r(i=>{i.applications=[]})}},createApplication:async(a,i,l)=>{try{const d=await t.createApplication({name:a,url:i,icon_url:l??null,user_id:n()}),u=s(d);r(g=>{g.applications=[u,...g.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(a,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(a,l),u=s(d);r(g=>{g.applications=g.applications.map(h=>h.id===a?u: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 a=>{try{await t.deleteApplication(a),r(i=>{i.applications=i.applications.filter(l=>l.id!==a),i.mcpConfigs=i.mcpConfigs.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==a):[]})),i.systemContexts=i.systemContexts.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==a):[]})),i.agents=i.agents.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(d=>d!==a):[]}))})}catch(i){console.error("Failed to delete application:",i),r(l=>{l.error=i instanceof Error?i.message:"Failed to delete application"})}},setSelectedApplication:a=>{console.log("[Store] setSelectedApplication:",a);const i=e().selectedApplicationId;console.log("[Store] setSelectedApplication - before:",{oldId:i,newId:a}),r(d=>({...d,selectedApplicationId:a}));const l=e().selectedApplicationId;console.log("[Store] setSelectedApplication - after:",{oldId:i,newId:l})},setMcpAppAssociation:(a,i)=>{r(l=>{l.mcpConfigs=l.mcpConfigs.map(d=>d.id===a?{...d,app_ids:Array.isArray(i)?i:[]}:d)})},setSystemContextAppAssociation:(a,i)=>{r(l=>{l.systemContexts=l.systemContexts.map(d=>d.id===a?{...d,app_ids:Array.isArray(i)?i:[]}:d)});try{(async()=>await t.updateSystemContext(a,{name:void 0,content:void 0,app_ids:Array.isArray(i)?i:[]}))()}catch{}},setAgentAppAssociation:(a,i)=>{r(l=>{l.agents=l.agents.map(d=>d.id===a?{...d,app_ids:Array.isArray(i)?i:[]}:d)});try{(async()=>await t.updateAgent(a,{app_ids:Array.isArray(i)?i:[]}))()}catch{}}}}function Hf({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(a=>{a.error=s instanceof Error?s.message:"Failed to load AI model configs"})}},updateAiModelConfig:async s=>{try{const a=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:a};l==="update"?await t.updateAiModelConfig(s.id,d):await t.createAiModelConfig(d),await e().loadAiModelConfigs()}catch(a){console.error("Failed to update AI model config:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to update AI model config"})}},deleteAiModelConfig:async s=>{try{await t.deleteAiModelConfig(s),r(a=>{a.aiModelConfigs=a.aiModelConfigs.filter(i=>i.id!==s)})}catch(a){console.error("Failed to delete AI model config:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to delete AI model config"})}},setSelectedModel:s=>{var l,d;const i=e().currentSessionId||null;r(u=>{var g,h;if(u.selectedModelId=s,s&&(u.selectedAgentId=null),u.currentSession&&u.currentSessionId){const p=u.currentSession.metadata;let w={};try{const f=typeof p=="string"?p?JSON.parse(p):{}:p&&typeof p=="object"?p:{};w=f&&typeof f=="object"&&!Array.isArray(f)?{...f}:{}}catch{w={}}s?w.ai_model_config_id=s:delete w.ai_model_config_id,u.currentSession.metadata=w;const m=((h=(g=u.sessions)==null?void 0:g.findIndex)==null?void 0:h.call(g,f=>f.id===u.currentSessionId))??-1;m!==-1&&u.sessions[m]&&(u.sessions[m]={...u.sessions[m],metadata:w})}}),i&&((d=(l=e()).updateSessionConfig)==null||d.call(l,i,{modelId:s}).catch(u=>{console.error("Failed to persist session model selection:",u)}))}}}function qf({set:r,get:e,client:t,getUserIdParam:n}){return{loadMcpConfigs:async()=>{var s;try{const a=n(),i=await t.getMcpConfigs(a);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(a){console.error("Failed to load MCP configs:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to load MCP configs"})}},updateMcpConfig:async s=>{try{const a=n();console.log("🔍 updateMcpConfig 调用:",{userId:a,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:a,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:a,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(g=>g.id===l?{...g,app_ids:d}:g)}),await e().loadMcpConfigs(),i}catch(a){return console.error("Failed to update MCP config:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to update MCP config"}),null}},deleteMcpConfig:async s=>{try{await t.deleteMcpConfig(s),r(a=>{a.mcpConfigs=a.mcpConfigs.filter(i=>i.id!==s)})}catch(a){console.error("Failed to delete MCP config:",a),r(i=>{i.error=a instanceof Error?a.message:"Failed to delete MCP config"})}}}}function zf({set:r}){return{updateChatConfig:async e=>{r(t=>{t.chatConfig={...t.chatConfig,...e}})}}}function Zr(r,e){const t=r||te,n=e==null?void 0:e.userId,s=e==null?void 0:e.projectId,a=e==null?void 0:e.configUrl,i=n||"default-user",l=s||"default-project",d=a||"/api",u=()=>i,g=()=>({userId:i,projectId:l}),h=new As(i,l,t),p=new Ul(h),w=new Bl(i,l,p,d);return console.log("chatService:",w),Oc()(Gc(ed((m,f)=>({sessions:[],currentSessionId:null,currentSession:null,sessionMcpRevision:0,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:x}=g();console.log("🔍 loadSessions 调用 client.getSessions",{userId:c,projectId:x,customUserId:n,customProjectId:s});const b=await t.getSessions(c,x);console.log("🔍 loadSessions 返回结果:",b),m(_=>{_.sessions=b,_.isLoading=!1});const y=f();if(b.length>0&&!y.currentSessionId){const _=localStorage.getItem(`lastSessionId_${c}_${x}`);let S=null;_&&(S=b.find(j=>j.id===_)),S||(S=[...b].sort((j,v)=>new Date(v.createdAt).getTime()-new Date(j.createdAt).getTime())[0]),S&&(console.log("🔍 自动选择会话:",S.id),setTimeout(()=>{f().selectSession(S.id)},0))}console.log("🔍 loadSessions 完成")}catch(c){console.error("🔍 loadSessions 错误:",c),m(x=>{x.error=c instanceof Error?c.message:"Failed to load sessions",x.isLoading=!1})}},createSession:async(c="New Chat")=>{try{const{userId:x,projectId:b}=g(),y=typeof c=="string"?{title:c}:c||{},_=y.title||"New Chat",S=y.modelId??f().selectedModelId??null,j=Array.isArray(y.mcpConfigIds)?y.mcpConfigIds:[],v=Array.isArray(y.promptIds)?y.promptIds:[];console.log("🔍 createSession 使用参数:",{userId:x,projectId:b,title:_}),console.log("🔍 createSession 自定义参数:",{customUserId:n,customProjectId:s}),console.log("🔍 createSession 最终使用的参数:",{userId:x,projectId:b,isCustomUserId:!!n,isCustomProjectId:!!s});const I=crypto.randomUUID(),P={id:I,title:_,user_id:x,project_id:b},T={...S?{ai_model_config_id:S}:{},...v.length>0?{prompt_ids:v}:{}};Object.keys(T).length>0&&(P.metadata=T),j.length>0&&(P.mcp_config_ids=j);const L=await t.createSession(P);console.log("✅ createSession API调用成功:",L);const W={id:(L==null?void 0:L.id)||I,title:L.title,createdAt:new Date(L.created_at),updatedAt:new Date(L.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:L.metadata||null};return m(B=>{B.sessions.unshift(W),B.currentSessionId=W.id,B.currentSession=W,B.messages=[],B.selectedModelId=S,B.selectedAgentId=null,B.error=null}),localStorage.setItem(`lastSessionId_${x}_${b}`,W.id),console.log("🔍 保存新创建的会话ID到 localStorage:",W.id),W.id}catch(x){throw console.error("❌ createSession 失败:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to create session"}),x}},getSessionMcpConfigIds:async c=>{try{if(!c)return[];const x=await t.getSessionMcpServers(c);return Array.from(new Set((x||[]).map(y=>y.mcp_config_id).filter(y=>typeof y=="string"&&y.trim()!=="")))}catch(x){return console.error("Failed to load session MCP config ids:",x),[]}},updateSessionConfig:async(c,x)=>{try{if(!c)return;const b=f(),y=b.sessions.find(v=>v.id===c)||(b.currentSessionId===c?b.currentSession:null),_=y==null?void 0:y.metadata;let S={};try{const v=typeof _=="string"?_?JSON.parse(_):{}:_&&typeof _=="object"?_:{};S=v&&typeof v=="object"&&!Array.isArray(v)?{...v}:{}}catch{S={}}if(x.modelId!==void 0&&(x.modelId?S.ai_model_config_id=x.modelId:delete S.ai_model_config_id),x.promptIds!==void 0){const v=Array.isArray(x.promptIds)?x.promptIds.map(I=>String(I)).filter(Boolean):[];v.length>0?S.prompt_ids=v:delete S.prompt_ids}if(x.promptText!==void 0){const v=x.promptText==null?"":String(x.promptText).trim();v.length>0?S.prompt_text=v:delete S.prompt_text,delete S.promptText,delete S.session_prompt,delete S.sessionPrompt}const j={};if(x.title!==void 0&&(j.title=x.title),j.metadata=S,await f().updateSession(c,j),b.currentSessionId===c&&x.modelId!==void 0&&m(v=>{v.selectedModelId=x.modelId||null,v.selectedAgentId=null}),x.mcpConfigIds!==void 0){const v=Array.from(new Set((Array.isArray(x.mcpConfigIds)?x.mcpConfigIds:[]).map(C=>String(C)).filter(Boolean))),I=await t.getSessionMcpServers(c),P=Array.from(new Set((I||[]).map(C=>C.mcp_config_id).filter(C=>typeof C=="string"&&C.trim()!==""))),T=P.filter(C=>!v.includes(C)),L=v.filter(C=>!P.includes(C));for(const C of T)try{await t.deleteSessionMcpServer(c,C)}catch(W){console.warn("Failed to delete session MCP server:",{sessionId:c,id:C,e:W})}if(L.length>0){const C=f().mcpConfigs||[];for(const W of L){const B=C.find(O=>O.id===W),z=B?`${B.name}_${String(W).slice(0,8)}`:`mcp_${String(W).slice(0,8)}`;try{await t.addSessionMcpServer(c,{mcp_server_name:z,mcp_config_id:W})}catch(O){console.warn("Failed to add session MCP server:",{sessionId:c,id:W,e:O})}}}(T.length>0||L.length>0)&&m(C=>{C.sessionMcpRevision=(C.sessionMcpRevision??0)+1})}}catch(b){throw console.error("Failed to update session config:",b),m(y=>{y.error=b instanceof Error?b.message:"Failed to update session config"}),b}},selectSession:async c=>{try{m(_=>{_.isLoading=!0,_.error=null});const x=await h.getSession(c),b=await h.getSessionMessages(c,{limit:10,offset:0});let y=null;try{const _=x==null?void 0:x.metadata,S=typeof _=="string"?_?JSON.parse(_):{}:_&&typeof _=="object"?_:{};y=S.ai_model_config_id||S.model_id||S.modelId||null}catch{y=null}if(m(_=>{_.currentSessionId=c,_.currentSession=x,_.messages=b,_.selectedModelId=y,_.selectedAgentId=null,_.isLoading=!1,_.hasMoreMessages=b.length===10,x||(_.error="Session not found")}),x){const{userId:_,projectId:S}=g();localStorage.setItem(`lastSessionId_${_}_${S}`,c),console.log("🔍 保存会话ID到 localStorage:",c)}}catch(x){console.error("Failed to select session:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to select session",b.isLoading=!1})}},updateSession:async(c,x)=>{try{const b=await h.updateSession(c,x);m(y=>{const _=y.sessions.findIndex(S=>S.id===c);_!==-1&&b&&(y.sessions[_]=b),y.currentSessionId===c&&(y.currentSession=b)})}catch(b){console.error("Failed to update session:",b),m(y=>{y.error=b instanceof Error?b.message:"Failed to update session"})}},deleteSession:async c=>{try{await h.deleteSession(c),m(x=>{x.sessions=x.sessions.filter(b=>b.id!==c),x.currentSessionId===c&&(x.currentSessionId=null,x.currentSession=null,x.messages=[])})}catch(x){console.error("Failed to delete session:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to delete session"})}},loadMessages:async c=>{try{m(b=>{b.isLoading=!0,b.error=null});const x=await h.getSessionMessages(c,{limit:10,offset:0});m(b=>{b.messages=x,b.isLoading=!1,b.hasMoreMessages=x.length===10})}catch(x){console.error("Failed to load messages:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to load messages",b.isLoading=!1})}},loadMoreMessages:async c=>{try{const b=f().messages.length,y=await h.getSessionMessages(c,{limit:10,offset:b});m(_=>{const S=new Set(_.messages.map(v=>v.id)),j=y.filter(v=>!S.has(v.id));_.messages=[...j,..._.messages],_.hasMoreMessages=y.length===10})}catch(x){console.error("Failed to load more messages:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to load more messages"})}},sendMessage:Bf({set:m,get:f,client:t,getUserIdParam:u}),updateMessage:async(c,x)=>{try{const b=await h.updateMessage(c,x);m(y=>{const _=y.messages.findIndex(S=>S.id===c);_!==-1&&b&&(y.messages[_]=b)})}catch(b){console.error("Failed to update message:",b),m(y=>{y.error=b instanceof Error?b.message:"Failed to update message"})}},deleteMessage:async c=>{try{await h.deleteMessage(c),m(x=>{x.messages=x.messages.filter(b=>b.id!==c)})}catch(x){console.error("Failed to delete message:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to delete message"})}},startStreaming:c=>{m(x=>{x.isStreaming=!0,x.streamingMessageId=c})},updateStreamingMessage:c=>{m(x=>{if(x.streamingMessageId){const b=x.messages.findIndex(y=>y.id===x.streamingMessageId);b!==-1&&(x.messages[b].content=c)}})},stopStreaming:()=>{m(c=>{c.isStreaming=!1,c.streamingMessageId=null})},abortCurrentConversation:async()=>{const{currentSessionId:c}=f();if(c)try{await t.stopChat(c),console.log("✅ 成功停止当前对话")}catch(x){console.error("❌ 停止对话失败:",x)}m(x=>{x.isStreaming=!1,x.streamingMessageId=null,x.isLoading=!1})},toggleSidebar:()=>{m(c=>{c.sidebarOpen=!c.sidebarOpen})},setTheme:c=>{m(x=>{x.theme=c})},...zf({set:m}),...qf({set:m,get:f,client:t,getUserIdParam:u}),...Wf({set:m,get:f,client:t,getUserIdParam:u}),...Hf({set:m,get:f,client:t,getUserIdParam:u}),loadAgents:async()=>{var c;try{const x=await t.getAgents(u());console.log("🔍 [后端返回] loadAgents 返回的数据:",x),console.log("🔍 [后端返回] 第一个智能体的 app_ids:",(c=x==null?void 0:x[0])==null?void 0:c.app_ids),m(b=>{b.agents=x||[]})}catch(x){console.error("Failed to load agents:",x),m(b=>{b.agents=[],b.error=x instanceof Error?x.message:"Failed to load agents"})}},setSelectedAgent:c=>{m(x=>{x.selectedAgentId=c,c&&(x.selectedModelId=null)})},loadSystemContexts:async()=>{try{const c=await t.getSystemContexts(u()),x=await t.getActiveSystemContext(u());m(b=>{const y=(c||[]).map(_=>({..._,isActive:!1}));if(x&&x.context){const _=x.context,S=y.findIndex(j=>j.id===_.id);S!==-1?(y[S].isActive=!0,b.activeSystemContext={...y[S]}):b.activeSystemContext=null}else b.activeSystemContext=null;b.systemContexts=y})}catch(c){console.error("Failed to load system contexts:",c),m(x=>{x.systemContexts=[],x.activeSystemContext=null})}},createSystemContext:async(c,x,b)=>{try{const y=await t.createSystemContext({name:c,content:x,user_id:u(),app_ids:Array.isArray(b)?b:void 0});return m(_=>{_.systemContexts.push(y)}),y}catch(y){return console.error("Failed to create system context:",y),m(_=>{_.error=y instanceof Error?y.message:"Failed to create system context"}),null}},updateSystemContext:async(c,x,b,y)=>{try{const _=await t.updateSystemContext(c,{name:x,content:b,app_ids:Array.isArray(y)?y:void 0});return m(S=>{const j=S.systemContexts.findIndex(v=>v.id===c);j!==-1&&(S.systemContexts[j]=_)}),_}catch(_){return console.error("Failed to update system context:",_),m(S=>{S.error=_ instanceof Error?_.message:"Failed to update system context"}),null}},deleteSystemContext:async c=>{try{await t.deleteSystemContext(c),m(x=>{var b;x.systemContexts=x.systemContexts.filter(y=>y.id!==c),((b=x.activeSystemContext)==null?void 0:b.id)===c&&(x.activeSystemContext=null)})}catch(x){console.error("Failed to delete system context:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to delete system context"})}},activateSystemContext:async c=>{try{await t.activateSystemContext(c,u()),m(x=>{const b=x.systemContexts.find(y=>y.id===c);b&&(x.systemContexts.forEach(y=>{y.isActive=y.id===c}),x.activeSystemContext={...b,isActive:!0})})}catch(x){console.error("Failed to activate system context:",x),m(b=>{b.error=x instanceof Error?x.message:"Failed to activate system context"})}},setError:c=>{m(x=>{x.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 mt=Zr();function Jf(r,e,t){return Zr(t,{userId:r,projectId:e})}const Cn=M.createContext(null),Vf=({children:r,userId:e,projectId:t,customApiClient:n})=>{const s=M.useMemo(()=>e||t||n?(console.log("🏪 创建自定义store:",{userId:e,projectId:t,hasCustomApiClient:!!n}),Jf(e||"default-user",t||"default-project",n)):(console.log("🏪 使用默认store"),mt),[e,t,n]);return o.jsx(Cn.Provider,{value:{store:s,userId:e,projectId:t,apiClient:n},children:r})},Wl=()=>{const r=M.useContext(Cn);if(!r)throw new Error("useChatStoreContext must be used within a ChatStoreProvider");return r.store},tt=()=>Wl()(),Gf=()=>{const r=M.useContext(Cn);return r?{userId:r.userId,projectId:r.projectId}:{userId:void 0,projectId:void 0}},Xf=()=>{const r=M.useContext(Cn);return r==null?void 0:r.apiClient},lt=({content:r,isStreaming:e=!1,className:t="",onApplyCode:n})=>{const[s,a]=M.useState(new Set),i=M.useCallback(async h=>{try{await navigator.clipboard.writeText(h)}catch(p){console.error("Failed to copy code:",p)}},[]),l=M.useCallback(h=>{a(p=>{const w=new Set(p);return w.has(h)?w.delete(h):w.add(h),w})},[]),d=M.useMemo(()=>h=>{if(!h)return"";let p=h;const w=/\$\$([\s\S]*?)\$\$/g;p=p.replace(w,(_,S)=>`<div class="math-block">${S.trim()}</div>`);const m=/\$([^$]+)\$/g;p=p.replace(m,(_,S)=>`<span class="math-inline">${S}</span>`);const f=/\|(.+)\|\n\|[-\s|:]+\|\n((?:\|.+\|\n?)*)/g;if(p=p.replace(f,(_,S,j)=>{const v=S.split("|").map(T=>T.trim()).filter(T=>T),I=j.trim().split(`
72
+ `).map(T=>T.split("|").map(L=>L.trim()).filter(L=>L));let P="<table>";return v.length>0&&(P+="<thead><tr>",v.forEach(T=>{P+=`<th>${T}</th>`}),P+="</tr></thead>"),I.length>0&&(P+="<tbody>",I.forEach(T=>{T.length>0&&(P+="<tr>",T.forEach(L=>{P+=`<td>${L}</td>`}),P+="</tr>")}),P+="</tbody>"),P+="</table>",e?`<div class="streaming-table-wrapper">
73
73
  <div class="streaming-table-indicator">● 正在生成表格...</div>
74
- ${T}
75
- </div>`:T}),e){const _=/\|(.+)\|\n\|[-\s|:]+\|(?:\n(?:\|.+\|)*)?$/,S=p.match(_);if(S){const[j,v]=S,I=v.split("|").map(B=>B.trim()).filter(B=>B),D=j.split(`
76
- `).slice(2).map(B=>B.split("|").map(W=>W.trim()).filter(W=>W)).filter(B=>B.length>0);let C='<div class="streaming-table-wrapper">';C+='<div class="streaming-table-indicator">● 正在生成表格...</div>',C+='<table class="streaming-table">',I.length>0&&(C+="<thead><tr>",I.forEach(B=>{C+=`<th>${B}</th>`}),C+="</tr></thead>"),D.length>0&&(C+="<tbody>",D.forEach(B=>{C+="<tr>",B.forEach(W=>{C+=`<td>${W}</td>`}),C+="</tr>"}),C+="</tbody>"),C+="</table></div>",p=p.replace(_,C)}}const c=/```(\w+)?\n?([\s\S]*?)```/g;let x=0;if(p=p.replace(c,(_,S,j)=>{const v=S||"text",I=u(j.trim()),T=`code-block-${x++}`,R=s.has(T),D=j.trim();return`<div class="code-block ${R?"expanded":""}" data-block-id="${T}">
74
+ ${P}
75
+ </div>`:P}),e){const _=/\|(.+)\|\n\|[-\s|:]+\|(?:\n(?:\|.+\|)*)?$/,S=p.match(_);if(S){const[j,v]=S,I=v.split("|").map(W=>W.trim()).filter(W=>W),L=j.split(`
76
+ `).slice(2).map(W=>W.split("|").map(B=>B.trim()).filter(B=>B)).filter(W=>W.length>0);let C='<div class="streaming-table-wrapper">';C+='<div class="streaming-table-indicator">● 正在生成表格...</div>',C+='<table class="streaming-table">',I.length>0&&(C+="<thead><tr>",I.forEach(W=>{C+=`<th>${W}</th>`}),C+="</tr></thead>"),L.length>0&&(C+="<tbody>",L.forEach(W=>{C+="<tr>",W.forEach(B=>{C+=`<td>${B}</td>`}),C+="</tr>"}),C+="</tbody>"),C+="</table></div>",p=p.replace(_,C)}}const c=/```(\w+)?\n?([\s\S]*?)```/g;let x=0;if(p=p.replace(c,(_,S,j)=>{const v=S||"text",I=u(j.trim()),P=`code-block-${x++}`,T=s.has(P),L=j.trim();return`<div class="code-block ${T?"expanded":""}" data-block-id="${P}">
77
77
  <div class="code-header">
78
78
  <span class="code-language">${v}</span>
79
79
  <div class="code-actions">
80
- <button class="code-action-btn copy-btn" data-code="${encodeURIComponent(D)}" title="复制代码">
80
+ <button class="code-action-btn copy-btn" data-code="${encodeURIComponent(L)}" title="复制代码">
81
81
  <span class="icon">复制</span>
82
82
  </button>
83
- <button class="code-action-btn apply-btn" data-code="${encodeURIComponent(D)}" data-language="${v}" title="应用代码">
83
+ <button class="code-action-btn apply-btn" data-code="${encodeURIComponent(L)}" data-language="${v}" title="应用代码">
84
84
  <span class="icon">应用</span>
85
85
  </button>
86
- <button class="code-action-btn expand-btn" data-block-id="${T}" title="${R?"收起":"展开"}">
87
- <span class="icon">${R?"收起":"展开"}</span>
86
+ <button class="code-action-btn expand-btn" data-block-id="${P}" title="${T?"收起":"展开"}">
87
+ <span class="icon">${T?"收起":"展开"}</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>`}),p=p.replace(/`([^`\n]+)`/g,"<code>$1</code>"),e){const _=/```(\w+)?\n?([\s\S]*?)$/,S=p.match(_);if(S&&!S[0].includes("```",3)){const[,j,v]=S,I=j||"text",T=u(v);p=p.replace(_,`<div class="code-block streaming-code">
94
+ </div>`}),p=p.replace(/`([^`\n]+)`/g,"<code>$1</code>"),e){const _=/```(\w+)?\n?([\s\S]*?)$/,S=p.match(_);if(S&&!S[0].includes("```",3)){const[,j,v]=S,I=j||"text",P=u(v);p=p.replace(_,`<div class="code-block streaming-code">
95
95
  <div class="code-header">${I} <span class="streaming-indicator">● 正在输入...</span></div>
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 b=[];let y=0;return p=p.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g,_=>{const S=`__PROTECTED_HTML_${y++}__`;return b.push(_),S}),p=p.replace(/<[^>]+>/g,_=>{const S=`__PROTECTED_HTML_${y++}__`;return b.push(_),S}),p=p.replace(/\n\n/g,"</p><p>"),p=p.replace(/\n/g,"<br>"),b.forEach((_,S)=>{p=p.replace(`__PROTECTED_HTML_${S}__`,_)}),p&&!p.startsWith("<")&&(p=`<p>${p}</p>`),p},[e,s,n]),u=(h,p)=>h.replace(/</g,"&lt;").replace(/>/g,"&gt;"),g=P.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")||""),f=w.getAttribute("data-language")||"text";n==null||n(m,f)}else if(w.classList.contains("expand-btn")){const m=w.getAttribute("data-block-id");m&&l(m)}}},[i,n,l]);return o.jsxs("div",{className:`markdown-renderer ${t}`,onClick:g,children:[o.jsx("div",{dangerouslySetInnerHTML:{__html:d(r)}}),e&&o.jsx("span",{className:"streaming-cursor"})]})};function Rl(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=Rl(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Ff(){for(var r,e,t=0,n="",s=arguments.length;t<s;t++)(r=arguments[t])&&(e=Rl(r))&&(n&&(n+=" "),n+=e);return n}const oo="-",Uf=r=>{const e=Wf(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:i=>{const l=i.split(oo);return l[0]===""&&l.length!==1&&l.shift(),$l(l,e)||Bf(i)},getConflictingClassGroupIds:(i,l)=>{const d=t[i]||[];return l&&n[i]?[...d,...n[i]]:d}}},$l=(r,e)=>{var i;if(r.length===0)return e.classGroupId;const t=r[0],n=e.nextPart.get(t),s=n?$l(r.slice(1),n):void 0;if(s)return s;if(e.validators.length===0)return;const a=r.join(oo);return(i=e.validators.find(({validator:l})=>l(a)))==null?void 0:i.classGroupId},ga=/^\[(.+)\]$/,Bf=r=>{if(ga.test(r)){const e=ga.exec(r)[1],t=e==null?void 0:e.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},Wf=r=>{const{theme:e,prefix:t}=r,n={nextPart:new Map,validators:[]};return qf(Object.entries(r.classGroups),t).forEach(([a,i])=>{fs(i,n,a,e)}),n},fs=(r,e,t,n)=>{r.forEach(s=>{if(typeof s=="string"){const a=s===""?e:pa(e,s);a.classGroupId=t;return}if(typeof s=="function"){if(Hf(s)){fs(s(n),e,t,n);return}e.validators.push({validator:s,classGroupId:t});return}Object.entries(s).forEach(([a,i])=>{fs(i,pa(e,a),t,n)})})},pa=(r,e)=>{let t=r;return e.split(oo).forEach(n=>{t.nextPart.has(n)||t.nextPart.set(n,{nextPart:new Map,validators:[]}),t=t.nextPart.get(n)}),t},Hf=r=>r.isThemeGetter,qf=(r,e)=>e?r.map(([t,n])=>{const s=n.map(a=>typeof a=="string"?e+a:typeof a=="object"?Object.fromEntries(Object.entries(a).map(([i,l])=>[e+i,l])):a);return[t,s]}):r,zf=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,n=new Map;const s=(a,i)=>{t.set(a,i),e++,e>r&&(e=0,n=t,t=new Map)};return{get(a){let i=t.get(a);if(i!==void 0)return i;if((i=n.get(a))!==void 0)return s(a,i),i},set(a,i){t.has(a)?t.set(a,i):s(a,i)}}},Ll="!",Jf=r=>{const{separator:e,experimentalParseClassName:t}=r,n=e.length===1,s=e[0],a=e.length,i=l=>{const d=[];let u=0,g=0,h;for(let c=0;c<l.length;c++){let x=l[c];if(u===0){if(x===s&&(n||l.slice(c,c+a)===e)){d.push(l.slice(g,c)),g=c+a;continue}if(x==="/"){h=c;continue}}x==="["?u++:x==="]"&&u--}const p=d.length===0?l:l.substring(g),w=p.startsWith(Ll),m=w?p.substring(1):p,f=h&&h>g?h-g:void 0;return{modifiers:d,hasImportantModifier:w,baseClassName:m,maybePostfixModifierPosition:f}};return t?l=>t({className:l,parseClassName:i}):i},Vf=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},Gf=r=>({cache:zf(r.cacheSize),parseClassName:Jf(r),...Uf(r)}),Xf=/\s+/,Kf=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:s}=e,a=[],i=r.trim().split(Xf);let l="";for(let d=i.length-1;d>=0;d-=1){const u=i[d],{modifiers:g,hasImportantModifier:h,baseClassName:p,maybePostfixModifierPosition:w}=t(u);let m=!!w,f=n(m?p.substring(0,w):p);if(!f){if(!m){l=u+(l.length>0?" "+l:l);continue}if(f=n(p),!f){l=u+(l.length>0?" "+l:l);continue}m=!1}const c=Vf(g).join(":"),x=h?c+Ll:c,b=x+f;if(a.includes(b))continue;a.push(b);const y=s(f,m);for(let _=0;_<y.length;++_){const S=y[_];a.push(x+S)}l=u+(l.length>0?" "+l:l)}return l};function Yf(){let r=0,e,t,n="";for(;r<arguments.length;)(e=arguments[r++])&&(t=Dl(e))&&(n&&(n+=" "),n+=t);return n}const Dl=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=Dl(r[n]))&&(t&&(t+=" "),t+=e);return t};function Qf(r,...e){let t,n,s,a=i;function i(d){const u=e.reduce((g,h)=>h(g),r());return t=Gf(u),n=t.cache.get,s=t.cache.set,a=l,l(d)}function l(d){const u=n(d);if(u)return u;const g=Kf(d,t);return s(d,g),g}return function(){return a(Yf.apply(null,arguments))}}const se=r=>{const e=t=>t[r]||[];return e.isThemeGetter=!0,e},Fl=/^\[(?:([a-z-]+):)?(.+)\]$/i,Zf=/^\d+\/\d+$/,eh=new Set(["px","full","screen"]),th=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,rh=/\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$/,nh=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,sh=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,oh=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Fe=r=>vt(r)||eh.has(r)||Zf.test(r),ze=r=>Et(r,"length",hh),vt=r=>!!r&&!Number.isNaN(Number(r)),Dn=r=>Et(r,"number",vt),Tt=r=>!!r&&Number.isInteger(Number(r)),ah=r=>r.endsWith("%")&&vt(r.slice(0,-1)),Z=r=>Fl.test(r),Je=r=>th.test(r),ih=new Set(["length","size","percentage"]),lh=r=>Et(r,ih,Ul),ch=r=>Et(r,"position",Ul),dh=new Set(["image","url"]),uh=r=>Et(r,dh,gh),fh=r=>Et(r,"",mh),Pt=()=>!0,Et=(r,e,t)=>{const n=Fl.exec(r);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):t(n[2]):!1},hh=r=>rh.test(r)&&!nh.test(r),Ul=()=>!1,mh=r=>sh.test(r),gh=r=>oh.test(r),ph=()=>{const r=se("colors"),e=se("spacing"),t=se("blur"),n=se("brightness"),s=se("borderColor"),a=se("borderRadius"),i=se("borderSpacing"),l=se("borderWidth"),d=se("contrast"),u=se("grayscale"),g=se("hueRotate"),h=se("invert"),p=se("gap"),w=se("gradientColorStops"),m=se("gradientColorStopPositions"),f=se("inset"),c=se("margin"),x=se("opacity"),b=se("padding"),y=se("saturate"),_=se("scale"),S=se("sepia"),j=se("skew"),v=se("space"),I=se("translate"),T=()=>["auto","contain","none"],R=()=>["auto","hidden","clip","visible","scroll"],D=()=>["auto",Z,e],C=()=>[Z,e],B=()=>["",Fe,ze],W=()=>["auto",vt,Z],H=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],O=()=>["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"],U=()=>["start","end","center","between","around","evenly","stretch"],z=()=>["","0",Z],J=()=>["auto","avoid","all","avoid-page","page","left","right","column"],F=()=>[vt,Z];return{cacheSize:500,separator:":",theme:{colors:[Pt],spacing:[Fe,ze],blur:["none","",Je,Z],brightness:F(),borderColor:[r],borderRadius:["none","","full",Je,Z],borderSpacing:C(),borderWidth:B(),contrast:F(),grayscale:z(),hueRotate:F(),invert:z(),gap:C(),gradientColorStops:[r],gradientColorStopPositions:[ah,ze],inset:D(),margin:D(),opacity:F(),padding:C(),saturate:F(),scale:F(),sepia:z(),skew:F(),space:C(),translate:C()},classGroups:{aspect:[{aspect:["auto","square","video",Z]}],container:["container"],columns:[{columns:[Je]}],"break-after":[{"break-after":J()}],"break-before":[{"break-before":J()}],"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:[...H(),Z]}],overflow:[{overflow:R()}],"overflow-x":[{"overflow-x":R()}],"overflow-y":[{"overflow-y":R()}],overscroll:[{overscroll:T()}],"overscroll-x":[{"overscroll-x":T()}],"overscroll-y":[{"overscroll-y":T()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[f]}],"inset-x":[{"inset-x":[f]}],"inset-y":[{"inset-y":[f]}],start:[{start:[f]}],end:[{end:[f]}],top:[{top:[f]}],right:[{right:[f]}],bottom:[{bottom:[f]}],left:[{left:[f]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Tt,Z]}],basis:[{basis:D()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Z]}],grow:[{grow:z()}],shrink:[{shrink:z()}],order:[{order:["first","last","none",Tt,Z]}],"grid-cols":[{"grid-cols":[Pt]}],"col-start-end":[{col:["auto",{span:["full",Tt,Z]},Z]}],"col-start":[{"col-start":W()}],"col-end":[{"col-end":W()}],"grid-rows":[{"grid-rows":[Pt]}],"row-start-end":[{row:["auto",{span:[Tt,Z]},Z]}],"row-start":[{"row-start":W()}],"row-end":[{"row-end":W()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Z]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Z]}],gap:[{gap:[p]}],"gap-x":[{"gap-x":[p]}],"gap-y":[{"gap-y":[p]}],"justify-content":[{justify:["normal",...U()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...U(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...U(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],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":[v]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[v]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Z,e]}],"min-w":[{"min-w":[Z,e,"min","max","fit"]}],"max-w":[{"max-w":[Z,e,"none","full","min","max","fit","prose",{screen:[Je]},Je]}],h:[{h:[Z,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Z,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Z,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Z,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",Dn]}],"font-family":[{font:[Pt]}],"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",Z]}],"line-clamp":[{"line-clamp":["none",vt,Dn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Fe,Z]}],"list-image":[{"list-image":["none",Z]}],"list-style-type":[{list:["none","disc","decimal",Z]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[r]}],"placeholder-opacity":[{"placeholder-opacity":[x]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[r]}],"text-opacity":[{"text-opacity":[x]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...O(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Fe,ze]}],"underline-offset":[{"underline-offset":["auto",Fe,Z]}],"text-decoration-color":[{decoration:[r]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Z]}],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",Z]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[x]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...H(),ch]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",lh]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},uh]}],"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:[a]}],"rounded-s":[{"rounded-s":[a]}],"rounded-e":[{"rounded-e":[a]}],"rounded-t":[{"rounded-t":[a]}],"rounded-r":[{"rounded-r":[a]}],"rounded-b":[{"rounded-b":[a]}],"rounded-l":[{"rounded-l":[a]}],"rounded-ss":[{"rounded-ss":[a]}],"rounded-se":[{"rounded-se":[a]}],"rounded-ee":[{"rounded-ee":[a]}],"rounded-es":[{"rounded-es":[a]}],"rounded-tl":[{"rounded-tl":[a]}],"rounded-tr":[{"rounded-tr":[a]}],"rounded-br":[{"rounded-br":[a]}],"rounded-bl":[{"rounded-bl":[a]}],"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":[x]}],"border-style":[{border:[...O(),"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":[x]}],"divide-style":[{divide:O()}],"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:["",...O()]}],"outline-offset":[{"outline-offset":[Fe,Z]}],"outline-w":[{outline:[Fe,ze]}],"outline-color":[{outline:[r]}],"ring-w":[{ring:B()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[r]}],"ring-opacity":[{"ring-opacity":[x]}],"ring-offset-w":[{"ring-offset":[Fe,ze]}],"ring-offset-color":[{"ring-offset":[r]}],shadow:[{shadow:["","inner","none",Je,fh]}],"shadow-color":[{shadow:[Pt]}],opacity:[{opacity:[x]}],"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,Z]}],grayscale:[{grayscale:[u]}],"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":[u]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[g]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[x]}],"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",Z]}],duration:[{duration:F()}],ease:[{ease:["linear","in","out","in-out",Z]}],delay:[{delay:F()}],animate:[{animate:["none","spin","ping","pulse","bounce",Z]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[_]}],"scale-x":[{"scale-x":[_]}],"scale-y":[{"scale-y":[_]}],rotate:[{rotate:[Tt,Z]}],"translate-x":[{"translate-x":[I]}],"translate-y":[{"translate-y":[I]}],"skew-x":[{"skew-x":[j]}],"skew-y":[{"skew-y":[j]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Z]}],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",Z]}],"caret-color":[{caret:[r]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",Z]}],fill:[{fill:[r,"none"]}],"stroke-w":[{stroke:[Fe,ze,Dn]}],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"]}}},xh=Qf(ph);let Cr;const bh=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(bh)}const he=[];for(let r=0;r<256;++r)he.push((r+256).toString(16).slice(1));function wh(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 vh=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),xa={randomUUID:vh};function _h(r,e,t){if(xa.randomUUID&&!r)return xa.randomUUID();r=r||{};const n=r.random||(r.rng||yh)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,wh(n)}const Bl=6048e5,Sh=864e5,jr=43200,ba=1440,ya=Symbol.for("constructDateFrom");function Be(r,e){return typeof r=="function"?r(e):r&&typeof r=="object"&&ya in r?r[ya](e):r instanceof Date?new r.constructor(e):new Date(e)}function fe(r,e){return Be(e||r,r)}let Ch={};function cr(){return Ch}function Kt(r,e){var l,d,u,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=(u=t.locale)==null?void 0:u.options)==null?void 0:g.weekStartsOn)??0,s=fe(r,e==null?void 0:e.in),a=s.getDay(),i=(a<n?7:0)+a-n;return s.setDate(s.getDate()-i),s.setHours(0,0,0,0),s}function Vr(r,e){return Kt(r,{...e,weekStartsOn:1})}function Wl(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 a=Vr(s),i=Be(t,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=Vr(i);return t.getTime()>=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function Gr(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 bn(r,...e){const t=Be.bind(null,r||e.find(n=>typeof n=="object"));return e.map(t)}function wa(r,e){const t=fe(r,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function jh(r,e,t){const[n,s]=bn(t==null?void 0:t.in,r,e),a=wa(n),i=wa(s),l=+a-Gr(a),d=+i-Gr(i);return Math.round((l-d)/Sh)}function Ah(r,e){const t=Wl(r,e),n=Be(r,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),Vr(n)}function Lr(r,e){const t=+fe(r)-+fe(e);return t<0?-1:t>0?1:t}function kh(r){return Be(r,Date.now())}function Nh(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function Mh(r){return!(!Nh(r)&&typeof r!="number"||isNaN(+fe(r)))}function Eh(r,e,t){const[n,s]=bn(t==null?void 0:t.in,r,e),a=n.getFullYear()-s.getFullYear(),i=n.getMonth()-s.getMonth();return a*12+i}function Ih(r){return e=>{const n=(r?Math[r]:Math.trunc)(e);return n===0?0:n}}function Th(r,e){return+fe(r)-+fe(e)}function Ph(r,e){const t=fe(r,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Oh(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 Rh(r,e){const t=fe(r,e==null?void 0:e.in);return+Ph(t,e)==+Oh(t,e)}function $h(r,e,t){const[n,s,a]=bn(t==null?void 0:t.in,r,r,e),i=Lr(s,a),l=Math.abs(Eh(s,a));if(l<1)return 0;s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-i*l);let d=Lr(s,a)===-i;Rh(n)&&l===1&&Lr(n,a)===1&&(d=!1);const u=i*(l-+d);return u===0?0:u}function Lh(r,e,t){const n=Th(r,e)/1e3;return Ih(t==null?void 0:t.roundingMethod)(n)}function Dh(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 Fh={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"}},Uh=(r,e,t)=>{let n;const s=Fh[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 Fn(r){return(e={})=>{const t=e.width?String(e.width):r.defaultWidth;return r.formats[t]||r.formats[r.defaultWidth]}}const Bh={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Wh={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Hh={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},qh={date:Fn({formats:Bh,defaultWidth:"full"}),time:Fn({formats:Wh,defaultWidth:"full"}),dateTime:Fn({formats:Hh,defaultWidth:"full"})},zh={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Jh=(r,e,t,n)=>zh[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 a=r.argumentCallback?r.argumentCallback(e):e;return s[a]}}const Vh={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Gh={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Xh={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"]},Kh={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"]},Yh={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"}},Qh={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"}},Zh=(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"},em={ordinalNumber:Zh,era:Ot({values:Vh,defaultWidth:"wide"}),quarter:Ot({values:Gh,defaultWidth:"wide",argumentCallback:r=>r-1}),month:Ot({values:Xh,defaultWidth:"wide"}),day:Ot({values:Kh,defaultWidth:"wide"}),dayPeriod:Ot({values:Yh,defaultWidth:"wide",formattingValues:Qh,defaultFormattingWidth:"wide"})};function Rt(r){return(e,t={})=>{const n=t.width,s=n&&r.matchPatterns[n]||r.matchPatterns[r.defaultMatchWidth],a=e.match(s);if(!a)return null;const i=a[0],l=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],d=Array.isArray(l)?rm(l,h=>h.test(i)):tm(l,h=>h.test(i));let u;u=r.valueCallback?r.valueCallback(d):d,u=t.valueCallback?t.valueCallback(u):u;const g=e.slice(i.length);return{value:u,rest:g}}}function tm(r,e){for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&e(r[t]))return t}function rm(r,e){for(let t=0;t<r.length;t++)if(e(r[t]))return t}function nm(r){return(e,t={})=>{const n=e.match(r.matchPattern);if(!n)return null;const s=n[0],a=e.match(r.parsePattern);if(!a)return null;let i=r.valueCallback?r.valueCallback(a[0]):a[0];i=t.valueCallback?t.valueCallback(i):i;const l=e.slice(s.length);return{value:i,rest:l}}}const sm=/^(\d+)(th|st|nd|rd)?/i,om=/\d+/i,am={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},im={any:[/^b/i,/^(a|c)/i]},lm={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},cm={any:[/1/i,/2/i,/3/i,/4/i]},dm={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},um={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]},fm={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},hm={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]},mm={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},gm={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}},pm={ordinalNumber:nm({matchPattern:sm,parsePattern:om,valueCallback:r=>parseInt(r,10)}),era:Rt({matchPatterns:am,defaultMatchWidth:"wide",parsePatterns:im,defaultParseWidth:"any"}),quarter:Rt({matchPatterns:lm,defaultMatchWidth:"wide",parsePatterns:cm,defaultParseWidth:"any",valueCallback:r=>r+1}),month:Rt({matchPatterns:dm,defaultMatchWidth:"wide",parsePatterns:um,defaultParseWidth:"any"}),day:Rt({matchPatterns:fm,defaultMatchWidth:"wide",parsePatterns:hm,defaultParseWidth:"any"}),dayPeriod:Rt({matchPatterns:mm,defaultMatchWidth:"any",parsePatterns:gm,defaultParseWidth:"any"})},Hl={code:"en-US",formatDistance:Uh,formatLong:qh,formatRelative:Jh,localize:em,match:pm,options:{weekStartsOn:0,firstWeekContainsDate:1}};function xm(r,e){const t=fe(r,e==null?void 0:e.in);return jh(t,Dh(t))+1}function bm(r,e){const t=fe(r,e==null?void 0:e.in),n=+Vr(t)-+Ah(t);return Math.round(n/Bl)+1}function ql(r,e){var g,h,p,w;const t=fe(r,e==null?void 0:e.in),n=t.getFullYear(),s=cr(),a=(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,a),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,a),d.setHours(0,0,0,0);const u=Kt(d,e);return+t>=+l?n+1:+t>=+u?n:n-1}function ym(r,e){var l,d,u,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=(u=t.locale)==null?void 0:u.options)==null?void 0:g.firstWeekContainsDate)??1,s=ql(r,e),a=Be((e==null?void 0:e.in)||r,0);return a.setFullYear(s,0,n),a.setHours(0,0,0,0),Kt(a,e)}function wm(r,e){const t=fe(r,e==null?void 0:e.in),n=+Kt(t,e)-+ym(t,e);return Math.round(n/Bl)+1}function re(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 re(e==="yy"?n%100:n,e.length)},M(r,e){const t=r.getMonth();return e==="M"?String(t+1):re(t+1,2)},d(r,e){return re(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 re(r.getHours()%12||12,e.length)},H(r,e){return re(r.getHours(),e.length)},m(r,e){return re(r.getMinutes(),e.length)},s(r,e){return re(r.getSeconds(),e.length)},S(r,e){const t=e.length,n=r.getMilliseconds(),s=Math.trunc(n*Math.pow(10,t-3));return re(s,e.length)}},gt={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},va={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=ql(r,n),a=s>0?s:1-s;if(e==="YY"){const i=a%100;return re(i,2)}return e==="Yo"?t.ordinalNumber(a,{unit:"year"}):re(a,e.length)},R:function(r,e){const t=Wl(r);return re(t,e.length)},u:function(r,e){const t=r.getFullYear();return re(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 re(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 re(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 re(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=wm(r,n);return e==="wo"?t.ordinalNumber(s,{unit:"week"}):re(s,e.length)},I:function(r,e,t){const n=bm(r);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):re(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=xm(r);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):re(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(),a=(s-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(a);case"ee":return re(a,2);case"eo":return t.ordinalNumber(a,{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(),a=(s-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(a);case"cc":return re(a,e.length);case"co":return t.ordinalNumber(a,{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 re(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"}):re(n,e.length)},k:function(r,e,t){let n=r.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):re(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 Sa(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 Sa(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"+_a(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"+_a(n,":");case"zzzz":default:return"GMT"+Ze(n,":")}},t:function(r,e,t){const n=Math.trunc(+r/1e3);return re(n,e.length)},T:function(r,e,t){return re(+r,e.length)}};function _a(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=Math.trunc(n/60),a=n%60;return a===0?t+String(s):t+String(s)+e+re(a,2)}function Sa(r,e){return r%60===0?(r>0?"-":"+")+re(Math.abs(r)/60,2):Ze(r,e)}function Ze(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=re(Math.trunc(n/60),2),a=re(n%60,2);return t+s+e+a}const Ca=(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"})}},zl=(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"})}},vm=(r,e)=>{const t=r.match(/(P+)(p+)?/)||[],n=t[1],s=t[2];if(!s)return Ca(r,e);let a;switch(n){case"P":a=e.dateTime({width:"short"});break;case"PP":a=e.dateTime({width:"medium"});break;case"PPP":a=e.dateTime({width:"long"});break;case"PPPP":default:a=e.dateTime({width:"full"});break}return a.replace("{{date}}",Ca(n,e)).replace("{{time}}",zl(s,e))},_m={p:zl,P:vm},Sm=/^D+$/,Cm=/^Y+$/,jm=["D","DD","YY","YYYY"];function Am(r){return Sm.test(r)}function km(r){return Cm.test(r)}function Nm(r,e,t){const n=Mm(r,e,t);if(console.warn(n),jm.includes(r))throw new RangeError(n)}function Mm(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 Em=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Im=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Tm=/^'([^]*?)'?$/,Pm=/''/g,Om=/[a-zA-Z]/;function ao(r,e,t){var g,h,p,w;const n=cr(),s=n.locale??Hl,a=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(!Mh(l))throw new RangeError("Invalid time value");let d=e.match(Im).map(m=>{const f=m[0];if(f==="p"||f==="P"){const c=_m[f];return c(m,s.formatLong)}return m}).join("").match(Em).map(m=>{if(m==="''")return{isToken:!1,value:"'"};const f=m[0];if(f==="'")return{isToken:!1,value:Rm(m)};if(va[f])return{isToken:!0,value:m};if(f.match(Om))throw new RangeError("Format string contains an unescaped latin alphabet character `"+f+"`");return{isToken:!1,value:m}});s.localize.preprocessor&&(d=s.localize.preprocessor(l,d));const u={firstWeekContainsDate:a,weekStartsOn:i,locale:s};return d.map(m=>{if(!m.isToken)return m.value;const f=m.value;(km(f)||Am(f))&&Nm(f,e,String(r));const c=va[f[0]];return c(l,f,s.localize,u)}).join("")}function Rm(r){const e=r.match(Tm);return e?e[1].replace(Pm,"'"):r}function $m(r,e,t){const n=cr(),s=(t==null?void 0:t.locale)??n.locale??Hl,a=2520,i=Lr(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]=bn(t==null?void 0:t.in,...i>0?[e,r]:[r,e]),g=Lh(u,d),h=(Gr(u)-Gr(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<ba){const m=Math.round(p/60);return s.formatDistance("aboutXHours",m,l)}else{if(p<a)return s.formatDistance("xDays",1,l);if(p<jr){const m=Math.round(p/ba);return s.formatDistance("xDays",m,l)}else if(p<jr*2)return w=Math.round(p/jr),s.formatDistance("aboutXMonths",w,l)}if(w=$h(u,d),w<12){const m=Math.round(p/jr);return s.formatDistance("xMonths",m,l)}else{const m=w%12,f=Math.trunc(w/12);return m<3?s.formatDistance("aboutXYears",f,l):m<9?s.formatDistance("overXYears",f,l):s.formatDistance("almostXYears",f+1,l)}}function Lm(r,e){return $m(r,kh(r),e)}function ke(...r){return xh(Ff(r))}function Dm(){return _h()}function Jl(r){if(!r)return"--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"--:--":ao(e,"HH:mm")}function Fm(r){if(!r)return"时间未知";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"时间未知":Lm(e,{addSuffix:!0})}function Um(r){if(!r)return"----/--/--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/--":ao(e,"yyyy-MM-dd")}function Bm(r){if(!r)return"----/--/-- --:--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/-- --:--:--":ao(e,"yyyy-MM-dd HH:mm:ss")}function Wm(r,e){return r.length<=e?r:r.slice(0,e)+"..."}function Hm(r){return r.replace(/<[^>]*>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').trim()}function qm(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function zm(r){try{return new URL(r),!0}catch{return!1}}function hs(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=>hs(e));if(typeof r=="object"){const e={};for(const t in r)r.hasOwnProperty(t)&&(e[t]=hs(r[t]));return e}return r}function Jm(r,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function Vm(r,e){let t;return(...n)=>{t||(r(...n),t=!0,setTimeout(()=>t=!1,e))}}function Vl(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 Gl(r){return r.slice((r.lastIndexOf(".")-1>>>0)+2)}function Gm(r){const e=["jpg","jpeg","png","gif","bmp","webp","svg"],t=Gl(r).toLowerCase();return e.includes(t)}function Xm(){const r=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6366f1"];return r[Math.floor(Math.random()*r.length)]}async function Km(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){return console.error("Failed to copy text to clipboard:",e),!1}}function Ym(r,e,t="text/plain"){const n=new Blob([r],{type:t}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(s)}function Qm(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Zm(){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 eg extends Error{constructor(t,n="UNKNOWN_ERROR",s=500){super(t);V(this,"code");V(this,"statusCode");this.name="AppError",this.code=n,this.statusCode=s}}async function tg(r,e=3,t=1e3){let n;for(let s=1;s<=e;s++)try{return await r()}catch(a){if(n=a,s===e)break;await new Promise(i=>setTimeout(i,t*s))}throw n}const rg={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)}}},Xl=({attachment:r,customRenderer:e,className:t})=>{if(e)return o.jsx("div",{children:e(r)});const n=r.type==="image",s=r.type==="audio",a=()=>n?o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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?o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}):o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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 o.jsxs("div",{className:ke("inline-flex items-center gap-2 p-2 bg-muted rounded-lg border max-w-sm",t),children:[o.jsx("div",{className:"flex-shrink-0 text-muted-foreground",children:a()}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-sm font-medium truncate",children:r.name}),o.jsx("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:Vl(r.size)})]}),r.mimeType&&o.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:r.mimeType})]}),o.jsx("div",{className:"flex-shrink-0",children:n?o.jsx("button",{onClick:()=>window.open(r.url,"_blank"),className:"p-1 hover:bg-background rounded transition-colors",title:"View image",children:o.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),o.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"})]})}):o.jsx("a",{href:r.url,download:r.name,className:"p-1 hover:bg-background rounded transition-colors inline-block",title:"Download file",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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&&o.jsx("div",{className:"w-full mt-2",children:o.jsx("img",{src:r.url,alt:r.name,className:"max-w-full h-auto rounded border",style:{maxHeight:"200px"},loading:"lazy"})}),s&&o.jsx("div",{className:"w-full mt-2",children:o.jsxs("audio",{controls:!0,className:"w-full",preload:"metadata",children:[o.jsx("source",{src:r.url,type:r.mimeType}),"Your browser does not support the audio element."]})})]})},ms=({toolCall:r,allMessages:e=[],className:t})=>{const[n,s]=P.useState(!1);console.log("🔍 ToolCallRenderer - 开始查找工具结果消息"),console.log("🔍 当前工具调用ID:",r.id),console.log("🔍 所有消息数量:",e.length),console.log("🔍 所有消息:",e.map(S=>{var j;return{id:S.id,role:S.role,tool_call_id:S.tool_call_id||S.toolCallId,metadata:S.metadata,content:((j=S.content)==null?void 0:j.substring(0,100))+"..."}}));const a=e.find(S=>{var I,T;if(S.role!=="tool")return!1;const j=S.tool_call_id||S.toolCallId,v=((I=S.metadata)==null?void 0:I.tool_call_id)||((T=S.metadata)==null?void 0:T.toolCallId);return j===r.id||v===r.id});console.log("🔍 找到的工具结果消息:",a),console.log("🎨 ToolCallRenderer - 工具调用:",r.id,"结果:",r.result,"工具消息:",a==null?void 0:a.content);const i=r.result||(a==null?void 0:a.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,j="")=>{const v={};for(const I in S)if(S.hasOwnProperty(I)){const T=S[I],R=j?`${j}.${I}`:I;T!==null&&typeof T=="object"&&!Array.isArray(T)?Object.assign(v,p(T,R)):v[R]=T}return v},m=(()=>{if(!h)return"";const S=p(g),j=Object.keys(S);let v=`| 参数 | 值 |
96
+ <pre><code>${P}</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 b=[];let y=0;return p=p.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g,_=>{const S=`__PROTECTED_HTML_${y++}__`;return b.push(_),S}),p=p.replace(/<[^>]+>/g,_=>{const S=`__PROTECTED_HTML_${y++}__`;return b.push(_),S}),p=p.replace(/\n\n/g,"</p><p>"),p=p.replace(/\n/g,"<br>"),b.forEach((_,S)=>{p=p.replace(`__PROTECTED_HTML_${S}__`,_)}),p&&!p.startsWith("<")&&(p=`<p>${p}</p>`),p},[e,s,n]),u=(h,p)=>h.replace(/</g,"&lt;").replace(/>/g,"&gt;"),g=M.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")||""),f=w.getAttribute("data-language")||"text";n==null||n(m,f)}else if(w.classList.contains("expand-btn")){const m=w.getAttribute("data-block-id");m&&l(m)}}},[i,n,l]);return o.jsxs("div",{className:`markdown-renderer ${t}`,onClick:g,children:[o.jsx("div",{dangerouslySetInnerHTML:{__html:d(r)}}),e&&o.jsx("span",{className:"streaming-cursor"})]})};function Hl(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=Hl(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Kf(){for(var r,e,t=0,n="",s=arguments.length;t<s;t++)(r=arguments[t])&&(e=Hl(r))&&(n&&(n+=" "),n+=e);return n}const mo="-",Yf=r=>{const e=Zf(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:i=>{const l=i.split(mo);return l[0]===""&&l.length!==1&&l.shift(),ql(l,e)||Qf(i)},getConflictingClassGroupIds:(i,l)=>{const d=t[i]||[];return l&&n[i]?[...d,...n[i]]:d}}},ql=(r,e)=>{var i;if(r.length===0)return e.classGroupId;const t=r[0],n=e.nextPart.get(t),s=n?ql(r.slice(1),n):void 0;if(s)return s;if(e.validators.length===0)return;const a=r.join(mo);return(i=e.validators.find(({validator:l})=>l(a)))==null?void 0:i.classGroupId},Sa=/^\[(.+)\]$/,Qf=r=>{if(Sa.test(r)){const e=Sa.exec(r)[1],t=e==null?void 0:e.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},Zf=r=>{const{theme:e,prefix:t}=r,n={nextPart:new Map,validators:[]};return th(Object.entries(r.classGroups),t).forEach(([a,i])=>{ws(i,n,a,e)}),n},ws=(r,e,t,n)=>{r.forEach(s=>{if(typeof s=="string"){const a=s===""?e:Ca(e,s);a.classGroupId=t;return}if(typeof s=="function"){if(eh(s)){ws(s(n),e,t,n);return}e.validators.push({validator:s,classGroupId:t});return}Object.entries(s).forEach(([a,i])=>{ws(i,Ca(e,a),t,n)})})},Ca=(r,e)=>{let t=r;return e.split(mo).forEach(n=>{t.nextPart.has(n)||t.nextPart.set(n,{nextPart:new Map,validators:[]}),t=t.nextPart.get(n)}),t},eh=r=>r.isThemeGetter,th=(r,e)=>e?r.map(([t,n])=>{const s=n.map(a=>typeof a=="string"?e+a:typeof a=="object"?Object.fromEntries(Object.entries(a).map(([i,l])=>[e+i,l])):a);return[t,s]}):r,rh=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,n=new Map;const s=(a,i)=>{t.set(a,i),e++,e>r&&(e=0,n=t,t=new Map)};return{get(a){let i=t.get(a);if(i!==void 0)return i;if((i=n.get(a))!==void 0)return s(a,i),i},set(a,i){t.has(a)?t.set(a,i):s(a,i)}}},zl="!",nh=r=>{const{separator:e,experimentalParseClassName:t}=r,n=e.length===1,s=e[0],a=e.length,i=l=>{const d=[];let u=0,g=0,h;for(let c=0;c<l.length;c++){let x=l[c];if(u===0){if(x===s&&(n||l.slice(c,c+a)===e)){d.push(l.slice(g,c)),g=c+a;continue}if(x==="/"){h=c;continue}}x==="["?u++:x==="]"&&u--}const p=d.length===0?l:l.substring(g),w=p.startsWith(zl),m=w?p.substring(1):p,f=h&&h>g?h-g:void 0;return{modifiers:d,hasImportantModifier:w,baseClassName:m,maybePostfixModifierPosition:f}};return t?l=>t({className:l,parseClassName:i}):i},sh=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},oh=r=>({cache:rh(r.cacheSize),parseClassName:nh(r),...Yf(r)}),ah=/\s+/,ih=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:s}=e,a=[],i=r.trim().split(ah);let l="";for(let d=i.length-1;d>=0;d-=1){const u=i[d],{modifiers:g,hasImportantModifier:h,baseClassName:p,maybePostfixModifierPosition:w}=t(u);let m=!!w,f=n(m?p.substring(0,w):p);if(!f){if(!m){l=u+(l.length>0?" "+l:l);continue}if(f=n(p),!f){l=u+(l.length>0?" "+l:l);continue}m=!1}const c=sh(g).join(":"),x=h?c+zl:c,b=x+f;if(a.includes(b))continue;a.push(b);const y=s(f,m);for(let _=0;_<y.length;++_){const S=y[_];a.push(x+S)}l=u+(l.length>0?" "+l:l)}return l};function lh(){let r=0,e,t,n="";for(;r<arguments.length;)(e=arguments[r++])&&(t=Jl(e))&&(n&&(n+=" "),n+=t);return n}const Jl=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=Jl(r[n]))&&(t&&(t+=" "),t+=e);return t};function ch(r,...e){let t,n,s,a=i;function i(d){const u=e.reduce((g,h)=>h(g),r());return t=oh(u),n=t.cache.get,s=t.cache.set,a=l,l(d)}function l(d){const u=n(d);if(u)return u;const g=ih(d,t);return s(d,g),g}return function(){return a(lh.apply(null,arguments))}}const oe=r=>{const e=t=>t[r]||[];return e.isThemeGetter=!0,e},Vl=/^\[(?:([a-z-]+):)?(.+)\]$/i,dh=/^\d+\/\d+$/,uh=new Set(["px","full","screen"]),fh=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,hh=/\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$/,mh=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,gh=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,ph=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Be=r=>jt(r)||uh.has(r)||dh.test(r),Xe=r=>Ot(r,"length",Ch),jt=r=>!!r&&!Number.isNaN(Number(r)),Jn=r=>Ot(r,"number",jt),Ft=r=>!!r&&Number.isInteger(Number(r)),xh=r=>r.endsWith("%")&&jt(r.slice(0,-1)),ee=r=>Vl.test(r),Ke=r=>fh.test(r),bh=new Set(["length","size","percentage"]),yh=r=>Ot(r,bh,Gl),wh=r=>Ot(r,"position",Gl),vh=new Set(["image","url"]),_h=r=>Ot(r,vh,Ah),Sh=r=>Ot(r,"",jh),Ut=()=>!0,Ot=(r,e,t)=>{const n=Vl.exec(r);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):t(n[2]):!1},Ch=r=>hh.test(r)&&!mh.test(r),Gl=()=>!1,jh=r=>gh.test(r),Ah=r=>ph.test(r),kh=()=>{const r=oe("colors"),e=oe("spacing"),t=oe("blur"),n=oe("brightness"),s=oe("borderColor"),a=oe("borderRadius"),i=oe("borderSpacing"),l=oe("borderWidth"),d=oe("contrast"),u=oe("grayscale"),g=oe("hueRotate"),h=oe("invert"),p=oe("gap"),w=oe("gradientColorStops"),m=oe("gradientColorStopPositions"),f=oe("inset"),c=oe("margin"),x=oe("opacity"),b=oe("padding"),y=oe("saturate"),_=oe("scale"),S=oe("sepia"),j=oe("skew"),v=oe("space"),I=oe("translate"),P=()=>["auto","contain","none"],T=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto",ee,e],C=()=>[ee,e],W=()=>["",Be,Xe],B=()=>["auto",jt,ee],z=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],O=()=>["solid","dashed","dotted","double","none"],U=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],J=()=>["start","end","center","between","around","evenly","stretch"],$=()=>["","0",ee],H=()=>["auto","avoid","all","avoid-page","page","left","right","column"],F=()=>[jt,ee];return{cacheSize:500,separator:":",theme:{colors:[Ut],spacing:[Be,Xe],blur:["none","",Ke,ee],brightness:F(),borderColor:[r],borderRadius:["none","","full",Ke,ee],borderSpacing:C(),borderWidth:W(),contrast:F(),grayscale:$(),hueRotate:F(),invert:$(),gap:C(),gradientColorStops:[r],gradientColorStopPositions:[xh,Xe],inset:L(),margin:L(),opacity:F(),padding:C(),saturate:F(),scale:F(),sepia:$(),skew:F(),space:C(),translate:C()},classGroups:{aspect:[{aspect:["auto","square","video",ee]}],container:["container"],columns:[{columns:[Ke]}],"break-after":[{"break-after":H()}],"break-before":[{"break-before":H()}],"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(),ee]}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:P()}],"overscroll-x":[{"overscroll-x":P()}],"overscroll-y":[{"overscroll-y":P()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[f]}],"inset-x":[{"inset-x":[f]}],"inset-y":[{"inset-y":[f]}],start:[{start:[f]}],end:[{end:[f]}],top:[{top:[f]}],right:[{right:[f]}],bottom:[{bottom:[f]}],left:[{left:[f]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ft,ee]}],basis:[{basis:L()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",ee]}],grow:[{grow:$()}],shrink:[{shrink:$()}],order:[{order:["first","last","none",Ft,ee]}],"grid-cols":[{"grid-cols":[Ut]}],"col-start-end":[{col:["auto",{span:["full",Ft,ee]},ee]}],"col-start":[{"col-start":B()}],"col-end":[{"col-end":B()}],"grid-rows":[{"grid-rows":[Ut]}],"row-start-end":[{row:["auto",{span:[Ft,ee]},ee]}],"row-start":[{"row-start":B()}],"row-end":[{"row-end":B()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",ee]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",ee]}],gap:[{gap:[p]}],"gap-x":[{"gap-x":[p]}],"gap-y":[{"gap-y":[p]}],"justify-content":[{justify:["normal",...J()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...J(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...J(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[b]}],px:[{px:[b]}],py:[{py:[b]}],ps:[{ps:[b]}],pe:[{pe:[b]}],pt:[{pt:[b]}],pr:[{pr:[b]}],pb:[{pb:[b]}],pl:[{pl:[b]}],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":[v]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[v]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",ee,e]}],"min-w":[{"min-w":[ee,e,"min","max","fit"]}],"max-w":[{"max-w":[ee,e,"none","full","min","max","fit","prose",{screen:[Ke]},Ke]}],h:[{h:[ee,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[ee,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[ee,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[ee,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Ke,Xe]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Jn]}],"font-family":[{font:[Ut]}],"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",ee]}],"line-clamp":[{"line-clamp":["none",jt,Jn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Be,ee]}],"list-image":[{"list-image":["none",ee]}],"list-style-type":[{list:["none","disc","decimal",ee]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[r]}],"placeholder-opacity":[{"placeholder-opacity":[x]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[r]}],"text-opacity":[{"text-opacity":[x]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...O(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Be,Xe]}],"underline-offset":[{"underline-offset":["auto",Be,ee]}],"text-decoration-color":[{decoration:[r]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",ee]}],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",ee]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[x]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...z(),wh]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",yh]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},_h]}],"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:[a]}],"rounded-s":[{"rounded-s":[a]}],"rounded-e":[{"rounded-e":[a]}],"rounded-t":[{"rounded-t":[a]}],"rounded-r":[{"rounded-r":[a]}],"rounded-b":[{"rounded-b":[a]}],"rounded-l":[{"rounded-l":[a]}],"rounded-ss":[{"rounded-ss":[a]}],"rounded-se":[{"rounded-se":[a]}],"rounded-ee":[{"rounded-ee":[a]}],"rounded-es":[{"rounded-es":[a]}],"rounded-tl":[{"rounded-tl":[a]}],"rounded-tr":[{"rounded-tr":[a]}],"rounded-br":[{"rounded-br":[a]}],"rounded-bl":[{"rounded-bl":[a]}],"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":[x]}],"border-style":[{border:[...O(),"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":[x]}],"divide-style":[{divide:O()}],"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:["",...O()]}],"outline-offset":[{"outline-offset":[Be,ee]}],"outline-w":[{outline:[Be,Xe]}],"outline-color":[{outline:[r]}],"ring-w":[{ring:W()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[r]}],"ring-opacity":[{"ring-opacity":[x]}],"ring-offset-w":[{"ring-offset":[Be,Xe]}],"ring-offset-color":[{"ring-offset":[r]}],shadow:[{shadow:["","inner","none",Ke,Sh]}],"shadow-color":[{shadow:[Ut]}],opacity:[{opacity:[x]}],"mix-blend":[{"mix-blend":[...U(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":U()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[n]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",Ke,ee]}],grayscale:[{grayscale:[u]}],"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":[u]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[g]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[x]}],"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",ee]}],duration:[{duration:F()}],ease:[{ease:["linear","in","out","in-out",ee]}],delay:[{delay:F()}],animate:[{animate:["none","spin","ping","pulse","bounce",ee]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[_]}],"scale-x":[{"scale-x":[_]}],"scale-y":[{"scale-y":[_]}],rotate:[{rotate:[Ft,ee]}],"translate-x":[{"translate-x":[I]}],"translate-y":[{"translate-y":[I]}],"skew-x":[{"skew-x":[j]}],"skew-y":[{"skew-y":[j]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",ee]}],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",ee]}],"caret-color":[{caret:[r]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",ee]}],fill:[{fill:[r,"none"]}],"stroke-w":[{stroke:[Be,Xe,Jn]}],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"]}}},Nh=ch(kh);let Ir;const Mh=new Uint8Array(16);function Eh(){if(!Ir&&(Ir=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Ir))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Ir(Mh)}const me=[];for(let r=0;r<256;++r)me.push((r+256).toString(16).slice(1));function Ih(r,e=0){return me[r[e+0]]+me[r[e+1]]+me[r[e+2]]+me[r[e+3]]+"-"+me[r[e+4]]+me[r[e+5]]+"-"+me[r[e+6]]+me[r[e+7]]+"-"+me[r[e+8]]+me[r[e+9]]+"-"+me[r[e+10]]+me[r[e+11]]+me[r[e+12]]+me[r[e+13]]+me[r[e+14]]+me[r[e+15]]}const Ph=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ja={randomUUID:Ph};function Th(r,e,t){if(ja.randomUUID&&!r)return ja.randomUUID();r=r||{};const n=r.random||(r.rng||Eh)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,Ih(n)}const Xl=6048e5,Oh=864e5,Pr=43200,Aa=1440,ka=Symbol.for("constructDateFrom");function He(r,e){return typeof r=="function"?r(e):r&&typeof r=="object"&&ka in r?r[ka](e):r instanceof Date?new r.constructor(e):new Date(e)}function he(r,e){return He(e||r,r)}let Rh={};function pr(){return Rh}function nr(r,e){var l,d,u,g;const t=pr(),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=(u=t.locale)==null?void 0:u.options)==null?void 0:g.weekStartsOn)??0,s=he(r,e==null?void 0:e.in),a=s.getDay(),i=(a<n?7:0)+a-n;return s.setDate(s.getDate()-i),s.setHours(0,0,0,0),s}function en(r,e){return nr(r,{...e,weekStartsOn:1})}function Kl(r,e){const t=he(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 a=en(s),i=He(t,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=en(i);return t.getTime()>=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function tn(r){const e=he(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 jn(r,...e){const t=He.bind(null,r||e.find(n=>typeof n=="object"));return e.map(t)}function Na(r,e){const t=he(r,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function $h(r,e,t){const[n,s]=jn(t==null?void 0:t.in,r,e),a=Na(n),i=Na(s),l=+a-tn(a),d=+i-tn(i);return Math.round((l-d)/Oh)}function Lh(r,e){const t=Kl(r,e),n=He(r,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),en(n)}function qr(r,e){const t=+he(r)-+he(e);return t<0?-1:t>0?1:t}function Dh(r){return He(r,Date.now())}function Fh(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function Uh(r){return!(!Fh(r)&&typeof r!="number"||isNaN(+he(r)))}function Bh(r,e,t){const[n,s]=jn(t==null?void 0:t.in,r,e),a=n.getFullYear()-s.getFullYear(),i=n.getMonth()-s.getMonth();return a*12+i}function Wh(r){return e=>{const n=(r?Math[r]:Math.trunc)(e);return n===0?0:n}}function Hh(r,e){return+he(r)-+he(e)}function qh(r,e){const t=he(r,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function zh(r,e){const t=he(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 Jh(r,e){const t=he(r,e==null?void 0:e.in);return+qh(t,e)==+zh(t,e)}function Vh(r,e,t){const[n,s,a]=jn(t==null?void 0:t.in,r,r,e),i=qr(s,a),l=Math.abs(Bh(s,a));if(l<1)return 0;s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-i*l);let d=qr(s,a)===-i;Jh(n)&&l===1&&qr(n,a)===1&&(d=!1);const u=i*(l-+d);return u===0?0:u}function Gh(r,e,t){const n=Hh(r,e)/1e3;return Wh(t==null?void 0:t.roundingMethod)(n)}function Xh(r,e){const t=he(r,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}const Kh={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"}},Yh=(r,e,t)=>{let n;const s=Kh[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 Vn(r){return(e={})=>{const t=e.width?String(e.width):r.defaultWidth;return r.formats[t]||r.formats[r.defaultWidth]}}const Qh={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Zh={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},em={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},tm={date:Vn({formats:Qh,defaultWidth:"full"}),time:Vn({formats:Zh,defaultWidth:"full"}),dateTime:Vn({formats:em,defaultWidth:"full"})},rm={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},nm=(r,e,t,n)=>rm[r];function Bt(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 a=r.argumentCallback?r.argumentCallback(e):e;return s[a]}}const sm={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},om={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},am={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"]},im={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"]},lm={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"}},cm={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"}},dm=(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"},um={ordinalNumber:dm,era:Bt({values:sm,defaultWidth:"wide"}),quarter:Bt({values:om,defaultWidth:"wide",argumentCallback:r=>r-1}),month:Bt({values:am,defaultWidth:"wide"}),day:Bt({values:im,defaultWidth:"wide"}),dayPeriod:Bt({values:lm,defaultWidth:"wide",formattingValues:cm,defaultFormattingWidth:"wide"})};function Wt(r){return(e,t={})=>{const n=t.width,s=n&&r.matchPatterns[n]||r.matchPatterns[r.defaultMatchWidth],a=e.match(s);if(!a)return null;const i=a[0],l=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],d=Array.isArray(l)?hm(l,h=>h.test(i)):fm(l,h=>h.test(i));let u;u=r.valueCallback?r.valueCallback(d):d,u=t.valueCallback?t.valueCallback(u):u;const g=e.slice(i.length);return{value:u,rest:g}}}function fm(r,e){for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&e(r[t]))return t}function hm(r,e){for(let t=0;t<r.length;t++)if(e(r[t]))return t}function mm(r){return(e,t={})=>{const n=e.match(r.matchPattern);if(!n)return null;const s=n[0],a=e.match(r.parsePattern);if(!a)return null;let i=r.valueCallback?r.valueCallback(a[0]):a[0];i=t.valueCallback?t.valueCallback(i):i;const l=e.slice(s.length);return{value:i,rest:l}}}const gm=/^(\d+)(th|st|nd|rd)?/i,pm=/\d+/i,xm={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},bm={any:[/^b/i,/^(a|c)/i]},ym={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},wm={any:[/1/i,/2/i,/3/i,/4/i]},vm={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},_m={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]},Sm={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},Cm={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]},jm={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},Am={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}},km={ordinalNumber:mm({matchPattern:gm,parsePattern:pm,valueCallback:r=>parseInt(r,10)}),era:Wt({matchPatterns:xm,defaultMatchWidth:"wide",parsePatterns:bm,defaultParseWidth:"any"}),quarter:Wt({matchPatterns:ym,defaultMatchWidth:"wide",parsePatterns:wm,defaultParseWidth:"any",valueCallback:r=>r+1}),month:Wt({matchPatterns:vm,defaultMatchWidth:"wide",parsePatterns:_m,defaultParseWidth:"any"}),day:Wt({matchPatterns:Sm,defaultMatchWidth:"wide",parsePatterns:Cm,defaultParseWidth:"any"}),dayPeriod:Wt({matchPatterns:jm,defaultMatchWidth:"any",parsePatterns:Am,defaultParseWidth:"any"})},Yl={code:"en-US",formatDistance:Yh,formatLong:tm,formatRelative:nm,localize:um,match:km,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Nm(r,e){const t=he(r,e==null?void 0:e.in);return $h(t,Xh(t))+1}function Mm(r,e){const t=he(r,e==null?void 0:e.in),n=+en(t)-+Lh(t);return Math.round(n/Xl)+1}function Ql(r,e){var g,h,p,w;const t=he(r,e==null?void 0:e.in),n=t.getFullYear(),s=pr(),a=(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=He((e==null?void 0:e.in)||r,0);i.setFullYear(n+1,0,a),i.setHours(0,0,0,0);const l=nr(i,e),d=He((e==null?void 0:e.in)||r,0);d.setFullYear(n,0,a),d.setHours(0,0,0,0);const u=nr(d,e);return+t>=+l?n+1:+t>=+u?n:n-1}function Em(r,e){var l,d,u,g;const t=pr(),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=(u=t.locale)==null?void 0:u.options)==null?void 0:g.firstWeekContainsDate)??1,s=Ql(r,e),a=He((e==null?void 0:e.in)||r,0);return a.setFullYear(s,0,n),a.setHours(0,0,0,0),nr(a,e)}function Im(r,e){const t=he(r,e==null?void 0:e.in),n=+nr(t,e)-+Em(t,e);return Math.round(n/Xl)+1}function re(r,e){const t=r<0?"-":"",n=Math.abs(r).toString().padStart(e,"0");return t+n}const Ye={y(r,e){const t=r.getFullYear(),n=t>0?t:1-t;return re(e==="yy"?n%100:n,e.length)},M(r,e){const t=r.getMonth();return e==="M"?String(t+1):re(t+1,2)},d(r,e){return re(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 re(r.getHours()%12||12,e.length)},H(r,e){return re(r.getHours(),e.length)},m(r,e){return re(r.getMinutes(),e.length)},s(r,e){return re(r.getSeconds(),e.length)},S(r,e){const t=e.length,n=r.getMilliseconds(),s=Math.trunc(n*Math.pow(10,t-3));return re(s,e.length)}},yt={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ma={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 Ye.y(r,e)},Y:function(r,e,t,n){const s=Ql(r,n),a=s>0?s:1-s;if(e==="YY"){const i=a%100;return re(i,2)}return e==="Yo"?t.ordinalNumber(a,{unit:"year"}):re(a,e.length)},R:function(r,e){const t=Kl(r);return re(t,e.length)},u:function(r,e){const t=r.getFullYear();return re(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 re(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 re(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 Ye.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 re(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=Im(r,n);return e==="wo"?t.ordinalNumber(s,{unit:"week"}):re(s,e.length)},I:function(r,e,t){const n=Mm(r);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):re(n,e.length)},d:function(r,e,t){return e==="do"?t.ordinalNumber(r.getDate(),{unit:"date"}):Ye.d(r,e)},D:function(r,e,t){const n=Nm(r);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):re(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(),a=(s-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(a);case"ee":return re(a,2);case"eo":return t.ordinalNumber(a,{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(),a=(s-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(a);case"cc":return re(a,e.length);case"co":return t.ordinalNumber(a,{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 re(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=yt.noon:n===0?s=yt.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=yt.evening:n>=12?s=yt.afternoon:n>=4?s=yt.morning:s=yt.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 Ye.h(r,e)},H:function(r,e,t){return e==="Ho"?t.ordinalNumber(r.getHours(),{unit:"hour"}):Ye.H(r,e)},K:function(r,e,t){const n=r.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):re(n,e.length)},k:function(r,e,t){let n=r.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):re(n,e.length)},m:function(r,e,t){return e==="mo"?t.ordinalNumber(r.getMinutes(),{unit:"minute"}):Ye.m(r,e)},s:function(r,e,t){return e==="so"?t.ordinalNumber(r.getSeconds(),{unit:"second"}):Ye.s(r,e)},S:function(r,e){return Ye.S(r,e)},X:function(r,e,t){const n=r.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return Ia(n);case"XXXX":case"XX":return st(n);case"XXXXX":case"XXX":default:return st(n,":")}},x:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"x":return Ia(n);case"xxxx":case"xx":return st(n);case"xxxxx":case"xxx":default:return st(n,":")}},O:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Ea(n,":");case"OOOO":default:return"GMT"+st(n,":")}},z:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Ea(n,":");case"zzzz":default:return"GMT"+st(n,":")}},t:function(r,e,t){const n=Math.trunc(+r/1e3);return re(n,e.length)},T:function(r,e,t){return re(+r,e.length)}};function Ea(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=Math.trunc(n/60),a=n%60;return a===0?t+String(s):t+String(s)+e+re(a,2)}function Ia(r,e){return r%60===0?(r>0?"-":"+")+re(Math.abs(r)/60,2):st(r,e)}function st(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=re(Math.trunc(n/60),2),a=re(n%60,2);return t+s+e+a}const Pa=(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"})}},Zl=(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"})}},Pm=(r,e)=>{const t=r.match(/(P+)(p+)?/)||[],n=t[1],s=t[2];if(!s)return Pa(r,e);let a;switch(n){case"P":a=e.dateTime({width:"short"});break;case"PP":a=e.dateTime({width:"medium"});break;case"PPP":a=e.dateTime({width:"long"});break;case"PPPP":default:a=e.dateTime({width:"full"});break}return a.replace("{{date}}",Pa(n,e)).replace("{{time}}",Zl(s,e))},Tm={p:Zl,P:Pm},Om=/^D+$/,Rm=/^Y+$/,$m=["D","DD","YY","YYYY"];function Lm(r){return Om.test(r)}function Dm(r){return Rm.test(r)}function Fm(r,e,t){const n=Um(r,e,t);if(console.warn(n),$m.includes(r))throw new RangeError(n)}function Um(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 Bm=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Wm=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Hm=/^'([^]*?)'?$/,qm=/''/g,zm=/[a-zA-Z]/;function go(r,e,t){var g,h,p,w;const n=pr(),s=n.locale??Yl,a=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=he(r,t==null?void 0:t.in);if(!Uh(l))throw new RangeError("Invalid time value");let d=e.match(Wm).map(m=>{const f=m[0];if(f==="p"||f==="P"){const c=Tm[f];return c(m,s.formatLong)}return m}).join("").match(Bm).map(m=>{if(m==="''")return{isToken:!1,value:"'"};const f=m[0];if(f==="'")return{isToken:!1,value:Jm(m)};if(Ma[f])return{isToken:!0,value:m};if(f.match(zm))throw new RangeError("Format string contains an unescaped latin alphabet character `"+f+"`");return{isToken:!1,value:m}});s.localize.preprocessor&&(d=s.localize.preprocessor(l,d));const u={firstWeekContainsDate:a,weekStartsOn:i,locale:s};return d.map(m=>{if(!m.isToken)return m.value;const f=m.value;(Dm(f)||Lm(f))&&Fm(f,e,String(r));const c=Ma[f[0]];return c(l,f,s.localize,u)}).join("")}function Jm(r){const e=r.match(Hm);return e?e[1].replace(qm,"'"):r}function Vm(r,e,t){const n=pr(),s=(t==null?void 0:t.locale)??n.locale??Yl,a=2520,i=qr(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]=jn(t==null?void 0:t.in,...i>0?[e,r]:[r,e]),g=Gh(u,d),h=(tn(u)-tn(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<Aa){const m=Math.round(p/60);return s.formatDistance("aboutXHours",m,l)}else{if(p<a)return s.formatDistance("xDays",1,l);if(p<Pr){const m=Math.round(p/Aa);return s.formatDistance("xDays",m,l)}else if(p<Pr*2)return w=Math.round(p/Pr),s.formatDistance("aboutXMonths",w,l)}if(w=Vh(u,d),w<12){const m=Math.round(p/Pr);return s.formatDistance("xMonths",m,l)}else{const m=w%12,f=Math.trunc(w/12);return m<3?s.formatDistance("aboutXYears",f,l):m<9?s.formatDistance("overXYears",f,l):s.formatDistance("almostXYears",f+1,l)}}function Gm(r,e){return Vm(r,Dh(r),e)}function ve(...r){return Nh(Kf(r))}function Xm(){return Th()}function ec(r){if(!r)return"--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"--:--":go(e,"HH:mm")}function Km(r){if(!r)return"时间未知";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"时间未知":Gm(e,{addSuffix:!0})}function Ym(r){if(!r)return"----/--/--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/--":go(e,"yyyy-MM-dd")}function Qm(r){if(!r)return"----/--/-- --:--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/-- --:--:--":go(e,"yyyy-MM-dd HH:mm:ss")}function Zm(r,e){return r.length<=e?r:r.slice(0,e)+"..."}function eg(r){return r.replace(/<[^>]*>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').trim()}function tg(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function rg(r){try{return new URL(r),!0}catch{return!1}}function vs(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=>vs(e));if(typeof r=="object"){const e={};for(const t in r)r.hasOwnProperty(t)&&(e[t]=vs(r[t]));return e}return r}function ng(r,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function sg(r,e){let t;return(...n)=>{t||(r(...n),t=!0,setTimeout(()=>t=!1,e))}}function tc(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 rc(r){return r.slice((r.lastIndexOf(".")-1>>>0)+2)}function og(r){const e=["jpg","jpeg","png","gif","bmp","webp","svg"],t=rc(r).toLowerCase();return e.includes(t)}function ag(){const r=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6366f1"];return r[Math.floor(Math.random()*r.length)]}async function ig(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){return console.error("Failed to copy text to clipboard:",e),!1}}function lg(r,e,t="text/plain"){const n=new Blob([r],{type:t}),s=URL.createObjectURL(n),a=document.createElement("a");a.href=s,a.download=e,document.body.appendChild(a),a.click(),document.body.removeChild(a),URL.revokeObjectURL(s)}function cg(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function dg(){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 ug extends Error{constructor(t,n="UNKNOWN_ERROR",s=500){super(t);V(this,"code");V(this,"statusCode");this.name="AppError",this.code=n,this.statusCode=s}}async function fg(r,e=3,t=1e3){let n;for(let s=1;s<=e;s++)try{return await r()}catch(a){if(n=a,s===e)break;await new Promise(i=>setTimeout(i,t*s))}throw n}const hg={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)}}},nc=({attachment:r,customRenderer:e,className:t})=>{if(e)return o.jsx("div",{children:e(r)});const n=r.type==="image",s=r.type==="audio",a=()=>n?o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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?o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}):o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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 o.jsxs("div",{className:ve("inline-flex items-center gap-2 p-2 bg-muted rounded-lg border max-w-sm",t),children:[o.jsx("div",{className:"flex-shrink-0 text-muted-foreground",children:a()}),o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-sm font-medium truncate",children:r.name}),o.jsx("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:tc(r.size)})]}),r.mimeType&&o.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:r.mimeType})]}),o.jsx("div",{className:"flex-shrink-0",children:n?o.jsx("button",{onClick:()=>window.open(r.url,"_blank"),className:"p-1 hover:bg-background rounded transition-colors",title:"View image",children:o.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),o.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"})]})}):o.jsx("a",{href:r.url,download:r.name,className:"p-1 hover:bg-background rounded transition-colors inline-block",title:"Download file",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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&&o.jsx("div",{className:"w-full mt-2",children:o.jsx("img",{src:r.url,alt:r.name,className:"max-w-full h-auto rounded border",style:{maxHeight:"200px"},loading:"lazy"})}),s&&o.jsx("div",{className:"w-full mt-2",children:o.jsxs("audio",{controls:!0,className:"w-full",preload:"metadata",children:[o.jsx("source",{src:r.url,type:r.mimeType}),"Your browser does not support the audio element."]})})]})},_s=({toolCall:r,allMessages:e=[],className:t})=>{const[n,s]=M.useState(!1);console.log("🔍 ToolCallRenderer - 开始查找工具结果消息"),console.log("🔍 当前工具调用ID:",r.id),console.log("🔍 所有消息数量:",e.length),console.log("🔍 所有消息:",e.map(S=>{var j;return{id:S.id,role:S.role,tool_call_id:S.tool_call_id||S.toolCallId,metadata:S.metadata,content:((j=S.content)==null?void 0:j.substring(0,100))+"..."}}));const a=e.find(S=>{var I,P;if(S.role!=="tool")return!1;const j=S.tool_call_id||S.toolCallId,v=((I=S.metadata)==null?void 0:I.tool_call_id)||((P=S.metadata)==null?void 0:P.toolCallId);return j===r.id||v===r.id});console.log("🔍 找到的工具结果消息:",a),console.log("🎨 ToolCallRenderer - 工具调用:",r.id,"结果:",r.result,"工具消息:",a==null?void 0:a.content);const i=r.result||(a==null?void 0:a.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,j="")=>{const v={};for(const I in S)if(S.hasOwnProperty(I)){const P=S[I],T=j?`${j}.${I}`:I;P!==null&&typeof P=="object"&&!Array.isArray(P)?Object.assign(v,p(P,T)):v[T]=P}return v},m=(()=>{if(!h)return"";const S=p(g),j=Object.keys(S);let v=`| 参数 | 值 |
98
98
  |------|------|
99
- `;return j.forEach(I=>{const T=S[I];let R;typeof T=="string"?R=T.replace(/\n/g,"<br>").replace(/\|/g,"\\|"):Array.isArray(T)?R=`[${T.join(", ")}]`.replace(/\|/g,"\\|"):R=JSON.stringify(T).replace(/\|/g,"\\|"),v+=`| ${I} | ${R} |
100
- `}),v})(),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})(),x=!!(c&&typeof c=="object"),b=S=>{if(S===null)return"null";if(Array.isArray(S)){if(S.length===0)return"array []";const j=S[0],v=b(j);return v==="object"?"object []":`${v}[]`}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,j="",v="")=>{const I=[];if(S==null)return I;if(Array.isArray(S)){const T={path:v||j||"list",name:j||"list",type:b(S),value:S,children:S.map((R,D)=>{const C=`${v||j||"list"}[${D}]`,B=b(R);return{path:C,name:`[${D}]`,type:B,value:R,children:B==="object"||Array.isArray(R)?y(R,`[${D}]`,C):[]}})};return I.push(T),I}return typeof S=="object"&&Object.keys(S).forEach(T=>{const R=S[T],D=v?`${v}.${T}`:T,C=b(R),B=C==="object"||Array.isArray(R)?y(R,T,D):[];I.push({path:D,name:T,type:C,value:R,children:B})}),I},_=({data:S})=>{const j=Array.isArray(S)?y(S,"list","list"):y(S,"",""),[v,I]=P.useState(()=>new Set(j.filter(C=>C.children.length>0).map(C=>C.path))),T=C=>{I(B=>{const W=new Set(B);return W.has(C)?W.delete(C):W.add(C),W})},R=C=>{if(C===null)return"null";if(Array.isArray(C))return`数组(${C.length})`;if(typeof C=="object")return"对象";if(typeof C=="string")return C;try{return JSON.stringify(C)}catch{return String(C)}},D=(C,B)=>C.map(W=>{const H=W.children&&W.children.length>0,O=v.has(W.path),N=H?O?"▾":"▸":"",U=R(W.value);return o.jsxs(P.Fragment,{children:[o.jsxs("tr",{children:[o.jsxs("td",{style:{paddingLeft:B*16},children:[H?o.jsx("button",{type:"button",onClick:()=>T(W.path),className:"mr-2 text-gray-600 dark:text-gray-300 hover:text-black dark:hover:text-white","aria-label":O?"收起":"展开",children:N}):o.jsx("span",{className:"mr-4"}),W.name]}),o.jsx("td",{style:{whiteSpace:"normal",wordBreak:"break-word"},children:U})]}),H&&O&&D(W.children,B+1)]},W.path)});return o.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:o.jsx("div",{className:"markdown-renderer",children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"字段"}),o.jsx("th",{children:"值"})]})}),o.jsx("tbody",{children:D(j,0)})]})})})};return o.jsxs("div",{className:"tool-call-renderer tool-call-container",children:[o.jsxs("div",{className:"tool-header",children:[o.jsxs("span",{className:"tool-name",children:["@",r.name]}),l&&o.jsx("span",{className:"status-badge status-error",children:"错误"}),d&&!l&&o.jsx("span",{className:"status-badge status-success",children:"完成"}),!d&&!l&&o.jsx("span",{className:"status-badge status-pending",children:"等待中"}),(h||d||l)&&o.jsx("button",{onClick:()=>s(!n),className:"toggle-button",children:n?"收起详情":"查看详情"})]}),n&&o.jsxs("div",{className:"details-container",children:[h&&o.jsx("div",{children:m&&o.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:o.jsx(nt,{content:m})})}),d&&o.jsxs("div",{children:[o.jsx("div",{className:"details-title",children:"结果:"}),x?o.jsx(_,{data:c}):o.jsx(nt,{content:typeof i=="string"?i:JSON.stringify(i)})]}),l&&o.jsxs("div",{children:[o.jsx("div",{className:"details-title",children:"错误:"}),o.jsx("div",{className:"status-badge status-error",style:{display:"block",padding:"0.5rem"},children:r.error})]}),o.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()})()]})]})]})},ng=({message:r,isLast:e=!1,isStreaming:t=!1,onEdit:n,onDelete:s,allMessages:a=[],customRenderer:i})=>{var v,I,T,R,D,C,B,W,H;console.log("🚀🚀🚀 MessageItem 组件被调用!消息ID:",r.id,"角色:",r.role),console.log("🚀🚀🚀 完整消息对象:",r);const[l,d]=P.useState(!1),[u,g]=P.useState(r.content),h=(O,N)=>{navigator.clipboard.writeText(O).then(()=>{console.log("代码已复制到剪贴板:",{code:O,language:N})}).catch(U=>{console.error("复制失败:",U)})},[p,w]=P.useState(!1),m=r.role==="user",f=r.role==="assistant",c=r.role==="system",x=r.role==="tool";if(x)return null;if(i!=null&&i.renderMessage)return o.jsx("div",{children:i.renderMessage(r)});const b=()=>{n&&u.trim()!==r.content&&n(r.id,u.trim()),d(!1)},y=()=>{g(r.content),d(!1)},_=async()=>{try{await navigator.clipboard.writeText(r.content)}catch(O){console.error("Failed to copy message:",O)}},S=((v=r.metadata)==null?void 0:v.attachments)||[],j=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长度:j.length,消息ID:r.id,contentSegments:(R=r.metadata)==null?void 0:R.contentSegments,contentSegments长度:((C=(D=r.metadata)==null?void 0:D.contentSegments)==null?void 0:C.length)||0}),o.jsxs("div",{className:ke("group relative rounded-lg transition-colors",!f&&"flex gap-3 px-4 py-4",f&&"px-4 py-2",m&&"bg-user-message",c&&"bg-muted border-l-4 border-primary",x&&"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:[!f&&o.jsx("div",{className:"flex-shrink-0",children:o.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",x&&"bg-blue-500 text-white"),children:m?"U":x?"T":"S"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[!f&&o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx("span",{className:"text-sm font-medium",children:m?"You":x?"Tool Result":"System"}),o.jsx("span",{className:"text-xs text-muted-foreground",children:Jl(r.createdAt)})]}),((B=r.metadata)==null?void 0:B.type)==="session_summary"&&o.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:[o.jsxs("div",{className:"text-xs text-amber-900 dark:text-amber-200 font-medium mb-1",children:["上下文已压缩为摘要",typeof((W=r.metadata)==null?void 0:W.keepLastN)=="number"?`(保留最近 ${r.metadata.keepLastN} 条)`:""]}),o.jsxs("details",{className:"group",children:[o.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground select-none",children:"查看摘要内容"}),o.jsx("div",{className:"mt-2 prose prose-sm max-w-none",children:o.jsx(nt,{content:(r.rawContent||((H=r.metadata)==null?void 0:H.summary)||"").toString(),isStreaming:!1,onApplyCode:()=>{}})})]})]}),S.length>0&&o.jsx("div",{className:"mb-3 space-y-2",children:S.map(O=>o.jsx(Xl,{attachment:O,customRenderer:i==null?void 0:i.renderAttachment},O.id))}),l?o.jsxs("div",{className:"space-y-2",children:[o.jsx("textarea",{value:u,onChange:O=>g(O.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}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:b,className:"px-3 py-1 text-sm bg-primary text-primary-foreground rounded hover:bg-primary/90",children:"Save"}),o.jsx("button",{onClick:y,className:"px-3 py-1 text-sm bg-muted text-muted-foreground rounded hover:bg-muted/80",children:"Cancel"})]})]}):o.jsx("div",{className:"space-y-3",children:(()=>{var z;const O=((z=r.metadata)==null?void 0:z.contentSegments)||[],N=r.content&&r.content.trim().length>0,U=t&&e;return O.length>0?(console.log("🎨 使用分段渲染,分段数量:",O.length),console.log("🎨 分段详情:",O),o.jsx("div",{className:"space-y-0.5",children:O.map((J,F)=>{if(console.log(`🎨 渲染分段 ${F}:`,J),J.type==="text")return console.log(`🎨 渲染文本分段 ${F}:`,J.content),o.jsx("div",{className:"prose prose-sm max-w-none",children:o.jsx(nt,{content:J.content,isStreaming:U&&F===O.length-1,onApplyCode:h})},`segment-${F}`);if(J.type==="tool_call"){console.log(`🎨 渲染工具调用分段 ${F}:`,J);const k=j.find(A=>A.id===J.toolCallId);if(console.log(`🎨 查找工具调用 ${J.toolCallId}:`,k),k)return console.log("🎨 找到工具调用,开始渲染:",k),o.jsx("div",{children:o.jsx(ms,{toolCall:k,allMessages:a})},`tool-${k.id}`);console.log(`🎨 ❌ 未找到工具调用 ${J.toolCallId}`)}else if(J.type==="thinking")return console.log(`🎨 渲染思考分段 ${F}:`,J.content),o.jsxs("details",{className:"group border border-gray-200 dark:border-gray-700 rounded-md bg-muted px-3 py-2",children:[o.jsx("summary",{className:"cursor-pointer text-xs text-gray-500 dark:text-gray-400 select-none",children:"思考过程"}),o.jsx("div",{className:"mt-1",children:o.jsx(nt,{content:J.content||"",isStreaming:U&&F===O.length-1,onApplyCode:h,className:"thinking not-prose"})})]},`thinking-${F}`);return null})})):(console.log("🎨 使用传统渲染方式"),console.log("🎨 hasContent:",N),console.log("🎨 toolCalls.length:",j.length),o.jsxs("div",{className:"space-y-0.5",children:[N&&o.jsx("div",{className:"prose prose-sm max-w-none",children:o.jsx(nt,{content:r.content,isStreaming:U,onApplyCode:h})}),j.length>0&&o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("div",{className:"text-sm text-muted-foreground font-medium",children:"工具调用:"}),j.map(J=>(console.log("🎨 传统方式渲染工具调用:",J),o.jsx("div",{children:o.jsx(ms,{toolCall:J,allMessages:a})},`tool-${J.id}`)))]})]}))})()}),r.tokensUsed&&o.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Tokens used: ",r.tokensUsed]})]}),p&&!l&&o.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:[o.jsx("button",{onClick:_,className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Copy message",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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&&o.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:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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&&o.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:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})})]})]})},Kl=P.memo(ng,(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)),Yl=({size:r="md",className:e})=>{const t={sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"};return o.jsx("div",{className:ke("animate-spin rounded-full border-2 border-current border-t-transparent",t[r],e),role:"status","aria-label":"Loading",children:o.jsx("span",{className:"sr-only",children:"Loading..."})})},io=({messages:r,isLoading:e=!1,isStreaming:t=!1,hasMore:n=!1,onLoadMore:s,onMessageEdit:a,onMessageDelete:i,customRenderer:l})=>{const d=P.useRef(null),u=P.useRef(null),[g,h]=P.useState(!0),[p,w]=P.useState(!0),m=()=>{const b=d.current;return b?b.scrollHeight-b.scrollTop-b.clientHeight<=40:!0},f=(b=!0)=>{var y;(y=u.current)==null||y.scrollIntoView({behavior:b?"smooth":"auto"})};P.useEffect(()=>{t&&g&&f(!0)},[r,t,g]),P.useEffect(()=>{w(m())},[r,t]),P.useEffect(()=>{t&&p&&h(!0),t||h(!1)},[t,p]);const c=()=>{const b=m();w(b),b||h(!1)},x=()=>{f(!0),h(!0)};return r.length===0&&!e?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsxs("div",{className:"text-center space-y-4",children:[o.jsx("div",{className:"w-16 h-16 mx-auto bg-muted rounded-full flex items-center justify-center",children:o.jsx("svg",{className:"w-8 h-8 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Start a conversation"}),o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Send a message to begin your chat with AI"})]})]})}):o.jsxs("div",{className:"flex flex-col h-full relative",children:[o.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&&o.jsx("div",{className:"flex justify-center mb-2",children:o.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(b=>{var y;return!((y=b==null?void 0:b.metadata)!=null&&y.hidden)}).map((b,y,_)=>o.jsx(Kl,{message:b,isLast:y===_.length-1,isStreaming:t&&y===_.length-1,onEdit:a,onDelete:i,allMessages:r,customRenderer:l},b.id)),e&&o.jsx("div",{className:"flex justify-start",children:o.jsxs("div",{className:"flex items-center space-x-2 bg-muted px-4 py-3 rounded-lg max-w-xs",children:[o.jsx(Yl,{size:"sm"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"AI is thinking..."})]})}),o.jsx("div",{ref:u})]}),!p&&o.jsxs("button",{type:"button","aria-label":"回到底部",title:"回到底部",onClick:x,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:[o.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M12 5v12"}),o.jsx("path",{d:"M19 12l-7 7-7-7"})]}),o.jsx("span",{className:"text-sm",children:"回到底部"})]})]})},lo=({onSend:r,onStop:e,disabled:t=!1,isStreaming:n=!1,placeholder:s="Type your message...",maxLength:a=4e3,allowAttachments:i=!1,supportedFileTypes:l=["image/*","text/*","application/pdf"],showModelSelector:d=!1,selectedModelId:u=null,availableModels:g=[],onModelChange:h,selectedAgentId:p=null,availableAgents:w=[],onAgentChange:m})=>{const[f,c]=P.useState(""),[x,b]=P.useState([]),[y,_]=P.useState(!1),S=P.useRef(null),j=P.useRef(null);P.useEffect(()=>{console.log("InputArea - isStreaming 状态变化:",{isStreaming:n,disabled:t,onStop:!!e,timestamp:new Date().toISOString()})},[n,t,e]);const v=P.useCallback(()=>{const N=S.current;if(N){N.style.height="auto";const U=N.scrollHeight,z=200;N.style.height=`${Math.min(U,z)}px`}},[]),I=N=>{const U=N.target.value;U.length<=a&&(c(U),v())},T=N=>{N.key==="Enter"&&!N.shiftKey&&(N.preventDefault(),R())},R=()=>{const N=f.trim();if(!(!N&&x.length===0)&&!t){if(d&&!u&&!p){alert("请先选择一个模型或智能体");return}r(N,x),c(""),b([]),S.current&&(S.current.style.height="auto")}},D=N=>{const U=Array.from(N.target.files||[]);b(z=>[...z,...U]),j.current&&(j.current.value="")},C=N=>{b(U=>U.filter((z,J)=>J!==N))},B=N=>{N.preventDefault(),i&&!t&&_(!0)},W=N=>{N.preventDefault(),_(!1)},H=N=>{if(N.preventDefault(),_(!1),!i||t)return;const U=Array.from(N.dataTransfer.files);b(z=>[...z,...U])},O=N=>{if(N===0)return"0 Bytes";const U=1024,z=["Bytes","KB","MB","GB"],J=Math.floor(Math.log(N)/Math.log(U));return parseFloat((N/Math.pow(U,J)).toFixed(2))+" "+z[J]};return o.jsxs("div",{className:"border-t bg-background p-4",children:[d&&o.jsx("div",{className:"mb-3",children:g.length>0||w.length>0?o.jsxs("select",{value:p?`agent:${p}`:u||"",onChange:N=>{const U=N.target.value;if(U.startsWith("agent:")){const z=U.replace("agent:","");m==null||m(z),h==null||h(null)}else h==null||h(U||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:[o.jsx("option",{value:"",children:"请选择模型或智能体..."}),w&&w.filter(N=>N.enabled).length>0&&o.jsx("optgroup",{label:"智能体",children:w.filter(N=>N.enabled).map(N=>o.jsxs("option",{value:`agent:${N.id}`,children:["[Agent] ",N.name]},N.id))}),g&&g.filter(N=>N.enabled).length>0&&o.jsx("optgroup",{label:"模型",children:g.filter(N=>N.enabled).map(N=>o.jsxs("option",{value:N.id,children:[N.name," (",N.model_name,")"]},N.id))})]}):o.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:"暂无可用模型或智能体,请先在右上角配置"})}),x.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:x.map((N,U)=>o.jsxs("div",{className:"flex items-center gap-2 bg-muted px-3 py-2 rounded-lg text-sm",children:[o.jsx("svg",{className:"w-4 h-4 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("span",{className:"truncate max-w-32",children:N.name}),o.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",O(N.size),")"]}),o.jsx("button",{onClick:()=>C(U),className:"text-muted-foreground hover:text-destructive transition-colors",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},U))}),o.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:B,onDragLeave:W,onDrop:H,children:[i&&o.jsx("button",{onClick:()=>{var N;return(N=j.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:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsx("textarea",{ref:S,value:f,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"}}),o.jsxs("div",{className:"flex-shrink-0 text-xs text-muted-foreground",children:[f.length,"/",a]}),n?o.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:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 6h12v12H6z"})})}):o.jsx("button",{onClick:R,disabled:t||n||!f.trim()&&x.length===0,className:ke("flex-shrink-0 p-2 rounded-md transition-colors","disabled:opacity-50 disabled:cursor-not-allowed",(f.trim()||x.length>0)&&!t&&!n?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground"),title:d&&!u?"请先选择AI模型":"Send message",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"})})}),i&&o.jsx("input",{ref:j,type:"file",multiple:!0,accept:l.join(","),onChange:D,className:"hidden"})]}),y&&i&&o.jsx("div",{className:"absolute inset-0 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center",children:o.jsxs("div",{className:"text-center",children:[o.jsx("svg",{className:"w-8 h-8 mx-auto text-primary mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to attach"})]})})]})},Ql=({className:r="w-5 h-5"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Zl=({className:r="w-5 h-5"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),gs=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),sg=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),og=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),tc=({className:r="w-5 h-5"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),ag=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),ig=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),lg=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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:a,onCancel:i,type:l="danger",verificationText:d,verificationLabel:u,verificationPlaceholder:g,verificationHint:h})=>{if(!r)return null;const[p,w]=P.useState("");P.useEffect(()=>{r&&w("")},[r,d]);const m=!!d,f=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 o.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:o.jsx("div",{className:"bg-card rounded-lg shadow-lg w-full max-w-sm border border-border animate-breathing-border",children:o.jsxs("div",{className:"p-6",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground mb-2",children:e}),o.jsx("p",{className:"text-muted-foreground text-sm mb-6",children:t}),m&&o.jsxs("div",{className:"mb-6",children:[o.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-2",children:u||"请输入以下内容以继续操作"}),o.jsx("div",{className:"px-3 py-2 bg-muted rounded-md text-sm font-mono text-foreground border border-border mb-2",children:d}),o.jsx("input",{type:"text",value:p,onChange:x=>w(x.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}),o.jsx("p",{className:"text-[12px] text-muted-foreground mt-2",children:h||"为了防止误删,需要您再次确认此操作。"})]}),o.jsxs("div",{className:"flex gap-3",children:[o.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}),o.jsx("button",{onClick:a,disabled:f,className:`flex-1 px-4 py-2 text-sm rounded-md transition-colors ${c()} ${f?"opacity-50 cursor-not-allowed":""}`,children:n})]})]})})})},ur=()=>{const[r,e]=P.useState({isOpen:!1,title:"",message:"",confirmText:"确认",cancelText:"取消",type:"danger"}),t=P.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=P.useCallback(()=>{e(i=>({...i,isOpen:!1}))},[]),s=P.useCallback(()=>{var i;(i=r.onConfirm)==null||i.call(r),n()},[r.onConfirm,n]),a=P.useCallback(()=>{var i;(i=r.onCancel)==null||i.call(r),n()},[r.onCancel,n]);return{dialogState:r,showConfirmDialog:t,hideConfirmDialog:n,handleConfirm:s,handleCancel:a}},Ar=r=>r===!0||r===1||r==="1",ja=(r,e)=>r.includes(e)?r.filter(t=>t!==e):[...r,e],Aa=({isOpen:r,onClose:e,onCreate:t,availableModels:n,availableMcpConfigs:s,availablePrompts:a,defaultTitle:i="New Chat",defaultModelId:l=null,initialMcpConfigIds:d,initialPromptIds:u,dialogTitle:g="新建会话",confirmText:h="创建"})=>{const p=P.useMemo(()=>(n||[]).filter(H=>Ar(H.enabled)),[n]),w=P.useMemo(()=>(s||[]).filter(H=>Ar(H.enabled)),[s]),m=P.useMemo(()=>s||[],[s]),[f,c]=P.useState(i),[x,b]=P.useState(""),[y,_]=P.useState([]),[S,j]=P.useState([]),[v,I]=P.useState(!1),[T,R]=P.useState(!1),[D,C]=P.useState(!1),B=P.useMemo(()=>(a||[]).filter(H=>Ar(H.isActive??H.is_active??!1)).map(H=>H.id),[a]);if(P.useEffect(()=>{var O;if(!r)return;c(i),_(Array.isArray(d)?d:w.map(N=>N.id)),j(Array.isArray(u)?u:B),I(!1),R(!1),C(!1);const H=((O=p[0])==null?void 0:O.id)||"";b(l||H)},[r]),P.useEffect(()=>{var O;if(!r||x)return;const H=((O=p[0])==null?void 0:O.id)||"";!l&&!H||b(l||H)},[r,x,l,p]),P.useEffect(()=>{r&&(Array.isArray(d)||T||y.length>0||w.length!==0&&_(w.map(H=>H.id)))},[r,d,T,y,w]),P.useEffect(()=>{r&&(Array.isArray(u)||D||S.length>0||B.length!==0&&j(B))},[r,u,D,S,B]),!r)return null;const W=!v&&!!x;return o.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:o.jsx("div",{className:"bg-card rounded-lg shadow-lg w-full max-w-lg border border-border animate-breathing-border",children:o.jsxs("div",{className:"p-6",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:g}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"会话标题"}),o.jsx("input",{value:f,onChange:H=>c(H.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:"New Chat",disabled:v})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择模型(必选)"}),o.jsxs("select",{value:x,onChange:H=>b(H.target.value),disabled:v,className:"w-full px-3 py-2 border border-input bg-background rounded-md text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[o.jsx("option",{value:"",disabled:!0,children:"请选择模型..."}),p.map(H=>o.jsxs("option",{value:H.id,children:[H.name," (",H.model_name,")"]},H.id))]}),p.length===0&&o.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"暂无可用模型,请先在右上角配置。"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 MCP(多选)"}),m.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"暂无 MCP 配置。"}):o.jsx("div",{className:"max-h-40 overflow-auto rounded-md border border-border bg-background",children:m.map(H=>{const O=Ar(H.enabled);return o.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 text-sm hover:bg-accent",children:[o.jsx("input",{type:"checkbox",checked:y.includes(H.id),onChange:()=>{R(!0),_(N=>ja(N,H.id))},disabled:v}),o.jsxs("span",{className:"truncate",title:H.name,children:[H.name,O?null:o.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(未启用)"})]})]},H.id)})})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 Prompt(多选)"}),a.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"暂无可用 Prompt(系统上下文)。"}):o.jsx("div",{className:"max-h-40 overflow-auto rounded-md border border-border bg-background",children:(a||[]).map(H=>{const O=H.isActive??H.is_active??!1;return o.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 text-sm hover:bg-accent",children:[o.jsx("input",{type:"checkbox",checked:S.includes(H.id),onChange:()=>{C(!0),j(N=>ja(N,H.id))},disabled:v}),o.jsxs("span",{className:"truncate",title:H.name,children:[H.name,O?o.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(当前激活)"}):null]})]},H.id)})})]})]}),o.jsxs("div",{className:"flex gap-3 mt-6",children:[o.jsx("button",{onClick:e,disabled:v,className:"flex-1 px-4 py-2 text-sm border border-border rounded-md hover:bg-accent transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"取消"}),o.jsx("button",{onClick:async()=>{if(W){I(!0);try{await t({title:f.trim()||i,modelId:x,mcpConfigIds:y,promptIds:S}),e()}finally{I(!1)}}},disabled:!W,className:"flex-1 px-4 py-2 text-sm rounded-md transition-colors bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed",children:h})]})]})})})},cg=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")},co=({isOpen:r=!0,onClose:e,store:t,embedded:n=!1})=>{let s=null;try{s=dt()}catch{}const a=t?t():s;if(!a)throw new Error("SessionList must be used within a ChatStoreProvider or receive a store prop");const{sessions:i,currentSession:l,createSession:d,selectSession:u,deleteSession:g,updateSessionConfig:h,getSessionMcpConfigIds:p,aiModelConfigs:w,loadAiModelConfigs:m,mcpConfigs:f,loadMcpConfigs:c,systemContexts:x,loadSystemContexts:b,selectedModelId:y}=a,_=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",S="transition-all duration-300 ease-in-out",[j,v]=P.useState(!1),[I,T]=P.useState(!1),[R,D]=P.useState(null),[C,B]=P.useState([]),[W,H]=P.useState(!r),{dialogState:O,showConfirmDialog:N,handleConfirm:U,handleCancel:z}=ur(),J=()=>{H(!W)},F=async()=>{try{v(!0),m==null||m(),c==null||c(),b==null||b(),W&&H(!1)}catch($){console.error("Failed to create session:",$)}},k=async $=>{try{await u($)}catch(q){console.error("Failed to select session:",q)}},A=async $=>{const q=i.find(ee=>ee.id===$);N({title:"删除确认",message:`确定要删除会话 "${(q==null?void 0:q.title)||"Untitled"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{try{await g($)}catch(ee){console.error("Failed to delete session:",ee)}}})},M=$=>{const q=$==null?void 0:$.metadata;try{return typeof q=="string"?q?JSON.parse(q):{}:q&&typeof q=="object"?q:{}}catch{return{}}},L=async $=>{try{m==null||m(),c==null||c(),b==null||b();const q=await(p==null?void 0:p($.id));B(Array.isArray(q)?q:[]),D($),T(!0),W&&H(!1)}catch(q){console.error("Failed to open session editor:",q)}};return o.jsx("div",{className:`${_} ${S} ${W?"w-32":"w-80 sm:w-96"}`,children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:`flex ${W?"flex-col items-center justify-center p-2":"items-center justify-between p-4"} border-b border-border transition-all duration-300`,children:[!W&&o.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"会话列表"}),o.jsxs("div",{className:`flex ${W?"flex-col space-y-2 items-center":"items-center space-x-2"}`,children:[o.jsx("button",{onClick:F,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"新建会话",children:o.jsx(Ql,{className:"w-5 h-5"})}),o.jsx("button",{onClick:J,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:W?"展开":"收起",children:W?o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})}):o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),e&&!W&&!n&&o.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:i.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground",children:[o.jsx(tc,{className:"w-12 h-12 mb-4 opacity-50"}),!W&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm",children:"还没有会话"}),o.jsx("button",{onClick:F,className:"mt-2 px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"创建第一个会话"})]})]}):o.jsx("div",{className:"p-2 space-y-1",children:i.map($=>o.jsxs("div",{className:`group relative flex items-center p-3 rounded-lg cursor-pointer transition-colors ${(l==null?void 0:l.id)===$.id?"bg-accent border border-border":"hover:bg-accent/50"}`,onClick:()=>k($.id),children:[o.jsx("div",{className:"flex-1 min-w-0",children:o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:`text-sm font-medium text-foreground truncate ${W?"text-center w-full":""}`,title:$.title,children:W&&$.title.length>4?$.title.slice(0,4)+"...":$.title}),!W&&o.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:cg($.updatedAt)})]})}),!W&&o.jsxs("div",{className:"relative flex items-center gap-1",children:[o.jsx("button",{className:"p-1 text-muted-foreground hover:text-foreground opacity-0 group-hover:opacity-100 transition-opacity",onClick:q=>{q.stopPropagation(),L($)},title:"编辑",children:o.jsx(gs,{className:"w-4 h-4"})}),o.jsx("button",{className:"p-1 text-muted-foreground hover:text-foreground opacity-0 group-hover:opacity-100 transition-opacity",onClick:q=>{q.stopPropagation();const ee=q.currentTarget.nextElementSibling;ee&&ee.classList.toggle("hidden")},children:o.jsx(Zl,{className:"w-4 h-4"})}),o.jsx("div",{className:"hidden absolute right-0 z-10 mt-1 w-32 bg-popover border border-border rounded-md shadow-lg",children:o.jsxs("div",{className:"py-1",children:[o.jsxs("button",{onClick:q=>{q.stopPropagation(),L($);const ee=q.currentTarget.closest(".absolute");ee&&ee.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-popover-foreground hover:bg-accent",children:[o.jsx(gs,{className:"w-4 h-4 mr-2"}),"编辑"]}),o.jsxs("button",{onClick:q=>{q.stopPropagation(),A($.id);const ee=q.currentTarget.closest(".absolute");ee&&ee.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-destructive hover:bg-destructive/10",children:[o.jsx(ec,{className:"w-4 h-4 mr-2"}),"删除"]})]})})]})]},$.id))})}),o.jsx(dr,{isOpen:O.isOpen,title:O.title,message:O.message,confirmText:O.confirmText,cancelText:O.cancelText,type:O.type,verificationText:O.verificationText,verificationLabel:O.verificationLabel,verificationPlaceholder:O.verificationPlaceholder,verificationHint:O.verificationHint,onConfirm:U,onCancel:z}),o.jsx(Aa,{isOpen:j,onClose:()=>v(!1),availableModels:w||[],availableMcpConfigs:f||[],availablePrompts:x||[],defaultModelId:y,dialogTitle:"新建会话",confirmText:"创建",onCreate:async $=>{try{await d({title:$.title,modelId:$.modelId,mcpConfigIds:$.mcpConfigIds,promptIds:$.promptIds})}catch(q){throw console.error("Failed to create session:",q),q}}}),o.jsx(Aa,{isOpen:I,onClose:()=>{T(!1),D(null),B([])},availableModels:w||[],availableMcpConfigs:f||[],availablePrompts:x||[],defaultTitle:(R==null?void 0:R.title)||"New Chat",defaultModelId:(()=>{const $=M(R);return $.ai_model_config_id||$.model_id||$.modelId||y||null})(),initialMcpConfigIds:C,initialPromptIds:(()=>{const $=M(R),q=$.prompt_ids||$.promptIds||[];return Array.isArray(q)?q.map(ee=>String(ee)).filter(Boolean):[]})(),dialogTitle:"编辑会话",confirmText:"保存",onCreate:async $=>{if(R)try{await(h==null?void 0:h(R.id,{title:$.title,modelId:$.modelId,mcpConfigIds:$.mcpConfigIds,promptIds:$.promptIds}))}catch(q){throw console.error("Failed to update session config:",q),q}}})]})})},rc=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",ka=r=>r==="system"?rc():r,Un=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")},Na=()=>typeof window>"u"?"system":localStorage.getItem("theme")||"system",dg=r=>{typeof window>"u"||localStorage.setItem("theme",r)},nc=()=>{const[r,e]=P.useState(()=>Na()),[t,n]=P.useState(()=>ka(Na())),s=i=>{e(i),dg(i);const l=ka(i);n(l),Un(l)},a=()=>{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 P.useEffect(()=>{if(r!=="system")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),l=()=>{const d=rc();n(d),Un(d)};return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[r]),P.useEffect(()=>{Un(t)},[t]),{theme:r,actualTheme:t,setTheme:s,toggleTheme:a}},uo=({className:r=""})=>{const{theme:e,toggleTheme:t}=nc(),n=()=>{switch(e){case"light":return o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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 o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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 o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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 o.jsx("button",{onClick:t,className:`p-2 hover:bg-muted rounded-lg transition-colors ${r}`,title:s(),"aria-label":s(),children:n()})},ug={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},fg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Ma=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),hg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),mg=({open:r,config:e,onClose:t})=>{const[n,s]=P.useState([]),[a,i]=P.useState(!1),[l,d]=P.useState(null),[u,g]=P.useState(null),[h,p]=P.useState(!1),[w,m]=P.useState({name:"",envJson:"",enabled:!1}),[f,c]=P.useState(null),[x,b]=P.useState({});if(P.useEffect(()=>{(async()=>{if(!(!r||!(e!=null&&e.id))){i(!0),d(null);try{const _=await te.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 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 o.jsxs("div",{className:"modal-container",children:[o.jsxs("div",{className:"modal-content w-full max-w-3xl max-h-[85vh] overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(fg,{}),o.jsxs("h3",{className:"text-lg font-semibold text-foreground",children:["配置档案 - ",e==null?void 0:e.name]})]}),o.jsx("button",{onClick:()=>t(),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(Ma,{})})]}),o.jsxs("div",{className:"p-4 overflow-y-auto overflow-x-hidden",style:{maxHeight:"calc(85vh - 100px)"},children:[e&&o.jsxs("div",{className:"mb-4 p-3 rounded-md border border-border bg-muted/40",children:[o.jsx("div",{className:"text-sm font-medium mb-2 text-foreground",children:"基本信息"}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-muted-foreground",children:[o.jsxs("div",{children:["协议类型:",o.jsx("span",{className:"ml-1 text-foreground",children:e.type==="http"?"HTTP":"Stdio"})]}),o.jsxs("div",{children:[e.type==="http"?"URL:":"命令:",o.jsx("span",{className:"ml-1 text-foreground break-all",children:e.command})]}),e.type==="stdio"&&e.cwd&&o.jsxs("div",{children:["cwd:",o.jsx("span",{className:"ml-1 text-foreground break-all",children:String(e.cwd)})]}),e.type==="stdio"&&o.jsxs("div",{className:"sm:col-span-2",children:["args:",o.jsx("span",{className:"ml-1 text-foreground break-all",children:(()=>{const y=e.args;if(!y)return"—";if(Array.isArray(y))return y.map(_=>String(_)).join(", ");if(typeof y=="string"){try{const _=JSON.parse(y);if(Array.isArray(_))return _.map(S=>String(S)).join(", ")}catch{}return y}return String(y)})()})]})]})]}),o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"已保存的配置档案"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.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 te.getMcpConfigProfiles(e.id);s(Array.isArray(y)?y:[])}finally{i(!1)}}},children:"刷新列表"}),o.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 _=await te.getMcpConfigResource(e.id),S=_&&_.config||{};S&&typeof S=="object"&&(y=S)}catch{}m({name:`配置_${new Date().toLocaleString("zh-CN")}`,envJson:"",enabled:!1}),b(y||{}),g(null),p(!0)},children:"新增配置档案"})]})]}),a?o.jsx("div",{className:"text-xs text-muted-foreground",children:"加载中..."}):l?o.jsx("div",{className:"text-xs text-destructive",children:l}):n.length===0?o.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案,点击右上角“新增配置档案”。"}):o.jsx("div",{className:"space-y-2",children:n.map(y=>o.jsx("div",{className:"px-2 py-2 border border-border rounded-md",children:o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"text-sm text-foreground font-medium truncate",title:y.name,children:y.name}),y.enabled&&o.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:"已启用"})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.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 te.activateMcpConfigProfile(e.id,y.id);const _=await te.getMcpConfigProfiles(e.id);s(Array.isArray(_)?_:[])}catch{}},children:"激活"}),o.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 _=y.env||{},S={};Object.keys(_||{}).forEach(j=>{const v=_[j];if(typeof v=="string"){const I=v.trim();try{S[j]=JSON.parse(I)}catch{I.includes(",")?S[j]=I.split(",").map(T=>T.trim()).filter(Boolean):S[j]=I}}else S[j]=v}),b(S),p(!0)},children:"编辑"}),o.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 te.deleteMcpConfigProfile(e.id,y.id);const S=await te.getMcpConfigProfiles(e.id);s(Array.isArray(S)?S:[])}catch(S){console.error("删除配置档案失败:",S)}},children:"删除"})]})]})},y.id))})]})]}),h&&o.jsxs("div",{className:"modal-container z-[100]",children:[o.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-sm",onClick:()=>{p(!1),c(null)}}),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:o.jsxs("div",{className:"modal-content w-full max-w-2xl transform overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(hg,{}),o.jsx("h3",{className:"text-base font-semibold text-foreground",children:u?"编辑配置档案":"新增配置档案"})]}),o.jsx("button",{onClick:()=>{p(!1),c(null)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(Ma,{})})]}),o.jsxs("div",{className:"p-4",children:[f&&o.jsx("div",{className:"mb-2 text-xs text-destructive",children:f}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),o.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"})]}),o.jsx("div",{children:x&&Object.keys(x).length>0&&o.jsxs("div",{className:"mb-3",children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"动态参数"}),o.jsx("div",{className:"grid grid-cols-1 gap-3",children:Object.keys(x).map(y=>{const _=x[y],S=typeof _,j=Array.isArray(_);return o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:y}),S==="boolean"?o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",checked:!!_,onChange:v=>b({...x,[y]:v.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),o.jsx("span",{className:"ml-2 text-xs",children:String(_)})]}):j?o.jsx("input",{type:"text",value:_.join(", "),onChange:v=>b({...x,[y]:v.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"&&_!==null?o.jsx("textarea",{value:(()=>{try{return JSON.stringify(_,null,2)}catch{return String(_)}})(),onChange:v=>{try{const I=JSON.parse(v.target.value);b({...x,[y]:I})}catch{b({...x,[y]:v.target.value})}},rows:4,className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md font-mono text-xs"}):o.jsx("input",{type:S==="number"?"number":"text",value:_??"",onChange:v=>b({...x,[y]:S==="number"?Number(v.target.value):v.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},y)})})]})})]}),o.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[o.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:"取消"}),o.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(x&&Object.keys(x).length>0)y=x;else{const j=(w.envJson||"").trim();if(j)try{const v=JSON.parse(j);v&&typeof v=="object"&&(y=v)}catch{throw new Error("env JSON 格式错误")}}let S=null;if(y&&typeof y=="object"){S={};for(const j of Object.keys(y)){const v=y[j];Array.isArray(v)?S[j]=v.join(","):typeof v=="boolean"||typeof v=="number"?S[j]=String(v):v==null?S[j]="":typeof v=="object"?S[j]=JSON.stringify(v):S[j]=String(v)}}if(u)if(await te.updateMcpConfigProfile(e.id,u,{name:w.name,env:S,enabled:w.enabled})){const v=await te.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[]),p(!1),g(null)}else throw new Error("更新失败");else{const j=await te.createMcpConfigProfile(e.id,{name:w.name,env:S,enabled:w.enabled});if(j&&(j.id||j.success)){const v=await te.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[]),p(!1)}else throw new Error("创建失败")}}catch(y){c((y==null?void 0:y.message)||"保存失败")}},children:"保存"})]})]})]})})]})]})},gg={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Ea=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),pg=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),xg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),bg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),fo=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=dt()}catch{t=ct()}const{mcpConfigs:n,updateMcpConfig:s,deleteMcpConfig:a,loadMcpConfigs:i}=t,{dialogState:l,showConfirmDialog:d,handleConfirm:u,handleCancel:g}=ur(),[h,p]=P.useState(!1),[w,m]=P.useState(null),[f,c]=P.useState({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),[x,b]=P.useState(!1),[y,_]=P.useState(null),[S,j]=P.useState({}),[v,I]=P.useState([]),[T,R]=P.useState(""),[D,C]=P.useState(!1),[B,W]=P.useState(null);P.useEffect(()=>{const k="__mcpManagerInitAt__",A=window[k]||0,M=Date.now();typeof A=="number"&&M-A<1e3||(window[k]=M,i())},[i]);const H=async k=>{W(k),C(!0);try{const A=await te.getMcpConfigProfiles(k.id);I(Array.isArray(A)?A:[])}catch{console.error("加载配置档案失败")}finally{}},O=()=>{c({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),m(null),p(!1),j({}),I([]),R("")},N=async k=>{var M,L;if(k.preventDefault(),!f.name.trim()||!f.command.trim())return;const A={name:f.name.trim(),command:f.command.trim(),type:f.type,enabled:f.enabled,cwd:(M=f.cwd)!=null&&M.trim()?f.cwd.trim():void 0,args:(L=f.argsInput)!=null&&L.trim()?f.argsInput.split(",").map($=>$.trim()).filter(Boolean):void 0,createdAt:new Date,updatedAt:new Date};await s(A),O()},U=async k=>{var M,L;if(k.preventDefault(),!w||!f.name.trim()||!f.command.trim())return;const A={...w,name:f.name.trim(),command:f.command.trim(),type:f.type,enabled:f.enabled,cwd:(M=f.cwd)!=null&&M.trim()?f.cwd.trim():void 0,args:(L=f.argsInput)!=null&&L.trim()?f.argsInput.split(",").map($=>$.trim()).filter(Boolean):void 0,updatedAt:new Date};await s(A),O()},z=k=>{m(k);let A="";const M=k.args;if(Array.isArray(M))A=M.map(L=>String(L)).join(", ");else if(typeof M=="string"&&M.trim()!=="")try{const L=JSON.parse(M);Array.isArray(L)?A=L.map($=>String($)).join(", "):A=M}catch{A=M}c({name:k.name,command:k.command,type:k.type||"stdio",enabled:k.enabled,cwd:k.cwd||"",argsInput:A}),p(!0),j({}),_(null),b(!1)},J=async k=>{var L;const A=n.find($=>$.id===k),M=((L=A==null?void 0:A.name)==null?void 0:L.trim())||"删除";d({title:"删除 MCP 服务器",message:`确定要删除服务器 "${(A==null?void 0:A.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",verificationText:M,verificationLabel:"请键入服务器名称以确认删除",verificationPlaceholder:`输入 "${M}"`,verificationHint:"删除后无法恢复,请再次确认操作。",onConfirm:()=>a(k)})},F=async k=>{const A={...k,enabled:!k.enabled,updatedAt:new Date};await s(A)};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),o.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:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(Ea,{}),o.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"MCP 服务器管理"})]}),o.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:o.jsx(pg,{})})]}),o.jsxs("div",{className:"p-4 flex-1 overflow-y-auto overflow-x-hidden",children:[!h&&o.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:[o.jsx(xg,{}),o.jsx("span",{children:"添加 MCP 服务器"})]}),h&&o.jsxs("form",{onSubmit:w?U:N,className:"mb-6 p-4 bg-muted rounded-lg",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:w?"编辑服务器":"添加新服务器"}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"服务器名称"}),o.jsx("input",{type:"text",value:f.name,onChange:k=>c({...f,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:"例如: File System",required:!0})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"协议类型"}),o.jsxs("select",{value:f.type,onChange:k=>c({...f,type: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",children:[o.jsx("option",{value:"stdio",children:"Stdio (标准输入输出)"}),o.jsx("option",{value:"http",children:"HTTP (网络协议)"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:f.type==="http"?"URL地址":"命令"}),o.jsx("input",{type:"text",value:f.command,onChange:k=>c({...f,command: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:f.type==="http"?"https://api.example.com/mcp":"npx @modelcontextprotocol/server-filesystem /path/to/allowed/files",required:!0}),f.type==="stdio"&&o.jsx(o.Fragment,{})]}),f.type==="stdio"&&o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"可执行地址(cwd)"}),o.jsx("input",{type:"text",value:f.cwd,onChange:k=>c({...f,cwd: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:"/absolute/path/to/executable"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"为空则使用当前页面的工作目录"}),o.jsx("div",{className:"mt-2 flex gap-2",children:o.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 k,A;if(f.command.trim()){b(!0),_(null);try{const M=await te.getMcpConfigResourceByCommand({type:f.type,command:f.command.trim(),args:(k=f.argsInput)!=null&&k.trim()?f.argsInput.split(",").map(L=>L.trim()).filter(Boolean):void 0,env:void 0,cwd:(A=f.cwd)!=null&&A.trim()?f.cwd.trim():void 0,alias:null});if(M&&M.success&&M.config){const L=M.config;if(j(L),w!=null&&w.id)try{const $=await te.getMcpConfigProfiles(w.id);I(Array.isArray($)?$:[])}catch{}}else _("无法获取服务器可配置参数")}catch(M){_((M==null?void 0:M.message)||"获取配置失败")}finally{b(!1)}}},children:x?"获取中…":"获取配置"})})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"启动参数(args,逗号分隔)"}),o.jsx("input",{type:"text",value:f.argsInput,onChange:k=>c({...f,argsInput: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:"--flag, value, --opt"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"将自动转换为参数数组"})]})]}),o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",id:"enabled",checked:f.enabled,onChange:k=>c({...f,enabled:k.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),o.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此服务器"})]}),f.type==="stdio"&&Object.keys(S).length>0&&o.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("span",{className:"text-sm font-medium text-foreground",children:"服务器可配置参数(动态解析)"}),x&&o.jsx("span",{className:"text-xs text-muted-foreground",children:"解析中…"})]}),y&&o.jsx("p",{className:"text-xs text-red-600 mb-2",children:y}),o.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[Object.keys(S).map(k=>{const A=S[k],M=typeof A,L=Array.isArray(A);return o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:k}),M==="boolean"?o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",checked:!!A,onChange:$=>j({...S,[k]:$.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),o.jsx("span",{className:"ml-2 text-xs",children:String(A)})]}):L?o.jsx("input",{type:"text",value:A.join(", "),onChange:$=>j({...S,[k]:$.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"}):o.jsx("input",{type:M==="number"?"number":"text",value:A??"",onChange:$=>j({...S,[k]:M==="number"?Number($.target.value):$.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},k)}),(w==null?void 0:w.id)&&o.jsxs("div",{className:"mt-2 p-2 border border-dashed rounded-md",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"text",value:T,onChange:k=>R(k.target.value),className:"flex-1 px-2 py-1 border border-input bg-background text-foreground rounded-md",placeholder:"配置档案名称(例如:开发环境)"}),o.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 k,A;if(w!=null&&w.id)try{await te.createMcpConfigProfile(w.id,{name:T||`配置-${new Date().toLocaleString()}`,env:Object.keys(S).reduce((L,$)=>{const q=S[$];return L[$]=typeof q=="string"?q:String(q),L},{}),args:(k=f.argsInput)!=null&&k.trim()?f.argsInput.split(",").map(L=>L.trim()).filter(Boolean):void 0,cwd:(A=f.cwd)!=null&&A.trim()?f.cwd.trim():void 0,enabled:!1});const M=await te.getMcpConfigProfiles(w.id);I(Array.isArray(M)?M:[]),R("")}catch(M){console.error("保存配置档案失败:",M),_("保存配置档案失败")}},children:"保存为配置档案"})]}),v.length>0&&o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"已有配置档案:"}),v.map(k=>{const A=Array.isArray(k.args)?k.args.join(", "):"",M=k.env?Object.keys(k.env):[];return o.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"text-xs text-foreground font-medium",children:k.name}),k.enabled&&o.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:"已启用"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.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 te.activateMcpConfigProfile(w.id,k.id);const L=await te.getMcpConfigProfiles(w.id);I(Array.isArray(L)?L:[])}catch{}},children:"激活"}),o.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(k.args)?k.args.join(", "):L.argsInput,cwd:k.cwd??L.cwd})),j(k.env||{})},children:"应用到表单"})]})]}),o.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[o.jsxs("div",{className:"truncate",title:k.cwd||"未设置",children:[o.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),k.cwd||"未设置"]}),o.jsxs("div",{className:"truncate",title:A||"未设置",children:[o.jsx("span",{className:"text-muted-foreground",children:"args:"}),A||"未设置"]}),o.jsxs("div",{children:[o.jsxs("span",{className:"text-muted-foreground",children:["env(",M.length,"):"]}),M.length===0?"未设置":o.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:M.map(L=>o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"text-muted-foreground shrink-0",children:L}),o.jsx("span",{className:"text-foreground truncate",title:String(k.env[L]),children:String(k.env[L])})]},L))})]})]})]},k.id)})]})]})]})]})]}),(w==null?void 0:w.id)&&!h&&o.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("span",{className:"text-sm font-medium text-foreground",children:"配置档案列表"}),o.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 k=await te.getMcpConfigProfiles(w.id);I(Array.isArray(k)?k:[])}catch{}},children:"刷新"})]}),v.length===0?o.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案"}):o.jsx("div",{className:"space-y-2",children:v.map(k=>{const A=Array.isArray(k.args)?k.args.join(", "):"",M=k.env?Object.keys(k.env):[];return o.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"text-xs text-foreground font-medium",children:k.name}),k.enabled&&o.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:"已启用"})]}),o.jsx("div",{className:"flex items-center gap-2",children:o.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 te.activateMcpConfigProfile(w.id,k.id);const L=await te.getMcpConfigProfiles(w.id);I(Array.isArray(L)?L:[])}catch{}},children:"激活"})})]}),o.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),k.cwd||"未设置"]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"args:"}),A||"未设置"]}),o.jsxs("div",{children:[o.jsxs("span",{className:"text-muted-foreground",children:["env(",M.length,"):"]}),M.length===0?"未设置":o.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:M.map(L=>o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-muted-foreground",children:L}),o.jsx("span",{className:"text-foreground",children:String(k.env[L])})]},L))})]})]})]},k.id)})})]}),o.jsxs("div",{className:"flex space-x-3 mt-6",children:[o.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?"更新":"添加"}),o.jsx("button",{type:"button",onClick:O,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:"取消"})]})]}),o.jsx("div",{className:"space-y-3",children:n.length===0?o.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[o.jsx(Ea,{}),o.jsx("p",{className:"mt-2",children:"暂无 MCP 服务器配置"}),o.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个服务器"})]}):n.map(k=>o.jsxs("div",{className:"flex items-center justify-between gap-3 p-4 bg-card border border-border rounded-lg",children:[o.jsxs("div",{className:"flex items-center space-x-3 flex-1 min-w-0",children:[o.jsx("div",{className:`w-3 h-3 rounded-full ${k.enabled?"bg-green-500":"bg-gray-400"}`}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center space-x-2 min-w-0",children:[o.jsx("h4",{className:"font-medium text-foreground truncate",title:k.name,children:k.name}),o.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${k.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:k.type==="http"?"HTTP":"Stdio"})]}),o.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground truncate break-all font-mono",title:k.command,children:k.command}),typeof window<"u"&&gg&&!1,k.type==="stdio"&&o.jsxs("div",{className:"mt-1 space-y-0.5 min-w-0",children:[k.cwd&&o.jsxs("div",{className:"text-xs text-muted-foreground truncate",title:String(k.cwd),children:["cwd: ",o.jsx("span",{className:"text-foreground",children:String(k.cwd)})]}),o.jsx("div",{className:"text-xs text-muted-foreground truncate",title:(()=>{const A=k.args;let M=null,L=!1;if(Array.isArray(A))M=A.map(q=>String(q));else if(typeof A=="string"&&A.trim()!=="")try{const q=JSON.parse(A);Array.isArray(q)&&(M=q.map(ee=>String(ee)),L=!0)}catch{}const $=Array.isArray(M)&&M.length>0?M.join(", "):typeof A=="string"&&!L?A:"—";return String($)})(),children:(()=>{const A=k.args;let M=null,L=!1;if(Array.isArray(A))M=A.map(q=>String(q));else if(typeof A=="string"&&A.trim()!=="")try{const q=JSON.parse(A);Array.isArray(q)&&(M=q.map(ee=>String(ee)),L=!0)}catch{}const $=Array.isArray(M)&&M.length>0?M.join(", "):typeof A=="string"&&!L?A:"—";return o.jsxs("span",{children:["参数(args):",o.jsx("span",{className:"text-foreground",children:$})]})})()})]})]})]}),o.jsxs("div",{className:"flex items-center space-x-2 shrink-0",children:[o.jsx("button",{onClick:()=>F(k),className:`px-3 py-1 text-xs rounded-full ${k.enabled?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-secondary text-secondary-foreground"}`,children:k.enabled?"已启用":"已禁用"}),o.jsx("button",{onClick:()=>H(k),className:"p-2 text-muted-foreground hover:text-indigo-600 transition-colors",title:"查看配置档案",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.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"})})}),o.jsx("button",{onClick:()=>z(k),className:"p-2 text-muted-foreground hover:text-blue-600 transition-colors",title:"编辑",children:o.jsx(yg,{})}),o.jsx("button",{onClick:()=>J(k.id),className:"p-2 text-muted-foreground hover:text-red-600 transition-colors",title:"删除",children:o.jsx(bg,{})})]})]},k.id))})]})]}),o.jsx(mg,{open:D,config:B,onClose:()=>{C(!1),W(null)}}),o.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:u,onCancel:g})]})},Ia=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),wg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),vg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),_g=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Sg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),ho=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=dt()}catch{t=ct()}const{aiModelConfigs:n,loadAiModelConfigs:s,updateAiModelConfig:a,deleteAiModelConfig:i}=t,[l,d]=P.useState(!1),[u,g]=P.useState(null),[h,p]=P.useState({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),{dialogState:w,showConfirmDialog:m,handleConfirm:f,handleCancel:c}=ur();P.useEffect(()=>{const v="__aiModelManagerInitAt__",I=window[v]||0,T=Date.now();typeof I=="number"&&T-I<1e3||(window[v]=T,s())},[s]);const x=()=>{p({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),g(null),d(!1)},b=async v=>{if(v.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 a(I),x()},y=async v=>{if(v.preventDefault(),!u||!h.name.trim()||!h.base_url.trim()||!h.api_key.trim()||!h.model_name.trim())return;const I={...u,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 a(I),x()},_=v=>{g(v),p({name:v.name,base_url:v.base_url,api_key:v.api_key,model_name:v.model_name,enabled:v.enabled}),d(!0)},S=async v=>{var R;const I=n.find(D=>D.id===v),T=((R=I==null?void 0:I.name)==null?void 0:R.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(v)}})},j=async v=>{const I={...v,enabled:!v.enabled,updatedAt:new Date};await a(I)};return o.jsxs("div",{className:"modal-container",children:[o.jsxs("div",{className:"modal-content w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(Ia,{}),o.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"AI 模型管理"})]}),o.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(wg,{})})]}),o.jsxs("div",{className:"p-6 overflow-y-auto overflow-x-hidden max-h-[calc(80vh-120px)]",children:[!l&&o.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:[o.jsx(vg,{}),o.jsx("span",{children:"添加 AI 模型"})]}),l&&o.jsxs("form",{onSubmit:u?y:b,className:"mb-6 p-4 bg-muted rounded-lg",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:u?"编辑 AI 模型":"添加 AI 模型"}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),o.jsx("input",{type:"text",value:h.name,onChange:v=>p({...h,name:v.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})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Base URL"}),o.jsx("input",{type:"url",value:h.base_url,onChange:v=>p({...h,base_url:v.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})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"API Key"}),o.jsx("input",{type:"password",value:h.api_key,onChange:v=>p({...h,api_key:v.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})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"模型名称"}),o.jsx("input",{type:"text",value:h.model_name,onChange:v=>p({...h,model_name:v.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})]}),o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",id:"enabled",checked:h.enabled,onChange:v=>p({...h,enabled:v.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),o.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此模型"})]})]}),o.jsxs("div",{className:"flex space-x-3 mt-6",children:[o.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?"更新":"添加"}),o.jsx("button",{type:"button",onClick:x,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:"取消"})]})]}),o.jsx("div",{className:"space-y-3",children:n.length===0?o.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[o.jsx(Ia,{}),o.jsx("p",{className:"mt-2",children:"暂无 AI 模型配置"}),o.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个模型"})]}):n.map(v=>o.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:[o.jsxs("div",{className:"flex items-center space-x-3 flex-1 min-w-0",children:[o.jsx("div",{className:`w-3 h-3 rounded-full ${v.enabled?"bg-green-500":"bg-gray-400"}`}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h4",{className:"font-medium text-foreground truncate",title:v.name,children:v.name}),o.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground truncate",title:`${v.base_url} - ${v.model_name}`,children:[v.base_url," - ",v.model_name]})]})]}),o.jsxs("div",{className:"flex items-center space-x-2 shrink-0",children:[o.jsx("button",{onClick:()=>j(v),className:`px-3 py-1 text-xs rounded-full transition-colors ${v.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:v.enabled?"已启用":"已禁用"}),o.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:o.jsx(_g,{})}),o.jsx("button",{onClick:()=>S(v.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:o.jsx(Sg,{})})]})]},v.id))})]})]}),o.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:f,onCancel:c})]})},Ta=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Cg=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),jg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Ag=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),kg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Ng=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Mg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),mo=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=dt()}catch{t=ct()}const{systemContexts:n,activeSystemContext:s,loadSystemContexts:a,createSystemContext:i,updateSystemContext:l,deleteSystemContext:d,activateSystemContext:u}=t,[g,h]=P.useState("list"),[p,w]=P.useState(null),[m,f]=P.useState({name:"",content:""}),[c,x]=P.useState(!1),[b,y]=P.useState(!1),{dialogState:_,showConfirmDialog:S,handleConfirm:j,handleCancel:v}=ur();P.useEffect(()=>{const O="__systemContextEditorInitAt__",N=window[O]||0,U=Date.now();if(typeof N=="number"&&U-N<1e3)return;window[O]=U,(async()=>{x(!0);try{await a()}catch(J){console.error("Failed to load system contexts:",J)}finally{x(!1)}})()},[a]);const I=()=>{f({name:"",content:""}),w(null),h("create")},T=O=>{f({name:O.name,content:O.content}),w(O),h("edit")},R=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(O){console.error("Failed to save system context:",O),alert("保存失败,请重试")}finally{y(!1)}},D=async O=>{var N,U;S({title:"删除确认",message:`确定要删除上下文 "${O.name}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",verificationText:((N=O.name)==null?void 0:N.trim())||"删除",verificationLabel:"请输入下方关键字确认删除",verificationPlaceholder:`输入 "${((U=O.name)==null?void 0:U.trim())||"删除"}"`,verificationHint:"为了防止误删,需要输入配置名称才能继续。",onConfirm:async()=>{try{await d(O.id)}catch(z){console.error("Failed to delete system context:",z),alert("删除失败,请重试")}}})},C=async O=>{try{await u(O.id),await a()}catch(N){console.error("Failed to activate system context:",N),alert("激活失败,请重试")}},B=O=>{O.ctrlKey&&O.key==="s"&&(O.preventDefault(),g!=="list"&&R())},W=()=>o.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[o.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:o.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:[o.jsx("strong",{children:"系统上下文"}),"将作为每次对话的系统提示词,支持 Markdown 格式。 您可以创建多个上下文配置,但同一时间只能激活一个。"]})}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:c?o.jsx("div",{className:"flex items-center justify-center h-32",children:o.jsx("div",{className:"text-muted-foreground",children:"加载中..."})}):n.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-muted-foreground",children:[o.jsx(Ta,{}),o.jsx("p",{className:"mt-2",children:"暂无系统上下文配置"}),o.jsx("p",{className:"text-sm",children:'点击"新建"按钮创建第一个配置'})]}):o.jsx("div",{className:"space-y-3",children:n.map(O=>o.jsx("div",{className:`p-4 border rounded-lg transition-colors ${O.isActive?"border-green-500 bg-green-50 dark:bg-green-900/20":"border-border bg-card"}`,children:o.jsxs("div",{className:"flex items-start justify-between",children:[o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("h3",{className:"font-medium text-foreground",children:O.name}),O.isActive&&o.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:[o.jsx(Mg,{}),o.jsx("span",{className:"ml-1",children:"已激活"})]})]}),o.jsxs("p",{className:"mt-1 text-sm text-muted-foreground line-clamp-2",children:[O.content.substring(0,100),O.content.length>100&&"..."]}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["创建时间: ",new Date(O.createdAt).toLocaleString()]})]}),o.jsxs("div",{className:"flex items-center space-x-2 ml-4",children:[!O.isActive&&o.jsx("button",{onClick:()=>C(O),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"激活"}),o.jsx("button",{onClick:()=>T(O),className:"p-2 text-muted-foreground hover:text-blue-600 hover:bg-accent rounded transition-colors",children:o.jsx(kg,{})}),o.jsx("button",{onClick:()=>D(O),className:"p-2 text-muted-foreground hover:text-red-600 hover:bg-accent rounded transition-colors",children:o.jsx(Ng,{})})]})]})},O.id))})})]}),H=()=>o.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[o.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:[o.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:g==="create"?"创建新的系统上下文配置":"编辑系统上下文配置"}),o.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300 mt-2",children:"提示:使用 Ctrl+S 快速保存"})]}),o.jsxs("div",{className:"flex-1 flex flex-col space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),o.jsx("input",{type:"text",value:m.name,onChange:O=>f({...m,name:O.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:"例如:编程助手、翻译专家、创意写作等"})]}),o.jsxs("div",{className:"flex-1 flex flex-col",children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[o.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Markdown 内容"}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.content.length," 字符"]})]}),o.jsx("textarea",{value:m.content,onChange:O=>f({...m,content:O.target.value}),onKeyDown:B,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})]}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[o.jsx("p",{children:"• 支持标准 Markdown 语法:标题、列表、代码块、链接等"}),o.jsx("p",{children:"• 内容将在每次对话开始时自动发送给 AI"}),o.jsx("p",{children:"• 留空则使用默认系统提示词"})]})]})]});return o.jsxs("div",{className:"modal-container",children:[o.jsxs("div",{className:"modal-content w-full max-w-4xl max-h-[90vh] overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(Ta,{}),o.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"系统上下文设置"})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[g==="list"?o.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:[o.jsx(Ag,{}),o.jsx("span",{children:"新建"})]}):o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:R,disabled:b,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:[o.jsx(jg,{}),o.jsx("span",{children:b?"保存中...":"保存"})]}),o.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:"取消"})]}),o.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(Cg,{})})]})]}),g==="list"?W():H()]}),o.jsx(dr,{isOpen:_.isOpen,title:_.title,message:_.message,confirmText:_.confirmText,cancelText:_.cancelText,type:_.type,verificationText:_.verificationText,verificationLabel:_.verificationLabel,verificationPlaceholder:_.verificationPlaceholder,verificationHint:_.verificationHint,onConfirm:j,onCancel:v})]})},Pa=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Oa=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),Eg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Ig=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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=dt()}catch{t=ct()}const{aiModelConfigs:n,loadAiModelConfigs:s,mcpConfigs:a,loadMcpConfigs:i,systemContexts:l,loadSystemContexts:d}=t,{userId:u}=Lf(),g=u||"custom_user_123",p=Df()||te,[w,m]=P.useState([]),[f,c]=P.useState(!1),[x,b]=P.useState(!1),[y,_]=P.useState(null),[S,j]=P.useState(null),[v,I]=P.useState({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),{dialogState:T,showConfirmDialog:R,handleConfirm:D,handleCancel:C}=ur(),B=async()=>{c(!0);try{await Promise.all([s(),i(),d(),t.loadAgents?t.loadAgents():Promise.resolve()]);const A=t.agents&&Array.isArray(t.agents)?t.agents:await p.getAgents(g),M=Array.isArray(A)?A:[];m(M)}catch(A){console.error("加载智能体失败",A)}finally{c(!1)}},W=async A=>{for(let L=0;L<3;L++)try{t.loadAgents&&await t.loadAgents();const $=await p.getAgents(g),q=Array.isArray($)?$:[];if(m(q),A&&Array.isArray(q)&&q.some(ee=>ee.id===A)||!A)break;await new Promise(ee=>setTimeout(ee,250))}catch($){console.warn("刷新智能体列表失败,重试中…",$),await new Promise(q=>setTimeout(q,250))}};P.useEffect(()=>{const A="__agentManagerInitAt__",M=window[A]||0,L=Date.now();typeof M=="number"&&L-M<1e3||(window[A]=L,B())},[]);const H=()=>{I({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),b(!1),j(null)},O=async A=>{var M;if(A.preventDefault(),!(!v.name.trim()||!v.ai_model_config_id))try{const L=await p.createAgent({name:v.name.trim(),description:((M=v.description)==null?void 0:M.trim())||void 0,ai_model_config_id:v.ai_model_config_id,mcp_config_ids:v.mcp_config_ids,system_context_id:v.system_context_id,user_id:g,enabled:!0});L&&L.id&&m($=>$.some(ee=>ee.id===L.id)?$.map(ee=>ee.id===L.id?{...ee,...L}:ee):[L,...$]),await W(L==null?void 0:L.id),H()}catch(L){console.error("创建智能体失败",L),alert("创建失败,请重试")}},N=async A=>{if(A.preventDefault(),!!S)try{const M=await p.updateAgent(S.id,{name:v.name,description:v.description,ai_model_config_id:v.ai_model_config_id,mcp_config_ids:v.mcp_config_ids,system_context_id:v.system_context_id,enabled:!0});m(L=>L.map($=>$.id===S.id?{...$,...M,name:v.name,description:v.description,ai_model_config_id:v.ai_model_config_id,mcp_config_ids:v.mcp_config_ids,system_context_id:v.system_context_id,enabled:!0}:$)),await W(S.id),H()}catch(M){console.error("更新智能体失败",M),alert("更新失败,请重试")}},U=A=>{var $;const M=w.find(q=>q.id===A),L=(($=M==null?void 0:M.name)==null?void 0:$.trim())||"删除";R({title:"删除智能体",message:`确定要删除智能体 "${(M==null?void 0:M.name)||"未命名"}" 吗?此操作将无法撤销。`,confirmText:"永久删除",cancelText:"取消",type:"danger",verificationText:L,verificationLabel:"请输入智能体名称以确认删除",verificationPlaceholder:`输入 "${L}"`,verificationHint:"删除后该智能体将从所有应用中移除且无法恢复。",onConfirm:async()=>{try{await p.deleteAgent(A),m(q=>q.filter(ee=>ee.id!==A)),await W()}catch(q){console.error("删除智能体失败",q),alert("删除失败,请重试")}}})},z=A=>{j(A),b(!0),I({name:A.name,description:A.description||"",ai_model_config_id:A.ai_model_config_id,mcp_config_ids:Array.isArray(A.mcp_config_ids)?A.mcp_config_ids:[],system_context_id:A.system_context_id})},J=A=>{const M=n.find(L=>L.id===A);return M?`${M.name}(${M.model_name})`:A},F=A=>{if(!A)return"未选择";const M=l.find(L=>L.id===A);return M?M.name:A},k=A=>A.map(L=>{const $=a.find(q=>q.id===L);return $?$.name:L}).join(",");return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),o.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:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(Pa,{}),o.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"智能体管理"})]}),o.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:o.jsx(Oa,{})})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[!x&&o.jsxs("button",{onClick:()=>b(!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:[o.jsx(Eg,{}),o.jsx("span",{children:"新增智能体"})]}),x&&o.jsxs("form",{onSubmit:S?N:O,className:"p-4 bg-muted rounded-lg space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),o.jsx("input",{type:"text",value:v.name,onChange:A=>I({...v,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:"例如:项目助理",required:!0})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"描述"}),o.jsx("textarea",{value:v.description,onChange:A=>I({...v,description: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:"智能体用途说明",rows:3})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择模型(单选)"}),o.jsxs("select",{value:v.ai_model_config_id,onChange:A=>I({...v,ai_model_config_id: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",required:!0,children:[o.jsx("option",{value:"",children:"请选择模型"}),n.map(A=>o.jsxs("option",{value:A.id,children:[A.name,"(",A.model_name,")"]},A.id))]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 MCP 配置(多选)"}),o.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 border rounded-md",children:a.map(A=>o.jsxs("label",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",checked:v.mcp_config_ids.includes(A.id),onChange:M=>{const L=M.target.checked;I($=>({...$,mcp_config_ids:L?[...$.mcp_config_ids,A.id]:$.mcp_config_ids.filter(q=>q!==A.id)}))}}),o.jsx("span",{children:A.name})]},A.id))})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择系统上下文"}),o.jsxs("select",{value:v.system_context_id||"",onChange:A=>I({...v,system_context_id:A.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:[o.jsx("option",{value:"",children:"不使用"}),l.map(A=>o.jsx("option",{value:A.id,children:A.name},A.id))]})]}),o.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[o.jsx("button",{type:"button",onClick:H,className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"取消"}),o.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:"保存"})]})]}),o.jsx("div",{children:f?o.jsx("div",{className:"text-muted-foreground",children:"加载中..."}):w.length===0?o.jsx("div",{className:"text-muted-foreground",children:"暂无智能体配置"}):o.jsx("div",{className:"space-y-3",children:w.map(A=>o.jsxs("div",{className:"p-4 border rounded-lg flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center space-x-2 min-w-0",children:[o.jsx("h3",{className:"font-medium text-foreground truncate",title:A.name,children:A.name}),!A.enabled&&o.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-muted text-muted-foreground",children:"未启用"})]}),A.description&&o.jsx("p",{className:"mt-1 text-sm text-muted-foreground truncate",title:A.description,children:A.description}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground truncate",title:J(A.ai_model_config_id),children:["模型:",J(A.ai_model_config_id)]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:F(A.system_context_id),children:["系统上下文:",F(A.system_context_id)]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:k(A.mcp_config_ids||[]),children:["MCP配置:",k(A.mcp_config_ids||[])]})]}),o.jsxs("div",{className:"flex items-center space-x-2 ml-4 shrink-0",children:[o.jsx("button",{onClick:()=>_(A),className:"px-3 py-1 text-sm bg-muted text-foreground rounded hover:bg-accent transition-colors",children:"详情"}),o.jsx("button",{onClick:()=>z(A),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"编辑"}),o.jsxs("button",{onClick:()=>U(A.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:[o.jsx(Ig,{}),o.jsx("span",{children:"删除"})]})]})]},A.id))})})]}),y&&o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[o.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:()=>_(null)}),o.jsxs("div",{className:"relative bg-card border border-border rounded-lg shadow-xl w-[520px] p-6",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx(Pa,{}),o.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"智能体详情"})]}),o.jsx("button",{onClick:()=>_(null),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(Oa,{})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"名称:"}),y.name]}),y.description&&o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"描述:"}),y.description]}),o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"模型:"}),J(y.ai_model_config_id)]}),o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"系统上下文:"}),F(y.system_context_id)]}),o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"MCP配置:"}),k(y.mcp_config_ids||[])]}),Array.isArray(y.mcp_config_ids)&&y.mcp_config_ids.length>0&&o.jsx("div",{className:"mt-2 space-y-2",children:(y.mcp_config_ids||[]).map(A=>{var q,ee;const M=(a||[]).find(be=>be.id===A);if(!M)return null;let L="—";const $=M.args;if(Array.isArray($))L=$.map(be=>String(be)).join(", ");else if(typeof $=="string"&&$.trim()!=="")try{const be=JSON.parse($);Array.isArray(be)?L=be.map(ac=>String(ac)).join(", "):L=$}catch{L=$}return o.jsxs("div",{className:"p-2 rounded border border-border",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-sm font-medium text-foreground",children:M.name}),o.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:((ee=(q=M.type)==null?void 0:q.toUpperCase)==null?void 0:ee.call(q))||M.type})]}),o.jsxs("div",{className:"mt-1 text-xs text-muted-foreground break-all",children:[M.type==="http"?"URL:":"命令:",o.jsx("span",{className:"text-foreground",children:M.command})]}),M.cwd&&o.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground break-all",children:["cwd:",o.jsx("span",{className:"text-foreground",children:String(M.cwd)})]}),M.type==="stdio"&&o.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground break-all",children:["args:",o.jsx("span",{className:"text-foreground",children:L})]})]},A)})}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:["创建时间:",y.created_at?new Date(y.created_at).toLocaleString():"-"]})]}),o.jsx("div",{className:"mt-4 flex justify-end space-x-2",children:o.jsx("button",{onClick:()=>_(null),className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"关闭"})})]})]})]}),o.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:D,onCancel:C})]})},oc=({isOpen:r,onClose:e,manageOnly:t=!1,title:n,layout:s="modal",onApplicationSelect:a})=>{let i;try{i=dt()}catch{i=ct()}const{applications:l,loadApplications:d,createApplication:u,updateApplication:g,deleteApplication:h}=i,p=P.useRef(new Map),[w,m]=P.useState(!!t),[f,c]=P.useState(!1),[x,b]=P.useState(null),[y,_]=P.useState({name:"",url:"",iconUrl:""});P.useEffect(()=>{try{console.log("[ApplicationsPanel] useEffect -> loadApplications"),d==null||d()}catch(C){console.error("[ApplicationsPanel] loadApplications error:",C)}},[d]);const S=()=>{b(null),_({name:"",url:"",iconUrl:""}),c(!1)},j=async C=>{C.preventDefault(),y.name.trim()&&(x?await(g==null?void 0:g(x,{name:y.name.trim(),url:y.url.trim(),iconUrl:y.iconUrl.trim()||void 0})):await(u==null?void 0:u(y.name.trim(),y.url.trim(),y.iconUrl.trim()||void 0)),S())},v=C=>{console.log("[ApplicationsPanel] closeAppWindow:",C);const B=p.current.get(C);B&&!B.closed&&B.close(),p.current.delete(C)},I=C=>{console.log("[ApplicationsPanel] handleAppClick - 应用被点击:",{id:C.id,name:C.name,url:C.url}),a?(console.log("[ApplicationsPanel] 调用 onApplicationSelect 回调"),a(C)):console.log("[ApplicationsPanel] ⚠️ 未提供 onApplicationSelect 回调"),e&&(console.log("[ApplicationsPanel] 关闭应用列表面板"),e())};if(!(s==="modal"?!!r:!0))return null;const R=t?!0:w,D=n??(R?"应用管理":"应用列表");return s==="modal"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:e}),o.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:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full bg-blue-500"}),o.jsx("h2",{className:"text-lg font-semibold text-foreground",children:D})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&o.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:R?"浏览模式":"管理模式"}),!R&&p.current.size>0&&o.jsx("button",{className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",onClick:()=>{p.current.forEach((C,B)=>v(B))},children:"关闭全部"}),o.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:R?o.jsxs("div",{className:"space-y-4",children:[!f&&o.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:[o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v12m6-6H6"})}),o.jsx("span",{children:"新增应用"})]}),f&&o.jsxs("form",{onSubmit:j,className:"p-4 bg-muted rounded-lg space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),o.jsx("input",{type:"text",value:y.name,onChange:C=>_({...y,name:C.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})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"URL"}),o.jsx("input",{type:"text",value:y.url,onChange:C=>_({...y,url:C.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"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"图标URL"}),o.jsx("input",{type:"text",value:y.iconUrl,onChange:C=>_({...y,iconUrl:C.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"})]}),o.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-muted hover:bg-accent",onClick:S,children:"取消"}),o.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:x?"保存":"创建"})]})]}),o.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(C=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.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:C.iconUrl?o.jsx("img",{src:C.iconUrl,alt:C.name,className:"w-full h-full object-cover"}):o.jsx("span",{className:"text-white text-sm font-bold",children:C.name.charAt(0).toUpperCase()})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:C.name}),C.url&&o.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:C.url})]})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("button",{className:"px-2 py-1 text-xs bg-muted rounded hover:bg-accent",onClick:()=>{b(C.id),c(!0),_({name:C.name,url:C.url||"",iconUrl:C.iconUrl||""})},children:"编辑"}),o.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(C.id),children:"删除"})]})]},C.id)),(l==null?void 0:l.length)===0&&o.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[o.jsx("svg",{className:"w-16 h-16 mx-auto mb-3 opacity-30",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("div",{className:"text-sm",children:"暂无应用,点击上方按钮添加"})]})]})]}):o.jsxs("div",{className:"grid grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-6",children:[l==null?void 0:l.map(C=>{const B=p.current.has(C.id);return o.jsxs("div",{className:"relative group/item",children:[o.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>I(C),title:C.url||"",children:[o.jsxs("div",{className:`relative w-16 h-16 rounded-full flex items-center justify-center overflow-hidden transition-all ${B?"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:[C.iconUrl?o.jsx("img",{src:C.iconUrl,alt:C.name,className:"w-full h-full object-cover"}):o.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:o.jsx("span",{className:"text-white text-xl font-bold",children:C.name.charAt(0).toUpperCase()})}),B&&o.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:o.jsx("div",{className:"w-2 h-2 bg-white rounded-full animate-pulse"})})]}),o.jsx("div",{className:"text-xs font-medium text-foreground text-center truncate w-full px-1",children:C.name})]}),B&&o.jsx("button",{onClick:W=>{W.stopPropagation(),v(C.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:o.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},C.id)}),((l==null?void 0:l.length)??0)===0&&o.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-20 text-center",children:[o.jsx("svg",{className:"w-20 h-20 text-muted-foreground/30 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),o.jsx("button",{onClick:()=>m(!0),className:"text-sm text-blue-500 hover:text-blue-600 underline",children:"点击切换到管理模式添加应用"})]})]})})]})]}):o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-border bg-card/50",children:[o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-blue-500"}),o.jsx("span",{className:"text-sm font-medium text-foreground",children:D})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&o.jsx("button",{onClick:()=>{m(!w),c(!1),S()},className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent transition-colors",children:R?"浏览模式":"管理模式"}),!R&&p.current.size>0&&o.jsx("button",{className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent",onClick:()=>{p.current.forEach((C,B)=>v(B))},children:"关闭全部"}),e&&o.jsx("button",{onClick:e,className:"p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded transition-colors",title:"关闭",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:R?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4 flex items-center justify-between",children:o.jsx("button",{type:"button",onClick:()=>{b(null),_({name:"",url:"",iconUrl:""}),c(C=>!C)},className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:f?"取消":"新增应用"})}),f&&o.jsxs("form",{onSubmit:C=>{var O,N,U;C.preventDefault();const B=((O=y.name)==null?void 0:O.trim())||"",W=((N=y.url)==null?void 0:N.trim())||"",H=((U=y.iconUrl)==null?void 0:U.trim())||void 0;B&&(x?g==null||g(x,{name:B,url:W,iconUrl:H}):u==null||u(B,W,H),c(!1),S())},className:"p-4 bg-muted rounded-lg space-y-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),o.jsx("input",{value:y.name,onChange:C=>_({...y,name:C.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"例如:飞书"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"URL"}),o.jsx("input",{value:y.url,onChange:C=>_({...y,url:C.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://example.com"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"图标地址"}),o.jsx("input",{value:y.iconUrl,onChange:C=>_({...y,iconUrl:C.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://.../icon.png"})]}),o.jsxs("div",{className:"flex justify-end space-x-2",children:[o.jsx("button",{type:"button",onClick:()=>{c(!1),S(),b(null)},className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",children:"取消"}),o.jsx("button",{type:"submit",className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:x?"保存":"创建"})]})]}),o.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(C=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.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:C.iconUrl?o.jsx("img",{src:C.iconUrl,alt:C.name,className:"w-full h-full object-cover"}):o.jsx("span",{className:"text-white text-sm font-bold",children:C.name.charAt(0).toUpperCase()})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:C.name}),C.url&&o.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:C.url})]})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("button",{className:"px-2 py-1 text-xs rounded bg-background hover:bg-accent",onClick:()=>{c(!0),b(C.id),_({name:C.name||"",url:C.url||"",iconUrl:C.iconUrl||""})},children:"编辑"}),o.jsx("button",{className:"px-2 py-1 text-xs rounded bg-destructive text-destructive-foreground hover:opacity-90",onClick:()=>h==null?void 0:h(C.id),children:"删除"})]})]},C.id)),((l==null?void 0:l.length)??0)===0&&o.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center",children:[o.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用,点击上方按钮添加。"})]})]})]}):o.jsxs("div",{className:"grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[l==null?void 0:l.map(C=>{const B=p.current.has(C.id);return o.jsxs("div",{className:"relative group/item",children:[o.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>I(C),title:C.url||"",children:[o.jsx("div",{className:`relative w-14 h-14 rounded-full flex items-center justify-center overflow-hidden transition-all ${B?"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:C.iconUrl?o.jsx("img",{src:C.iconUrl,alt:C.name,className:"w-full h-full object-cover"}):o.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:o.jsx("span",{className:"text-white text-lg font-bold",children:C.name.charAt(0).toUpperCase()})})}),o.jsx("div",{className:"text-xs font-medium text-foreground truncate max-w-full",children:C.name}),C.url&&o.jsx("div",{className:"text-[10px] text-muted-foreground truncate max-w-full",children:C.url})]}),B&&o.jsx("button",{onClick:W=>{W.stopPropagation(),v(C.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:o.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},C.id)}),((l==null?void 0:l.length)??0)===0&&o.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-10 text-center",children:[o.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),o.jsx("button",{onClick:()=>m(!0),className:"text-sm text-blue-500 hover:text-blue-600 underline",children:"切换到管理模式以添加应用"})]})]})})]})},go=({className:r,apiBaseUrl:e,port:t,userId:n,projectId:s,showMcpManager:a=!0,showAiModelManager:i=!0,showSystemContextEditor:l=!0,showAgentManager:d=!0,onApplicationSelect:u})=>{const g=P.useMemo(()=>{if(e)return e;if(t)return`http://localhost:${t}/api`},[e,t]),h=P.useMemo(()=>{if(g)return new Vt(g)},[g]);return o.jsx($f,{userId:n,projectId:s,customApiClient:h,children:o.jsx(Tg,{className:r,showMcpManager:a,showAiModelManager:i,showSystemContextEditor:l,showAgentManager:d,onApplicationSelect:u})})},Tg=({className:r,showMcpManager:e,showAiModelManager:t,showSystemContextEditor:n,showAgentManager:s,onApplicationSelect:a})=>{const i=Ol(),{currentSession:l,messages:d,isLoading:u,isStreaming:g,hasMoreMessages:h,error:p,loadSessions:w,sendMessage:m,clearError:f,aiModelConfigs:c,selectedModelId:x,setSelectedModel:b,loadAiModelConfigs:y,agents:_,selectedAgentId:S,setSelectedAgent:j,loadAgents:v,abortCurrentConversation:I,loadMoreMessages:T}=i(),R=P.useRef(null),[D,C]=P.useState(!1),[B,W]=P.useState(!1),[H,O]=P.useState(!1),[N,U]=P.useState(!1),[z,J]=P.useState(!1),[F,k]=P.useState(!1);P.useEffect(()=>{(window.__standaloneChatInterfaceDidInit__??!1)||(window.__standaloneChatInterfaceDidInit__=!0,w(),y(),v())},[w,y,v]),P.useEffect(()=>{R.current&&R.current.scrollIntoView({behavior:"smooth"})},[d,g]);const A=async(M,L)=>{try{await m(M,L)}catch($){console.error("Failed to send message:",$)}};return o.jsxs("div",{className:ke("flex flex-col h-screen bg-background text-foreground",r),children:[o.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx("button",{onClick:()=>C(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),l&&o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:l.title})})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[a&&o.jsx("button",{onClick:()=>{console.log("[StandaloneChat] open ApplicationsPanel button clicked"),k(!0)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:o.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[o.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),o.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),e&&o.jsx("button",{onClick:()=>W(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP服务管理",children:o.jsxs("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:[o.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"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}),t&&o.jsx("button",{onClick:()=>O(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI配置管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.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&&o.jsx("button",{onClick:()=>U(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"System Prompt编辑器",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.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&&o.jsx("button",{onClick:()=>J(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.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"})})}),o.jsx(uo,{})]})]}),p&&o.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:o.jsxs("div",{className:"flex items中心 justify-between",children:[o.jsx("p",{className:"text-sm text-destructive",children:p}),o.jsx("button",{onClick:f,className:"text-destructive hover:text-destructive/80 transition-colors",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),o.jsx("div",{className:"flex-1 flex overflow-hidden",children:o.jsxs("div",{className:"flex-1 overflow-hidden",children:[l?o.jsx(io,{messages:d,isLoading:u,isStreaming:g,hasMore:h,onLoadMore:()=>l&&T(l.id)}):o.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:o.jsxs("div",{className:"text-center",children:[o.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 opacity-50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("p",{className:"text-lg mb-2",children:"欢迎使用AI聊天助手"}),o.jsx("p",{className:"text-sm",children:"点击左上角按钮创建新会话开始对话"})]})}),o.jsx("div",{ref:R})]})}),l&&o.jsx(lo,{onSend:A,onStop:I,disabled:u||g,isStreaming:g,selectedModelId:x,availableModels:c,onModelChange:b,showModelSelector:!0,selectedAgentId:S,availableAgents:_,onAgentChange:j}),o.jsx(co,{isOpen:D,onClose:()=>C(!1),store:i}),o.jsx(oc,{isOpen:F,onClose:()=>k(!1),title:"应用列表",layout:"modal",onApplicationSelect:a}),B&&o.jsx(fo,{onClose:()=>W(!1),store:i}),H&&o.jsx(ho,{onClose:()=>O(!1),store:i}),s&&z&&o.jsx(sc,{onClose:()=>J(!1),store:i}),N&&o.jsx(mo,{onClose:()=>U(!1),store:i})]})};class Pg{constructor(e,t,n,s,a=!0,i=!0,l=!0,d=!0,u){V(this,"userId");V(this,"projectId");V(this,"configUrl");V(this,"apiClient");V(this,"store");V(this,"className");V(this,"showMcpManager");V(this,"showAiModelManager");V(this,"showSystemContextEditor");V(this,"showAgentManager");V(this,"onApplicationSelect");this.userId=e,this.projectId=t,this.configUrl=n||"/api",this.className=s,this.showMcpManager=a,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 Vt(this.configUrl),this.store=Jr(this.apiClient,{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl})}render(){return P.createElement(Og,{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=Jr(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(a=>a.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 a=s.selectedApplicationId;if(console.log("[AiChat] store.subscribe 被触发, currentId:",a,"previousId:",t),a!==t){console.log("[AiChat] selectedApplicationId 变化检测到:",{old:t,new:a}),t=a;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 Og=({className:r,userId:e,projectId:t,configUrl:n,showMcpManager:s,showAiModelManager:a,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d})=>o.jsx(go,{className:r,apiBaseUrl:n,userId:e,projectId:t,showMcpManager:s,showAiModelManager:a,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d}),Rg=({className:r,onMessageSend:e,customRenderer:t})=>{const{currentSession:n,messages:s,isLoading:a,isStreaming:i,hasMoreMessages:l,error:d,loadSessions:u,loadMoreMessages:g,sendMessage:h,clearError:p,aiModelConfigs:w,selectedModelId:m,setSelectedModel:f,loadAiModelConfigs:c,agents:x,selectedAgentId:b,setSelectedAgent:y,loadAgents:_,abortCurrentConversation:S}=dt(),j=P.useRef(null),[v,I]=P.useState(!1),[T,R]=P.useState(!1),[D,C]=P.useState(!1),[B,W]=P.useState(!1),[H,O]=P.useState(!1);P.useEffect(()=>{(window.__chatInterfaceDidInit__??!1)||(window.__chatInterfaceDidInit__=!0,u(),c(),_())},[u,c,_]),P.useEffect(()=>{j.current&&j.current.scrollIntoView({behavior:"smooth"})},[s,i]);const N=async(U,z)=>{try{await h(U,z),e==null||e(U,[])}catch(J){console.error("Failed to send message:",J)}};return o.jsxs("div",{className:ke("flex flex-col h-screen bg-background text-foreground",r),children:[d&&o.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("p",{className:"text-sm text-destructive",children:d}),o.jsx("button",{onClick:p,className:"text-destructive hover:text-destructive/80 transition-colors",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),o.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[o.jsx("div",{className:"flex flex-col h-full",children:o.jsx(co,{embedded:!0})}),o.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[n&&o.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[o.jsx("div",{className:"flex items-center space-x-3"}),o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx(uo,{}),o.jsx("button",{onClick:()=>O(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:o.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[o.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),o.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),o.jsx("button",{onClick:()=>I(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP 服务器管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsx("button",{onClick:()=>W(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsx("button",{onClick:()=>R(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI 模型管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsx("button",{onClick:()=>C(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"系统上下文设置",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex-1 overflow-auto",children:[o.jsx(io,{messages:s,isLoading:a,isStreaming:i,hasMore:l,onLoadMore:()=>n&&g(n.id),customRenderer:t}),o.jsx("div",{ref:j})]}),o.jsx("div",{className:"border-t border-border",children:o.jsx(lo,{onSend:N,onStop:S,disabled:a,isStreaming:i,placeholder:"输入消息...",showModelSelector:!0,selectedModelId:m,availableModels:w,onModelChange:f,selectedAgentId:b,availableAgents:x,onAgentChange:y})})]}):o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h2",{className:"text-xl font-semibold text-muted-foreground mb-2",children:"欢迎使用 AI 聊天"}),o.jsx("p",{className:"text-muted-foreground mb-4",children:"从左侧会话列表选择会话,或创建新的会话开始对话"})]})})]})]}),v&&o.jsx(fo,{onClose:()=>I(!1)}),B&&o.jsx(sc,{onClose:()=>W(!1)}),T&&o.jsx(ho,{onClose:()=>R(!1)}),D&&o.jsx(mo,{onClose:()=>C(!1)}),o.jsx(oc,{isOpen:H,onClose:()=>O(!1),title:"应用列表",layout:"modal"})]})};class $g extends P.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:o.jsx("div",{className:"flex items-center justify-center h-full p-8",children:o.jsxs("div",{className:"text-center space-y-4",children:[o.jsx("div",{className:"w-16 h-16 mx-auto bg-destructive/10 rounded-full flex items-center justify-center",children:o.jsx("svg",{className:"w-8 h-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Something went wrong"}),o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),o.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 Lg="1.0.11";exports.AiChat=Pg;exports.AiModelManager=ho;exports.AiServer=Il;exports.ApiClient=Vt;exports.AppError=eg;exports.AttachmentRenderer=Xl;exports.ChatIcon=tc;exports.ChatInterface=Rg;exports.ChatService=Pl;exports.CheckIcon=sg;exports.ChevronDownIcon=lg;exports.CopyIcon=ag;exports.DatabaseService=bs;exports.DotsVerticalIcon=Zl;exports.ErrorBoundary=$g;exports.InputArea=lo;exports.LoadingSpinner=Yl;exports.MarkdownRenderer=nt;exports.McpManager=fo;exports.MessageItem=Kl;exports.MessageList=io;exports.MessageManager=Tl;exports.PencilIcon=gs;exports.PlayIcon=ig;exports.PlusIcon=Ql;exports.SessionList=co;exports.StandaloneChatInterface=go;exports.SystemContextEditor=mo;exports.ThemeToggle=uo;exports.ToolCallRenderer=ms;exports.TrashIcon=ec;exports.XIcon=og;exports.apiClient=te;exports.cleanHtmlContent=Hm;exports.cn=ke;exports.conversationsApi=kr;exports.copyToClipboard=Km;exports.debounce=Jm;exports.deepClone=hs;exports.default=go;exports.downloadFile=Ym;exports.formatDate=Um;exports.formatDateTime=Bm;exports.formatFileSize=Vl;exports.formatRelativeTime=Fm;exports.formatTime=Jl;exports.generateId=Dm;exports.generateRandomColor=Xm;exports.getFileExtension=Gl;exports.getOS=Zm;exports.isImageFile=Gm;exports.isMobile=Qm;exports.isValidEmail=qm;exports.isValidUrl=zm;exports.retry=tg;exports.storage=rg;exports.throttle=Vm;exports.truncateText=Wm;exports.useChatStore=ct;exports.useTheme=nc;exports.version=Lg;
99
+ `;return j.forEach(I=>{const P=S[I];let T;typeof P=="string"?T=P.replace(/\n/g,"<br>").replace(/\|/g,"\\|"):Array.isArray(P)?T=`[${P.join(", ")}]`.replace(/\|/g,"\\|"):T=JSON.stringify(P).replace(/\|/g,"\\|"),v+=`| ${I} | ${T} |
100
+ `}),v})(),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})(),x=!!(c&&typeof c=="object"),b=S=>{if(S===null)return"null";if(Array.isArray(S)){if(S.length===0)return"array []";const j=S[0],v=b(j);return v==="object"?"object []":`${v}[]`}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,j="",v="")=>{const I=[];if(S==null)return I;if(Array.isArray(S)){const P={path:v||j||"list",name:j||"list",type:b(S),value:S,children:S.map((T,L)=>{const C=`${v||j||"list"}[${L}]`,W=b(T);return{path:C,name:`[${L}]`,type:W,value:T,children:W==="object"||Array.isArray(T)?y(T,`[${L}]`,C):[]}})};return I.push(P),I}return typeof S=="object"&&Object.keys(S).forEach(P=>{const T=S[P],L=v?`${v}.${P}`:P,C=b(T),W=C==="object"||Array.isArray(T)?y(T,P,L):[];I.push({path:L,name:P,type:C,value:T,children:W})}),I},_=({data:S})=>{const j=Array.isArray(S)?y(S,"list","list"):y(S,"",""),[v,I]=M.useState(()=>new Set(j.filter(C=>C.children.length>0).map(C=>C.path))),P=C=>{I(W=>{const B=new Set(W);return B.has(C)?B.delete(C):B.add(C),B})},T=C=>{if(C===null)return"null";if(Array.isArray(C))return`数组(${C.length})`;if(typeof C=="object")return"对象";if(typeof C=="string")return C;try{return JSON.stringify(C)}catch{return String(C)}},L=(C,W)=>C.map(B=>{const z=B.children&&B.children.length>0,O=v.has(B.path),U=z?O?"▾":"▸":"",J=T(B.value);return o.jsxs(M.Fragment,{children:[o.jsxs("tr",{children:[o.jsxs("td",{style:{paddingLeft:W*16},children:[z?o.jsx("button",{type:"button",onClick:()=>P(B.path),className:"mr-2 text-gray-600 dark:text-gray-300 hover:text-black dark:hover:text-white","aria-label":O?"收起":"展开",children:U}):o.jsx("span",{className:"mr-4"}),B.name]}),o.jsx("td",{style:{whiteSpace:"normal",wordBreak:"break-word"},children:J})]}),z&&O&&L(B.children,W+1)]},B.path)});return o.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:o.jsx("div",{className:"markdown-renderer",children:o.jsxs("table",{children:[o.jsx("thead",{children:o.jsxs("tr",{children:[o.jsx("th",{children:"字段"}),o.jsx("th",{children:"值"})]})}),o.jsx("tbody",{children:L(j,0)})]})})})};return o.jsxs("div",{className:"tool-call-renderer tool-call-container",children:[o.jsxs("div",{className:"tool-header",children:[o.jsxs("span",{className:"tool-name",children:["@",r.name]}),l&&o.jsx("span",{className:"status-badge status-error",children:"错误"}),d&&!l&&o.jsx("span",{className:"status-badge status-success",children:"完成"}),!d&&!l&&o.jsx("span",{className:"status-badge status-pending",children:"等待中"}),(h||d||l)&&o.jsx("button",{onClick:()=>s(!n),className:"toggle-button",children:n?"收起详情":"查看详情"})]}),n&&o.jsxs("div",{className:"details-container",children:[h&&o.jsx("div",{children:m&&o.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:o.jsx(lt,{content:m})})}),d&&o.jsxs("div",{children:[o.jsx("div",{className:"details-title",children:"结果:"}),x?o.jsx(_,{data:c}):o.jsx(lt,{content:typeof i=="string"?i:JSON.stringify(i)})]}),l&&o.jsxs("div",{children:[o.jsx("div",{className:"details-title",children:"错误:"}),o.jsx("div",{className:"status-badge status-error",style:{display:"block",padding:"0.5rem"},children:r.error})]}),o.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()})()]})]})]})},mg=({message:r,isLast:e=!1,isStreaming:t=!1,onEdit:n,onDelete:s,allMessages:a=[],customRenderer:i})=>{var v,I,P,T,L,C,W,B,z;console.log("🚀🚀🚀 MessageItem 组件被调用!消息ID:",r.id,"角色:",r.role),console.log("🚀🚀🚀 完整消息对象:",r);const[l,d]=M.useState(!1),[u,g]=M.useState(r.content),h=(O,U)=>{navigator.clipboard.writeText(O).then(()=>{console.log("代码已复制到剪贴板:",{code:O,language:U})}).catch(J=>{console.error("复制失败:",J)})},[p,w]=M.useState(!1),m=r.role==="user",f=r.role==="assistant",c=r.role==="system",x=r.role==="tool";if(x)return null;if(i!=null&&i.renderMessage)return o.jsx("div",{children:i.renderMessage(r)});const b=()=>{n&&u.trim()!==r.content&&n(r.id,u.trim()),d(!1)},y=()=>{g(r.content),d(!1)},_=async()=>{try{await navigator.clipboard.writeText(r.content)}catch(O){console.error("Failed to copy message:",O)}},S=((v=r.metadata)==null?void 0:v.attachments)||[],j=r.toolCalls||((I=r.metadata)==null?void 0:I.toolCalls)||[];return console.log("🔧 工具调用数据:",{顶层toolCalls:r.toolCalls,"metadata.toolCalls":(P=r.metadata)==null?void 0:P.toolCalls,最终toolCalls长度:j.length,消息ID:r.id,contentSegments:(T=r.metadata)==null?void 0:T.contentSegments,contentSegments长度:((C=(L=r.metadata)==null?void 0:L.contentSegments)==null?void 0:C.length)||0}),o.jsxs("div",{className:ve("group relative rounded-lg transition-colors",!f&&"flex gap-3 px-4 py-4",f&&"px-4 py-2",m&&"bg-user-message",c&&"bg-muted border-l-4 border-primary",x&&"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:[!f&&o.jsx("div",{className:"flex-shrink-0",children:o.jsx("div",{className:ve("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",x&&"bg-blue-500 text-white"),children:m?"U":x?"T":"S"})}),o.jsxs("div",{className:"flex-1 min-w-0",children:[!f&&o.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[o.jsx("span",{className:"text-sm font-medium",children:m?"You":x?"Tool Result":"System"}),o.jsx("span",{className:"text-xs text-muted-foreground",children:ec(r.createdAt)})]}),((W=r.metadata)==null?void 0:W.type)==="session_summary"&&o.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:[o.jsxs("div",{className:"text-xs text-amber-900 dark:text-amber-200 font-medium mb-1",children:["上下文已压缩为摘要",typeof((B=r.metadata)==null?void 0:B.keepLastN)=="number"?`(保留最近 ${r.metadata.keepLastN} 条)`:""]}),o.jsxs("details",{className:"group",children:[o.jsx("summary",{className:"cursor-pointer text-xs text-muted-foreground select-none",children:"查看摘要内容"}),o.jsx("div",{className:"mt-2 prose prose-sm max-w-none",children:o.jsx(lt,{content:(r.rawContent||((z=r.metadata)==null?void 0:z.summary)||"").toString(),isStreaming:!1,onApplyCode:()=>{}})})]})]}),S.length>0&&o.jsx("div",{className:"mb-3 space-y-2",children:S.map(O=>o.jsx(nc,{attachment:O,customRenderer:i==null?void 0:i.renderAttachment},O.id))}),l?o.jsxs("div",{className:"space-y-2",children:[o.jsx("textarea",{value:u,onChange:O=>g(O.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}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx("button",{onClick:b,className:"px-3 py-1 text-sm bg-primary text-primary-foreground rounded hover:bg-primary/90",children:"Save"}),o.jsx("button",{onClick:y,className:"px-3 py-1 text-sm bg-muted text-muted-foreground rounded hover:bg-muted/80",children:"Cancel"})]})]}):o.jsx("div",{className:"space-y-3",children:(()=>{var $;const O=(($=r.metadata)==null?void 0:$.contentSegments)||[],U=r.content&&r.content.trim().length>0,J=t&&e;return O.length>0?(console.log("🎨 使用分段渲染,分段数量:",O.length),console.log("🎨 分段详情:",O),o.jsx("div",{className:"space-y-0.5",children:O.map((H,F)=>{if(console.log(`🎨 渲染分段 ${F}:`,H),H.type==="text")return console.log(`🎨 渲染文本分段 ${F}:`,H.content),o.jsx("div",{className:"prose prose-sm max-w-none",children:o.jsx(lt,{content:H.content,isStreaming:J&&F===O.length-1,onApplyCode:h})},`segment-${F}`);if(H.type==="tool_call"){console.log(`🎨 渲染工具调用分段 ${F}:`,H);const k=j.find(A=>A.id===H.toolCallId);if(console.log(`🎨 查找工具调用 ${H.toolCallId}:`,k),k)return console.log("🎨 找到工具调用,开始渲染:",k),o.jsx("div",{children:o.jsx(_s,{toolCall:k,allMessages:a})},`tool-${k.id}`);console.log(`🎨 ❌ 未找到工具调用 ${H.toolCallId}`)}else if(H.type==="thinking")return console.log(`🎨 渲染思考分段 ${F}:`,H.content),o.jsxs("details",{className:"group border border-gray-200 dark:border-gray-700 rounded-md bg-muted px-3 py-2",children:[o.jsx("summary",{className:"cursor-pointer text-xs text-gray-500 dark:text-gray-400 select-none",children:"思考过程"}),o.jsx("div",{className:"mt-1",children:o.jsx(lt,{content:H.content||"",isStreaming:J&&F===O.length-1,onApplyCode:h,className:"thinking not-prose"})})]},`thinking-${F}`);return null})})):(console.log("🎨 使用传统渲染方式"),console.log("🎨 hasContent:",U),console.log("🎨 toolCalls.length:",j.length),o.jsxs("div",{className:"space-y-0.5",children:[U&&o.jsx("div",{className:"prose prose-sm max-w-none",children:o.jsx(lt,{content:r.content,isStreaming:J,onApplyCode:h})}),j.length>0&&o.jsxs("div",{className:"space-y-0.5",children:[o.jsx("div",{className:"text-sm text-muted-foreground font-medium",children:"工具调用:"}),j.map(H=>(console.log("🎨 传统方式渲染工具调用:",H),o.jsx("div",{children:o.jsx(_s,{toolCall:H,allMessages:a})},`tool-${H.id}`)))]})]}))})()}),r.tokensUsed&&o.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Tokens used: ",r.tokensUsed]})]}),p&&!l&&o.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:[o.jsx("button",{onClick:_,className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Copy message",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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&&o.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:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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&&o.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:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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=M.memo(mg,(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)),oc=({size:r="md",className:e})=>{const t={sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"};return o.jsx("div",{className:ve("animate-spin rounded-full border-2 border-current border-t-transparent",t[r],e),role:"status","aria-label":"Loading",children:o.jsx("span",{className:"sr-only",children:"Loading..."})})},po=({messages:r,isLoading:e=!1,isStreaming:t=!1,hasMore:n=!1,onLoadMore:s,onMessageEdit:a,onMessageDelete:i,customRenderer:l})=>{const d=M.useRef(null),u=M.useRef(null),[g,h]=M.useState(!0),[p,w]=M.useState(!0),m=()=>{const b=d.current;return b?b.scrollHeight-b.scrollTop-b.clientHeight<=40:!0},f=(b=!0)=>{var y;(y=u.current)==null||y.scrollIntoView({behavior:b?"smooth":"auto"})};M.useEffect(()=>{t&&g&&f(!0)},[r,t,g]),M.useEffect(()=>{w(m())},[r,t]),M.useEffect(()=>{t&&p&&h(!0),t||h(!1)},[t,p]);const c=()=>{const b=m();w(b),b||h(!1)},x=()=>{f(!0),h(!0)};return r.length===0&&!e?o.jsx("div",{className:"flex items-center justify-center h-full",children:o.jsxs("div",{className:"text-center space-y-4",children:[o.jsx("div",{className:"w-16 h-16 mx-auto bg-muted rounded-full flex items-center justify-center",children:o.jsx("svg",{className:"w-8 h-8 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Start a conversation"}),o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Send a message to begin your chat with AI"})]})]})}):o.jsxs("div",{className:"flex flex-col h-full relative",children:[o.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&&o.jsx("div",{className:"flex justify-center mb-2",children:o.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(b=>{var y;return!((y=b==null?void 0:b.metadata)!=null&&y.hidden)}).map((b,y,_)=>o.jsx(sc,{message:b,isLast:y===_.length-1,isStreaming:t&&y===_.length-1,onEdit:a,onDelete:i,allMessages:r,customRenderer:l},b.id)),e&&o.jsx("div",{className:"flex justify-start",children:o.jsxs("div",{className:"flex items-center space-x-2 bg-muted px-4 py-3 rounded-lg max-w-xs",children:[o.jsx(oc,{size:"sm"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"AI is thinking..."})]})}),o.jsx("div",{ref:u})]}),!p&&o.jsxs("button",{type:"button","aria-label":"回到底部",title:"回到底部",onClick:x,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:[o.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[o.jsx("path",{d:"M12 5v12"}),o.jsx("path",{d:"M19 12l-7 7-7-7"})]}),o.jsx("span",{className:"text-sm",children:"回到底部"})]})]})},xo=({onSend:r,onStop:e,disabled:t=!1,isStreaming:n=!1,placeholder:s="Type your message...",maxLength:a=4e3,allowAttachments:i=!1,supportedFileTypes:l=["image/*","text/*","application/pdf"],showModelSelector:d=!1,selectedModelId:u=null,availableModels:g=[],onModelChange:h,selectedAgentId:p=null,availableAgents:w=[],onAgentChange:m,sessionMcpSummary:f,sessionMcpTooltip:c})=>{const[x,b]=M.useState(""),[y,_]=M.useState([]),[S,j]=M.useState(!1),v=M.useRef(null),I=M.useRef(null);M.useEffect(()=>{console.log("InputArea - isStreaming 状态变化:",{isStreaming:n,disabled:t,onStop:!!e,timestamp:new Date().toISOString()})},[n,t,e]);const P=M.useCallback(()=>{const $=v.current;if($){$.style.height="auto";const H=$.scrollHeight,F=200;$.style.height=`${Math.min(H,F)}px`}},[]),T=$=>{const H=$.target.value;H.length<=a&&(b(H),P())},L=$=>{$.key==="Enter"&&!$.shiftKey&&($.preventDefault(),C())},C=()=>{const $=x.trim();if(!(!$&&y.length===0)&&!t){if(d&&!u&&!p){alert("请先选择一个模型或智能体");return}r($,y),b(""),_([]),v.current&&(v.current.style.height="auto")}},W=$=>{const H=Array.from($.target.files||[]);_(F=>[...F,...H]),I.current&&(I.current.value="")},B=$=>{_(H=>H.filter((F,k)=>k!==$))},z=$=>{$.preventDefault(),i&&!t&&j(!0)},O=$=>{$.preventDefault(),j(!1)},U=$=>{if($.preventDefault(),j(!1),!i||t)return;const H=Array.from($.dataTransfer.files);_(F=>[...F,...H])},J=$=>{if($===0)return"0 Bytes";const H=1024,F=["Bytes","KB","MB","GB"],k=Math.floor(Math.log($)/Math.log(H));return parseFloat(($/Math.pow(H,k)).toFixed(2))+" "+F[k]};return o.jsxs("div",{className:"border-t bg-background p-4",children:[d&&o.jsxs("div",{className:"mb-3 flex items-center gap-3 flex-wrap",children:[g.length>0||w.length>0?o.jsxs("select",{value:p?`agent:${p}`:u||"",onChange:$=>{const H=$.target.value;if(H.startsWith("agent:")){const F=H.replace("agent:","");m==null||m(F),h==null||h(null)}else h==null||h(H||null),m==null||m(null)},disabled:t,className:ve("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:[o.jsx("option",{value:"",children:"请选择模型或智能体..."}),w&&w.filter($=>$.enabled).length>0&&o.jsx("optgroup",{label:"智能体",children:w.filter($=>$.enabled).map($=>o.jsxs("option",{value:`agent:${$.id}`,children:["[Agent] ",$.name]},$.id))}),g&&g.filter($=>$.enabled).length>0&&o.jsx("optgroup",{label:"模型",children:g.filter($=>$.enabled).map($=>o.jsxs("option",{value:$.id,children:[$.name," (",$.model_name,")"]},$.id))})]}):o.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:"暂无可用模型或智能体,请先在右上角配置"}),f?o.jsx("div",{className:"max-w-[360px] min-w-0 px-2 py-1 rounded-lg border border-border bg-muted/10 text-xs text-muted-foreground",title:c||f,children:o.jsx("span",{className:"truncate min-w-0 block",children:f})}):null]}),y.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:y.map(($,H)=>o.jsxs("div",{className:"flex items-center gap-2 bg-muted px-3 py-2 rounded-lg text-sm",children:[o.jsx("svg",{className:"w-4 h-4 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("span",{className:"truncate max-w-32",children:$.name}),o.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",J($.size),")"]}),o.jsx("button",{onClick:()=>B(H),className:"text-muted-foreground hover:text-destructive transition-colors",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},H))}),o.jsxs("div",{className:ve("relative flex items-end gap-2 p-3 border rounded-lg transition-colors","focus-within:border-primary",S&&"border-primary bg-primary/5",t&&"opacity-50 cursor-not-allowed"),onDragOver:z,onDragLeave:O,onDrop:U,children:[i&&o.jsx("button",{onClick:()=>{var $;return($=I.current)==null?void 0:$.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:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsx("textarea",{ref:v,value:x,onChange:T,onKeyDown:L,placeholder:s,disabled:t,className:ve("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"}}),o.jsxs("div",{className:"flex-shrink-0 text-xs text-muted-foreground",children:[x.length,"/",a]}),n?o.jsx("button",{onClick:()=>{console.log("停止按钮被点击",{onStop:e,disabled:t}),e&&e()},disabled:!1,className:ve("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:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 6h12v12H6z"})})}):o.jsx("button",{onClick:C,disabled:t||n||!x.trim()&&y.length===0,className:ve("flex-shrink-0 p-2 rounded-md transition-colors","disabled:opacity-50 disabled:cursor-not-allowed",(x.trim()||y.length>0)&&!t&&!n?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground"),title:d&&!u?"请先选择AI模型":"Send message",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"})})}),i&&o.jsx("input",{ref:I,type:"file",multiple:!0,accept:l.join(","),onChange:W,className:"hidden"})]}),S&&i&&o.jsx("div",{className:"absolute inset-0 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center",children:o.jsxs("div",{className:"text-center",children:[o.jsx("svg",{className:"w-8 h-8 mx-auto text-primary mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to attach"})]})})]})},ac=({className:r="w-5 h-5"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),ic=({className:r="w-5 h-5"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Ss=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),lc=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),gg=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),pg=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),cc=({className:r="w-5 h-5"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),xg=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),bg=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),yg=({className:r="w-4 h-4"})=>o.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}),xr=({isOpen:r,title:e,message:t,confirmText:n="确认",cancelText:s="取消",onConfirm:a,onCancel:i,type:l="danger",verificationText:d,verificationLabel:u,verificationPlaceholder:g,verificationHint:h})=>{if(!r)return null;const[p,w]=M.useState("");M.useEffect(()=>{r&&w("")},[r,d]);const m=!!d,f=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 o.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:o.jsx("div",{className:"bg-card rounded-lg shadow-lg w-full max-w-sm border border-border animate-breathing-border",children:o.jsxs("div",{className:"p-6",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground mb-2",children:e}),o.jsx("p",{className:"text-muted-foreground text-sm mb-6",children:t}),m&&o.jsxs("div",{className:"mb-6",children:[o.jsx("label",{className:"block text-xs font-medium text-muted-foreground mb-2",children:u||"请输入以下内容以继续操作"}),o.jsx("div",{className:"px-3 py-2 bg-muted rounded-md text-sm font-mono text-foreground border border-border mb-2",children:d}),o.jsx("input",{type:"text",value:p,onChange:x=>w(x.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}),o.jsx("p",{className:"text-[12px] text-muted-foreground mt-2",children:h||"为了防止误删,需要您再次确认此操作。"})]}),o.jsxs("div",{className:"flex gap-3",children:[o.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}),o.jsx("button",{onClick:a,disabled:f,className:`flex-1 px-4 py-2 text-sm rounded-md transition-colors ${c()} ${f?"opacity-50 cursor-not-allowed":""}`,children:n})]})]})})})},br=()=>{const[r,e]=M.useState({isOpen:!1,title:"",message:"",confirmText:"确认",cancelText:"取消",type:"danger"}),t=M.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=M.useCallback(()=>{e(i=>({...i,isOpen:!1}))},[]),s=M.useCallback(()=>{var i;(i=r.onConfirm)==null||i.call(r),n()},[r.onConfirm,n]),a=M.useCallback(()=>{var i;(i=r.onCancel)==null||i.call(r),n()},[r.onCancel,n]);return{dialogState:r,showConfirmDialog:t,hideConfirmDialog:n,handleConfirm:s,handleCancel:a}},Tr=r=>r===!0||r===1||r==="1",Ta=(r,e)=>r.includes(e)?r.filter(t=>t!==e):[...r,e],Oa=({isOpen:r,onClose:e,onCreate:t,availableModels:n,availableMcpConfigs:s,availablePrompts:a,defaultTitle:i="New Chat",defaultModelId:l=null,initialMcpConfigIds:d,initialPromptIds:u,dialogTitle:g="新建会话",confirmText:h="创建"})=>{const p=M.useMemo(()=>(n||[]).filter(z=>Tr(z.enabled)),[n]),w=M.useMemo(()=>(s||[]).filter(z=>Tr(z.enabled)),[s]),m=M.useMemo(()=>s||[],[s]),[f,c]=M.useState(i),[x,b]=M.useState(""),[y,_]=M.useState([]),[S,j]=M.useState([]),[v,I]=M.useState(!1),[P,T]=M.useState(!1),[L,C]=M.useState(!1),W=M.useMemo(()=>(a||[]).filter(z=>Tr(z.isActive??z.is_active??!1)).map(z=>z.id),[a]);if(M.useEffect(()=>{var O;if(!r)return;c(i),_(Array.isArray(d)?d:w.map(U=>U.id)),j(Array.isArray(u)?u:W),I(!1),T(!1),C(!1);const z=((O=p[0])==null?void 0:O.id)||"";b(l||z)},[r]),M.useEffect(()=>{var O;if(!r||x)return;const z=((O=p[0])==null?void 0:O.id)||"";!l&&!z||b(l||z)},[r,x,l,p]),M.useEffect(()=>{r&&(Array.isArray(d)||P||y.length>0||w.length!==0&&_(w.map(z=>z.id)))},[r,d,P,y,w]),M.useEffect(()=>{r&&(Array.isArray(u)||L||S.length>0||W.length!==0&&j(W))},[r,u,L,S,W]),!r)return null;const B=!v&&!!x;return o.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:o.jsx("div",{className:"bg-card rounded-lg shadow-lg w-full max-w-lg border border-border animate-breathing-border",children:o.jsxs("div",{className:"p-6",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:g}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"会话标题"}),o.jsx("input",{value:f,onChange:z=>c(z.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:"New Chat",disabled:v})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择模型(必选)"}),o.jsxs("select",{value:x,onChange:z=>b(z.target.value),disabled:v,className:"w-full px-3 py-2 border border-input bg-background rounded-md text-sm text-foreground focus:outline-none focus:ring-2 focus:ring-ring",children:[o.jsx("option",{value:"",disabled:!0,children:"请选择模型..."}),p.map(z=>o.jsxs("option",{value:z.id,children:[z.name," (",z.model_name,")"]},z.id))]}),p.length===0&&o.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"暂无可用模型,请先在右上角配置。"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 MCP(多选)"}),m.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"暂无 MCP 配置。"}):o.jsx("div",{className:"max-h-40 overflow-auto rounded-md border border-border bg-background",children:m.map(z=>{const O=Tr(z.enabled);return o.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 text-sm hover:bg-accent",children:[o.jsx("input",{type:"checkbox",checked:y.includes(z.id),onChange:()=>{T(!0),_(U=>Ta(U,z.id))},disabled:v}),o.jsxs("span",{className:"truncate",title:z.name,children:[z.name,O?null:o.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(未启用)"})]})]},z.id)})})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 Prompt(多选)"}),a.length===0?o.jsx("p",{className:"text-xs text-muted-foreground",children:"暂无可用 Prompt(系统上下文)。"}):o.jsx("div",{className:"max-h-40 overflow-auto rounded-md border border-border bg-background",children:(a||[]).map(z=>{const O=z.isActive??z.is_active??!1;return o.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 text-sm hover:bg-accent",children:[o.jsx("input",{type:"checkbox",checked:S.includes(z.id),onChange:()=>{C(!0),j(U=>Ta(U,z.id))},disabled:v}),o.jsxs("span",{className:"truncate",title:z.name,children:[z.name,O?o.jsx("span",{className:"ml-2 text-xs text-muted-foreground",children:"(当前激活)"}):null]})]},z.id)})})]})]}),o.jsxs("div",{className:"flex gap-3 mt-6",children:[o.jsx("button",{onClick:e,disabled:v,className:"flex-1 px-4 py-2 text-sm border border-border rounded-md hover:bg-accent transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"取消"}),o.jsx("button",{onClick:async()=>{if(B){I(!0);try{await t({title:f.trim()||i,modelId:x,mcpConfigIds:y,promptIds:S}),e()}finally{I(!1)}}},disabled:!B,className:"flex-1 px-4 py-2 text-sm rounded-md transition-colors bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50 disabled:cursor-not-allowed",children:h})]})]})})})},wg=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")},bo=({isOpen:r=!0,onClose:e,store:t,embedded:n=!1})=>{let s=null;try{s=tt()}catch{}const a=t?t():s;if(!a)throw new Error("SessionList must be used within a ChatStoreProvider or receive a store prop");const{sessions:i,currentSession:l,createSession:d,selectSession:u,deleteSession:g,updateSessionConfig:h,getSessionMcpConfigIds:p,aiModelConfigs:w,loadAiModelConfigs:m,mcpConfigs:f,loadMcpConfigs:c,systemContexts:x,loadSystemContexts:b,selectedModelId:y}=a,_=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",S="transition-all duration-300 ease-in-out",[j,v]=M.useState(!1),[I,P]=M.useState(!1),[T,L]=M.useState(null),[C,W]=M.useState([]),[B,z]=M.useState(!r),{dialogState:O,showConfirmDialog:U,handleConfirm:J,handleCancel:$}=br(),H=()=>{z(!B)},F=async()=>{try{v(!0),m==null||m(),c==null||c(),b==null||b(),B&&z(!1)}catch(R){console.error("Failed to create session:",R)}},k=async R=>{try{await u(R)}catch(q){console.error("Failed to select session:",q)}},A=async R=>{const q=i.find(Q=>Q.id===R);U({title:"删除确认",message:`确定要删除会话 "${(q==null?void 0:q.title)||"Untitled"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{try{await g(R)}catch(Q){console.error("Failed to delete session:",Q)}}})},N=R=>{const q=R==null?void 0:R.metadata;try{return typeof q=="string"?q?JSON.parse(q):{}:q&&typeof q=="object"?q:{}}catch{return{}}},D=async R=>{try{m==null||m(),c==null||c(),b==null||b();const q=await(p==null?void 0:p(R.id));W(Array.isArray(q)?q:[]),L(R),P(!0),B&&z(!1)}catch(q){console.error("Failed to open session editor:",q)}};return o.jsx("div",{className:`${_} ${S} ${B?"w-32":"w-80 sm:w-96"}`,children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:`flex ${B?"flex-col items-center justify-center p-2":"items-center justify-between p-4"} border-b border-border transition-all duration-300`,children:[!B&&o.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"会话列表"}),o.jsxs("div",{className:`flex ${B?"flex-col space-y-2 items-center":"items-center space-x-2"}`,children:[o.jsx("button",{onClick:F,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"新建会话",children:o.jsx(ac,{className:"w-5 h-5"})}),o.jsx("button",{onClick:H,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:B?"展开":"收起",children:B?o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 5l7 7-7 7"})}):o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 19l-7-7 7-7"})})}),e&&!B&&!n&&o.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:i.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground",children:[o.jsx(cc,{className:"w-12 h-12 mb-4 opacity-50"}),!B&&o.jsxs(o.Fragment,{children:[o.jsx("p",{className:"text-sm",children:"还没有会话"}),o.jsx("button",{onClick:F,className:"mt-2 px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"创建第一个会话"})]})]}):o.jsx("div",{className:"p-2 space-y-1",children:i.map(R=>o.jsxs("div",{className:`group relative flex items-center p-3 rounded-lg cursor-pointer transition-colors ${(l==null?void 0:l.id)===R.id?"bg-accent border border-border":"hover:bg-accent/50"}`,onClick:()=>k(R.id),children:[o.jsx("div",{className:"flex-1 min-w-0",children:o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:`text-sm font-medium text-foreground truncate ${B?"text-center w-full":""}`,title:R.title,children:B&&R.title.length>4?R.title.slice(0,4)+"...":R.title}),!B&&o.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:wg(R.updatedAt)})]})}),!B&&o.jsxs("div",{className:"relative flex items-center gap-1",children:[o.jsx("button",{className:"p-1 text-muted-foreground hover:text-foreground opacity-0 group-hover:opacity-100 transition-opacity",onClick:q=>{q.stopPropagation(),D(R)},title:"编辑",children:o.jsx(Ss,{className:"w-4 h-4"})}),o.jsx("button",{className:"p-1 text-muted-foreground hover:text-foreground opacity-0 group-hover:opacity-100 transition-opacity",onClick:q=>{q.stopPropagation();const Q=q.currentTarget.nextElementSibling;Q&&Q.classList.toggle("hidden")},children:o.jsx(ic,{className:"w-4 h-4"})}),o.jsx("div",{className:"hidden absolute right-0 z-10 mt-1 w-32 bg-popover border border-border rounded-md shadow-lg",children:o.jsxs("div",{className:"py-1",children:[o.jsxs("button",{onClick:q=>{q.stopPropagation(),D(R);const Q=q.currentTarget.closest(".absolute");Q&&Q.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-popover-foreground hover:bg-accent",children:[o.jsx(Ss,{className:"w-4 h-4 mr-2"}),"编辑"]}),o.jsxs("button",{onClick:q=>{q.stopPropagation(),A(R.id);const Q=q.currentTarget.closest(".absolute");Q&&Q.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-destructive hover:bg-destructive/10",children:[o.jsx(lc,{className:"w-4 h-4 mr-2"}),"删除"]})]})})]})]},R.id))})}),o.jsx(xr,{isOpen:O.isOpen,title:O.title,message:O.message,confirmText:O.confirmText,cancelText:O.cancelText,type:O.type,verificationText:O.verificationText,verificationLabel:O.verificationLabel,verificationPlaceholder:O.verificationPlaceholder,verificationHint:O.verificationHint,onConfirm:J,onCancel:$}),o.jsx(Oa,{isOpen:j,onClose:()=>v(!1),availableModels:w||[],availableMcpConfigs:f||[],availablePrompts:x||[],defaultModelId:y,dialogTitle:"新建会话",confirmText:"创建",onCreate:async R=>{try{await d({title:R.title,modelId:R.modelId,mcpConfigIds:R.mcpConfigIds,promptIds:R.promptIds})}catch(q){throw console.error("Failed to create session:",q),q}}}),o.jsx(Oa,{isOpen:I,onClose:()=>{P(!1),L(null),W([])},availableModels:w||[],availableMcpConfigs:f||[],availablePrompts:x||[],defaultTitle:(T==null?void 0:T.title)||"New Chat",defaultModelId:(()=>{const R=N(T);return R.ai_model_config_id||R.model_id||R.modelId||y||null})(),initialMcpConfigIds:C,initialPromptIds:(()=>{const R=N(T),q=R.prompt_ids||R.promptIds||[];return Array.isArray(q)?q.map(Q=>String(Q)).filter(Boolean):[]})(),dialogTitle:"编辑会话",confirmText:"保存",onCreate:async R=>{if(T)try{await(h==null?void 0:h(T.id,{title:R.title,modelId:R.modelId,mcpConfigIds:R.mcpConfigIds,promptIds:R.promptIds}))}catch(q){throw console.error("Failed to update session config:",q),q}}})]})})},dc=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",Ra=r=>r==="system"?dc():r,Gn=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")},$a=()=>typeof window>"u"?"system":localStorage.getItem("theme")||"system",vg=r=>{typeof window>"u"||localStorage.setItem("theme",r)},uc=()=>{const[r,e]=M.useState(()=>$a()),[t,n]=M.useState(()=>Ra($a())),s=i=>{e(i),vg(i);const l=Ra(i);n(l),Gn(l)},a=()=>{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 M.useEffect(()=>{if(r!=="system")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),l=()=>{const d=dc();n(d),Gn(d)};return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[r]),M.useEffect(()=>{Gn(t)},[t]),{theme:r,actualTheme:t,setTheme:s,toggleTheme:a}},yo=({className:r=""})=>{const{theme:e,toggleTheme:t}=uc(),n=()=>{switch(e){case"light":return o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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 o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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 o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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 o.jsx("button",{onClick:t,className:`p-2 hover:bg-muted rounded-lg transition-colors ${r}`,title:s(),"aria-label":s(),children:n()})},_g={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Sg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),La=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),Cg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),jg=({open:r,config:e,onClose:t})=>{const[n,s]=M.useState([]),[a,i]=M.useState(!1),[l,d]=M.useState(null),[u,g]=M.useState(null),[h,p]=M.useState(!1),[w,m]=M.useState({name:"",envJson:"",enabled:!1}),[f,c]=M.useState(null),[x,b]=M.useState({});if(M.useEffect(()=>{(async()=>{if(!(!r||!(e!=null&&e.id))){i(!0),d(null);try{const _=await te.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 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 o.jsxs("div",{className:"modal-container",children:[o.jsxs("div",{className:"modal-content w-full max-w-3xl max-h-[85vh] overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(Sg,{}),o.jsxs("h3",{className:"text-lg font-semibold text-foreground",children:["配置档案 - ",e==null?void 0:e.name]})]}),o.jsx("button",{onClick:()=>t(),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(La,{})})]}),o.jsxs("div",{className:"p-4 overflow-y-auto overflow-x-hidden",style:{maxHeight:"calc(85vh - 100px)"},children:[e&&o.jsxs("div",{className:"mb-4 p-3 rounded-md border border-border bg-muted/40",children:[o.jsx("div",{className:"text-sm font-medium mb-2 text-foreground",children:"基本信息"}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 text-xs text-muted-foreground",children:[o.jsxs("div",{children:["协议类型:",o.jsx("span",{className:"ml-1 text-foreground",children:e.type==="http"?"HTTP":"Stdio"})]}),o.jsxs("div",{children:[e.type==="http"?"URL:":"命令:",o.jsx("span",{className:"ml-1 text-foreground break-all",children:e.command})]}),e.type==="stdio"&&e.cwd&&o.jsxs("div",{children:["cwd:",o.jsx("span",{className:"ml-1 text-foreground break-all",children:String(e.cwd)})]}),e.type==="stdio"&&o.jsxs("div",{className:"sm:col-span-2",children:["args:",o.jsx("span",{className:"ml-1 text-foreground break-all",children:(()=>{const y=e.args;if(!y)return"—";if(Array.isArray(y))return y.map(_=>String(_)).join(", ");if(typeof y=="string"){try{const _=JSON.parse(y);if(Array.isArray(_))return _.map(S=>String(S)).join(", ")}catch{}return y}return String(y)})()})]})]})]}),o.jsxs("div",{className:"flex items-center justify-between mb-3",children:[o.jsx("span",{className:"text-sm text-muted-foreground",children:"已保存的配置档案"}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.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 te.getMcpConfigProfiles(e.id);s(Array.isArray(y)?y:[])}finally{i(!1)}}},children:"刷新列表"}),o.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 _=await te.getMcpConfigResource(e.id),S=_&&_.config||{};S&&typeof S=="object"&&(y=S)}catch{}m({name:`配置_${new Date().toLocaleString("zh-CN")}`,envJson:"",enabled:!1}),b(y||{}),g(null),p(!0)},children:"新增配置档案"})]})]}),a?o.jsx("div",{className:"text-xs text-muted-foreground",children:"加载中..."}):l?o.jsx("div",{className:"text-xs text-destructive",children:l}):n.length===0?o.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案,点击右上角“新增配置档案”。"}):o.jsx("div",{className:"space-y-2",children:n.map(y=>o.jsx("div",{className:"px-2 py-2 border border-border rounded-md",children:o.jsxs("div",{className:"flex items-center justify-between gap-2",children:[o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("div",{className:"text-sm text-foreground font-medium truncate",title:y.name,children:y.name}),y.enabled&&o.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:"已启用"})]}),o.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[o.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 te.activateMcpConfigProfile(e.id,y.id);const _=await te.getMcpConfigProfiles(e.id);s(Array.isArray(_)?_:[])}catch{}},children:"激活"}),o.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 _=y.env||{},S={};Object.keys(_||{}).forEach(j=>{const v=_[j];if(typeof v=="string"){const I=v.trim();try{S[j]=JSON.parse(I)}catch{I.includes(",")?S[j]=I.split(",").map(P=>P.trim()).filter(Boolean):S[j]=I}}else S[j]=v}),b(S),p(!0)},children:"编辑"}),o.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 te.deleteMcpConfigProfile(e.id,y.id);const S=await te.getMcpConfigProfiles(e.id);s(Array.isArray(S)?S:[])}catch(S){console.error("删除配置档案失败:",S)}},children:"删除"})]})]})},y.id))})]})]}),h&&o.jsxs("div",{className:"modal-container z-[100]",children:[o.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-sm",onClick:()=>{p(!1),c(null)}}),o.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:o.jsxs("div",{className:"modal-content w-full max-w-2xl transform overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Cg,{}),o.jsx("h3",{className:"text-base font-semibold text-foreground",children:u?"编辑配置档案":"新增配置档案"})]}),o.jsx("button",{onClick:()=>{p(!1),c(null)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(La,{})})]}),o.jsxs("div",{className:"p-4",children:[f&&o.jsx("div",{className:"mb-2 text-xs text-destructive",children:f}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),o.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"})]}),o.jsx("div",{children:x&&Object.keys(x).length>0&&o.jsxs("div",{className:"mb-3",children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"动态参数"}),o.jsx("div",{className:"grid grid-cols-1 gap-3",children:Object.keys(x).map(y=>{const _=x[y],S=typeof _,j=Array.isArray(_);return o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:y}),S==="boolean"?o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",checked:!!_,onChange:v=>b({...x,[y]:v.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),o.jsx("span",{className:"ml-2 text-xs",children:String(_)})]}):j?o.jsx("input",{type:"text",value:_.join(", "),onChange:v=>b({...x,[y]:v.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"&&_!==null?o.jsx("textarea",{value:(()=>{try{return JSON.stringify(_,null,2)}catch{return String(_)}})(),onChange:v=>{try{const I=JSON.parse(v.target.value);b({...x,[y]:I})}catch{b({...x,[y]:v.target.value})}},rows:4,className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md font-mono text-xs"}):o.jsx("input",{type:S==="number"?"number":"text",value:_??"",onChange:v=>b({...x,[y]:S==="number"?Number(v.target.value):v.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},y)})})]})})]}),o.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[o.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:"取消"}),o.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(x&&Object.keys(x).length>0)y=x;else{const j=(w.envJson||"").trim();if(j)try{const v=JSON.parse(j);v&&typeof v=="object"&&(y=v)}catch{throw new Error("env JSON 格式错误")}}let S=null;if(y&&typeof y=="object"){S={};for(const j of Object.keys(y)){const v=y[j];Array.isArray(v)?S[j]=v.join(","):typeof v=="boolean"||typeof v=="number"?S[j]=String(v):v==null?S[j]="":typeof v=="object"?S[j]=JSON.stringify(v):S[j]=String(v)}}if(u)if(await te.updateMcpConfigProfile(e.id,u,{name:w.name,env:S,enabled:w.enabled})){const v=await te.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[]),p(!1),g(null)}else throw new Error("更新失败");else{const j=await te.createMcpConfigProfile(e.id,{name:w.name,env:S,enabled:w.enabled});if(j&&(j.id||j.success)){const v=await te.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[]),p(!1)}else throw new Error("创建失败")}}catch(y){c((y==null?void 0:y.message)||"保存失败")}},children:"保存"})]})]})]})})]})]})},Ag={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Da=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),kg=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),Ng=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Mg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Eg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),wo=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=tt()}catch{t=mt()}const{mcpConfigs:n,updateMcpConfig:s,deleteMcpConfig:a,loadMcpConfigs:i}=t,{dialogState:l,showConfirmDialog:d,handleConfirm:u,handleCancel:g}=br(),[h,p]=M.useState(!1),[w,m]=M.useState(null),[f,c]=M.useState({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),[x,b]=M.useState(!1),[y,_]=M.useState(null),[S,j]=M.useState({}),[v,I]=M.useState([]),[P,T]=M.useState(""),[L,C]=M.useState(!1),[W,B]=M.useState(null);M.useEffect(()=>{const k="__mcpManagerInitAt__",A=window[k]||0,N=Date.now();typeof A=="number"&&N-A<1e3||(window[k]=N,i())},[i]);const z=async k=>{B(k),C(!0);try{const A=await te.getMcpConfigProfiles(k.id);I(Array.isArray(A)?A:[])}catch{console.error("加载配置档案失败")}finally{}},O=()=>{c({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),m(null),p(!1),j({}),I([]),T("")},U=async k=>{var N,D;if(k.preventDefault(),!f.name.trim()||!f.command.trim())return;const A={name:f.name.trim(),command:f.command.trim(),type:f.type,enabled:f.enabled,cwd:(N=f.cwd)!=null&&N.trim()?f.cwd.trim():void 0,args:(D=f.argsInput)!=null&&D.trim()?f.argsInput.split(",").map(R=>R.trim()).filter(Boolean):void 0,createdAt:new Date,updatedAt:new Date};await s(A),O()},J=async k=>{var N,D;if(k.preventDefault(),!w||!f.name.trim()||!f.command.trim())return;const A={...w,name:f.name.trim(),command:f.command.trim(),type:f.type,enabled:f.enabled,cwd:(N=f.cwd)!=null&&N.trim()?f.cwd.trim():void 0,args:(D=f.argsInput)!=null&&D.trim()?f.argsInput.split(",").map(R=>R.trim()).filter(Boolean):void 0,updatedAt:new Date};await s(A),O()},$=k=>{m(k);let A="";const N=k.args;if(Array.isArray(N))A=N.map(D=>String(D)).join(", ");else if(typeof N=="string"&&N.trim()!=="")try{const D=JSON.parse(N);Array.isArray(D)?A=D.map(R=>String(R)).join(", "):A=N}catch{A=N}c({name:k.name,command:k.command,type:k.type||"stdio",enabled:k.enabled,cwd:k.cwd||"",argsInput:A}),p(!0),j({}),_(null),b(!1)},H=async k=>{var D;const A=n.find(R=>R.id===k),N=((D=A==null?void 0:A.name)==null?void 0:D.trim())||"删除";d({title:"删除 MCP 服务器",message:`确定要删除服务器 "${(A==null?void 0:A.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",verificationText:N,verificationLabel:"请键入服务器名称以确认删除",verificationPlaceholder:`输入 "${N}"`,verificationHint:"删除后无法恢复,请再次确认操作。",onConfirm:()=>a(k)})},F=async k=>{const A={...k,enabled:!k.enabled,updatedAt:new Date};await s(A)};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),o.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:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(Da,{}),o.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"MCP 服务器管理"})]}),o.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:o.jsx(kg,{})})]}),o.jsxs("div",{className:"p-4 flex-1 overflow-y-auto overflow-x-hidden",children:[!h&&o.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:[o.jsx(Ng,{}),o.jsx("span",{children:"添加 MCP 服务器"})]}),h&&o.jsxs("form",{onSubmit:w?J:U,className:"mb-6 p-4 bg-muted rounded-lg",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:w?"编辑服务器":"添加新服务器"}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"服务器名称"}),o.jsx("input",{type:"text",value:f.name,onChange:k=>c({...f,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:"例如: File System",required:!0})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"协议类型"}),o.jsxs("select",{value:f.type,onChange:k=>c({...f,type: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",children:[o.jsx("option",{value:"stdio",children:"Stdio (标准输入输出)"}),o.jsx("option",{value:"http",children:"HTTP (网络协议)"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:f.type==="http"?"URL地址":"命令"}),o.jsx("input",{type:"text",value:f.command,onChange:k=>c({...f,command: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:f.type==="http"?"https://api.example.com/mcp":"npx @modelcontextprotocol/server-filesystem /path/to/allowed/files",required:!0}),f.type==="stdio"&&o.jsx(o.Fragment,{})]}),f.type==="stdio"&&o.jsxs("div",{className:"space-y-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"可执行地址(cwd)"}),o.jsx("input",{type:"text",value:f.cwd,onChange:k=>c({...f,cwd: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:"/absolute/path/to/executable"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"为空则使用当前页面的工作目录"}),o.jsx("div",{className:"mt-2 flex gap-2",children:o.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 k,A;if(f.command.trim()){b(!0),_(null);try{const N=await te.getMcpConfigResourceByCommand({type:f.type,command:f.command.trim(),args:(k=f.argsInput)!=null&&k.trim()?f.argsInput.split(",").map(D=>D.trim()).filter(Boolean):void 0,env:void 0,cwd:(A=f.cwd)!=null&&A.trim()?f.cwd.trim():void 0,alias:null});if(N&&N.success&&N.config){const D=N.config;if(j(D),w!=null&&w.id)try{const R=await te.getMcpConfigProfiles(w.id);I(Array.isArray(R)?R:[])}catch{}}else _("无法获取服务器可配置参数")}catch(N){_((N==null?void 0:N.message)||"获取配置失败")}finally{b(!1)}}},children:x?"获取中…":"获取配置"})})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"启动参数(args,逗号分隔)"}),o.jsx("input",{type:"text",value:f.argsInput,onChange:k=>c({...f,argsInput: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:"--flag, value, --opt"}),o.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"将自动转换为参数数组"})]})]}),o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",id:"enabled",checked:f.enabled,onChange:k=>c({...f,enabled:k.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),o.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此服务器"})]}),f.type==="stdio"&&Object.keys(S).length>0&&o.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("span",{className:"text-sm font-medium text-foreground",children:"服务器可配置参数(动态解析)"}),x&&o.jsx("span",{className:"text-xs text-muted-foreground",children:"解析中…"})]}),y&&o.jsx("p",{className:"text-xs text-red-600 mb-2",children:y}),o.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[Object.keys(S).map(k=>{const A=S[k],N=typeof A,D=Array.isArray(A);return o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:k}),N==="boolean"?o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",checked:!!A,onChange:R=>j({...S,[k]:R.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),o.jsx("span",{className:"ml-2 text-xs",children:String(A)})]}):D?o.jsx("input",{type:"text",value:A.join(", "),onChange:R=>j({...S,[k]:R.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"}):o.jsx("input",{type:N==="number"?"number":"text",value:A??"",onChange:R=>j({...S,[k]:N==="number"?Number(R.target.value):R.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},k)}),(w==null?void 0:w.id)&&o.jsxs("div",{className:"mt-2 p-2 border border-dashed rounded-md",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("input",{type:"text",value:P,onChange:k=>T(k.target.value),className:"flex-1 px-2 py-1 border border-input bg-background text-foreground rounded-md",placeholder:"配置档案名称(例如:开发环境)"}),o.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 k,A;if(w!=null&&w.id)try{await te.createMcpConfigProfile(w.id,{name:P||`配置-${new Date().toLocaleString()}`,env:Object.keys(S).reduce((D,R)=>{const q=S[R];return D[R]=typeof q=="string"?q:String(q),D},{}),args:(k=f.argsInput)!=null&&k.trim()?f.argsInput.split(",").map(D=>D.trim()).filter(Boolean):void 0,cwd:(A=f.cwd)!=null&&A.trim()?f.cwd.trim():void 0,enabled:!1});const N=await te.getMcpConfigProfiles(w.id);I(Array.isArray(N)?N:[]),T("")}catch(N){console.error("保存配置档案失败:",N),_("保存配置档案失败")}},children:"保存为配置档案"})]}),v.length>0&&o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"已有配置档案:"}),v.map(k=>{const A=Array.isArray(k.args)?k.args.join(", "):"",N=k.env?Object.keys(k.env):[];return o.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"text-xs text-foreground font-medium",children:k.name}),k.enabled&&o.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:"已启用"})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.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 te.activateMcpConfigProfile(w.id,k.id);const D=await te.getMcpConfigProfiles(w.id);I(Array.isArray(D)?D:[])}catch{}},children:"激活"}),o.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{c(D=>({...D,argsInput:Array.isArray(k.args)?k.args.join(", "):D.argsInput,cwd:k.cwd??D.cwd})),j(k.env||{})},children:"应用到表单"})]})]}),o.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[o.jsxs("div",{className:"truncate",title:k.cwd||"未设置",children:[o.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),k.cwd||"未设置"]}),o.jsxs("div",{className:"truncate",title:A||"未设置",children:[o.jsx("span",{className:"text-muted-foreground",children:"args:"}),A||"未设置"]}),o.jsxs("div",{children:[o.jsxs("span",{className:"text-muted-foreground",children:["env(",N.length,"):"]}),N.length===0?"未设置":o.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:N.map(D=>o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"text-muted-foreground shrink-0",children:D}),o.jsx("span",{className:"text-foreground truncate",title:String(k.env[D]),children:String(k.env[D])})]},D))})]})]})]},k.id)})]})]})]})]})]}),(w==null?void 0:w.id)&&!h&&o.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[o.jsxs("div",{className:"flex items-center justify-between mb-2",children:[o.jsx("span",{className:"text-sm font-medium text-foreground",children:"配置档案列表"}),o.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 k=await te.getMcpConfigProfiles(w.id);I(Array.isArray(k)?k:[])}catch{}},children:"刷新"})]}),v.length===0?o.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案"}):o.jsx("div",{className:"space-y-2",children:v.map(k=>{const A=Array.isArray(k.args)?k.args.join(", "):"",N=k.env?Object.keys(k.env):[];return o.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"text-xs text-foreground font-medium",children:k.name}),k.enabled&&o.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:"已启用"})]}),o.jsx("div",{className:"flex items-center gap-2",children:o.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 te.activateMcpConfigProfile(w.id,k.id);const D=await te.getMcpConfigProfiles(w.id);I(Array.isArray(D)?D:[])}catch{}},children:"激活"})})]}),o.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),k.cwd||"未设置"]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"args:"}),A||"未设置"]}),o.jsxs("div",{children:[o.jsxs("span",{className:"text-muted-foreground",children:["env(",N.length,"):"]}),N.length===0?"未设置":o.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:N.map(D=>o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-muted-foreground",children:D}),o.jsx("span",{className:"text-foreground",children:String(k.env[D])})]},D))})]})]})]},k.id)})})]}),o.jsxs("div",{className:"flex space-x-3 mt-6",children:[o.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?"更新":"添加"}),o.jsx("button",{type:"button",onClick:O,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:"取消"})]})]}),o.jsx("div",{className:"space-y-3",children:n.length===0?o.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[o.jsx(Da,{}),o.jsx("p",{className:"mt-2",children:"暂无 MCP 服务器配置"}),o.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个服务器"})]}):n.map(k=>o.jsxs("div",{className:"flex items-center justify-between gap-3 p-4 bg-card border border-border rounded-lg",children:[o.jsxs("div",{className:"flex items-center space-x-3 flex-1 min-w-0",children:[o.jsx("div",{className:`w-3 h-3 rounded-full ${k.enabled?"bg-green-500":"bg-gray-400"}`}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsxs("div",{className:"flex items-center space-x-2 min-w-0",children:[o.jsx("h4",{className:"font-medium text-foreground truncate",title:k.name,children:k.name}),o.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${k.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:k.type==="http"?"HTTP":"Stdio"})]}),o.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground truncate break-all font-mono",title:k.command,children:k.command}),typeof window<"u"&&Ag&&!1,k.type==="stdio"&&o.jsxs("div",{className:"mt-1 space-y-0.5 min-w-0",children:[k.cwd&&o.jsxs("div",{className:"text-xs text-muted-foreground truncate",title:String(k.cwd),children:["cwd: ",o.jsx("span",{className:"text-foreground",children:String(k.cwd)})]}),o.jsx("div",{className:"text-xs text-muted-foreground truncate",title:(()=>{const A=k.args;let N=null,D=!1;if(Array.isArray(A))N=A.map(q=>String(q));else if(typeof A=="string"&&A.trim()!=="")try{const q=JSON.parse(A);Array.isArray(q)&&(N=q.map(Q=>String(Q)),D=!0)}catch{}const R=Array.isArray(N)&&N.length>0?N.join(", "):typeof A=="string"&&!D?A:"—";return String(R)})(),children:(()=>{const A=k.args;let N=null,D=!1;if(Array.isArray(A))N=A.map(q=>String(q));else if(typeof A=="string"&&A.trim()!=="")try{const q=JSON.parse(A);Array.isArray(q)&&(N=q.map(Q=>String(Q)),D=!0)}catch{}const R=Array.isArray(N)&&N.length>0?N.join(", "):typeof A=="string"&&!D?A:"—";return o.jsxs("span",{children:["参数(args):",o.jsx("span",{className:"text-foreground",children:R})]})})()})]})]})]}),o.jsxs("div",{className:"flex items-center space-x-2 shrink-0",children:[o.jsx("button",{onClick:()=>F(k),className:`px-3 py-1 text-xs rounded-full ${k.enabled?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-secondary text-secondary-foreground"}`,children:k.enabled?"已启用":"已禁用"}),o.jsx("button",{onClick:()=>z(k),className:"p-2 text-muted-foreground hover:text-indigo-600 transition-colors",title:"查看配置档案",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.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"})})}),o.jsx("button",{onClick:()=>$(k),className:"p-2 text-muted-foreground hover:text-blue-600 transition-colors",title:"编辑",children:o.jsx(Eg,{})}),o.jsx("button",{onClick:()=>H(k.id),className:"p-2 text-muted-foreground hover:text-red-600 transition-colors",title:"删除",children:o.jsx(Mg,{})})]})]},k.id))})]})]}),o.jsx(jg,{open:L,config:W,onClose:()=>{C(!1),B(null)}}),o.jsx(xr,{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:u,onCancel:g})]})},Fa=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Ig=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),Pg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Tg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Og=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),vo=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=tt()}catch{t=mt()}const{aiModelConfigs:n,loadAiModelConfigs:s,updateAiModelConfig:a,deleteAiModelConfig:i}=t,[l,d]=M.useState(!1),[u,g]=M.useState(null),[h,p]=M.useState({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),{dialogState:w,showConfirmDialog:m,handleConfirm:f,handleCancel:c}=br();M.useEffect(()=>{const v="__aiModelManagerInitAt__",I=window[v]||0,P=Date.now();typeof I=="number"&&P-I<1e3||(window[v]=P,s())},[s]);const x=()=>{p({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),g(null),d(!1)},b=async v=>{if(v.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 a(I),x()},y=async v=>{if(v.preventDefault(),!u||!h.name.trim()||!h.base_url.trim()||!h.api_key.trim()||!h.model_name.trim())return;const I={...u,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 a(I),x()},_=v=>{g(v),p({name:v.name,base_url:v.base_url,api_key:v.api_key,model_name:v.model_name,enabled:v.enabled}),d(!0)},S=async v=>{var T;const I=n.find(L=>L.id===v),P=((T=I==null?void 0:I.name)==null?void 0:T.trim())||"删除";m({title:"删除确认",message:`确定要删除AI模型配置 "${(I==null?void 0:I.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",verificationText:P,verificationLabel:"请输入下方关键字确认删除",verificationPlaceholder:`输入 "${P}"`,verificationHint:"删除后无法恢复,请谨慎操作。",onConfirm:async()=>{await i(v)}})},j=async v=>{const I={...v,enabled:!v.enabled,updatedAt:new Date};await a(I)};return o.jsxs("div",{className:"modal-container",children:[o.jsxs("div",{className:"modal-content w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(Fa,{}),o.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"AI 模型管理"})]}),o.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(Ig,{})})]}),o.jsxs("div",{className:"p-6 overflow-y-auto overflow-x-hidden max-h-[calc(80vh-120px)]",children:[!l&&o.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:[o.jsx(Pg,{}),o.jsx("span",{children:"添加 AI 模型"})]}),l&&o.jsxs("form",{onSubmit:u?y:b,className:"mb-6 p-4 bg-muted rounded-lg",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:u?"编辑 AI 模型":"添加 AI 模型"}),o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),o.jsx("input",{type:"text",value:h.name,onChange:v=>p({...h,name:v.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})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Base URL"}),o.jsx("input",{type:"url",value:h.base_url,onChange:v=>p({...h,base_url:v.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})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"API Key"}),o.jsx("input",{type:"password",value:h.api_key,onChange:v=>p({...h,api_key:v.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})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"模型名称"}),o.jsx("input",{type:"text",value:h.model_name,onChange:v=>p({...h,model_name:v.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})]}),o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",id:"enabled",checked:h.enabled,onChange:v=>p({...h,enabled:v.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),o.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此模型"})]})]}),o.jsxs("div",{className:"flex space-x-3 mt-6",children:[o.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?"更新":"添加"}),o.jsx("button",{type:"button",onClick:x,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:"取消"})]})]}),o.jsx("div",{className:"space-y-3",children:n.length===0?o.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[o.jsx(Fa,{}),o.jsx("p",{className:"mt-2",children:"暂无 AI 模型配置"}),o.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个模型"})]}):n.map(v=>o.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:[o.jsxs("div",{className:"flex items-center space-x-3 flex-1 min-w-0",children:[o.jsx("div",{className:`w-3 h-3 rounded-full ${v.enabled?"bg-green-500":"bg-gray-400"}`}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx("h4",{className:"font-medium text-foreground truncate",title:v.name,children:v.name}),o.jsxs("p",{className:"text-xs sm:text-sm text-muted-foreground truncate",title:`${v.base_url} - ${v.model_name}`,children:[v.base_url," - ",v.model_name]})]})]}),o.jsxs("div",{className:"flex items-center space-x-2 shrink-0",children:[o.jsx("button",{onClick:()=>j(v),className:`px-3 py-1 text-xs rounded-full transition-colors ${v.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:v.enabled?"已启用":"已禁用"}),o.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:o.jsx(Tg,{})}),o.jsx("button",{onClick:()=>S(v.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:o.jsx(Og,{})})]})]},v.id))})]})]}),o.jsx(xr,{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:f,onCancel:c})]})},Ua=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Rg=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),$g=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Lg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Dg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Fg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Ug=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),_o=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=tt()}catch{t=mt()}const{systemContexts:n,activeSystemContext:s,loadSystemContexts:a,createSystemContext:i,updateSystemContext:l,deleteSystemContext:d,activateSystemContext:u}=t,[g,h]=M.useState("list"),[p,w]=M.useState(null),[m,f]=M.useState({name:"",content:""}),[c,x]=M.useState(!1),[b,y]=M.useState(!1),{dialogState:_,showConfirmDialog:S,handleConfirm:j,handleCancel:v}=br();M.useEffect(()=>{const O="__systemContextEditorInitAt__",U=window[O]||0,J=Date.now();if(typeof U=="number"&&J-U<1e3)return;window[O]=J,(async()=>{x(!0);try{await a()}catch(H){console.error("Failed to load system contexts:",H)}finally{x(!1)}})()},[a]);const I=()=>{f({name:"",content:""}),w(null),h("create")},P=O=>{f({name:O.name,content:O.content}),w(O),h("edit")},T=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(O){console.error("Failed to save system context:",O),alert("保存失败,请重试")}finally{y(!1)}},L=async O=>{var U,J;S({title:"删除确认",message:`确定要删除上下文 "${O.name}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",verificationText:((U=O.name)==null?void 0:U.trim())||"删除",verificationLabel:"请输入下方关键字确认删除",verificationPlaceholder:`输入 "${((J=O.name)==null?void 0:J.trim())||"删除"}"`,verificationHint:"为了防止误删,需要输入配置名称才能继续。",onConfirm:async()=>{try{await d(O.id)}catch($){console.error("Failed to delete system context:",$),alert("删除失败,请重试")}}})},C=async O=>{try{await u(O.id),await a()}catch(U){console.error("Failed to activate system context:",U),alert("激活失败,请重试")}},W=O=>{O.ctrlKey&&O.key==="s"&&(O.preventDefault(),g!=="list"&&T())},B=()=>o.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[o.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:o.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:[o.jsx("strong",{children:"系统上下文"}),"将作为每次对话的系统提示词,支持 Markdown 格式。 您可以创建多个上下文配置,但同一时间只能激活一个。"]})}),o.jsx("div",{className:"flex-1 overflow-y-auto",children:c?o.jsx("div",{className:"flex items-center justify-center h-32",children:o.jsx("div",{className:"text-muted-foreground",children:"加载中..."})}):n.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-muted-foreground",children:[o.jsx(Ua,{}),o.jsx("p",{className:"mt-2",children:"暂无系统上下文配置"}),o.jsx("p",{className:"text-sm",children:'点击"新建"按钮创建第一个配置'})]}):o.jsx("div",{className:"space-y-3",children:n.map(O=>o.jsx("div",{className:`p-4 border rounded-lg transition-colors ${O.isActive?"border-green-500 bg-green-50 dark:bg-green-900/20":"border-border bg-card"}`,children:o.jsxs("div",{className:"flex items-start justify-between",children:[o.jsxs("div",{className:"flex-1",children:[o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("h3",{className:"font-medium text-foreground",children:O.name}),O.isActive&&o.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:[o.jsx(Ug,{}),o.jsx("span",{className:"ml-1",children:"已激活"})]})]}),o.jsxs("p",{className:"mt-1 text-sm text-muted-foreground line-clamp-2",children:[O.content.substring(0,100),O.content.length>100&&"..."]}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["创建时间: ",new Date(O.createdAt).toLocaleString()]})]}),o.jsxs("div",{className:"flex items-center space-x-2 ml-4",children:[!O.isActive&&o.jsx("button",{onClick:()=>C(O),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"激活"}),o.jsx("button",{onClick:()=>P(O),className:"p-2 text-muted-foreground hover:text-blue-600 hover:bg-accent rounded transition-colors",children:o.jsx(Dg,{})}),o.jsx("button",{onClick:()=>L(O),className:"p-2 text-muted-foreground hover:text-red-600 hover:bg-accent rounded transition-colors",children:o.jsx(Fg,{})})]})]})},O.id))})})]}),z=()=>o.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[o.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:[o.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:g==="create"?"创建新的系统上下文配置":"编辑系统上下文配置"}),o.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300 mt-2",children:"提示:使用 Ctrl+S 快速保存"})]}),o.jsxs("div",{className:"flex-1 flex flex-col space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),o.jsx("input",{type:"text",value:m.name,onChange:O=>f({...m,name:O.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:"例如:编程助手、翻译专家、创意写作等"})]}),o.jsxs("div",{className:"flex-1 flex flex-col",children:[o.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[o.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Markdown 内容"}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[m.content.length," 字符"]})]}),o.jsx("textarea",{value:m.content,onChange:O=>f({...m,content:O.target.value}),onKeyDown:W,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})]}),o.jsxs("div",{className:"text-xs text-muted-foreground",children:[o.jsx("p",{children:"• 支持标准 Markdown 语法:标题、列表、代码块、链接等"}),o.jsx("p",{children:"• 内容将在每次对话开始时自动发送给 AI"}),o.jsx("p",{children:"• 留空则使用默认系统提示词"})]})]})]});return o.jsxs("div",{className:"modal-container",children:[o.jsxs("div",{className:"modal-content w-full max-w-4xl max-h-[90vh] overflow-hidden",children:[o.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(Ua,{}),o.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"系统上下文设置"})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[g==="list"?o.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:[o.jsx(Lg,{}),o.jsx("span",{children:"新建"})]}):o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:T,disabled:b,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:[o.jsx($g,{}),o.jsx("span",{children:b?"保存中...":"保存"})]}),o.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:"取消"})]}),o.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(Rg,{})})]})]}),g==="list"?B():z()]}),o.jsx(xr,{isOpen:_.isOpen,title:_.title,message:_.message,confirmText:_.confirmText,cancelText:_.cancelText,type:_.type,verificationText:_.verificationText,verificationLabel:_.verificationLabel,verificationPlaceholder:_.verificationPlaceholder,verificationHint:_.verificationHint,onConfirm:j,onCancel:v})]})},Ba=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),Wa=()=>o.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),Bg=()=>o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Wg=()=>o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),fc=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=tt()}catch{t=mt()}const{aiModelConfigs:n,loadAiModelConfigs:s,mcpConfigs:a,loadMcpConfigs:i,systemContexts:l,loadSystemContexts:d}=t,{userId:u}=Gf(),g=u||"custom_user_123",p=Xf()||te,[w,m]=M.useState([]),[f,c]=M.useState(!1),[x,b]=M.useState(!1),[y,_]=M.useState(null),[S,j]=M.useState(null),[v,I]=M.useState({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),{dialogState:P,showConfirmDialog:T,handleConfirm:L,handleCancel:C}=br(),W=async()=>{c(!0);try{await Promise.all([s(),i(),d(),t.loadAgents?t.loadAgents():Promise.resolve()]);const A=t.agents&&Array.isArray(t.agents)?t.agents:await p.getAgents(g),N=Array.isArray(A)?A:[];m(N)}catch(A){console.error("加载智能体失败",A)}finally{c(!1)}},B=async A=>{for(let D=0;D<3;D++)try{t.loadAgents&&await t.loadAgents();const R=await p.getAgents(g),q=Array.isArray(R)?R:[];if(m(q),A&&Array.isArray(q)&&q.some(Q=>Q.id===A)||!A)break;await new Promise(Q=>setTimeout(Q,250))}catch(R){console.warn("刷新智能体列表失败,重试中…",R),await new Promise(q=>setTimeout(q,250))}};M.useEffect(()=>{const A="__agentManagerInitAt__",N=window[A]||0,D=Date.now();typeof N=="number"&&D-N<1e3||(window[A]=D,W())},[]);const z=()=>{I({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),b(!1),j(null)},O=async A=>{var N;if(A.preventDefault(),!(!v.name.trim()||!v.ai_model_config_id))try{const D=await p.createAgent({name:v.name.trim(),description:((N=v.description)==null?void 0:N.trim())||void 0,ai_model_config_id:v.ai_model_config_id,mcp_config_ids:v.mcp_config_ids,system_context_id:v.system_context_id,user_id:g,enabled:!0});D&&D.id&&m(R=>R.some(Q=>Q.id===D.id)?R.map(Q=>Q.id===D.id?{...Q,...D}:Q):[D,...R]),await B(D==null?void 0:D.id),z()}catch(D){console.error("创建智能体失败",D),alert("创建失败,请重试")}},U=async A=>{if(A.preventDefault(),!!S)try{const N=await p.updateAgent(S.id,{name:v.name,description:v.description,ai_model_config_id:v.ai_model_config_id,mcp_config_ids:v.mcp_config_ids,system_context_id:v.system_context_id,enabled:!0});m(D=>D.map(R=>R.id===S.id?{...R,...N,name:v.name,description:v.description,ai_model_config_id:v.ai_model_config_id,mcp_config_ids:v.mcp_config_ids,system_context_id:v.system_context_id,enabled:!0}:R)),await B(S.id),z()}catch(N){console.error("更新智能体失败",N),alert("更新失败,请重试")}},J=A=>{var R;const N=w.find(q=>q.id===A),D=((R=N==null?void 0:N.name)==null?void 0:R.trim())||"删除";T({title:"删除智能体",message:`确定要删除智能体 "${(N==null?void 0:N.name)||"未命名"}" 吗?此操作将无法撤销。`,confirmText:"永久删除",cancelText:"取消",type:"danger",verificationText:D,verificationLabel:"请输入智能体名称以确认删除",verificationPlaceholder:`输入 "${D}"`,verificationHint:"删除后该智能体将从所有应用中移除且无法恢复。",onConfirm:async()=>{try{await p.deleteAgent(A),m(q=>q.filter(Q=>Q.id!==A)),await B()}catch(q){console.error("删除智能体失败",q),alert("删除失败,请重试")}}})},$=A=>{j(A),b(!0),I({name:A.name,description:A.description||"",ai_model_config_id:A.ai_model_config_id,mcp_config_ids:Array.isArray(A.mcp_config_ids)?A.mcp_config_ids:[],system_context_id:A.system_context_id})},H=A=>{const N=n.find(D=>D.id===A);return N?`${N.name}(${N.model_name})`:A},F=A=>{if(!A)return"未选择";const N=l.find(D=>D.id===A);return N?N.name:A},k=A=>A.map(D=>{const R=a.find(q=>q.id===D);return R?R.name:D}).join(",");return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),o.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:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx(Ba,{}),o.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"智能体管理"})]}),o.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:o.jsx(Wa,{})})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[!x&&o.jsxs("button",{onClick:()=>b(!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:[o.jsx(Bg,{}),o.jsx("span",{children:"新增智能体"})]}),x&&o.jsxs("form",{onSubmit:S?U:O,className:"p-4 bg-muted rounded-lg space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),o.jsx("input",{type:"text",value:v.name,onChange:A=>I({...v,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:"例如:项目助理",required:!0})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"描述"}),o.jsx("textarea",{value:v.description,onChange:A=>I({...v,description: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:"智能体用途说明",rows:3})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择模型(单选)"}),o.jsxs("select",{value:v.ai_model_config_id,onChange:A=>I({...v,ai_model_config_id: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",required:!0,children:[o.jsx("option",{value:"",children:"请选择模型"}),n.map(A=>o.jsxs("option",{value:A.id,children:[A.name,"(",A.model_name,")"]},A.id))]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 MCP 配置(多选)"}),o.jsx("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 border rounded-md",children:a.map(A=>o.jsxs("label",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",checked:v.mcp_config_ids.includes(A.id),onChange:N=>{const D=N.target.checked;I(R=>({...R,mcp_config_ids:D?[...R.mcp_config_ids,A.id]:R.mcp_config_ids.filter(q=>q!==A.id)}))}}),o.jsx("span",{children:A.name})]},A.id))})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择系统上下文"}),o.jsxs("select",{value:v.system_context_id||"",onChange:A=>I({...v,system_context_id:A.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:[o.jsx("option",{value:"",children:"不使用"}),l.map(A=>o.jsx("option",{value:A.id,children:A.name},A.id))]})]}),o.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[o.jsx("button",{type:"button",onClick:z,className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"取消"}),o.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:"保存"})]})]}),o.jsx("div",{children:f?o.jsx("div",{className:"text-muted-foreground",children:"加载中..."}):w.length===0?o.jsx("div",{className:"text-muted-foreground",children:"暂无智能体配置"}):o.jsx("div",{className:"space-y-3",children:w.map(A=>o.jsxs("div",{className:"p-4 border rounded-lg flex items-start justify-between gap-3",children:[o.jsxs("div",{className:"flex-1 min-w-0",children:[o.jsxs("div",{className:"flex items-center space-x-2 min-w-0",children:[o.jsx("h3",{className:"font-medium text-foreground truncate",title:A.name,children:A.name}),!A.enabled&&o.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-muted text-muted-foreground",children:"未启用"})]}),A.description&&o.jsx("p",{className:"mt-1 text-sm text-muted-foreground truncate",title:A.description,children:A.description}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground truncate",title:H(A.ai_model_config_id),children:["模型:",H(A.ai_model_config_id)]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:F(A.system_context_id),children:["系统上下文:",F(A.system_context_id)]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:k(A.mcp_config_ids||[]),children:["MCP配置:",k(A.mcp_config_ids||[])]})]}),o.jsxs("div",{className:"flex items-center space-x-2 ml-4 shrink-0",children:[o.jsx("button",{onClick:()=>_(A),className:"px-3 py-1 text-sm bg-muted text-foreground rounded hover:bg-accent transition-colors",children:"详情"}),o.jsx("button",{onClick:()=>$(A),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"编辑"}),o.jsxs("button",{onClick:()=>J(A.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:[o.jsx(Wg,{}),o.jsx("span",{children:"删除"})]})]})]},A.id))})})]}),y&&o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[o.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:()=>_(null)}),o.jsxs("div",{className:"relative bg-card border border-border rounded-lg shadow-xl w-[520px] p-6",children:[o.jsxs("div",{className:"flex items-center justify-between mb-4",children:[o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx(Ba,{}),o.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"智能体详情"})]}),o.jsx("button",{onClick:()=>_(null),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(Wa,{})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"名称:"}),y.name]}),y.description&&o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"描述:"}),y.description]}),o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"模型:"}),H(y.ai_model_config_id)]}),o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"系统上下文:"}),F(y.system_context_id)]}),o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"MCP配置:"}),k(y.mcp_config_ids||[])]}),Array.isArray(y.mcp_config_ids)&&y.mcp_config_ids.length>0&&o.jsx("div",{className:"mt-2 space-y-2",children:(y.mcp_config_ids||[]).map(A=>{var q,Q;const N=(a||[]).find(se=>se.id===A);if(!N)return null;let D="—";const R=N.args;if(Array.isArray(R))D=R.map(se=>String(se)).join(", ");else if(typeof R=="string"&&R.trim()!=="")try{const se=JSON.parse(R);Array.isArray(se)?D=se.map(Te=>String(Te)).join(", "):D=R}catch{D=R}return o.jsxs("div",{className:"p-2 rounded border border-border",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("span",{className:"text-sm font-medium text-foreground",children:N.name}),o.jsx("span",{className:`px-1.5 py-0.5 text-xs rounded ${N.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:((Q=(q=N.type)==null?void 0:q.toUpperCase)==null?void 0:Q.call(q))||N.type})]}),o.jsxs("div",{className:"mt-1 text-xs text-muted-foreground break-all",children:[N.type==="http"?"URL:":"命令:",o.jsx("span",{className:"text-foreground",children:N.command})]}),N.cwd&&o.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground break-all",children:["cwd:",o.jsx("span",{className:"text-foreground",children:String(N.cwd)})]}),N.type==="stdio"&&o.jsxs("div",{className:"mt-0.5 text-xs text-muted-foreground break-all",children:["args:",o.jsx("span",{className:"text-foreground",children:D})]})]},A)})}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:["创建时间:",y.created_at?new Date(y.created_at).toLocaleString():"-"]})]}),o.jsx("div",{className:"mt-4 flex justify-end space-x-2",children:o.jsx("button",{onClick:()=>_(null),className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"关闭"})})]})]})]}),o.jsx(xr,{isOpen:P.isOpen,title:P.title,message:P.message,confirmText:P.confirmText,cancelText:P.cancelText,type:P.type,verificationText:P.verificationText,verificationLabel:P.verificationLabel,verificationPlaceholder:P.verificationPlaceholder,verificationHint:P.verificationHint,onConfirm:L,onCancel:C})]})},Hg=r=>{const e=r==null?void 0:r.metadata;try{return typeof e=="string"?e?JSON.parse(e):{}:e&&typeof e=="object"?e:{}}catch{return{}}},qg=r=>{const e=Hg(r),t=e.prompt_text??e.promptText??e.session_prompt??e.sessionPrompt??null;return typeof t=="string"?t:""},hc=({className:r})=>{const{currentSession:e,updateSessionConfig:t}=tt(),n=M.useMemo(()=>qg(e),[e]),[s,a]=M.useState(!1),[i,l]=M.useState(""),[d,u]=M.useState(!1);if(M.useEffect(()=>{s&&l(n)},[s,n]),!e)return null;const g=n.trim().length>0,h=M.useMemo(()=>n.replace(/\s+/g," ").trim(),[n]),p=async()=>{if(e){u(!0);try{await t(e.id,{promptText:i}),a(!1)}finally{u(!1)}}};return o.jsxs(o.Fragment,{children:[o.jsxs("button",{type:"button",onClick:()=>a(!0),className:ve("inline-flex items-center gap-1.5 px-2.5 py-1.5 rounded-lg border border-border bg-muted/10 hover:bg-accent","text-xs text-foreground max-w-[520px] min-w-0",r),title:g?n:"未设置会话 Prompt(点击编辑)",children:[o.jsx("span",{className:"shrink-0 text-muted-foreground",children:"Prompt"}),o.jsx("span",{className:ve("truncate min-w-0",g?"text-foreground":"text-muted-foreground"),children:g?h:"未设置"})]}),s&&o.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:o.jsx("div",{className:"bg-card rounded-lg shadow-lg w-full max-w-3xl border border-border",children:o.jsxs("div",{className:"p-6",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground",children:"编辑会话 Prompt"}),o.jsx("button",{type:"button",onClick:()=>!d&&a(!1),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors","aria-label":"关闭",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),o.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"此 Prompt 会在每次对话时作为 system prompt 使用(会话级,独立于全局激活 Prompt)。"}),o.jsx("textarea",{value:i,onChange:w=>l(w.target.value),className:"mt-4 w-full min-h-[220px] px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"输入会话 Prompt...",disabled:d}),o.jsxs("div",{className:"flex gap-3 mt-4",children:[o.jsx("button",{type:"button",onClick:()=>a(!1),disabled:d,className:"flex-1 px-4 py-2 text-sm border border-border rounded-md hover:bg-accent transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:"取消"}),o.jsx("button",{type:"button",onClick:p,disabled:d,className:"flex-1 px-4 py-2 text-sm bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors disabled:opacity-50 disabled:cursor-not-allowed",children:d?"保存中...":"保存"})]})]})})})]})},mc=({isOpen:r,onClose:e,manageOnly:t=!1,title:n,layout:s="modal",onApplicationSelect:a})=>{let i;try{i=tt()}catch{i=mt()}const{applications:l,loadApplications:d,createApplication:u,updateApplication:g,deleteApplication:h}=i,p=M.useRef(new Map),[w,m]=M.useState(!!t),[f,c]=M.useState(!1),[x,b]=M.useState(null),[y,_]=M.useState({name:"",url:"",iconUrl:""});M.useEffect(()=>{try{console.log("[ApplicationsPanel] useEffect -> loadApplications"),d==null||d()}catch(C){console.error("[ApplicationsPanel] loadApplications error:",C)}},[d]);const S=()=>{b(null),_({name:"",url:"",iconUrl:""}),c(!1)},j=async C=>{C.preventDefault(),y.name.trim()&&(x?await(g==null?void 0:g(x,{name:y.name.trim(),url:y.url.trim(),iconUrl:y.iconUrl.trim()||void 0})):await(u==null?void 0:u(y.name.trim(),y.url.trim(),y.iconUrl.trim()||void 0)),S())},v=C=>{console.log("[ApplicationsPanel] closeAppWindow:",C);const W=p.current.get(C);W&&!W.closed&&W.close(),p.current.delete(C)},I=C=>{console.log("[ApplicationsPanel] handleAppClick - 应用被点击:",{id:C.id,name:C.name,url:C.url}),a?(console.log("[ApplicationsPanel] 调用 onApplicationSelect 回调"),a(C)):console.log("[ApplicationsPanel] ⚠️ 未提供 onApplicationSelect 回调"),e&&(console.log("[ApplicationsPanel] 关闭应用列表面板"),e())};if(!(s==="modal"?!!r:!0))return null;const T=t?!0:w,L=n??(T?"应用管理":"应用列表");return s==="modal"?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:e}),o.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:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full bg-blue-500"}),o.jsx("h2",{className:"text-lg font-semibold text-foreground",children:L})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&o.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:T?"浏览模式":"管理模式"}),!T&&p.current.size>0&&o.jsx("button",{className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",onClick:()=>{p.current.forEach((C,W)=>v(W))},children:"关闭全部"}),o.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:T?o.jsxs("div",{className:"space-y-4",children:[!f&&o.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:[o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v12m6-6H6"})}),o.jsx("span",{children:"新增应用"})]}),f&&o.jsxs("form",{onSubmit:j,className:"p-4 bg-muted rounded-lg space-y-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),o.jsx("input",{type:"text",value:y.name,onChange:C=>_({...y,name:C.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})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"URL"}),o.jsx("input",{type:"text",value:y.url,onChange:C=>_({...y,url:C.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"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"图标URL"}),o.jsx("input",{type:"text",value:y.iconUrl,onChange:C=>_({...y,iconUrl:C.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"})]}),o.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[o.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-muted hover:bg-accent",onClick:S,children:"取消"}),o.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:x?"保存":"创建"})]})]}),o.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(C=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.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:C.iconUrl?o.jsx("img",{src:C.iconUrl,alt:C.name,className:"w-full h-full object-cover"}):o.jsx("span",{className:"text-white text-sm font-bold",children:C.name.charAt(0).toUpperCase()})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:C.name}),C.url&&o.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:C.url})]})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("button",{className:"px-2 py-1 text-xs bg-muted rounded hover:bg-accent",onClick:()=>{b(C.id),c(!0),_({name:C.name,url:C.url||"",iconUrl:C.iconUrl||""})},children:"编辑"}),o.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(C.id),children:"删除"})]})]},C.id)),(l==null?void 0:l.length)===0&&o.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[o.jsx("svg",{className:"w-16 h-16 mx-auto mb-3 opacity-30",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("div",{className:"text-sm",children:"暂无应用,点击上方按钮添加"})]})]})]}):o.jsxs("div",{className:"grid grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-6",children:[l==null?void 0:l.map(C=>{const W=p.current.has(C.id);return o.jsxs("div",{className:"relative group/item",children:[o.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>I(C),title:C.url||"",children:[o.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:[C.iconUrl?o.jsx("img",{src:C.iconUrl,alt:C.name,className:"w-full h-full object-cover"}):o.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:o.jsx("span",{className:"text-white text-xl font-bold",children:C.name.charAt(0).toUpperCase()})}),W&&o.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:o.jsx("div",{className:"w-2 h-2 bg-white rounded-full animate-pulse"})})]}),o.jsx("div",{className:"text-xs font-medium text-foreground text-center truncate w-full px-1",children:C.name})]}),W&&o.jsx("button",{onClick:B=>{B.stopPropagation(),v(C.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:o.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},C.id)}),((l==null?void 0:l.length)??0)===0&&o.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-20 text-center",children:[o.jsx("svg",{className:"w-20 h-20 text-muted-foreground/30 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),o.jsx("button",{onClick:()=>m(!0),className:"text-sm text-blue-500 hover:text-blue-600 underline",children:"点击切换到管理模式添加应用"})]})]})})]})]}):o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-border bg-card/50",children:[o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-blue-500"}),o.jsx("span",{className:"text-sm font-medium text-foreground",children:L})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&o.jsx("button",{onClick:()=>{m(!w),c(!1),S()},className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent transition-colors",children:T?"浏览模式":"管理模式"}),!T&&p.current.size>0&&o.jsx("button",{className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent",onClick:()=>{p.current.forEach((C,W)=>v(W))},children:"关闭全部"}),e&&o.jsx("button",{onClick:e,className:"p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded transition-colors",title:"关闭",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),o.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:T?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4 flex items-center justify-between",children:o.jsx("button",{type:"button",onClick:()=>{b(null),_({name:"",url:"",iconUrl:""}),c(C=>!C)},className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:f?"取消":"新增应用"})}),f&&o.jsxs("form",{onSubmit:C=>{var O,U,J;C.preventDefault();const W=((O=y.name)==null?void 0:O.trim())||"",B=((U=y.url)==null?void 0:U.trim())||"",z=((J=y.iconUrl)==null?void 0:J.trim())||void 0;W&&(x?g==null||g(x,{name:W,url:B,iconUrl:z}):u==null||u(W,B,z),c(!1),S())},className:"p-4 bg-muted rounded-lg space-y-3",children:[o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),o.jsx("input",{value:y.name,onChange:C=>_({...y,name:C.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"例如:飞书"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"URL"}),o.jsx("input",{value:y.url,onChange:C=>_({...y,url:C.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://example.com"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"图标地址"}),o.jsx("input",{value:y.iconUrl,onChange:C=>_({...y,iconUrl:C.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://.../icon.png"})]}),o.jsxs("div",{className:"flex justify-end space-x-2",children:[o.jsx("button",{type:"button",onClick:()=>{c(!1),S(),b(null)},className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",children:"取消"}),o.jsx("button",{type:"submit",className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:x?"保存":"创建"})]})]}),o.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(C=>o.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.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:C.iconUrl?o.jsx("img",{src:C.iconUrl,alt:C.name,className:"w-full h-full object-cover"}):o.jsx("span",{className:"text-white text-sm font-bold",children:C.name.charAt(0).toUpperCase()})}),o.jsxs("div",{children:[o.jsx("div",{className:"text-sm font-medium text-foreground",children:C.name}),C.url&&o.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:C.url})]})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("button",{className:"px-2 py-1 text-xs rounded bg-background hover:bg-accent",onClick:()=>{c(!0),b(C.id),_({name:C.name||"",url:C.url||"",iconUrl:C.iconUrl||""})},children:"编辑"}),o.jsx("button",{className:"px-2 py-1 text-xs rounded bg-destructive text-destructive-foreground hover:opacity-90",onClick:()=>h==null?void 0:h(C.id),children:"删除"})]})]},C.id)),((l==null?void 0:l.length)??0)===0&&o.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center",children:[o.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用,点击上方按钮添加。"})]})]})]}):o.jsxs("div",{className:"grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[l==null?void 0:l.map(C=>{const W=p.current.has(C.id);return o.jsxs("div",{className:"relative group/item",children:[o.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>I(C),title:C.url||"",children:[o.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:C.iconUrl?o.jsx("img",{src:C.iconUrl,alt:C.name,className:"w-full h-full object-cover"}):o.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:o.jsx("span",{className:"text-white text-lg font-bold",children:C.name.charAt(0).toUpperCase()})})}),o.jsx("div",{className:"text-xs font-medium text-foreground truncate max-w-full",children:C.name}),C.url&&o.jsx("div",{className:"text-[10px] text-muted-foreground truncate max-w-full",children:C.url})]}),W&&o.jsx("button",{onClick:B=>{B.stopPropagation(),v(C.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:o.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},C.id)}),((l==null?void 0:l.length)??0)===0&&o.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-10 text-center",children:[o.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),o.jsx("button",{onClick:()=>m(!0),className:"text-sm text-blue-500 hover:text-blue-600 underline",children:"切换到管理模式以添加应用"})]})]})})]})},So=({className:r,apiBaseUrl:e,port:t,userId:n,projectId:s,showMcpManager:a=!0,showAiModelManager:i=!0,showSystemContextEditor:l=!0,showAgentManager:d=!0,onApplicationSelect:u})=>{const g=M.useMemo(()=>{if(e)return e;if(t)return`http://localhost:${t}/api`},[e,t]),h=M.useMemo(()=>{if(g)return new er(g)},[g]);return o.jsx(Vf,{userId:n,projectId:s,customApiClient:h,children:o.jsx(zg,{className:r,showMcpManager:a,showAiModelManager:i,showSystemContextEditor:l,showAgentManager:d,onApplicationSelect:u})})},zg=({className:r,showMcpManager:e,showAiModelManager:t,showSystemContextEditor:n,showAgentManager:s,onApplicationSelect:a})=>{const i=Wl(),{currentSession:l,messages:d,isLoading:u,isStreaming:g,hasMoreMessages:h,error:p,loadSessions:w,sendMessage:m,clearError:f,mcpConfigs:c,loadMcpConfigs:x,getSessionMcpConfigIds:b,sessionMcpRevision:y,aiModelConfigs:_,selectedModelId:S,setSelectedModel:j,loadAiModelConfigs:v,agents:I,selectedAgentId:P,setSelectedAgent:T,loadAgents:L,abortCurrentConversation:C,loadMoreMessages:W}=i(),B=M.useRef(null),[z,O]=M.useState(!1),[U,J]=M.useState(""),[$,H]=M.useState(""),[F,k]=M.useState(!1),[A,N]=M.useState(!1),[D,R]=M.useState(!1),[q,Q]=M.useState(!1),[se,Te]=M.useState(!1);M.useEffect(()=>{(window.__standaloneChatInterfaceDidInit__??!1)||(window.__standaloneChatInterfaceDidInit__=!0,w(),v(),x(),L())},[w,v,x,L]),M.useEffect(()=>{B.current&&B.current.scrollIntoView({behavior:"smooth"})},[d,g]),M.useEffect(()=>{let qe=!1;const Rt=Fe=>{if(Fe.length===0)return{summary:"MCP:未选择",tooltip:"未选择 MCP"};const $t=Fe.join(",");return Fe.length<=2?{summary:`MCP:${$t}`,tooltip:`MCP:${$t}`}:{summary:`MCP:${Fe.slice(0,2).join(",")} +${Fe.length-2}`,tooltip:`MCP:${$t}`}};return(async()=>{if(!(l!=null&&l.id)){J(""),H("");return}try{const Fe=await b(l.id);if(qe)return;const $t=new Map((c||[]).map(Lt=>[Lt.id,Lt.name])),gc=(Fe||[]).map(Lt=>$t.get(Lt)||Lt),{summary:pc,tooltip:xc}=Rt(gc);J(pc),H(xc)}catch(Fe){if(console.error("Failed to load session MCP summary:",Fe),qe)return;J("MCP:加载失败"),H("MCP:加载失败")}})(),()=>{qe=!0}},[l==null?void 0:l.id,y,c,b]);const An=async(qe,Rt)=>{try{await m(qe,Rt)}catch(ze){console.error("Failed to send message:",ze)}};return o.jsxs("div",{className:ve("flex flex-col h-screen bg-background text-foreground",r),children:[o.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[o.jsxs("div",{className:"flex items-center space-x-3",children:[o.jsx("button",{onClick:()=>O(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),l&&o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:l.title})}),o.jsx(hc,{})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[a&&o.jsx("button",{onClick:()=>{console.log("[StandaloneChat] open ApplicationsPanel button clicked"),Te(!0)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:o.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[o.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),o.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),e&&o.jsx("button",{onClick:()=>k(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP服务管理",children:o.jsxs("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:[o.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"}),o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}),t&&o.jsx("button",{onClick:()=>N(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI配置管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.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&&o.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:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.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&&o.jsx("button",{onClick:()=>Q(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:o.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"})})}),o.jsx(yo,{})]})]}),p&&o.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:o.jsxs("div",{className:"flex items中心 justify-between",children:[o.jsx("p",{className:"text-sm text-destructive",children:p}),o.jsx("button",{onClick:f,className:"text-destructive hover:text-destructive/80 transition-colors",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),o.jsx("div",{className:"flex-1 flex overflow-hidden",children:o.jsxs("div",{className:"flex-1 overflow-hidden",children:[l?o.jsx("div",{className:"flex flex-col h-full",children:o.jsx("div",{className:"flex-1 overflow-hidden",children:o.jsx(po,{messages:d,isLoading:u,isStreaming:g,hasMore:h,onLoadMore:()=>l&&W(l.id)})})}):o.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:o.jsxs("div",{className:"text-center",children:[o.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 opacity-50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})}),o.jsx("p",{className:"text-lg mb-2",children:"欢迎使用AI聊天助手"}),o.jsx("p",{className:"text-sm",children:"点击左上角按钮创建新会话开始对话"})]})}),o.jsx("div",{ref:B})]})}),l&&o.jsx(xo,{onSend:An,onStop:C,disabled:u||g,isStreaming:g,selectedModelId:S,availableModels:_,onModelChange:j,showModelSelector:!0,selectedAgentId:P,availableAgents:I,onAgentChange:T,sessionMcpSummary:U,sessionMcpTooltip:$}),o.jsx(bo,{isOpen:z,onClose:()=>O(!1),store:i}),o.jsx(mc,{isOpen:se,onClose:()=>Te(!1),title:"应用列表",layout:"modal",onApplicationSelect:a}),F&&o.jsx(wo,{onClose:()=>k(!1),store:i}),A&&o.jsx(vo,{onClose:()=>N(!1),store:i}),s&&q&&o.jsx(fc,{onClose:()=>Q(!1),store:i}),D&&o.jsx(_o,{onClose:()=>R(!1),store:i})]})};class Jg{constructor(e,t,n,s,a=!0,i=!0,l=!0,d=!0,u){V(this,"userId");V(this,"projectId");V(this,"configUrl");V(this,"apiClient");V(this,"store");V(this,"className");V(this,"showMcpManager");V(this,"showAiModelManager");V(this,"showSystemContextEditor");V(this,"showAgentManager");V(this,"onApplicationSelect");this.userId=e,this.projectId=t,this.configUrl=n||"/api",this.className=s,this.showMcpManager=a,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 er(this.configUrl),this.store=Zr(this.apiClient,{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl})}render(){return M.createElement(Vg,{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 er(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(a=>a.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 a=s.selectedApplicationId;if(console.log("[AiChat] store.subscribe 被触发, currentId:",a,"previousId:",t),a!==t){console.log("[AiChat] selectedApplicationId 变化检测到:",{old:t,new:a}),t=a;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 Vg=({className:r,userId:e,projectId:t,configUrl:n,showMcpManager:s,showAiModelManager:a,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d})=>o.jsx(So,{className:r,apiBaseUrl:n,userId:e,projectId:t,showMcpManager:s,showAiModelManager:a,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d}),Gg=({className:r,onMessageSend:e,customRenderer:t})=>{const{currentSession:n,messages:s,isLoading:a,isStreaming:i,hasMoreMessages:l,error:d,loadSessions:u,loadMoreMessages:g,sendMessage:h,clearError:p,mcpConfigs:w,loadMcpConfigs:m,getSessionMcpConfigIds:f,sessionMcpRevision:c,aiModelConfigs:x,selectedModelId:b,setSelectedModel:y,loadAiModelConfigs:_,agents:S,selectedAgentId:j,setSelectedAgent:v,loadAgents:I,abortCurrentConversation:P}=tt(),T=M.useRef(null),[L,C]=M.useState(!1),[W,B]=M.useState(!1),[z,O]=M.useState(!1),[U,J]=M.useState(!1),[$,H]=M.useState(!1),[F,k]=M.useState(""),[A,N]=M.useState("");M.useEffect(()=>{(window.__chatInterfaceDidInit__??!1)||(window.__chatInterfaceDidInit__=!0,u(),_(),m(),I())},[u,_,m,I]),M.useEffect(()=>{T.current&&T.current.scrollIntoView({behavior:"smooth"})},[s,i]),M.useEffect(()=>{let R=!1;const q=se=>{if(se.length===0)return{summary:"MCP:未选择",tooltip:"未选择 MCP"};const Te=se.join(",");return se.length<=2?{summary:`MCP:${Te}`,tooltip:`MCP:${Te}`}:{summary:`MCP:${se.slice(0,2).join(",")} +${se.length-2}`,tooltip:`MCP:${Te}`}};return(async()=>{if(!(n!=null&&n.id)){k(""),N("");return}try{const se=await f(n.id);if(R)return;const Te=new Map((w||[]).map(ze=>[ze.id,ze.name])),An=(se||[]).map(ze=>Te.get(ze)||ze),{summary:qe,tooltip:Rt}=q(An);k(qe),N(Rt)}catch(se){if(console.error("Failed to load session MCP summary:",se),R)return;k("MCP:加载失败"),N("MCP:加载失败")}})(),()=>{R=!0}},[n==null?void 0:n.id,c,w,f]);const D=async(R,q)=>{try{await h(R,q),e==null||e(R,[])}catch(Q){console.error("Failed to send message:",Q)}};return o.jsxs("div",{className:ve("flex flex-col h-screen bg-background text-foreground",r),children:[d&&o.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("p",{className:"text-sm text-destructive",children:d}),o.jsx("button",{onClick:p,className:"text-destructive hover:text-destructive/80 transition-colors",children:o.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),o.jsxs("div",{className:"flex flex-1 overflow-hidden",children:[o.jsx("div",{className:"flex flex-col h-full",children:o.jsx(bo,{embedded:!0})}),o.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden",children:[n&&o.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[o.jsx("div",{className:"flex items-center space-x-3",children:o.jsx(hc,{})}),o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx(yo,{}),o.jsx("button",{onClick:()=>H(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:o.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[o.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),o.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),o.jsx("button",{onClick:()=>C(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP 服务器管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsx("button",{onClick:()=>J(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsx("button",{onClick:()=>B(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI 模型管理",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsx("button",{onClick:()=>O(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"系统上下文设置",children:o.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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?o.jsxs(o.Fragment,{children:[o.jsxs("div",{className:"flex-1 overflow-auto",children:[o.jsx(po,{messages:s,isLoading:a,isStreaming:i,hasMore:l,onLoadMore:()=>n&&g(n.id),customRenderer:t}),o.jsx("div",{ref:T})]}),o.jsx("div",{className:"border-t border-border",children:o.jsx(xo,{onSend:D,onStop:P,disabled:a,isStreaming:i,placeholder:"输入消息...",showModelSelector:!0,selectedModelId:b,availableModels:x,onModelChange:y,selectedAgentId:j,availableAgents:S,onAgentChange:v,sessionMcpSummary:F,sessionMcpTooltip:A})})]}):o.jsx("div",{className:"flex-1 flex items-center justify-center",children:o.jsxs("div",{className:"text-center",children:[o.jsx("h2",{className:"text-xl font-semibold text-muted-foreground mb-2",children:"欢迎使用 AI 聊天"}),o.jsx("p",{className:"text-muted-foreground mb-4",children:"从左侧会话列表选择会话,或创建新的会话开始对话"})]})})]})]}),L&&o.jsx(wo,{onClose:()=>C(!1)}),U&&o.jsx(fc,{onClose:()=>J(!1)}),W&&o.jsx(vo,{onClose:()=>B(!1)}),z&&o.jsx(_o,{onClose:()=>O(!1)}),o.jsx(mc,{isOpen:$,onClose:()=>H(!1),title:"应用列表",layout:"modal"})]})};class Xg extends M.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("ErrorBoundary caught an error:",e,t)}render(){var e;return this.state.hasError?this.props.fallback?this.props.fallback:o.jsx("div",{className:"flex items-center justify-center h-full p-8",children:o.jsxs("div",{className:"text-center space-y-4",children:[o.jsx("div",{className:"w-16 h-16 mx-auto bg-destructive/10 rounded-full flex items-center justify-center",children:o.jsx("svg",{className:"w-8 h-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:o.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"})})}),o.jsxs("div",{children:[o.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Something went wrong"}),o.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),o.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 Kg="1.0.11";exports.AiChat=Jg;exports.AiModelManager=vo;exports.AiServer=Fl;exports.ApiClient=er;exports.AppError=ug;exports.AttachmentRenderer=nc;exports.ChatIcon=cc;exports.ChatInterface=Gg;exports.ChatService=Bl;exports.CheckIcon=gg;exports.ChevronDownIcon=yg;exports.CopyIcon=xg;exports.DatabaseService=As;exports.DotsVerticalIcon=ic;exports.ErrorBoundary=Xg;exports.InputArea=xo;exports.LoadingSpinner=oc;exports.MarkdownRenderer=lt;exports.McpManager=wo;exports.MessageItem=sc;exports.MessageList=po;exports.MessageManager=Ul;exports.PencilIcon=Ss;exports.PlayIcon=bg;exports.PlusIcon=ac;exports.SessionList=bo;exports.StandaloneChatInterface=So;exports.SystemContextEditor=_o;exports.ThemeToggle=yo;exports.ToolCallRenderer=_s;exports.TrashIcon=lc;exports.XIcon=pg;exports.apiClient=te;exports.cleanHtmlContent=eg;exports.cn=ve;exports.conversationsApi=Or;exports.copyToClipboard=ig;exports.debounce=ng;exports.deepClone=vs;exports.default=So;exports.downloadFile=lg;exports.formatDate=Ym;exports.formatDateTime=Qm;exports.formatFileSize=tc;exports.formatRelativeTime=Km;exports.formatTime=ec;exports.generateId=Xm;exports.generateRandomColor=ag;exports.getFileExtension=rc;exports.getOS=dg;exports.isImageFile=og;exports.isMobile=cg;exports.isValidEmail=tg;exports.isValidUrl=rg;exports.retry=fg;exports.storage=hg;exports.throttle=sg;exports.truncateText=Zm;exports.useChatStore=mt;exports.useTheme=uc;exports.version=Kg;
101
101
  //# sourceMappingURL=index.cjs.js.map