@leeoohoo/aichat 1.0.7 → 1.0.10

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 oc=Object.defineProperty;var ac=(r,e,t)=>e in r?oc(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var W=(r,e,t)=>ac(r,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const a=require("react/jsx-runtime"),I=require("react"),ic={},po=r=>{let e;const t=new Set,n=(m,f)=>{const p=typeof m=="function"?m(e):m;if(!Object.is(p,e)){const y=e;e=f??(typeof p!="object"||p===null)?p:Object.assign({},e,p),t.forEach(h=>h(e,y))}},s=()=>e,c={setState:n,getState:s,getInitialState:()=>d,subscribe:m=>(t.add(m),()=>t.delete(m)),destroy:()=>{(ic?"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()}},d=e=r(n,s,c);return c},lc=r=>r?po(r):po;function cc(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Wn={exports:{}},wn={},fr={exports:{}},vn={};/**
1
+ "use strict";require('./index.css');var Ec=Object.defineProperty;var Pc=(r,e,t)=>e in r?Ec(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var q=(r,e,t)=>Pc(r,typeof e!="symbol"?e+"":e,t);Object.defineProperties(exports,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}});const o=require("react/jsx-runtime"),T=require("react"),Ic={},No=r=>{let e;const t=new Set,n=(g,h)=>{const x=typeof g=="function"?g(e):g;if(!Object.is(x,e)){const w=e;e=h??(typeof x!="object"||x===null)?x:Object.assign({},e,x),t.forEach(m=>m(e,w))}},s=()=>e,d={setState:n,getState:s,getInitialState:()=>u,subscribe:g=>(t.add(g),()=>t.delete(g)),destroy:()=>{(Ic?"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},Tc=r=>r?No(r):No;function Oc(r){return r&&r.__esModule&&Object.prototype.hasOwnProperty.call(r,"default")?r.default:r}var Zn={exports:{}},Pn={},Sr={exports:{}},In={};/**
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 dc(){if(xo)return vn;xo=1;var r=I;function e(f,p){return f===p&&(f!==0||1/f===1/p)||f!==f&&p!==p}var t=typeof Object.is=="function"?Object.is:e,n=r.useState,s=r.useEffect,o=r.useLayoutEffect,i=r.useDebugValue;function l(f,p){var y=p(),h=n({inst:{value:y,getSnapshot:p}}),x=h[0].inst,u=h[1];return o(function(){x.value=y,x.getSnapshot=p,c(x)&&u({inst:x})},[f,y,p]),s(function(){return c(x)&&u({inst:x}),f(function(){c(x)&&u({inst:x})})},[f]),i(y),y}function c(f){var p=f.getSnapshot;f=f.value;try{var y=p();return!t(f,y)}catch{return!0}}function d(f,p){return p()}var m=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:l;return vn.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:m,vn}var _n={};/**
9
+ */var ko;function Rc(){if(ko)return In;ko=1;var r=T;function e(h,x){return h===x&&(h!==0||1/h===1/x)||h!==h&&x!==x}var t=typeof Object.is=="function"?Object.is:e,n=r.useState,s=r.useEffect,a=r.useLayoutEffect,i=r.useDebugValue;function l(h,x){var w=x(),m=n({inst:{value:w,getSnapshot:x}}),f=m[0].inst,c=m[1];return a(function(){f.value=w,f.getSnapshot=x,d(f)&&c({inst:f})},[h,w,x]),s(function(){return d(f)&&c({inst:f}),h(function(){d(f)&&c({inst:f})})},[h]),i(w),w}function d(h){var x=h.getSnapshot;h=h.value;try{var w=x();return!t(h,w)}catch{return!0}}function u(h,x){return x()}var g=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?u:l;return In.useSyncExternalStore=r.useSyncExternalStore!==void 0?r.useSyncExternalStore:g,In}var Tn={};/**
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 uc(){return bo||(bo=1,process.env.NODE_ENV!=="production"&&function(){function r(y,h){return y===h&&(y!==0||1/y===1/h)||y!==y&&h!==h}function e(y,h){m||s.startTransition===void 0||(m=!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 x=h();if(!f){var u=h();o(x,u)||(console.error("The result of getSnapshot should be cached to avoid an infinite loop"),f=!0)}u=i({inst:{value:x,getSnapshot:h}});var g=u[0].inst,b=u[1];return c(function(){g.value=x,g.getSnapshot=h,t(g)&&b({inst:g})},[y,x,h]),l(function(){return t(g)&&b({inst:g}),y(function(){t(g)&&b({inst:g})})},[y]),d(x),x}function t(y){var h=y.getSnapshot;y=y.value;try{var x=h();return!o(y,x)}catch{return!0}}function n(y,h){return h()}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var s=I,o=typeof Object.is=="function"?Object.is:r,i=s.useState,l=s.useEffect,c=s.useLayoutEffect,d=s.useDebugValue,m=!1,f=!1,p=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n:e;_n.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())}()),_n}var yo;function Pa(){return yo||(yo=1,process.env.NODE_ENV==="production"?fr.exports=dc():fr.exports=uc()),fr.exports}/**
17
+ */var Mo;function Lc(){return Mo||(Mo=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 p=c[0].inst,y=c[1];return d(function(){p.value=f,p.getSnapshot=m,t(p)&&y({inst:p})},[w,f,m]),l(function(){return t(p)&&y({inst:p}),w(function(){t(p)&&y({inst:p})})},[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=T,a=typeof Object.is=="function"?Object.is:r,i=s.useState,l=s.useEffect,d=s.useLayoutEffect,u=s.useDebugValue,g=!1,h=!1,x=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?n:e;Tn.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:x,typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Tn}var Eo;function za(){return Eo||(Eo=1,process.env.NODE_ENV==="production"?Sr.exports=Rc():Sr.exports=Lc()),Sr.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 fc(){if(wo)return wn;wo=1;var r=I,e=Pa();function t(d,m){return d===m&&(d!==0||1/d===1/m)||d!==d&&m!==m}var n=typeof Object.is=="function"?Object.is:t,s=e.useSyncExternalStore,o=r.useRef,i=r.useEffect,l=r.useMemo,c=r.useDebugValue;return wn.useSyncExternalStoreWithSelector=function(d,m,f,p,y){var h=o(null);if(h.current===null){var x={hasValue:!1,value:null};h.current=x}else x=h.current;h=l(function(){function g(C){if(!b){if(b=!0,w=C,C=p(C),y!==void 0&&x.hasValue){var _=x.value;if(y(_,C))return S=_}return S=C}if(_=S,n(w,C))return _;var T=p(C);return y!==void 0&&y(_,T)?(w=C,_):(w=C,S=T)}var b=!1,w,S,v=f===void 0?null:f;return[function(){return g(m())},v===null?void 0:function(){return g(v())}]},[m,f,p,y]);var u=s(d,h[0],h[1]);return i(function(){x.hasValue=!0,x.value=u},[u]),c(u),u},wn}var Sn={};/**
25
+ */var Po;function $c(){if(Po)return Pn;Po=1;var r=T,e=za();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 Pn.useSyncExternalStoreWithSelector=function(u,g,h,x,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 p(j){if(!y){if(y=!0,b=j,j=x(j),w!==void 0&&f.hasValue){var v=f.value;if(w(v,j))return S=v}return S=j}if(v=S,n(b,j))return v;var I=x(j);return w!==void 0&&w(v,I)?(b=j,v):(b=j,S=I)}var y=!1,b,S,_=h===void 0?null:h;return[function(){return p(g())},_===null?void 0:function(){return p(_())}]},[g,h,x,w]);var c=s(u,m[0],m[1]);return i(function(){f.hasValue=!0,f.value=c},[c]),d(c),c},Pn}var On={};/**
26
26
  * @license React
27
27
  * use-sync-external-store-shim/with-selector.development.js
28
28
  *
@@ -30,16 +30,37 @@
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 hc(){return vo||(vo=1,process.env.NODE_ENV!=="production"&&function(){function r(d,m){return d===m&&(d!==0||1/d===1/m)||d!==d&&m!==m}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=I,t=Pa(),n=typeof Object.is=="function"?Object.is:r,s=t.useSyncExternalStore,o=e.useRef,i=e.useEffect,l=e.useMemo,c=e.useDebugValue;Sn.useSyncExternalStoreWithSelector=function(d,m,f,p,y){var h=o(null);if(h.current===null){var x={hasValue:!1,value:null};h.current=x}else x=h.current;h=l(function(){function g(C){if(!b){if(b=!0,w=C,C=p(C),y!==void 0&&x.hasValue){var _=x.value;if(y(_,C))return S=_}return S=C}if(_=S,n(w,C))return _;var T=p(C);return y!==void 0&&y(_,T)?(w=C,_):(w=C,S=T)}var b=!1,w,S,v=f===void 0?null:f;return[function(){return g(m())},v===null?void 0:function(){return g(v())}]},[m,f,p,y]);var u=s(d,h[0],h[1]);return i(function(){x.hasValue=!0,x.value=u},[u]),c(u),u},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),Sn}process.env.NODE_ENV==="production"?Wn.exports=fc():Wn.exports=hc();var mc=Wn.exports;const gc=cc(mc),Oa={},{useDebugValue:pc}=I,{useSyncExternalStoreWithSelector:xc}=gc;let _o=!1;const bc=r=>r;function yc(r,e=bc,t){(Oa?"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=xc(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return pc(n),n}const wc=r=>{(Oa?"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"?lc(r):r,t=(n,s)=>yc(e,n,s);return Object.assign(t,e),t},vc=r=>wc;var Ra=Symbol.for("immer-nothing"),So=Symbol.for("immer-draftable"),ke=Symbol.for("immer-state"),_c=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 ve(r,...e){if(process.env.NODE_ENV!=="production"){const t=_c[r],n=typeof t=="function"?t.apply(null,e):t;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${r}. Full error at: https://bit.ly/3cXEKWf`)}var Ct=Object.getPrototypeOf;function jt(r){return!!r&&!!r[ke]}function at(r){var e;return r?$a(r)||Array.isArray(r)||!!r[So]||!!((e=r.constructor)!=null&&e[So])||Zt(r)||Xr(r):!1}var Sc=Object.prototype.constructor.toString();function $a(r){if(!r||typeof r!="object")return!1;const e=Ct(r);if(e===null)return!0;const t=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return t===Object?!0:typeof t=="function"&&Function.toString.call(t)===Sc}function Lr(r,e){Gr(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function Gr(r){const e=r[ke];return e?e.type_:Array.isArray(r)?1:Zt(r)?2:Xr(r)?3:0}function Hn(r,e){return Gr(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function La(r,e,t){const n=Gr(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function Cc(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function Zt(r){return r instanceof Map}function Xr(r){return r instanceof Set}function et(r){return r.copy_||r.base_}function qn(r,e){if(Zt(r))return new Map(r);if(Xr(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);const t=$a(r);if(e===!0||e==="class_only"&&!t){const n=Object.getOwnPropertyDescriptors(r);delete n[ke];let s=Reflect.ownKeys(n);for(let o=0;o<s.length;o++){const i=s[o],l=n[i];l.writable===!1&&(l.writable=!0,l.configurable=!0),(l.get||l.set)&&(n[i]={configurable:!0,writable:!0,enumerable:l.enumerable,value:r[i]})}return Object.create(Ct(r),n)}else{const n=Ct(r);if(n!==null&&t)return{...r};const s=Object.create(n);return Object.assign(s,r)}}function ps(r,e=!1){return Kr(r)||jt(r)||!at(r)||(Gr(r)>1&&Object.defineProperties(r,{set:{value:hr},add:{value:hr},clear:{value:hr},delete:{value:hr}}),Object.freeze(r),e&&Object.values(r).forEach(t=>ps(t,!0))),r}function hr(){ve(2)}function Kr(r){return Object.isFrozen(r)}var jc={};function it(r){const e=jc[r];return e||ve(0,r),e}var Jt;function Da(){return Jt}function Ac(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Co(r,e){e&&(it("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function zn(r){Jn(r),r.drafts_.forEach(kc),r.drafts_=null}function Jn(r){r===Jt&&(Jt=r.parent_)}function jo(r){return Jt=Ac(Jt,r)}function kc(r){const e=r[ke];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[ke].modified_&&(zn(e),ve(4)),at(r)&&(r=Dr(e,r),e.parent_||Fr(e,r)),e.patches_&&it("Patches").generateReplacementPatches_(t[ke].base_,r,e.patches_,e.inversePatches_)):r=Dr(e,t,[]),zn(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==Ra?r:void 0}function Dr(r,e,t){if(Kr(e))return e;const n=e[ke];if(!n)return Lr(e,(s,o)=>ko(r,n,e,s,o,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return Fr(r,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const s=n.copy_;let o=s,i=!1;n.type_===3&&(o=new Set(s),s.clear(),i=!0),Lr(o,(l,c)=>ko(r,n,s,l,c,t,i)),Fr(r,s,!1),t&&r.patches_&&it("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function ko(r,e,t,n,s,o,i){if(process.env.NODE_ENV!=="production"&&s===t&&ve(5),jt(s)){const l=o&&e&&e.type_!==3&&!Hn(e.assigned_,n)?o.concat(n):void 0,c=Dr(r,s,l);if(La(t,n,c),jt(c))r.canAutoFreeze_=!1;else return}else i&&t.add(s);if(at(s)&&!Kr(s)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;Dr(r,s),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&(Zt(t)?t.has(n):Object.prototype.propertyIsEnumerable.call(t,n))&&Fr(r,s)}}function Fr(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&ps(e,t)}function Nc(r,e){const t=Array.isArray(r),n={type_:t?1:0,scope_:e?e.scope_:Da(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=n,o=xs;t&&(s=[n],o=Vt);const{revoke:i,proxy:l}=Proxy.revocable(s,o);return n.draft_=l,n.revoke_=i,l}var xs={get(r,e){if(e===ke)return r;const t=et(r);if(!Hn(t,e))return Mc(r,t,e);const n=t[e];return r.finalized_||!at(n)?n:n===Cn(r.base_,e)?(jn(r),r.copy_[e]=Gn(n,r)):n},has(r,e){return e in et(r)},ownKeys(r){return Reflect.ownKeys(et(r))},set(r,e,t){const n=Fa(et(r),e);if(n!=null&&n.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){const s=Cn(et(r),e),o=s==null?void 0:s[ke];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(Cc(t,s)&&(t!==void 0||Hn(r.base_,e)))return!0;jn(r),Vn(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 Cn(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,jn(r),Vn(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){const t=et(r),n=Reflect.getOwnPropertyDescriptor(t,e);return n&&{writable:!0,configurable:r.type_!==1||e!=="length",enumerable:n.enumerable,value:t[e]}},defineProperty(){ve(11)},getPrototypeOf(r){return Ct(r.base_)},setPrototypeOf(){ve(12)}},Vt={};Lr(xs,(r,e)=>{Vt[r]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});Vt.deleteProperty=function(r,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&ve(13),Vt.set.call(this,r,e,void 0)};Vt.set=function(r,e,t){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&ve(14),xs.set.call(this,r[0],e,t,r[0])};function Cn(r,e){const t=r[ke];return(t?et(t):r)[e]}function Mc(r,e,t){var s;const n=Fa(e,t);return n?"value"in n?n.value:(s=n.get)==null?void 0:s.call(r.draft_):void 0}function Fa(r,e){if(!(e in r))return;let t=Ct(r);for(;t;){const n=Object.getOwnPropertyDescriptor(t,e);if(n)return n;t=Ct(t)}}function Vn(r){r.modified_||(r.modified_=!0,r.parent_&&Vn(r.parent_))}function jn(r){r.copy_||(r.copy_=qn(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Ec=class{constructor(r){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if(typeof e=="function"&&typeof t!="function"){const o=t;t=e;const i=this;return function(c=o,...d){return i.produce(c,m=>t.call(this,m,...d))}}typeof t!="function"&&ve(6),n!==void 0&&typeof n!="function"&&ve(7);let s;if(at(e)){const o=jo(this),i=Gn(e,void 0);let l=!0;try{s=t(i),l=!1}finally{l?zn(o):Jn(o)}return Co(o,n),Ao(s,o)}else if(!e||typeof e!="object"){if(s=t(e),s===void 0&&(s=e),s===Ra&&(s=void 0),this.autoFreeze_&&ps(s,!0),n){const o=[],i=[];it("Patches").generateReplacementPatches_(e,s,o,i),n(o,i)}return s}else ve(1,e)},this.produceWithPatches=(e,t)=>{if(typeof e=="function")return(i,...l)=>this.produceWithPatches(i,c=>e(c,...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){at(r)||ve(8),jt(r)&&(r=Ic(r));const e=jo(this),t=Gn(r,void 0);return t[ke].isManual_=!0,Jn(e),t}finishDraft(r,e){const t=r&&r[ke];(!t||!t.isManual_)&&ve(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=it("Patches").applyPatches_;return jt(r)?n(r,e):this.produce(r,s=>n(s,e))}};function Gn(r,e){const t=Zt(r)?it("MapSet").proxyMap_(r,e):Xr(r)?it("MapSet").proxySet_(r,e):Nc(r,e);return(e?e.scope_:Da()).drafts_.push(t),t}function Ic(r){return jt(r)||ve(10,r),Ua(r)}function Ua(r){if(!at(r)||Kr(r))return r;const e=r[ke];let t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=qn(r,e.scope_.immer_.useStrictShallowCopy_)}else t=qn(r,!0);return Lr(t,(n,s)=>{La(t,n,Ua(s))}),e&&(e.finalized_=!1),t}var Tc=new Ec,Pc=Tc.produce;const Oc=r=>(e,t,n)=>(n.setState=(s,o,...i)=>{const l=typeof s=="function"?Pc(s):s;return e(l,o,...i)},r(n.setState,t,n)),Rc=Oc,$c={};function Lc(r,e){let t;try{t=r()}catch{return}return{getItem:s=>{var o;const i=c=>c===null?null:JSON.parse(c,void 0),l=(o=t.getItem(s))!=null?o:null;return l instanceof Promise?l.then(i):i(l)},setItem:(s,o)=>t.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>t.removeItem(s)}}const Gt=r=>e=>{try{const t=r(e);return t instanceof Promise?t:{then(n){return Gt(n)(t)},catch(n){return this}}}catch(t){return{then(n){return this},catch(n){return Gt(n)(t)}}}},Dc=(r,e)=>(t,n,s)=>{let o={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:u=>u,version:0,merge:(u,g)=>({...g,...u}),...e},i=!1;const l=new Set,c=new Set;let d;try{d=o.getStorage()}catch{}if(!d)return r((...u)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...u)},n,s);const m=Gt(o.serialize),f=()=>{const u=o.partialize({...n()});let g;const b=m({state:u,version:o.version}).then(w=>d.setItem(o.name,w)).catch(w=>{g=w});if(g)throw g;return b},p=s.setState;s.setState=(u,g)=>{p(u,g),f()};const y=r((...u)=>{t(...u),f()},n,s);let h;const x=()=>{var u;if(!d)return;i=!1,l.forEach(b=>b(n()));const g=((u=o.onRehydrateStorage)==null?void 0:u.call(o,n()))||void 0;return Gt(d.getItem.bind(d))(o.name).then(b=>{if(b)return o.deserialize(b)}).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==o.version){if(o.migrate)return o.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 w;return h=o.merge(b,(w=n())!=null?w:y),t(h,!0),f()}).then(()=>{g==null||g(h,void 0),i=!0,c.forEach(b=>b(h))}).catch(b=>{g==null||g(void 0,b)})};return s.persist={setOptions:u=>{o={...o,...u},u.getStorage&&(d=u.getStorage())},clearStorage:()=>{d==null||d.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>x(),hasHydrated:()=>i,onHydrate:u=>(l.add(u),()=>{l.delete(u)}),onFinishHydration:u=>(c.add(u),()=>{c.delete(u)})},x(),h||y},Fc=(r,e)=>(t,n,s)=>{let o={storage:Lc(()=>localStorage),partialize:x=>x,version:0,merge:(x,u)=>({...u,...x}),...e},i=!1;const l=new Set,c=new Set;let d=o.storage;if(!d)return r((...x)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...x)},n,s);const m=()=>{const x=o.partialize({...n()});return d.setItem(o.name,{state:x,version:o.version})},f=s.setState;s.setState=(x,u)=>{f(x,u),m()};const p=r((...x)=>{t(...x),m()},n,s);s.getInitialState=()=>p;let y;const h=()=>{var x,u;if(!d)return;i=!1,l.forEach(b=>{var w;return b((w=n())!=null?w:p)});const g=((u=o.onRehydrateStorage)==null?void 0:u.call(o,(x=n())!=null?x:p))||void 0;return Gt(d.getItem.bind(d))(o.name).then(b=>{if(b)if(typeof b.version=="number"&&b.version!==o.version){if(o.migrate)return[!0,o.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 w;const[S,v]=b;if(y=o.merge(v,(w=n())!=null?w:p),t(y,!0),S)return m()}).then(()=>{g==null||g(y,void 0),y=n(),i=!0,c.forEach(b=>b(y))}).catch(b=>{g==null||g(void 0,b)})};return s.persist={setOptions:x=>{o={...o,...x},x.storage&&(d=x.storage)},clearStorage:()=>{d==null||d.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>h(),hasHydrated:()=>i,onHydrate:x=>(l.add(x),()=>{l.delete(x)}),onFinishHydration:x=>(c.add(x),()=>{c.delete(x)})},o.skipHydration||h(),y||p},Uc=(r,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?(($c?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),Dc(r,e)):Fc(r,e),Bc=Uc,Wc="/api";class Xt{constructor(e=Wc){W(this,"baseUrl");this.baseUrl=e}getBaseUrl(){return this.baseUrl}async request(e,t={}){const n=`${this.baseUrl}${e}`,s={headers:{"Content-Type":"application/json",...t.headers},...t};try{const o=await fetch(n,s);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);const i=await o.text();if(!i)return{};try{return JSON.parse(i)}catch(l){throw console.error(`JSON parse error for ${e}:`,l,"Response text:",i),new Error(`Invalid JSON response: ${i}`)}}catch(o){throw console.error(`API request failed: ${e}`,o),o}}async getSessions(e,t){const n=new URLSearchParams;e&&n.append("user_id",e),t&&n.append("project_id",t);const s=n.toString();return console.log("🔍 getSessions API调用:",{userId:e,projectId:t,queryString:s}),this.request(`/sessions${s?`?${s}`:""}`)}async createSession(e){return console.log("🔍 createSession API调用:",e),this.request("/sessions",{method:"POST",body:JSON.stringify(e)})}async getSession(e){return this.request(`/sessions/${e}`)}async deleteSession(e){return this.request(`/sessions/${e}`,{method:"DELETE"})}async getSessionMessages(e,t){const n=[];(t==null?void 0:t.limit)!==void 0&&n.push(`limit=${encodeURIComponent(String(t.limit))}`),(t==null?void 0:t.offset)!==void 0&&n.push(`offset=${encodeURIComponent(String(t.offset))}`);const s=n.length?`?${n.join("&")}`:"";return this.request(`/sessions/${e}/messages${s}`)}async createMessage(e){const t={...e,createdAt:e.createdAt?e.createdAt.toISOString():void 0};return this.request(`/sessions/${e.sessionId}/messages`,{method:"POST",body:JSON.stringify(t)})}async getMcpConfigs(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return console.log("🔍 getMcpConfigs API调用:",{userId:e,params:t}),this.request(`/mcp-configs${t}`)}async createMcpConfig(e){return console.log("🔍 API client createMcpConfig 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),this.request("/mcp-configs",{method:"POST",body:JSON.stringify(e)})}async updateMcpConfig(e,t){return console.log("🔍 API client updateMcpConfig 调用:",{id:e,data:t}),console.log("🔍 [关键] app_ids 字段:",t.app_ids,"类型:",typeof t.app_ids,"是否为数组:",Array.isArray(t.app_ids)),this.request(`/mcp-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteMcpConfig(e){return this.request(`/mcp-configs/${e}`,{method:"DELETE"})}async getAiModelConfigs(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return console.log("🔍 getAiModelConfigs API调用:",{userId:e,params:t}),this.request(`/ai-model-configs${t}`)}async createAiModelConfig(e){return this.request("/ai-model-configs",{method:"POST",body:JSON.stringify(e)})}async updateAiModelConfig(e,t){return this.request(`/ai-model-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteAiModelConfig(e){return this.request(`/ai-model-configs/${e}`,{method:"DELETE"})}async getSystemContexts(e){return this.request(`/system-contexts?user_id=${e}`)}async getActiveSystemContext(e){return this.request(`/system-context/active?user_id=${e}`)}async createSystemContext(e){return console.log("🔍 API client createSystemContext 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),this.request("/system-contexts",{method:"POST",body:JSON.stringify(e)})}async updateSystemContext(e,t){return console.log("🔍 API client updateSystemContext 调用:",{id:e,data:t}),console.log("🔍 [关键] app_ids 字段:",t.app_ids,"类型:",typeof t.app_ids,"是否为数组:",Array.isArray(t.app_ids)),this.request(`/system-contexts/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteSystemContext(e){return this.request(`/system-contexts/${e}`,{method:"DELETE"})}async activateSystemContext(e,t){return this.request(`/system-contexts/${e}/activate`,{method:"POST",body:JSON.stringify({user_id:t,is_active:!0})})}async getApplications(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return this.request(`/applications${t}`)}async getApplication(e){return this.request(`/applications/${e}`)}async createApplication(e){return this.request("/applications",{method:"POST",body:JSON.stringify(e)})}async updateApplication(e,t){return this.request(`/applications/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteApplication(e){return this.request(`/applications/${e}`,{method:"DELETE"})}async getAgents(e){const t=e?`?user_id=${encodeURIComponent(e)}`:"";return this.request(`/agents${t}`)}async createAgent(e){return console.log("🔍 API client createAgent 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),this.request("/agents",{method:"POST",body:JSON.stringify(e)})}async updateAgent(e,t){return console.log("🔍 API client updateAgent 调用:",{agentId:e,data:t}),console.log("🔍 [关键] app_ids 字段:",t.app_ids,"类型:",typeof t.app_ids,"是否为数组:",Array.isArray(t.app_ids)),this.request(`/agents/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteAgent(e){return this.request(`/agents/${e}`,{method:"DELETE"})}async getConversationDetails(e){try{const t=await this.request(`/sessions/${e}`);return{data:{conversation:{id:t.id,title:t.title,created_at:t.created_at,updated_at:t.updated_at}}}}catch(t){return console.error("Failed to get conversation details:",t),{data:{conversation:{id:e,title:"Default Conversation",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}}}}}async getAssistant(e){try{const t=await this.request("/ai-model-configs"),n=t.find(s=>s.enabled)||t[0];if(!n)throw new Error("No AI model configuration found");return{data:{assistant:{id:n.id,name:n.name,model_config:{model_name:n.model_name,temperature:.7,max_tokens:4e3,api_key:n.api_key,base_url:n.base_url}}}}}catch(t){return console.error("Failed to get assistant:",t),{data:{assistant:{id:"default-assistant",name:"AI Assistant",model_config:{model_name:"gpt-3.5-turbo",temperature:.7,max_tokens:4e3,api_key:"",base_url:"https://api.openai.com/v1"}}}}}}async getMcpServers(e){try{return{data:{mcp_servers:(await this.request("/mcp-configs")).filter(s=>s.enabled).map(s=>({name:s.name,url:s.command}))}}}catch(t){return console.error("Failed to get MCP servers:",t),{data:{mcp_servers:[]}}}}async getMcpConfigResource(e){try{return await this.request(`/mcp-configs/${e}/resource/config`)}catch(t){return console.error("Failed to get MCP config resource:",t),{success:!1,config:null}}}async getMcpConfigResourceByCommand(e){try{return await this.request("/mcp-configs/resource/config",{method:"POST",body:JSON.stringify(e)})}catch(t){return console.error("Failed to get MCP config resource by command:",t),{success:!1,config:null}}}async getMcpConfigProfiles(e){const t=await this.request(`/mcp-configs/${e}/profiles`);return Array.isArray(t)?t:t&&typeof t=="object"&&Array.isArray(t.items)?t.items:[]}async createMcpConfigProfile(e,t){return this.request(`/mcp-configs/${e}/profiles`,{method:"POST",body:JSON.stringify(t)})}async updateMcpConfigProfile(e,t,n){return this.request(`/mcp-configs/${e}/profiles/${t}`,{method:"PUT",body:JSON.stringify(n)})}async deleteMcpConfigProfile(e,t){return this.request(`/mcp-configs/${e}/profiles/${t}`,{method:"DELETE"})}async activateMcpConfigProfile(e,t){return this.request(`/mcp-configs/${e}/profiles/${t}/activate`,{method:"POST",body:JSON.stringify({is_active:!0})})}async saveMessage(e,t){try{const n=t.id||`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{data:{message:await this.request("/messages",{method:"POST",body:JSON.stringify({id:n,sessionId:e,role:t.role,content:t.content,toolCalls:t.tool_calls||null,toolCallId:t.tool_call_id||null,reasoning:t.reasoning||null,metadata:t.metadata||null})})}}}catch(n){return console.error("Failed to save message:",n),{data:{message:{...t,id:Date.now().toString(),created_at:new Date().toISOString()}}}}}async getMessages(e,t={}){try{const n=[];t.limit!==void 0&&n.push(`limit=${encodeURIComponent(String(t.limit))}`),t.offset!==void 0&&n.push(`offset=${encodeURIComponent(String(t.offset))}`);const s=n.length?`?${n.join("&")}`:"";return{data:{messages:await this.request(`/sessions/${e}/messages${s}`)}}}catch(n){return console.error("Failed to get messages:",n),{data:{messages:[]}}}}async addMessage(e,t){return this.saveMessage(e,t)}async streamChat(e,t,n,s){const o=`${this.baseUrl}/agent_v2/chat/stream`,i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:e,content:t,user_id:s,ai_model_config:{model_name:n.model_name,temperature:n.temperature||.7,max_tokens:n.max_tokens||1e3,api_key:n.api_key,base_url:n.base_url}})});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);if(!i.body)throw new Error("Response body is null");return i.body}async streamAgentChat(e,t,n,s){const o=`${this.baseUrl}/agents/chat/stream`,i=await fetch(o,{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream"},body:JSON.stringify({session_id:e,content:t,agent_id:n,user_id:s})});if(!i.ok)throw new Error(`HTTP error! status: ${i.status}`);if(!i.body)throw new Error("Response body is null");return i.body}async stopChat(e){return this.request("/chat/stop",{method:"POST",body:JSON.stringify({session_id:e})})}}const re=new Xt,Ar={getDetails:r=>re.getConversationDetails(r),getAssistant:r=>re.getAssistant(r),getMcpServers:r=>re.getMcpServers(r),saveMessage:(r,e)=>re.saveMessage(r,e),getMessages:(r,e)=>re.getMessages(r,e),addMessage:(r,e)=>re.addMessage(r,e)};class bs{constructor(e,t,n=re){W(this,"userId");W(this,"projectId");W(this,"client");this.userId=e,this.projectId=t,this.client=n}async createSession(e){const t={id:crypto.randomUUID(),title:e.title,user_id:this.userId,project_id:this.projectId},n=await this.client.createSession(t);return{id:n.id,title:n.title,createdAt:new Date(n.created_at),updatedAt:new Date(n.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}}async getSession(e){try{const t=await this.client.getSession(e);return t?{id:t.id,title:t.title,createdAt:new Date(t.created_at),updatedAt:new Date(t.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}:null}catch{return null}}async getAllSessions(){console.log("🔍 DatabaseService.getAllSessions 调用:",{userId:this.userId,projectId:this.projectId});const e=await this.client.getSessions(this.userId,this.projectId);console.log("🔍 API返回的会话数据:",e);const t=e.map(n=>({id:n.id,title:n.title,createdAt:new Date(n.created_at||n.createdAt),updatedAt:new Date(n.updated_at||n.updatedAt),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}));return console.log("🔍 格式化后的会话数据:",t),t}async updateSession(e,t){return console.warn("updateSession not implemented yet"),null}async deleteSession(e){try{return await this.client.deleteSession(e),!0}catch{return!1}}async createMessage(e){var o;const t={id:crypto.randomUUID(),session_id:e.sessionId,role:e.role,content:e.content,summary:e.rawContent,tool_calls:(o=e.metadata)!=null&&o.toolCalls?JSON.stringify(e.metadata.toolCalls):void 0,tool_call_id:e.toolCallId,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n={id:t.id,sessionId:t.session_id,role:t.role,content:t.content,metadata:t.metadata?typeof t.metadata=="string"?JSON.parse(t.metadata):t.metadata:void 0,toolCalls:t.tool_calls?typeof t.tool_calls=="string"?JSON.parse(t.tool_calls):t.tool_calls:void 0},s=await this.client.createMessage(n);return{id:s.id,sessionId:s.session_id,role:s.role,content:s.content,rawContent:s.summary,tokensUsed:e.tokensUsed,status:e.status||"completed",createdAt:new Date(s.created_at),updatedAt:e.updatedAt,toolCallId:s.tool_call_id,metadata:s.metadata?typeof s.metadata=="string"?JSON.parse(s.metadata):s.metadata:e.metadata}}async getSessionMessages(e,t={limit:10,offset:0}){const n=t.limit??10,s=t.offset??0,i=(await this.client.getSessionMessages(e,{limit:n,offset:s})).map(c=>{let d;if(c.metadata)try{d=typeof c.metadata=="string"?JSON.parse(c.metadata):c.metadata}catch(f){console.warn("Failed to parse message metadata:",f),d={}}let m;if(c.toolCalls)try{m=typeof c.toolCalls=="string"?JSON.parse(c.toolCalls):c.toolCalls}catch(f){console.warn("Failed to parse top-level toolCalls:",f)}return{id:c.id,sessionId:c.session_id,role:c.role,content:c.content,summary:c.summary,toolCallId:c.tool_call_id,reasoning:c.reasoning,metadata:d,topLevelToolCalls:m,createdAt:new Date(c.created_at),originalMessage:c}}),l=new Map;return i.forEach(c=>{var d;if(c.role==="tool"&&c.toolCallId){const m=((d=c.metadata)==null?void 0:d.isError)||!1;l.set(c.toolCallId,{content:c.content,error:m?c.content:void 0})}}),i.map(c=>{var y,h;let d;const m=c.topLevelToolCalls||((y=c.metadata)==null?void 0:y.toolCalls);c.role==="assistant"&&m&&Array.isArray(m)&&(console.log("[Database] 处理工具调用:",{messageId:c.id,sourceToolCalls:m}),d=m.map(x=>{if(x.function){let u={};try{u=typeof x.function.arguments=="string"?JSON.parse(x.function.arguments):x.function.arguments}catch(b){console.warn("Failed to parse tool call arguments:",b),u={}}const g=l.get(x.id);return{id:x.id||`tool_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,messageId:c.id,name:x.function.name,arguments:u,result:(g==null?void 0:g.content)||void 0,error:(g==null?void 0:g.error)||void 0,createdAt:c.createdAt}}return null}).filter(Boolean));const f=[],p=typeof c.reasoning=="string"&&c.reasoning.trim().length>0;return c.role==="assistant"&&p&&f.push({type:"thinking",content:c.reasoning}),typeof c.content=="string"&&c.content.trim().length>0&&f.push({type:"text",content:c.content}),d&&Array.isArray(d)&&d.length>0&&d.forEach(x=>{f.push({type:"tool_call",toolCallId:x.id})}),{id:c.id,sessionId:c.sessionId,role:c.role,content:c.content,rawContent:c.summary,tokensUsed:void 0,status:"completed",createdAt:c.createdAt,updatedAt:void 0,toolCallId:c.toolCallId,metadata:{...c.metadata,toolCalls:d,contentSegments:f.length>0?f:(h=c.metadata)==null?void 0:h.contentSegments}}})}async updateMessage(e,t){return console.warn("updateMessage not implemented yet"),null}async deleteMessage(e){return console.warn("deleteMessage not implemented yet"),!1}}const Xn="RFC3986",Kn={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},Hc="RFC1738",qc=Array.isArray,Oe=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),An=1024,zc=(r,e,t,n,s)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(l){return"%26%23"+parseInt(l.slice(2),16)+"%3B"});let i="";for(let l=0;l<o.length;l+=An){const c=o.length>=An?o.slice(l,l+An):o,d=[];for(let m=0;m<c.length;++m){let f=c.charCodeAt(m);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||s===Hc&&(f===40||f===41)){d[d.length]=c.charAt(m);continue}if(f<128){d[d.length]=Oe[f];continue}if(f<2048){d[d.length]=Oe[192|f>>6]+Oe[128|f&63];continue}if(f<55296||f>=57344){d[d.length]=Oe[224|f>>12]+Oe[128|f>>6&63]+Oe[128|f&63];continue}m+=1,f=65536+((f&1023)<<10|c.charCodeAt(m)&1023),d[d.length]=Oe[240|f>>18]+Oe[128|f>>12&63]+Oe[128|f>>6&63]+Oe[128|f&63]}i+=d.join("")}return i};function Jc(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function No(r,e){if(qc(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const Vc=Object.prototype.hasOwnProperty,Ba={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},$e=Array.isArray,Gc=Array.prototype.push,Wa=function(r,e){Gc.apply(r,$e(e)?e:[e])},Xc=Date.prototype.toISOString,ue={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:zc,encodeValuesOnly:!1,format:Xn,formatter:Kn[Xn],indices:!1,serializeDate(r){return Xc.call(r)},skipNulls:!1,strictNullHandling:!1};function Kc(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const kn={};function Ha(r,e,t,n,s,o,i,l,c,d,m,f,p,y,h,x,u,g){let b=r,w=g,S=0,v=!1;for(;(w=w.get(kn))!==void 0&&!v;){const P=w.get(r);if(S+=1,typeof P<"u"){if(P===S)throw new RangeError("Cyclic object value");v=!0}typeof w.get(kn)>"u"&&(S=0)}if(typeof d=="function"?b=d(e,b):b instanceof Date?b=p==null?void 0:p(b):t==="comma"&&$e(b)&&(b=No(b,function(P){return P instanceof Date?p==null?void 0:p(P):P})),b===null){if(o)return c&&!x?c(e,ue.encoder,u,"key",y):e;b=""}if(Kc(b)||Jc(b)){if(c){const P=x?e:c(e,ue.encoder,u,"key",y);return[(h==null?void 0:h(P))+"="+(h==null?void 0:h(c(b,ue.encoder,u,"value",y)))]}return[(h==null?void 0:h(e))+"="+(h==null?void 0:h(String(b)))]}const C=[];if(typeof b>"u")return C;let _;if(t==="comma"&&$e(b))x&&c&&(b=No(b,c)),_=[{value:b.length>0?b.join(",")||null:void 0}];else if($e(d))_=d;else{const P=Object.keys(b);_=m?P.sort(m):P}const T=l?String(e).replace(/\./g,"%2E"):String(e),N=n&&$e(b)&&b.length===1?T+"[]":T;if(s&&$e(b)&&b.length===0)return N+"[]";for(let P=0;P<_.length;++P){const R=_[P],j=typeof R=="object"&&typeof R.value<"u"?R.value:b[R];if(i&&j===null)continue;const F=f&&l?R.replace(/\./g,"%2E"):R,O=$e(b)?typeof t=="function"?t(N,F):N:N+(f?"."+F:"["+F+"]");g.set(r,S);const z=new WeakMap;z.set(kn,g),Wa(C,Ha(j,O,t,n,s,o,i,l,t==="comma"&&x&&$e(b)?null:c,d,m,f,p,y,h,x,u,z))}return C}function Yc(r=ue){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||ue.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=Xn;if(typeof r.format<"u"){if(!Vc.call(Kn,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=Kn[t];let s=ue.filter;(typeof r.filter=="function"||$e(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in Ba?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=ue.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:ue.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:ue.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:ue.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:ue.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?ue.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:ue.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:ue.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:ue.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:ue.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:ue.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:ue.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:ue.strictNullHandling}}function Qc(r,e={}){let t=r;const n=Yc(e);let s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):$e(n.filter)&&(o=n.filter,s=o);const i=[];if(typeof t!="object"||t===null)return"";const l=Ba[n.arrayFormat],c=l==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const d=new WeakMap;for(let p=0;p<s.length;++p){const y=s[p];n.skipNulls&&t[y]===null||Wa(i,Ha(t[y],y,l,c,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,d))}const m=i.join(n.delimiter);let f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),m.length>0?f+m:""}const xt="4.104.0";let Mo=!1,qt,qa,za,Yn,Ja,Va,Ga,Xa,Ka;function Zc(r,e={auto:!1}){if(Mo)throw new Error(`you must \`import 'openai/shims/${r.kind}'\` before importing anything else from openai`);if(qt)throw new Error(`can't \`import 'openai/shims/${r.kind}'\` after \`import 'openai/shims/${qt}'\``);Mo=e.auto,qt=r.kind,qa=r.fetch,za=r.FormData,Yn=r.File,Ja=r.ReadableStream,Va=r.getMultipartRequestOptions,Ga=r.getDefaultAgent,Xa=r.fileFromPath,Ka=r.isFsReadStream}class ed{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function td({manuallyImported:r}={}){const e=r?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let t,n,s,o;try{t=fetch,n=Request,s=Response,o=Headers}catch(i){throw new Error(`this environment is missing the following Web Fetch API type: ${i.message}. ${e}`)}return{kind:"web",fetch:t,Request:n,Response:s,Headers:o,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(i,l)=>({...l,body:new ed(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 Ya=()=>{qt||Zc(td(),{auto:!0})};Ya();class Y extends Error{}class xe extends Y{constructor(e,t,n,s){super(`${xe.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s==null?void 0:s["x-request-id"],this.error=t;const o=t;this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(e,t,n){const s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new Yr({message:n,cause:Zn(t)});const o=t==null?void 0:t.error;return e===400?new Qa(e,o,n,s):e===401?new Za(e,o,n,s):e===403?new ei(e,o,n,s):e===404?new ti(e,o,n,s):e===409?new ri(e,o,n,s):e===422?new ni(e,o,n,s):e===429?new si(e,o,n,s):e>=500?new oi(e,o,n,s):new xe(e,o,n,s)}}class Me extends xe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Yr extends xe{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ys extends Yr{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Qa extends xe{}class Za extends xe{}class ei extends xe{}class ti extends xe{}class ri extends xe{}class ni extends xe{}class si extends xe{}class oi extends xe{}class ai extends Y{constructor(){super("Could not parse response content as the length limit was reached")}}class ii extends Y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var mr=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},Ze=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},je;class Qr{constructor(){je.set(this,void 0),this.buffer=new Uint8Array,mr(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 o;for(;(o=rd(this.buffer,Ze(this,je,"f")))!=null;){if(o.carriage&&Ze(this,je,"f")==null){mr(this,je,o.index,"f");continue}if(Ze(this,je,"f")!=null&&(o.index!==Ze(this,je,"f")+1||o.carriage)){s.push(this.decodeText(this.buffer.slice(0,Ze(this,je,"f")-1))),this.buffer=this.buffer.slice(Ze(this,je,"f")),mr(this,je,null,"f");continue}const i=Ze(this,je,"f")!==null?o.preceding-1:o.preceding,l=this.decodeText(this.buffer.slice(0,i));s.push(l),this.buffer=this.buffer.slice(o.index),mr(this,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 Y(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new Y(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new Y("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
34
- `):[]}}je=new WeakMap;Qr.NEWLINE_CHARS=new Set([`
35
- `,"\r"]);Qr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function rd(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 nd(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 li(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 o=!1;try{for await(const i of sd(e,t))if(!o){if(i.data.startsWith("[DONE]")){o=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let l;try{l=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(l&&l.error)throw new xe(void 0,l.error,void 0,gi(e.headers));yield l}else{let l;try{l=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(i.event=="error")throw new xe(void 0,l.error,l.message,void 0);yield{event:i.event,data:l}}}o=!0}catch(i){if(i instanceof Error&&i.name==="AbortError")return;throw i}finally{o||t.abort()}}return new De(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){const i=new Qr,l=li(e);for await(const c of l)for(const d of i.decode(c))yield d;for(const c of i.flush())yield c}async function*o(){if(n)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(const l of s())i||l&&(yield JSON.parse(l));i=!0}catch(l){if(l instanceof Error&&l.name==="AbortError")return;throw l}finally{i||t.abort()}}return new De(o,t)}[Symbol.asyncIterator](){return this.iterator()}tee(){const e=[],t=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){const i=n.next();e.push(i),t.push(i)}return o.shift()}});return[new De(()=>s(e),this.controller),new De(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new Ja({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:o,done:i}=await t.next();if(i)return s.close();const l=n.encode(JSON.stringify(o)+`
36
- `);s.enqueue(l)}catch(o){s.error(o)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}}async function*sd(r,e){if(!r.body)throw e.abort(),new Y("Attempted to iterate over a response with no body");const t=new ad,n=new Qr,s=li(r.body);for await(const o of od(s))for(const i of n.decode(o)){const l=t.decode(i);l&&(yield l)}for(const o of n.flush()){const i=t.decode(o);i&&(yield i)}}async function*od(r){let e=new Uint8Array;for await(const t of r){if(t==null)continue;const n=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?new TextEncoder().encode(t):t;let s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=nd(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}class ad{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const o={event:this.event,data:this.data.join(`
37
- `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=id(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function id(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}const ci=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",di=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Zr(r),Zr=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",ld=r=>di(r)||ci(r)||Ka(r);async function ui(r,e,t){var s;if(r=await r,di(r))return r;if(ci(r)){const o=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");const i=Zr(o)?[await o.arrayBuffer()]:[o];return new Yn(i,e,t)}const n=await cd(r);if(e||(e=ud(r)??"unknown_file"),!(t!=null&&t.type)){const o=(s=n[0])==null?void 0:s.type;typeof o=="string"&&(t={...t,type:o})}return new Yn(n,e,t)}async function cd(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Zr(r))e.push(await r.arrayBuffer());else if(fd(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: ${dd(r)}`);return e}function dd(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function ud(r){var e;return Nn(r.name)||Nn(r.filename)||((e=Nn(r.path))==null?void 0:e.split(/[\\/]/).pop())}const Nn=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},fd=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Eo=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody",lt=async r=>{const e=await hd(r.body);return Va(e,r)},hd=async r=>{const e=new za;return await Promise.all(Object.entries(r||{}).map(([t,n])=>Qn(e,t,n))),e},Qn=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(ld(t)){const n=await ui(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>Qn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>Qn(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 md=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},gd=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;Ya();async function fi(r){var i;const{response:e}=r;if(r.options.stream)return Ke("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):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 Ke("response",e.status,e.url,e.headers,l),hi(l,e)}const o=await e.text();return Ke("response",e.status,e.url,e.headers,o),o}function hi(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}class en extends Promise{constructor(e,t=fi){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new en(this.responsePromise,async t=>hi(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 pd{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:o}){this.baseURL=e,this.maxRetries=Mn("maxRetries",t),this.timeout=Mn("timeout",n),this.httpAgent=s,this.fetch=o??qa}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...vd(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${jd()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async s=>{const o=s&&Zr(s==null?void 0:s.body)?new DataView(await s.body.arrayBuffer()):(s==null?void 0:s.body)instanceof DataView?s.body:(s==null?void 0:s.body)instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s==null?void 0:s.body)?new DataView(s.body.buffer):s==null?void 0:s.body;return{method:e,path:t,...s,body:o}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){var x;const n={...e},{method:s,path:o,query:i,headers:l={}}=n,c=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,d=this.calculateContentLength(c),m=this.buildURL(o,i);"timeout"in n&&Mn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const f=n.httpAgent??this.httpAgent??Ga(m),p=n.timeout+1e3;typeof((x=f==null?void 0:f.options)==null?void 0:x.timeout)=="number"&&p>(f.options.timeout??0)&&(f.options.timeout=p),this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),l[this.idempotencyHeader]=e.idempotencyKey);const y=this.buildHeaders({options:n,headers:l,contentLength:d,retryCount:t});return{req:{method:s,...c&&{body:c},headers:y,...f&&{agent:f},signal:n.signal??null},url:m,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const o={};n&&(o["content-length"]=n);const i=this.defaultHeaders(e);return Oo(o,i),Oo(o,t),Eo(e.body)&&qt!=="node"&&delete o["content-type"],xr(i,"x-stainless-retry-count")===void 0&&xr(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(s)),xr(i,"x-stainless-timeout")===void 0&&xr(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(o,t),o}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,s){return xe.generate(e,t,n,s)}request(e,t=null){return new en(this.makeRequest(e,t))}async makeRequest(e,t){var f,p;const n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);const{req:o,url:i,timeout:l}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(o,{url:i,options:n}),Ke("request",i,n,o.headers),(f=n.signal)!=null&&f.aborted)throw new Me;const c=new AbortController,d=await this.fetchWithTimeout(i,o,l,c).catch(Zn);if(d instanceof Error){if((p=n.signal)!=null&&p.aborted)throw new Me;if(t)return this.retryRequest(n,t);throw d.name==="AbortError"?new ys:new Yr({cause:d})}const m=gi(d.headers);if(!d.ok){if(t&&this.shouldRetry(d)){const b=`retrying, ${t} attempts remaining`;return Ke(`response (error; ${b})`,d.status,i,m),this.retryRequest(n,t,m)}const y=await d.text().catch(b=>Zn(b).message),h=_d(y),x=h?void 0:y;throw Ke(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,d.status,i,m,x),this.makeStatusError(d.status,h,x,m)}return{response:d,options:n,controller:c}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new xd(this,n,e)}buildURL(e,t){const n=Cd(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return pi(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new Y(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){const{signal:o,...i}=t||{};o&&o.addEventListener("abort",()=>s.abort());const l=setTimeout(()=>s.abort(),n),c={signal:s.signal,...i};return c.method&&(c.method=c.method.toUpperCase()),this.fetch.call(void 0,e,c).finally(()=>{clearTimeout(l)})}shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n){let s;const o=n==null?void 0:n["retry-after-ms"];if(o){const l=parseFloat(o);Number.isNaN(l)||(s=l)}const i=n==null?void 0:n["retry-after"];if(i&&!s){const l=parseFloat(i);Number.isNaN(l)?s=Date.parse(i)-Date.now():s=l*1e3}if(!(s&&0<=s&&s<60*1e3)){const l=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,l)}return await er(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const o=t-e,i=Math.min(.5*Math.pow(2,o),8),l=1-Math.random()*.25;return i*l*1e3}getUserAgent(){return`${this.constructor.name}/JS ${xt}`}}class mi{constructor(e,t,n,s){gr.set(this,void 0),md(this,gr,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new Y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[s,o]of n)e.url.searchParams.set(s,o);t.query=void 0,t.path=e.url.toString()}return await gd(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 xd extends en{constructor(e,t,n){super(t,async s=>new n(e,s.response,await fi(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const gi=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),bd={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},ie=r=>typeof r=="object"&&r!==null&&!pi(r)&&Object.keys(r).every(e=>xi(bd,e)),yd=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xt,"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":xt,"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":xt,"X-Stainless-OS":To(process.platform),"X-Stainless-Arch":Io(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const r=wd();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":xt,"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":xt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function wd(){if(typeof navigator>"u"||!navigator)return null;const r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of r){const n=t.exec(navigator.userAgent);if(n){const s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}const 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 vd=()=>Po??(Po=yd()),_d=r=>{try{return JSON.parse(r)}catch{return}},Sd=/^[a-z][a-z0-9+.-]*:/i,Cd=r=>Sd.test(r),er=r=>new Promise(e=>setTimeout(e,r)),Mn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Y(`${r} must be an integer`);if(e<0)throw new Y(`${r} must be a positive integer`);return e},Zn=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(r)},pr=r=>{var e,t,n,s,o;if(typeof process<"u")return((t=(e=process.env)==null?void 0:e[r])==null?void 0:t.trim())??void 0;if(typeof Deno<"u")return(o=(s=(n=Deno.env)==null?void 0:n.get)==null?void 0:s.call(n,r))==null?void 0:o.trim()};function pi(r){if(!r)return!0;for(const e in r)return!1;return!0}function xi(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Oo(r,e){for(const t in e){if(!xi(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 Ke(r,...e){var t;if(typeof process<"u"&&((t=process==null?void 0:process.env)==null?void 0:t.DEBUG)==="true"){const n=e.map(s=>{if(!s)return s;if(s.headers){const i={...s,headers:{...s.headers}};for(const l in s.headers)Ro.has(l.toLowerCase())&&(i.headers[l]="REDACTED");return i}let o=null;for(const i in s)Ro.has(i.toLowerCase())&&(o??(o={...s}),o[i]="REDACTED");return o??s});console.log(`OpenAI:DEBUG:${r}`,...n)}}const jd=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),Ad=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",kd=r=>typeof(r==null?void 0:r.get)=="function",xr=(r,e)=>{var n;const t=e.toLowerCase();if(kd(r)){const s=((n=e[0])==null?void 0:n.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(o,i,l)=>i+l.toUpperCase());for(const o of[e,t,e.toUpperCase(),s]){const i=r.get(o);if(i)return i}}for(const[s,o]of Object.entries(r))if(s.toLowerCase()===t)return Array.isArray(o)?(o.length<=1||console.warn(`Received ${o.length} entries for the ${e} header, using the first entry.`),o[0]):o},Nd=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 En(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}class tn extends mi{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 fe extends mi{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){var n;const e=this.getPaginatedItems();if(!e.length)return null;const t=(n=e[e.length-1])==null?void 0:n.id;return t?{params:{after:t}}:null}}class Q{constructor(e){this._client=e}}let bi=class extends Q{list(e,t={},n){return ie(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Md,{query:t,...n})}},rn=class extends Q{constructor(){super(...arguments),this.messages=new bi(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return ie(e)?this.list({},e):this._client.getAPIList("/chat/completions",nn,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class nn extends fe{}class Md extends fe{}rn.ChatCompletionsPage=nn;rn.Messages=bi;let sn=class extends Q{constructor(){super(...arguments),this.completions=new rn(this._client)}};sn.Completions=rn;sn.ChatCompletionsPage=nn;class yi extends Q{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t==null?void 0:t.headers},__binaryResponse:!0})}}class wi extends Q{create(e,t){return this._client.post("/audio/transcriptions",lt({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class vi extends Q{create(e,t){return this._client.post("/audio/translations",lt({body:e,...t,__metadata:{model:e.model}}))}}class tr extends Q{constructor(){super(...arguments),this.transcriptions=new wi(this._client),this.translations=new vi(this._client),this.speech=new yi(this._client)}}tr.Transcriptions=wi;tr.Translations=vi;tr.Speech=yi;class ws extends Q{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return ie(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 fe{}ws.BatchesPage=vs;var Ee=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)},es,kr,Nr,Dt,Ft,Mr,Ut,We,Bt,Ur,Br,bt,_i;class _s{constructor(){es.add(this),this.controller=new AbortController,kr.set(this,void 0),Nr.set(this,()=>{}),Dt.set(this,()=>{}),Ft.set(this,void 0),Mr.set(this,()=>{}),Ut.set(this,()=>{}),We.set(this,{}),Bt.set(this,!1),Ur.set(this,!1),Br.set(this,!1),bt.set(this,!1),Ee(this,kr,new Promise((e,t)=>{Ee(this,Nr,e,"f"),Ee(this,Dt,t,"f")}),"f"),Ee(this,Ft,new Promise((e,t)=>{Ee(this,Mr,e,"f"),Ee(this,Ut,t,"f")}),"f"),ae(this,kr,"f").catch(()=>{}),ae(this,Ft,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},ae(this,es,"m",_i).bind(this))},0)}_connected(){this.ended||(ae(this,Nr,"f").call(this),this._emit("connect"))}get ended(){return ae(this,Bt,"f")}get errored(){return ae(this,Ur,"f")}get aborted(){return ae(this,Br,"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(o=>o.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)=>{Ee(this,bt,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){Ee(this,bt,!0,"f"),await ae(this,Ft,"f")}_emit(e,...t){if(ae(this,Bt,"f"))return;e==="end"&&(Ee(this,Bt,!0,"f"),ae(this,Mr,"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,bt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),ae(this,Dt,"f").call(this,s),ae(this,Ut,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!ae(this,bt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),ae(this,Dt,"f").call(this,s),ae(this,Ut,"f").call(this,s),this._emit("end")}}_emitFinal(){}}kr=new WeakMap,Nr=new WeakMap,Dt=new WeakMap,Ft=new WeakMap,Mr=new WeakMap,Ut=new WeakMap,We=new WeakMap,Bt=new WeakMap,Ur=new WeakMap,Br=new WeakMap,bt=new WeakMap,es=new WeakSet,_i=function(e){if(Ee(this,Ur,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Me),e instanceof Me)return Ee(this,Br,!0,"f"),this._emit("abort",e);if(e instanceof Y)return this._emit("error",e);if(e instanceof Error){const t=new Y(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new Y(String(e)))};var 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},pe,ts,Le,Er,Ie,nt,yt,rt,Wr,Ae,Ir,Tr,zt,Wt,Ht,$o,Lo,Do,Fo,Uo,Bo,Wo;class Te extends _s{constructor(){super(...arguments),pe.add(this),ts.set(this,[]),Le.set(this,{}),Er.set(this,{}),Ie.set(this,void 0),nt.set(this,void 0),yt.set(this,void 0),rt.set(this,void 0),Wr.set(this,void 0),Ae.set(this,void 0),Ir.set(this,void 0),Tr.set(this,void 0),zt.set(this,void 0)}[(ts=new WeakMap,Le=new WeakMap,Er=new WeakMap,Ie=new WeakMap,nt=new WeakMap,yt=new WeakMap,rt=new WeakMap,Wr=new WeakMap,Ae=new WeakMap,Ir=new WeakMap,Tr=new WeakMap,zt=new WeakMap,pe=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Te;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var o;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=De.fromReadableStream(e,this.controller);for await(const i of s)G(this,pe,"m",Wt).call(this,i);if((o=s.controller.signal)!=null&&o.aborted)throw new Me;return this._addRun(G(this,pe,"m",Ht).call(this))}toReadableStream(){return new De(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,o){const i=new Te;return i._run(()=>i._runToolAssistantStream(e,t,n,s,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,n,s,o){var d;const i=o==null?void 0:o.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const l={...s,stream:!0},c=await e.submitToolOutputs(t,n,l,{...o,signal:this.controller.signal});this._connected();for await(const m of c)G(this,pe,"m",Wt).call(this,m);if((d=c.controller.signal)!=null&&d.aborted)throw new Me;return this._addRun(G(this,pe,"m",Ht).call(this))}static createThreadAssistantStream(e,t,n){const s=new Te;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){const o=new Te;return o._run(()=>o._runAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return G(this,Ir,"f")}currentRun(){return G(this,Tr,"f")}currentMessageSnapshot(){return G(this,Ie,"f")}currentRunStepSnapshot(){return G(this,zt,"f")}async finalRunSteps(){return await this.done(),Object.values(G(this,Le,"f"))}async finalMessages(){return await this.done(),Object.values(G(this,Er,"f"))}async finalRun(){if(await this.done(),!G(this,nt,"f"))throw Error("Final run was not received.");return G(this,nt,"f")}async _createThreadAssistantStream(e,t,n){var l;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const o={...t,stream:!0},i=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(const c of i)G(this,pe,"m",Wt).call(this,c);if((l=i.controller.signal)!=null&&l.aborted)throw new Me;return this._addRun(G(this,pe,"m",Ht).call(this))}async _createAssistantStream(e,t,n,s){var c;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},l=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const d of l)G(this,pe,"m",Wt).call(this,d);if((c=l.controller.signal)!=null&&c.aborted)throw new Me;return this._addRun(G(this,pe,"m",Ht).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let o=e[n];if(o==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(En(o)&&En(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(const i of s){if(!En(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 c=o[l];c==null?o.push(i):o[l]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,o){return await this._createToolAssistantStream(n,e,t,s,o)}}Wt=function(e){if(!this.ended)switch(Ce(this,Ir,e,"f"),G(this,pe,"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,pe,"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,pe,"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,pe,"m",$o).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ht=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");if(!G(this,nt,"f"))throw Error("Final run has not been received");return G(this,nt,"f")},$o=function(e){const[t,n]=G(this,pe,"m",Uo).call(this,e,G(this,Ie,"f"));Ce(this,Ie,t,"f"),G(this,Er,"f")[t.id]=t;for(const s of n){const o=t.content[s.index];(o==null?void 0:o.type)=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=G(this,yt,"f")){if(G(this,rt,"f"))switch(G(this,rt,"f").type){case"text":this._emit("textDone",G(this,rt,"f").text,G(this,Ie,"f"));break;case"image_file":this._emit("imageFileDone",G(this,rt,"f").image_file,G(this,Ie,"f"));break}Ce(this,yt,s.index,"f")}Ce(this,rt,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(G(this,yt,"f")!==void 0){const s=e.data.content[G(this,yt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,G(this,Ie,"f"));break;case"text":this._emit("textDone",s.text,G(this,Ie,"f"));break}}G(this,Ie,"f")&&this._emit("messageDone",e.data),Ce(this,Ie,void 0,"f")}},Lo=function(e){const t=G(this,pe,"m",Fo).call(this,e);switch(Ce(this,zt,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const o of n.step_details.tool_calls)o.index==G(this,Wr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(G(this,Ae,"f")&&this._emit("toolCallDone",G(this,Ae,"f")),Ce(this,Wr,o.index,"f"),Ce(this,Ae,t.step_details.tool_calls[o.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,zt,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}},Do=function(e){G(this,ts,"f").push(e),this._emit("event",e)},Fo=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=Te.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")},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 o of s.delta.content)if(o.index in t.content){let i=t.content[o.index];t.content[o.index]=G(this,pe,"m",Bo).call(this,o,i)}else t.content[o.index]=o,n.push(o);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Bo=function(e,t){return Te.accumulateDelta(t,e)},Wo=function(e){switch(Ce(this,Tr,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":Ce(this,nt,e.data,"f"),G(this,Ae,"f")&&(this._emit("toolCallDone",G(this,Ae,"f")),Ce(this,Ae,void 0,"f"));break}};class Ss extends Q{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e={},t){return ie(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 fe{}Ss.AssistantsPage=Cs;function Ho(r){return typeof r.parse=="function"}const wt=r=>(r==null?void 0:r.role)==="assistant",Si=r=>(r==null?void 0:r.role)==="function",Ci=r=>(r==null?void 0:r.role)==="tool";function js(r){return(r==null?void 0:r.$brand)==="auto-parseable-response-format"}function rr(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function Ed(r,e){return!e||!ji(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:As(r,e)}function As(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new ai;if(n.finish_reason==="content_filter")throw new ii;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(o=>Td(e,o)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Id(e,n.message.content):null}}});return{...r,choices:t}}function Id(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 Td(r,e){var n;const t=(n=r.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:rr(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function Pd(r,e){var n;if(!r)return!1;const t=(n=r.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return rr(t)||(t==null?void 0:t.function.strict)||!1}function ji(r){var e;return js(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>rr(t)||t.type==="function"&&t.function.strict===!0))??!1}function Od(r){for(const e of r??[]){if(e.type!=="function")throw new Y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var we=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},be,rs,Hr,ns,ss,os,Ai,as;const qo=10;class ki extends _s{constructor(){super(...arguments),be.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(n=e.choices[0])==null?void 0:n.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(Si(e)||Ci(e))&&e.content)this._emit("functionCallResult",e.content);else if(wt(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(wt(e)&&e.tool_calls)for(const n of e.tool_calls)n.type==="function"&&this._emit("functionCall",n.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),we(this,be,"m",rs).call(this)}async finalMessage(){return await this.done(),we(this,be,"m",Hr).call(this)}async finalFunctionCall(){return await this.done(),we(this,be,"m",ns).call(this)}async finalFunctionCallResult(){return await this.done(),we(this,be,"m",ss).call(this)}async totalUsage(){return await this.done(),we(this,be,"m",os).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=we(this,be,"m",Hr).call(this);t&&this._emit("finalMessage",t);const n=we(this,be,"m",rs).call(this);n&&this._emit("finalContent",n);const s=we(this,be,"m",ns).call(this);s&&this._emit("finalFunctionCall",s);const o=we(this,be,"m",ss).call(this);o!=null&&this._emit("finalFunctionCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",we(this,be,"m",os).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())),we(this,be,"m",Ai).call(this,t);const o=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(As(o,t))}async _runChatCompletion(e,t,n){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){var p;const s="function",{function_call:o="auto",stream:i,...l}=t,c=typeof o!="string"&&(o==null?void 0:o.name),{maxChatCompletions:d=qo}=n||{},m={};for(const y of t.functions)m[y.name||y.function.name]=y;const f=t.functions.map(y=>({name:y.name||y.function.name,parameters:y.parameters,description:y.description}));for(const y of t.messages)this._addMessage(y,!1);for(let y=0;y<d;++y){const x=(p=(await this._createChatCompletion(e,{...l,function_call:o,functions:f,messages:[...this.messages]},n)).choices[0])==null?void 0:p.message;if(!x)throw new Y("missing message in ChatCompletion response");if(!x.function_call)return;const{name:u,arguments:g}=x.function_call,b=m[u];if(b){if(c&&c!==u){const C=`Invalid function_call: ${JSON.stringify(u)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,name:u,content:C});continue}}else{const C=`Invalid function_call: ${JSON.stringify(u)}. Available options are: ${f.map(_=>JSON.stringify(_.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:u,content:C});continue}let w;try{w=Ho(b)?await b.parse(g):g}catch(C){this._addMessage({role:s,name:u,content:C instanceof Error?C.message:String(C)});continue}const S=await b.function(w,this),v=we(this,be,"m",as).call(this,S);if(this._addMessage({role:s,name:u,content:v}),c)return}}async _runTools(e,t,n){var y,h,x;const s="tool",{tool_choice:o="auto",stream:i,...l}=t,c=typeof o!="string"&&((y=o==null?void 0:o.function)==null?void 0:y.name),{maxChatCompletions:d=qo}=n||{},m=t.tools.map(u=>{if(rr(u)){if(!u.$callback)throw new Y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:u.$callback,name:u.function.name,description:u.function.description||"",parameters:u.function.parameters,parse:u.$parseRaw,strict:!0}}}return u}),f={};for(const u of m)u.type==="function"&&(f[u.function.name||u.function.function.name]=u.function);const p="tools"in t?m.map(u=>u.type==="function"?{type:"function",function:{name:u.function.name||u.function.function.name,parameters:u.function.parameters,description:u.function.description,strict:u.function.strict}}:u):void 0;for(const u of t.messages)this._addMessage(u,!1);for(let u=0;u<d;++u){const b=(h=(await this._createChatCompletion(e,{...l,tool_choice:o,tools:p,messages:[...this.messages]},n)).choices[0])==null?void 0:h.message;if(!b)throw new Y("missing message in ChatCompletion response");if(!((x=b.tool_calls)!=null&&x.length))return;for(const w of b.tool_calls){if(w.type!=="function")continue;const S=w.id,{name:v,arguments:C}=w.function,_=f[v];if(_){if(c&&c!==v){const R=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:S,content:R});continue}}else{const R=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(f).map(j=>JSON.stringify(j)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:S,content:R});continue}let T;try{T=Ho(_)?await _.parse(C):C}catch(R){const j=R instanceof Error?R.message:String(R);this._addMessage({role:s,tool_call_id:S,content:j});continue}const N=await _.function(T,this),P=we(this,be,"m",as).call(this,N);if(this._addMessage({role:s,tool_call_id:S,content:P}),c)return}}}}be=new WeakSet,rs=function(){return we(this,be,"m",Hr).call(this).content??null},Hr=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(wt(t)){const{function_call:n,...s}=t,o={...s,content:t.content??null,refusal:t.refusal??null};return n&&(o.function_call=n),o}}throw new Y("stream ended without producing a ChatCompletionMessage with role=assistant")},ns=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const s=this.messages[n];if(wt(s)&&(s!=null&&s.function_call))return s.function_call;if(wt(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},ss=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Si(t)&&t.content!=null||Ci(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>{var s;return n.role==="assistant"&&((s=n.tool_calls)==null?void 0:s.some(o=>o.type==="function"&&o.id===t.tool_call_id))}))return t.content}},os=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},Ai=function(e){if(e.n!=null&&e.n>1)throw new Y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},as=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Kt extends ki{static runFunctions(e,t,n){const s=new Kt,o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,o)),s}static runTools(e,t,n){const s=new Kt,o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),wt(e)&&e.content&&this._emit("content",e.content)}}const Ni=1,Mi=2,Ei=4,Ii=8,Ti=16,Pi=32,Oi=64,Ri=128,$i=256,Li=Ri|$i,Di=Ti|Pi|Li|Oi,Fi=Ni|Mi|Di,Ui=Ei|Ii,Rd=Fi|Ui,he={STR:Ni,NUM:Mi,ARR:Ei,OBJ:Ii,NULL:Ti,BOOL:Pi,NAN:Oi,INFINITY:Ri,MINUS_INFINITY:$i,INF:Li,SPECIAL:Di,ATOM:Fi,COLLECTION:Ui,ALL:Rd};class $d extends Error{}class Ld extends Error{}function Dd(r,e=he.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Fd(r.trim(),e)}const Fd=(r,e)=>{const t=r.length;let n=0;const s=p=>{throw new $d(`${p} at position ${n}`)},o=p=>{throw new Ld(`${p} at position ${n}`)},i=()=>(f(),n>=t&&s("Unexpected end of input"),r[n]==='"'?l():r[n]==="{"?c():r[n]==="["?d():r.substring(n,n+4)==="null"||he.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||he.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||he.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||he.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||he.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||he.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):m()),l=()=>{const p=n;let y=!1;for(n++;n<t&&(r[n]!=='"'||y&&r[n-1]==="\\");)y=r[n]==="\\"?!y:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(p,++n-Number(y)))}catch(h){o(String(h))}else if(he.STR&e)try{return JSON.parse(r.substring(p,n-Number(y))+'"')}catch{return JSON.parse(r.substring(p,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{n++,f();const p={};try{for(;r[n]!=="}";){if(f(),n>=t&&he.OBJ&e)return p;const y=l();f(),n++;try{const h=i();Object.defineProperty(p,y,{value:h,writable:!0,enumerable:!0,configurable:!0})}catch(h){if(he.OBJ&e)return p;throw h}f(),r[n]===","&&n++}}catch{if(he.OBJ&e)return p;s("Expected '}' at end of object")}return n++,p},d=()=>{n++;const p=[];try{for(;r[n]!=="]";)p.push(i()),f(),r[n]===","&&n++}catch{if(he.ARR&e)return p;s("Expected ']' at end of array")}return n++,p},m=()=>{if(n===0){r==="-"&&he.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(y){if(he.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(y))}}const p=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(he.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(p,n))}catch{r.substring(p,n)==="-"&&he.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(p,r.lastIndexOf("e")))}catch(h){o(String(h))}}},f=()=>{for(;n<t&&`
38
- \r `.includes(r[n]);)n++};return i()},zo=r=>Dd(r,he.ALL^he.NUM);var ft=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},se=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},de,Ue,ht,qe,In,br,Tn,Pn,On,yr,Rn,Jo;class Yt extends ki{constructor(e){super(),de.add(this),Ue.set(this,void 0),ht.set(this,void 0),qe.set(this,void 0),ft(this,Ue,e,"f"),ft(this,ht,[],"f")}get currentChatCompletionSnapshot(){return se(this,qe,"f")}static fromReadableStream(e){const t=new Yt(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new Yt(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,n){var i;super._createChatCompletion;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),se(this,de,"m",In).call(this);const o=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(const l of o)se(this,de,"m",Tn).call(this,l);if((i=o.controller.signal)!=null&&i.aborted)throw new Me;return this._addChatCompletion(se(this,de,"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())),se(this,de,"m",In).call(this),this._connected();const s=De.fromReadableStream(e,this.controller);let o;for await(const l of s)o&&o!==l.id&&this._addChatCompletion(se(this,de,"m",yr).call(this)),se(this,de,"m",Tn).call(this,l),o=l.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Me;return this._addChatCompletion(se(this,de,"m",yr).call(this))}[(Ue=new WeakMap,ht=new WeakMap,qe=new WeakMap,de=new WeakSet,In=function(){this.ended||ft(this,qe,void 0,"f")},br=function(t){let n=se(this,ht,"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},se(this,ht,"f")[t.index]=n,n)},Tn=function(t){var s,o,i,l,c,d,m,f,p,y,h,x,u,g,b;if(this.ended)return;const n=se(this,de,"m",Jo).call(this,t);this._emit("chunk",t,n);for(const w of t.choices){const S=n.choices[w.index];w.delta.content!=null&&((s=S.message)==null?void 0:s.role)==="assistant"&&((o=S.message)!=null&&o.content)&&(this._emit("content",w.delta.content,S.message.content),this._emit("content.delta",{delta:w.delta.content,snapshot:S.message.content,parsed:S.message.parsed})),w.delta.refusal!=null&&((i=S.message)==null?void 0:i.role)==="assistant"&&((l=S.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:w.delta.refusal,snapshot:S.message.refusal}),((c=w.logprobs)==null?void 0:c.content)!=null&&((d=S.message)==null?void 0:d.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(m=w.logprobs)==null?void 0:m.content,snapshot:((f=S.logprobs)==null?void 0:f.content)??[]}),((p=w.logprobs)==null?void 0:p.refusal)!=null&&((y=S.message)==null?void 0:y.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(h=w.logprobs)==null?void 0:h.refusal,snapshot:((x=S.logprobs)==null?void 0:x.refusal)??[]});const v=se(this,de,"m",br).call(this,S);S.finish_reason&&(se(this,de,"m",On).call(this,S),v.current_tool_call_index!=null&&se(this,de,"m",Pn).call(this,S,v.current_tool_call_index));for(const C of w.delta.tool_calls??[])v.current_tool_call_index!==C.index&&(se(this,de,"m",On).call(this,S),v.current_tool_call_index!=null&&se(this,de,"m",Pn).call(this,S,v.current_tool_call_index)),v.current_tool_call_index=C.index;for(const C of w.delta.tool_calls??[]){const _=(u=S.message.tool_calls)==null?void 0:u[C.index];_!=null&&_.type&&((_==null?void 0:_.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(g=_.function)==null?void 0:g.name,index:C.index,arguments:_.function.arguments,parsed_arguments:_.function.parsed_arguments,arguments_delta:((b=C.function)==null?void 0:b.arguments)??""}):(_==null||_.type,void 0))}}},Pn=function(t,n){var i,l,c;if(se(this,de,"m",br).call(this,t).done_tool_calls.has(n))return;const o=(i=t.message.tool_calls)==null?void 0:i[n];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){const d=(c=(l=se(this,Ue,"f"))==null?void 0:l.tools)==null?void 0:c.find(m=>m.type==="function"&&m.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:rr(d)?d.$parseRaw(o.function.arguments):d!=null&&d.function.strict?JSON.parse(o.function.arguments):null})}else o.type},On=function(t){var s,o;const n=se(this,de,"m",br).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=se(this,de,"m",Rn).call(this);this._emit("content.done",{content:t.message.content,parsed:i?i.$parseRaw(t.message.content):null})}t.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),(s=t.logprobs)!=null&&s.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),(o=t.logprobs)!=null&&o.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},yr=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");const t=se(this,qe,"f");if(!t)throw new Y("request ended without sending any chunks");return ft(this,qe,void 0,"f"),ft(this,ht,[],"f"),Ud(t,se(this,Ue,"f"))},Rn=function(){var n;const t=(n=se(this,Ue,"f"))==null?void 0:n.response_format;return js(t)?t:null},Jo=function(t){var n,s,o,i;let l=se(this,qe,"f");const{choices:c,...d}=t;l?Object.assign(l,d):l=ft(this,qe,{...d,choices:[]},"f");for(const{delta:m,finish_reason:f,index:p,logprobs:y=null,...h}of t.choices){let x=l.choices[p];if(x||(x=l.choices[p]={finish_reason:f,index:p,message:{},logprobs:y,...h}),y)if(!x.logprobs)x.logprobs=Object.assign({},y);else{const{content:C,refusal:_,...T}=y;Object.assign(x.logprobs,T),C&&((n=x.logprobs).content??(n.content=[]),x.logprobs.content.push(...C)),_&&((s=x.logprobs).refusal??(s.refusal=[]),x.logprobs.refusal.push(..._))}if(f&&(x.finish_reason=f,se(this,Ue,"f")&&ji(se(this,Ue,"f")))){if(f==="length")throw new ai;if(f==="content_filter")throw new ii}if(Object.assign(x,h),!m)continue;const{content:u,refusal:g,function_call:b,role:w,tool_calls:S,...v}=m;if(Object.assign(x.message,v),g&&(x.message.refusal=(x.message.refusal||"")+g),w&&(x.message.role=w),b&&(x.message.function_call?(b.name&&(x.message.function_call.name=b.name),b.arguments&&((o=x.message.function_call).arguments??(o.arguments=""),x.message.function_call.arguments+=b.arguments)):x.message.function_call=b),u&&(x.message.content=(x.message.content||"")+u,!x.message.refusal&&se(this,de,"m",Rn).call(this)&&(x.message.parsed=zo(x.message.content))),S){x.message.tool_calls||(x.message.tool_calls=[]);for(const{index:C,id:_,type:T,function:N,...P}of S){const R=(i=x.message.tool_calls)[C]??(i[C]={});Object.assign(R,P),_&&(R.id=_),T&&(R.type=T),N&&(R.function??(R.function={name:N.name??"",arguments:""})),N!=null&&N.name&&(R.function.name=N.name),N!=null&&N.arguments&&(R.function.arguments+=N.arguments,Pd(se(this,Ue,"f"),R)&&(R.function.parsed_arguments=zo(R.function.arguments)))}}}return l},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("chunk",s=>{const o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new De(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Ud(r,e){const{id:t,choices:n,created:s,model:o,system_fingerprint:i,...l}=r,c={...l,id:t,choices:n.map(({message:d,finish_reason:m,index:f,logprobs:p,...y})=>{if(!m)throw new Y(`missing finish_reason for choice ${f}`);const{content:h=null,function_call:x,tool_calls:u,...g}=d,b=d.role;if(!b)throw new Y(`missing role for choice ${f}`);if(x){const{arguments:w,name:S}=x;if(w==null)throw new Y(`missing function_call.arguments for choice ${f}`);if(!S)throw new Y(`missing function_call.name for choice ${f}`);return{...y,message:{content:h,function_call:{arguments:w,name:S},role:b,refusal:d.refusal??null},finish_reason:m,index:f,logprobs:p}}return u?{...y,index:f,finish_reason:m,logprobs:p,message:{...g,role:b,content:h,refusal:d.refusal??null,tool_calls:u.map((w,S)=>{const{function:v,type:C,id:_,...T}=w,{arguments:N,name:P,...R}=v||{};if(_==null)throw new Y(`missing choices[${f}].tool_calls[${S}].id
39
- ${wr(r)}`);if(C==null)throw new Y(`missing choices[${f}].tool_calls[${S}].type
40
- ${wr(r)}`);if(P==null)throw new Y(`missing choices[${f}].tool_calls[${S}].function.name
41
- ${wr(r)}`);if(N==null)throw new Y(`missing choices[${f}].tool_calls[${S}].function.arguments
42
- ${wr(r)}`);return{...T,id:_,type:C,function:{...R,name:P,arguments:N}}})}}:{...y,message:{...g,content:h,role:b,refusal:d.refusal??null},finish_reason:m,index:f,logprobs:p}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Ed(c,e)}function wr(r){return JSON.stringify(r)}class vt extends Yt{static fromReadableStream(e){const t=new vt(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new vt(null),o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,o)),s}static runTools(e,t,n){const s=new vt(t),o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}}let Bi=class extends Q{parse(e,t){return Od(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?vt.runFunctions(this._client,e,t):Kt.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?vt.runTools(this._client,e,t):Kt.runTools(this._client,e,t)}stream(e,t){return Yt.createChatCompletion(this._client,e,t)}};class is extends Q{constructor(){super(...arguments),this.completions=new Bi(this._client)}}(function(r){r.Completions=Bi})(is||(is={}));class Wi extends Q{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Hi extends Q{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class on extends Q{constructor(){super(...arguments),this.sessions=new Wi(this._client),this.transcriptionSessions=new Hi(this._client)}}on.Sessions=Wi;on.TranscriptionSessions=Hi;class ks extends Q{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return ie(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 fe{}ks.MessagesPage=Ns;class Ms extends Q{retrieve(e,t,n,s={},o){return ie(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...o,headers:{"OpenAI-Beta":"assistants=v2",...o==null?void 0:o.headers}})}list(e,t,n={},s){return ie(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 fe{}Ms.RunStepsPage=Es;let nr=class extends Q{constructor(){super(...arguments),this.steps=new Ms(this._client)}create(e,t,n){const{include:s,...o}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return ie(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 Te.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:o,response:i}=await this.retrieve(e,t,{...n,headers:{...n==null?void 0:n.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const c=i.headers.get("openai-poll-after-ms");if(c){const d=parseInt(c);isNaN(d)||(l=d)}}await er(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,n){return Te.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const o=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,o.id,s)}submitToolOutputsStream(e,t,n,s){return Te.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class Is extends fe{}nr.RunsPage=Is;nr.Steps=Ms;nr.RunStepsPage=Es;class kt extends Q{constructor(){super(...arguments),this.runs=new nr(this._client),this.messages=new ks(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 Te.createThreadAssistantStream(e,this._client.beta.threads,t)}}kt.Runs=nr;kt.RunsPage=Is;kt.Messages=ks;kt.MessagesPage=Ns;class Nt extends Q{constructor(){super(...arguments),this.realtime=new on(this._client),this.chat=new is(this._client),this.assistants=new Ss(this._client),this.threads=new kt(this._client)}}Nt.Realtime=on;Nt.Assistants=Ss;Nt.AssistantsPage=Cs;Nt.Threads=kt;class qi extends Q{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class zi extends Q{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n==null?void 0:n.headers},__binaryResponse:!0})}}let an=class extends Q{constructor(){super(...arguments),this.content=new zi(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,lt({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`,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 fe{}an.FileListResponsesPage=Ts;an.Content=zi;class sr extends Q{constructor(){super(...arguments),this.files=new an(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return ie(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 fe{}sr.ContainerListResponsesPage=Ps;sr.Files=an;sr.FileListResponsesPage=Ts;class Ji extends Q{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&Ke("Request","User defined encoding_format:",e.encoding_format);const o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?o:(Ke("response","Decoding base64 embeddings to float32 array"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const c=l.embedding;l.embedding=Nd(c)}),i)))}}class Os extends Q{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return ie(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Rs,{query:n,...s})}}class Rs extends fe{}Os.OutputItemListResponsesPage=Rs;class or extends Q{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 ie(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 fe{}or.RunListResponsesPage=$s;or.OutputItems=Os;or.OutputItemListResponsesPage=Rs;class ar extends Q{constructor(){super(...arguments),this.runs=new or(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,n){return this._client.post(`/evals/${e}`,{body:t,...n})}list(e={},t){return ie(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 fe{}ar.EvalListResponsesPage=Ls;ar.Runs=or;ar.RunListResponsesPage=$s;let Ds=class extends Q{create(e,t){return this._client.post("/files",lt({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",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"]),o=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await er(t),i=await this.retrieve(e),Date.now()-o>n)throw new ys({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class Fs extends fe{}Ds.FileObjectsPage=Fs;class Vi extends Q{}let Gi=class extends Q{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Us extends Q{constructor(){super(...arguments),this.graders=new Gi(this._client)}}Us.Graders=Gi;class Bs extends Q{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Ws,{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 Ws extends tn{}Bs.PermissionCreateResponsesPage=Ws;let ln=class extends Q{constructor(){super(...arguments),this.permissions=new Bs(this._client)}};ln.Permissions=Bs;ln.PermissionCreateResponsesPage=Ws;class Hs extends Q{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 fe{}Hs.FineTuningJobCheckpointsPage=qs;class Mt extends Q{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 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`,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 fe{}class Js extends fe{}Mt.FineTuningJobsPage=zs;Mt.FineTuningJobEventsPage=Js;Mt.Checkpoints=Hs;Mt.FineTuningJobCheckpointsPage=qs;class Ye extends Q{constructor(){super(...arguments),this.methods=new Vi(this._client),this.jobs=new Mt(this._client),this.checkpoints=new ln(this._client),this.alpha=new Us(this._client)}}Ye.Methods=Vi;Ye.Jobs=Mt;Ye.FineTuningJobsPage=zs;Ye.FineTuningJobEventsPage=Js;Ye.Checkpoints=ln;Ye.Alpha=Us;class Xi extends Q{}class Vs extends Q{constructor(){super(...arguments),this.graderModels=new Xi(this._client)}}Vs.GraderModels=Xi;class Ki extends Q{createVariation(e,t){return this._client.post("/images/variations",lt({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",lt({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Gs extends Q{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 tn{}Gs.ModelsPage=Xs;class Yi extends Q{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Bd(r,e){return!e||!Hd(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)}:Qi(r,e)}function Qi(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Jd(e,s)};if(s.type==="message"){const o=s.content.map(i=>i.type==="output_text"?{...i,parsed:Wd(e,i.text)}:i);return{...s,content:o}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||Zi(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const s of n.output)if(s.type==="message"){for(const o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function Wd(r,e){var t,n,s,o;return((n=(t=r.text)==null?void 0:t.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((s=r.text)==null?void 0:s.format)?((o=r.text)==null?void 0:o.format).$parseRaw(e):JSON.parse(e)}function Hd(r){var e;return!!js((e=r.text)==null?void 0:e.format)}function qd(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function zd(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function Jd(r,e){const t=zd(r.tools??[],e.name);return{...e,...e,parsed_arguments:qd(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function Zi(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 el extends Q{list(e,t={},n){return ie(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Gd,{query:t,...n})}}var mt=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},ze=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},gt,vr,Je,_r,Vo,Go,Xo,Ko;class Ks extends _s{constructor(e){super(),gt.add(this),vr.set(this,void 0),Je.set(this,void 0),_r.set(this,void 0),mt(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())),ze(this,gt,"m",Vo).call(this);let o,i=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const c of o)ze(this,gt,"m",Go).call(this,c,i);if((l=o.controller.signal)!=null&&l.aborted)throw new Me;return ze(this,gt,"m",Xo).call(this)}[(vr=new WeakMap,Je=new WeakMap,_r=new WeakMap,gt=new WeakSet,Vo=function(){this.ended||mt(this,Je,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)},o=ze(this,gt,"m",Ko).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const i=o.output[t.output_index];if(!i)throw new Y(`missing output at index ${t.output_index}`);if(i.type==="message"){const l=i.content[t.content_index];if(!l)throw new Y(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new Y(`expected content to be 'output_text', got ${l.type}`);s("response.output_text.delta",{...t,snapshot:l.text})}break}case"response.function_call_arguments.delta":{const i=o.output[t.output_index];if(!i)throw new Y(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},Xo=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");const t=ze(this,Je,"f");if(!t)throw new Y("request ended without sending any events");mt(this,Je,void 0,"f");const n=Vd(t,ze(this,vr,"f"));return mt(this,_r,n,"f"),n},Ko=function(t){let n=ze(this,Je,"f");if(!n){if(t.type!=="response.created")throw new Y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=mt(this,Je,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{const s=n.output[t.output_index];if(!s)throw new Y(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{const s=n.output[t.output_index];if(!s)throw new Y(`missing output at index ${t.output_index}`);if(s.type==="message"){const o=s.content[t.content_index];if(!o)throw new Y(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new Y(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{const s=n.output[t.output_index];if(!s)throw new Y(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{mt(this,Je,t.response,"f");break}}return n},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>t.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=ze(this,_r,"f");if(!e)throw new Y("stream ended without producing a ChatCompletion");return e}}function Vd(r,e){return Bd(r,e)}class Ys extends Q{constructor(){super(...arguments),this.inputItems=new el(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"&&Zi(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=>Qi(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 Gd extends fe{}Ys.InputItems=el;class tl extends Q{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,lt({body:t,...n}))}}class Qs extends Q{constructor(){super(...arguments),this.parts=new tl(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=tl;const Xd=async r=>{const e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length){for(const s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const n=[];for(const s of e)s.status==="fulfilled"&&n.push(s.value);return n};class cn extends Q{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return ie(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,dn,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const o=await this.retrieve(e,t,{...n,headers:s}).withResponse(),i=o.data;switch(i.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const c=o.response.headers.get("openai-poll-after-ms");if(c){const d=parseInt(c);isNaN(d)||(l=d)}}await er(l);break;case"failed":case"completed":return i}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Zs,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class dn extends fe{}class Zs extends tn{}cn.VectorStoreFilesPage=dn;cn.FileContentResponsesPage=Zs;class rl extends Q{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return ie(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,dn,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:o,response:i}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(o.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{const c=i.headers.get("openai-poll-after-ms");if(c){const d=parseInt(c);isNaN(d)||(l=d)}}await er(l);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const o=(s==null?void 0:s.maxConcurrency)??5,i=Math.min(o,t.length),l=this._client,c=t.values(),d=[...n];async function m(p){for(let y of p){const h=await l.files.create({file:y,purpose:"assistants"},s);d.push(h.id)}}const f=Array(i).fill(c).map(m);return await Xd(f),await this.createAndPoll(e,{file_ids:d})}}class Qe extends Q{constructor(){super(...arguments),this.files=new cn(this._client),this.fileBatches=new rl(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",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 fe{}class to extends tn{}Qe.VectorStoresPage=eo;Qe.VectorStoreSearchResponsesPage=to;Qe.Files=cn;Qe.VectorStoreFilesPage=dn;Qe.FileContentResponsesPage=Zs;Qe.FileBatches=rl;var nl;class Z extends pd{constructor({baseURL:e=pr("OPENAI_BASE_URL"),apiKey:t=pr("OPENAI_API_KEY"),organization:n=pr("OPENAI_ORG_ID")??null,project:s=pr("OPENAI_PROJECT_ID")??null,...o}={}){if(t===void 0)throw new Y("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const i={apiKey:t,organization:n,project:s,...o,baseURL:e||"https://api.openai.com/v1"};if(!i.dangerouslyAllowBrowser&&Ad())throw new Y(`It looks like you're running in a browser-like environment.
33
+ */var Io;function Dc(){return Io||(Io=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=T,t=za(),n=typeof Object.is=="function"?Object.is:r,s=t.useSyncExternalStore,a=e.useRef,i=e.useEffect,l=e.useMemo,d=e.useDebugValue;On.useSyncExternalStoreWithSelector=function(u,g,h,x,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 p(j){if(!y){if(y=!0,b=j,j=x(j),w!==void 0&&f.hasValue){var v=f.value;if(w(v,j))return S=v}return S=j}if(v=S,n(b,j))return v;var I=x(j);return w!==void 0&&w(v,I)?(b=j,v):(b=j,S=I)}var y=!1,b,S,_=h===void 0?null:h;return[function(){return p(g())},_===null?void 0:function(){return p(_())}]},[g,h,x,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())}()),On}process.env.NODE_ENV==="production"?Zn.exports=$c():Zn.exports=Dc();var Fc=Zn.exports;const Uc=Oc(Fc),qa={},{useDebugValue:Bc}=T,{useSyncExternalStoreWithSelector:Wc}=Uc;let To=!1;const Hc=r=>r;function zc(r,e=Hc,t){(qa?"production":void 0)!=="production"&&t&&!To&&(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"),To=!0);const n=Wc(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return Bc(n),n}const qc=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"?Tc(r):r,t=(n,s)=>zc(e,n,s);return Object.assign(t,e),t},Jc=r=>qc;var Ja=Symbol.for("immer-nothing"),Oo=Symbol.for("immer-draftable"),De=Symbol.for("immer-state"),Vc=process.env.NODE_ENV!=="production"?[function(r){return`The plugin for '${r}' has not been loaded into Immer. To enable the plugin, import and call \`enable${r}()\` when initializing your application.`},function(r){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${r}'`},"This object has been frozen and should not be mutated",function(r){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+r},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(r){return`'current' expects a draft, got: ${r}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(r){return`'original' expects a draft, got: ${r}`}]:[];function Pe(r,...e){if(process.env.NODE_ENV!=="production"){const t=Vc[r],n=typeof t=="function"?t.apply(null,e):t;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${r}. Full error at: https://bit.ly/3cXEKWf`)}var Ot=Object.getPrototypeOf;function Rt(r){return!!r&&!!r[De]}function xt(r){var e;return r?Va(r)||Array.isArray(r)||!!r[Oo]||!!((e=r.constructor)!=null&&e[Oo])||dr(r)||an(r):!1}var Xc=Object.prototype.constructor.toString();function Va(r){if(!r||typeof r!="object")return!1;const e=Ot(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)===Xc}function Xr(r,e){on(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function on(r){const e=r[De];return e?e.type_:Array.isArray(r)?1:dr(r)?2:an(r)?3:0}function es(r,e){return on(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function Xa(r,e,t){const n=on(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function Gc(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function dr(r){return r instanceof Map}function an(r){return r instanceof Set}function dt(r){return r.copy_||r.base_}function ts(r,e){if(dr(r))return new Map(r);if(an(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);const t=Va(r);if(e===!0||e==="class_only"&&!t){const n=Object.getOwnPropertyDescriptors(r);delete n[De];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(Ot(r),n)}else{const n=Ot(r);if(n!==null&&t)return{...r};const s=Object.create(n);return Object.assign(s,r)}}function Ns(r,e=!1){return ln(r)||Rt(r)||!xt(r)||(on(r)>1&&Object.defineProperties(r,{set:{value:Cr},add:{value:Cr},clear:{value:Cr},delete:{value:Cr}}),Object.freeze(r),e&&Object.values(r).forEach(t=>Ns(t,!0))),r}function Cr(){Pe(2)}function ln(r){return Object.isFrozen(r)}var Yc={};function yt(r){const e=Yc[r];return e||Pe(0,r),e}var nr;function Ga(){return nr}function Kc(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function Ro(r,e){e&&(yt("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function rs(r){ns(r),r.drafts_.forEach(Qc),r.drafts_=null}function ns(r){r===nr&&(nr=r.parent_)}function Lo(r){return nr=Kc(nr,r)}function Qc(r){const e=r[De];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function $o(r,e){e.unfinalizedDrafts_=e.drafts_.length;const t=e.drafts_[0];return r!==void 0&&r!==t?(t[De].modified_&&(rs(e),Pe(4)),xt(r)&&(r=Gr(e,r),e.parent_||Yr(e,r)),e.patches_&&yt("Patches").generateReplacementPatches_(t[De].base_,r,e.patches_,e.inversePatches_)):r=Gr(e,t,[]),rs(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==Ja?r:void 0}function Gr(r,e,t){if(ln(e))return e;const n=e[De];if(!n)return Xr(e,(s,a)=>Do(r,n,e,s,a,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return Yr(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),Xr(a,(l,d)=>Do(r,n,s,l,d,t,i)),Yr(r,s,!1),t&&r.patches_&&yt("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function Do(r,e,t,n,s,a,i){if(process.env.NODE_ENV!=="production"&&s===t&&Pe(5),Rt(s)){const l=a&&e&&e.type_!==3&&!es(e.assigned_,n)?a.concat(n):void 0,d=Gr(r,s,l);if(Xa(t,n,d),Rt(d))r.canAutoFreeze_=!1;else return}else i&&t.add(s);if(xt(s)&&!ln(s)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;Gr(r,s),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&(dr(t)?t.has(n):Object.prototype.propertyIsEnumerable.call(t,n))&&Yr(r,s)}}function Yr(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&Ns(e,t)}function Zc(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=ks;t&&(s=[n],a=sr);const{revoke:i,proxy:l}=Proxy.revocable(s,a);return n.draft_=l,n.revoke_=i,l}var ks={get(r,e){if(e===De)return r;const t=dt(r);if(!es(t,e))return ed(r,t,e);const n=t[e];return r.finalized_||!xt(n)?n:n===Rn(r.base_,e)?(Ln(r),r.copy_[e]=os(n,r)):n},has(r,e){return e in dt(r)},ownKeys(r){return Reflect.ownKeys(dt(r))},set(r,e,t){const n=Ya(dt(r),e);if(n!=null&&n.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){const s=Rn(dt(r),e),a=s==null?void 0:s[De];if(a&&a.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(Gc(t,s)&&(t!==void 0||es(r.base_,e)))return!0;Ln(r),ss(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 Rn(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,Ln(r),ss(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){const t=dt(r),n=Reflect.getOwnPropertyDescriptor(t,e);return n&&{writable:!0,configurable:r.type_!==1||e!=="length",enumerable:n.enumerable,value:t[e]}},defineProperty(){Pe(11)},getPrototypeOf(r){return Ot(r.base_)},setPrototypeOf(){Pe(12)}},sr={};Xr(ks,(r,e)=>{sr[r]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});sr.deleteProperty=function(r,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&Pe(13),sr.set.call(this,r,e,void 0)};sr.set=function(r,e,t){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&Pe(14),ks.set.call(this,r[0],e,t,r[0])};function Rn(r,e){const t=r[De];return(t?dt(t):r)[e]}function ed(r,e,t){var s;const n=Ya(e,t);return n?"value"in n?n.value:(s=n.get)==null?void 0:s.call(r.draft_):void 0}function Ya(r,e){if(!(e in r))return;let t=Ot(r);for(;t;){const n=Object.getOwnPropertyDescriptor(t,e);if(n)return n;t=Ot(t)}}function ss(r){r.modified_||(r.modified_=!0,r.parent_&&ss(r.parent_))}function Ln(r){r.copy_||(r.copy_=ts(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var td=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"&&Pe(6),n!==void 0&&typeof n!="function"&&Pe(7);let s;if(xt(e)){const a=Lo(this),i=os(e,void 0);let l=!0;try{s=t(i),l=!1}finally{l?rs(a):ns(a)}return Ro(a,n),$o(s,a)}else if(!e||typeof e!="object"){if(s=t(e),s===void 0&&(s=e),s===Ja&&(s=void 0),this.autoFreeze_&&Ns(s,!0),n){const a=[],i=[];yt("Patches").generateReplacementPatches_(e,s,a,i),n(a,i)}return s}else Pe(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){xt(r)||Pe(8),Rt(r)&&(r=rd(r));const e=Lo(this),t=os(r,void 0);return t[De].isManual_=!0,ns(e),t}finishDraft(r,e){const t=r&&r[De];(!t||!t.isManual_)&&Pe(9);const{scope_:n}=t;return Ro(n,e),$o(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=yt("Patches").applyPatches_;return Rt(r)?n(r,e):this.produce(r,s=>n(s,e))}};function os(r,e){const t=dr(r)?yt("MapSet").proxyMap_(r,e):an(r)?yt("MapSet").proxySet_(r,e):Zc(r,e);return(e?e.scope_:Ga()).drafts_.push(t),t}function rd(r){return Rt(r)||Pe(10,r),Ka(r)}function Ka(r){if(!xt(r)||ln(r))return r;const e=r[De];let t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=ts(r,e.scope_.immer_.useStrictShallowCopy_)}else t=ts(r,!0);return Xr(t,(n,s)=>{Xa(t,n,Ka(s))}),e&&(e.finalized_=!1),t}var nd=new td,sd=nd.produce;const od=r=>(e,t,n)=>(n.setState=(s,a,...i)=>{const l=typeof s=="function"?sd(s):s;return e(l,a,...i)},r(n.setState,t,n)),ad=od,id={};function ld(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 or=r=>e=>{try{const t=r(e);return t instanceof Promise?t:{then(n){return or(n)(t)},catch(n){return this}}}catch(t){return{then(n){return this},catch(n){return or(n)(t)}}}},cd=(r,e)=>(t,n,s)=>{let a={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:c=>c,version:0,merge:(c,p)=>({...p,...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=or(a.serialize),h=()=>{const c=a.partialize({...n()});let p;const y=g({state:c,version:a.version}).then(b=>u.setItem(a.name,b)).catch(b=>{p=b});if(p)throw p;return y},x=s.setState;s.setState=(c,p)=>{x(c,p),h()};const w=r((...c)=>{t(...c),h()},n,s);let m;const f=()=>{var c;if(!u)return;i=!1,l.forEach(y=>y(n()));const p=((c=a.onRehydrateStorage)==null?void 0:c.call(a,n()))||void 0;return or(u.getItem.bind(u))(a.name).then(y=>{if(y)return a.deserialize(y)}).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==a.version){if(a.migrate)return a.migrate(y.state,y.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return y.state}).then(y=>{var b;return m=a.merge(y,(b=n())!=null?b:w),t(m,!0),h()}).then(()=>{p==null||p(m,void 0),i=!0,d.forEach(y=>y(m))}).catch(y=>{p==null||p(void 0,y)})};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},dd=(r,e)=>(t,n,s)=>{let a={storage:ld(()=>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 x=r((...f)=>{t(...f),g()},n,s);s.getInitialState=()=>x;let w;const m=()=>{var f,c;if(!u)return;i=!1,l.forEach(y=>{var b;return y((b=n())!=null?b:x)});const p=((c=a.onRehydrateStorage)==null?void 0:c.call(a,(f=n())!=null?f:x))||void 0;return or(u.getItem.bind(u))(a.name).then(y=>{if(y)if(typeof y.version=="number"&&y.version!==a.version){if(a.migrate)return[!0,a.migrate(y.state,y.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,y.state];return[!1,void 0]}).then(y=>{var b;const[S,_]=y;if(w=a.merge(_,(b=n())!=null?b:x),t(w,!0),S)return g()}).then(()=>{p==null||p(w,void 0),w=n(),i=!0,d.forEach(y=>y(w))}).catch(y=>{p==null||p(void 0,y)})};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||x},ud=(r,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((id?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),cd(r,e)):dd(r,e),fd=ud;function te(){try{return typeof window<"u"&&!!window.chatAPI&&typeof window.chatAPI.startStream=="function"&&typeof window.chatAPI.onStream=="function"&&typeof window.chatAPI.stopStream=="function"}catch{return!1}}function hd(r){try{if(!r||typeof r!="object")return`data: ${JSON.stringify({type:"error",data:{error:"invalid_event"}})}
34
+
35
+ `;let t={type:r.type||"chunk"};return r.content!==void 0&&(t.content=r.content),r.data!==void 0&&(t.data=r.data),r.result!==void 0&&(t.result=r.result),r.error!==void 0&&(t={type:"error",data:{error:String(r.error)}}),`data: ${JSON.stringify(t)}
36
+
37
+ `}catch{return`data: ${JSON.stringify({type:"error",data:{error:"serialize_failed"}})}
38
+
39
+ `}}function Qa(r,e){const t=window.chatAPI,n=new TextEncoder;return new ReadableStream({start(s){let a=null;try{a=t.onStream(r,i=>{try{const l=hd(i);s.enqueue(n.encode(l));const d=i&&i.type||"";(d==="complete"||d==="cancelled"||d==="error")&&(s.enqueue(n.encode(`data: [DONE]
40
+
41
+ `)),a&&a(),s.close())}catch{s.enqueue(n.encode(`data: ${JSON.stringify({type:"error",data:{error:"ipc_stream_failed"}})}
42
+
43
+ `)),s.enqueue(n.encode(`data: [DONE]
44
+
45
+ `)),a&&a(),s.close()}}),Promise.resolve(t.startStream(e)).catch(i=>{s.enqueue(n.encode(`data: ${JSON.stringify({type:"error",data:{error:String((i==null?void 0:i.message)||i)}})}
46
+
47
+ `)),s.enqueue(n.encode(`data: [DONE]
48
+
49
+ `)),a&&a(),s.close()})}catch(i){s.enqueue(n.encode(`data: ${JSON.stringify({type:"error",data:{error:String((i==null?void 0:i.message)||i)}})}
50
+
51
+ `)),s.enqueue(n.encode(`data: [DONE]
52
+
53
+ `)),a&&a(),s.close()}},cancel(){}})}function Za(r,e,t,n,s){const a={session_id:r,content:e,user_id:n,attachments:s||[],ai_model_config:{model_name:t==null?void 0:t.model_name,temperature:(t==null?void 0:t.temperature)??.7,use_tools:!0,api_key:t==null?void 0:t.api_key,base_url:t==null?void 0:t.base_url}};return Qa(r,a)}function ei(r,e,t,n,s){return Qa(r,{session_id:r,content:e,agent_id:t,user_id:n,attachments:s||[]})}async function ti(r){try{const e=window.chatAPI;e&&typeof e.stopStream=="function"&&await e.stopStream(r)}catch{}}async function ri(r,e){const t=window.chatAPI;if(t!=null&&t.listSessions)return t.listSessions({user_id:r,project_id:e});throw new Error("IPC listSessions not available")}async function ni(r){const e=window.chatAPI;if(e!=null&&e.createSession)return e.createSession(r);throw new Error("IPC createSession not available")}async function si(r){const e=window.chatAPI;if(e!=null&&e.getSession)return e.getSession(r);throw new Error("IPC getSession not available")}async function oi(r){const e=window.chatAPI;if(e!=null&&e.deleteSession)return e.deleteSession(r);throw new Error("IPC deleteSession not available")}async function ai(r,e){const t=window.chatAPI;if(t!=null&&t.getSessionMessages)return t.getSessionMessages(r,e||{});throw new Error("IPC getSessionMessages not available")}async function ii(r){const e=window.chatAPI;if(e!=null&&e.createMessage)return e.createMessage(r);throw new Error("IPC createMessage not available")}async function li(r){const e=window.chatAPI;if(e!=null&&e.getUserSettings)return e.getUserSettings(r);throw new Error("IPC getUserSettings not available")}async function ci(r,e){const t=window.chatAPI;if(t!=null&&t.updateUserSettings)return t.updateUserSettings(r,e);throw new Error("IPC updateUserSettings not available")}async function md(r){const e=window.chatAPI;if(e!=null&&e.getMcpConfigs)return e.getMcpConfigs(r);throw new Error("IPC getMcpConfigs not available")}async function gd(r){const e=window.chatAPI;if(e!=null&&e.createMcpConfig)return e.createMcpConfig(r);throw new Error("IPC createMcpConfig not available")}async function pd(r,e){const t=window.chatAPI;if(t!=null&&t.updateMcpConfig)return t.updateMcpConfig(r,e);throw new Error("IPC updateMcpConfig not available")}async function xd(r){const e=window.chatAPI;if(e!=null&&e.deleteMcpConfig)return e.deleteMcpConfig(r);throw new Error("IPC deleteMcpConfig not available")}async function yd(r){const e=window.chatAPI;if(e!=null&&e.getMcpConfigResource)return e.getMcpConfigResource(r);throw new Error("IPC getMcpConfigResource not available")}async function bd(r){const e=window.chatAPI;if(e!=null&&e.getMcpConfigResourceByCommand)return e.getMcpConfigResourceByCommand(r);throw new Error("IPC getMcpConfigResourceByCommand not available")}async function wd(r){const e=window.chatAPI;if(e!=null&&e.getMcpConfigProfiles)return e.getMcpConfigProfiles(r);throw new Error("IPC getMcpConfigProfiles not available")}async function vd(r,e){const t=window.chatAPI;if(t!=null&&t.createMcpConfigProfile)return t.createMcpConfigProfile(r,e);throw new Error("IPC createMcpConfigProfile not available")}async function _d(r,e,t){const n=window.chatAPI;if(n!=null&&n.updateMcpConfigProfile)return n.updateMcpConfigProfile(r,e,t);throw new Error("IPC updateMcpConfigProfile not available")}async function Sd(r,e){const t=window.chatAPI;if(t!=null&&t.deleteMcpConfigProfile)return t.deleteMcpConfigProfile(r,e);throw new Error("IPC deleteMcpConfigProfile not available")}async function Cd(r,e){const t=window.chatAPI;if(t!=null&&t.activateMcpConfigProfile)return t.activateMcpConfigProfile(r,e);throw new Error("IPC activateMcpConfigProfile not available")}async function jd(r){const e=window.chatAPI;if(e!=null&&e.getAiModelConfigs)return e.getAiModelConfigs(r);throw new Error("IPC getAiModelConfigs not available")}async function Ad(r){const e=window.chatAPI;if(e!=null&&e.createAiModelConfig)return e.createAiModelConfig(r);throw new Error("IPC createAiModelConfig not available")}async function Nd(r,e){const t=window.chatAPI;if(t!=null&&t.updateAiModelConfig)return t.updateAiModelConfig(r,e);throw new Error("IPC updateAiModelConfig not available")}async function kd(r){const e=window.chatAPI;if(e!=null&&e.deleteAiModelConfig)return e.deleteAiModelConfig(r);throw new Error("IPC deleteAiModelConfig not available")}async function Md(r){const e=window.chatAPI;if(e!=null&&e.getSystemContexts)return e.getSystemContexts(r);throw new Error("IPC getSystemContexts not available")}async function Ed(r){const e=window.chatAPI;if(e!=null&&e.getActiveSystemContext)return e.getActiveSystemContext(r);throw new Error("IPC getActiveSystemContext not available")}async function Pd(r){const e=window.chatAPI;if(e!=null&&e.createSystemContext)return e.createSystemContext(r);throw new Error("IPC createSystemContext not available")}async function Id(r,e){const t=window.chatAPI;if(t!=null&&t.updateSystemContext)return t.updateSystemContext(r,e);throw new Error("IPC updateSystemContext not available")}async function Td(r){const e=window.chatAPI;if(e!=null&&e.deleteSystemContext)return e.deleteSystemContext(r);throw new Error("IPC deleteSystemContext not available")}async function Od(r,e){const t=window.chatAPI;if(t!=null&&t.activateSystemContext)return t.activateSystemContext(r,e);throw new Error("IPC activateSystemContext not available")}async function Rd(r){const e=window.chatAPI;if(e!=null&&e.getAgents)return e.getAgents(r);throw new Error("IPC getAgents not available")}async function Ld(r){const e=window.chatAPI;if(e!=null&&e.createAgent)return e.createAgent(r);throw new Error("IPC createAgent not available")}async function $d(r,e){const t=window.chatAPI;if(t!=null&&t.updateAgent)return t.updateAgent(r,e);throw new Error("IPC updateAgent not available")}async function Dd(r){const e=window.chatAPI;if(e!=null&&e.deleteAgent)return e.deleteAgent(r);throw new Error("IPC deleteAgent not available")}async function Fd(r){const e=window.chatAPI;if(e!=null&&e.getApplications)return e.getApplications(r);throw new Error("IPC getApplications not available")}async function Ud(r){const e=window.chatAPI;if(e!=null&&e.getApplication)return e.getApplication(r);throw new Error("IPC getApplication not available")}async function Bd(r){const e=window.chatAPI;if(e!=null&&e.createApplication)return e.createApplication(r);throw new Error("IPC createApplication not available")}async function Wd(r,e){const t=window.chatAPI;if(t!=null&&t.updateApplication)return t.updateApplication(r,e);throw new Error("IPC updateApplication not available")}async function Hd(r){const e=window.chatAPI;if(e!=null&&e.deleteApplication)return e.deleteApplication(r);throw new Error("IPC deleteApplication not available")}const ce=Object.freeze(Object.defineProperty({__proto__:null,activateMcpConfigProfileIPC:Cd,activateSystemContextIPC:Od,createAgentIPC:Ld,createAiModelConfigIPC:Ad,createApplicationIPC:Bd,createMcpConfigIPC:gd,createMcpConfigProfileIPC:vd,createMessageIPC:ii,createSessionIPC:ni,createSystemContextIPC:Pd,deleteAgentIPC:Dd,deleteAiModelConfigIPC:kd,deleteApplicationIPC:Hd,deleteMcpConfigIPC:xd,deleteMcpConfigProfileIPC:Sd,deleteSessionIPC:oi,deleteSystemContextIPC:Td,getActiveSystemContextIPC:Ed,getAgentsIPC:Rd,getAiModelConfigsIPC:jd,getApplicationIPC:Ud,getApplicationsIPC:Fd,getMcpConfigProfilesIPC:wd,getMcpConfigResourceByCommandIPC:bd,getMcpConfigResourceIPC:yd,getMcpConfigsIPC:md,getSessionIPC:si,getSessionMessagesIPC:ai,getSystemContextsIPC:Md,getUserSettingsIPC:li,ipcAvailable:te,listSessionsIPC:ri,stopChatIPC:ti,streamAgentChatIPC:ei,streamChatIPC:Za,updateAgentIPC:$d,updateAiModelConfigIPC:Nd,updateApplicationIPC:Wd,updateMcpConfigIPC:pd,updateMcpConfigProfileIPC:_d,updateSystemContextIPC:Id,updateUserSettingsIPC:ci},Symbol.toStringTag,{value:"Module"})),zd="/api";class ar{constructor(e=zd){q(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){if(te())return ri(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),te()?ni(e):this.request("/sessions",{method:"POST",body:JSON.stringify(e)})}async getSession(e){return te()?si(e):this.request(`/sessions/${e}`)}async deleteSession(e){return te()?oi(e):this.request(`/sessions/${e}`,{method:"DELETE"})}async getSessionMessages(e,t){if(te())return ai(e,t);const n=[];(t==null?void 0:t.limit)!==void 0&&n.push(`limit=${encodeURIComponent(String(t.limit))}`),(t==null?void 0:t.offset)!==void 0&&n.push(`offset=${encodeURIComponent(String(t.offset))}`);const s=n.length?`?${n.join("&")}`:"";return this.request(`/sessions/${e}/messages${s}`)}async createMessage(e){const t={...e,createdAt:e.createdAt?e.createdAt.toISOString():void 0};if(te()){const n={sessionId:e.sessionId,role:e.role,content:e.content,toolCalls:e.toolCalls,toolCallId:e.toolCallId,reasoning:e.reasoning,metadata:e.metadata};return ii(n)}return this.request(`/sessions/${e.sessionId}/messages`,{method:"POST",body:JSON.stringify(t)})}async getMcpConfigs(e){if(te()){const{getMcpConfigsIPC:n}=await Promise.resolve().then(()=>ce);return n(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){if(console.log("🔍 API client createMcpConfig 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),te()){const{createMcpConfigIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request("/mcp-configs",{method:"POST",body:JSON.stringify(e)})}async updateMcpConfig(e,t){if(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)),te()){const{updateMcpConfigIPC:n}=await Promise.resolve().then(()=>ce);return n(e,t)}return this.request(`/mcp-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteMcpConfig(e){if(te()){const{deleteMcpConfigIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request(`/mcp-configs/${e}`,{method:"DELETE"})}async getAiModelConfigs(e){if(te()){const{getAiModelConfigsIPC:n}=await Promise.resolve().then(()=>ce);return n(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){if(te()){const{createAiModelConfigIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request("/ai-model-configs",{method:"POST",body:JSON.stringify(e)})}async updateAiModelConfig(e,t){if(te()){const{updateAiModelConfigIPC:n}=await Promise.resolve().then(()=>ce);return n(e,t)}return this.request(`/ai-model-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteAiModelConfig(e){if(te()){const{deleteAiModelConfigIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request(`/ai-model-configs/${e}`,{method:"DELETE"})}async getSystemContexts(e){if(te()){const{getSystemContextsIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request(`/system-contexts?user_id=${e}`)}async getActiveSystemContext(e){if(te()){const{getActiveSystemContextIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request(`/system-context/active?user_id=${e}`)}async createSystemContext(e){if(console.log("🔍 API client createSystemContext 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),te()){const{createSystemContextIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request("/system-contexts",{method:"POST",body:JSON.stringify(e)})}async updateSystemContext(e,t){if(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)),te()){const{updateSystemContextIPC:n}=await Promise.resolve().then(()=>ce);return n(e,t)}return this.request(`/system-contexts/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteSystemContext(e){if(te()){const{deleteSystemContextIPC:t}=await Promise.resolve().then(()=>ce);await t(e);return}return this.request(`/system-contexts/${e}`,{method:"DELETE"})}async activateSystemContext(e,t){if(te()){const{activateSystemContextIPC:n}=await Promise.resolve().then(()=>ce);return n(e,t)}return this.request(`/system-contexts/${e}/activate`,{method:"POST",body:JSON.stringify({user_id:t,is_active:!0})})}async getApplications(e){if(te()){const{getApplicationsIPC:n}=await Promise.resolve().then(()=>ce);return n(e)}const t=e?`?user_id=${encodeURIComponent(e)}`:"";return this.request(`/applications${t}`)}async getApplication(e){if(te()){const{getApplicationIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request(`/applications/${e}`)}async createApplication(e){if(te()){const{createApplicationIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request("/applications",{method:"POST",body:JSON.stringify(e)})}async updateApplication(e,t){if(te()){const{updateApplicationIPC:n}=await Promise.resolve().then(()=>ce);return n(e,t)}return this.request(`/applications/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteApplication(e){if(te()){const{deleteApplicationIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request(`/applications/${e}`,{method:"DELETE"})}async getAgents(e){if(te()){const{getAgentsIPC:n}=await Promise.resolve().then(()=>ce);return n(e)}const t=e?`?user_id=${encodeURIComponent(e)}`:"";return this.request(`/agents${t}`)}async createAgent(e){if(console.log("🔍 API client createAgent 调用:",e),console.log("🔍 [关键] app_ids 字段:",e.app_ids,"类型:",typeof e.app_ids,"是否为数组:",Array.isArray(e.app_ids)),te()){const{createAgentIPC:t}=await Promise.resolve().then(()=>ce);return t(e)}return this.request("/agents",{method:"POST",body:JSON.stringify(e)})}async updateAgent(e,t){if(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)),te()){const{updateAgentIPC:n}=await Promise.resolve().then(()=>ce);return n(e,t)}return this.request(`/agents/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteAgent(e){if(te()){const{deleteAgentIPC:t}=await Promise.resolve().then(()=>ce);return t(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,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,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{if(te()){const{getMcpConfigResourceIPC:n}=await Promise.resolve().then(()=>ce);return await n(e)}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{if(te()){const{getMcpConfigResourceByCommandIPC:n}=await Promise.resolve().then(()=>ce);return await n(e)}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){if(te()){const{getMcpConfigProfilesIPC:n}=await Promise.resolve().then(()=>ce),s=await n(e);return s&&typeof s=="object"&&Array.isArray(s.items)?s.items:Array.isArray(s)?s:[]}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){if(te()){const{createMcpConfigProfileIPC:n}=await Promise.resolve().then(()=>ce);return n(e,t)}return this.request(`/mcp-configs/${e}/profiles`,{method:"POST",body:JSON.stringify(t)})}async updateMcpConfigProfile(e,t,n){if(te()){const{updateMcpConfigProfileIPC:s}=await Promise.resolve().then(()=>ce);return s(e,t,n)}return this.request(`/mcp-configs/${e}/profiles/${t}`,{method:"PUT",body:JSON.stringify(n)})}async deleteMcpConfigProfile(e,t){if(te()){const{deleteMcpConfigProfileIPC:n}=await Promise.resolve().then(()=>ce);return n(e,t)}return this.request(`/mcp-configs/${e}/profiles/${t}`,{method:"DELETE"})}async activateMcpConfigProfile(e,t){if(te()){const{activateMcpConfigProfileIPC:n}=await Promise.resolve().then(()=>ce);return n(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,a){if(te())return Za(e,t,n,s,a);const i=`${this.baseUrl}/agent_v2/chat/stream`,l=await fetch(i,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:e,content:t,user_id:s,attachments:a||[],ai_model_config:{model_name:n.model_name,temperature:n.temperature||.7,api_key:n.api_key,base_url:n.base_url}})});if(!l.ok)throw new Error(`HTTP error! status: ${l.status}`);if(!l.body)throw new Error("Response body is null");return l.body}async streamAgentChat(e,t,n,s,a){if(te())return ei(e,t,n,s,a);const i=`${this.baseUrl}/agents/chat/stream`,l=await fetch(i,{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,attachments:a||[]})});if(!l.ok)throw new Error(`HTTP error! status: ${l.status}`);if(!l.body)throw new Error("Response body is null");return l.body}async stopChat(e){return te()?(await ti(e),{ok:!0}):this.request("/chat/stop",{method:"POST",body:JSON.stringify({session_id:e})})}async getUserSettings(e){if(te())return li(e);const t=e?`?user_id=${encodeURIComponent(e)}`:"";return this.request(`/user-settings${t}`)}async updateUserSettings(e,t){return te()?ci(e,t):this.request("/user-settings",{method:"PUT",body:JSON.stringify({user_id:e,settings:t})})}}const ie=new ar,$r={getDetails:r=>ie.getConversationDetails(r),getAssistant:r=>ie.getAssistant(r),getMcpServers:r=>ie.getMcpServers(r),saveMessage:(r,e)=>ie.saveMessage(r,e),getMessages:(r,e)=>ie.getMessages(r,e),addMessage:(r,e)=>ie.addMessage(r,e)};class Ms{constructor(e,t,n=ie){q(this,"userId");q(this,"projectId");q(this,"client");this.userId=e,this.projectId=t,this.client=n}async createSession(e){const t={id:crypto.randomUUID(),title:e.title,user_id:this.userId,project_id:this.projectId},n=await this.client.createSession(t);return{id:n.id,title:n.title,createdAt:new Date(n.created_at),updatedAt:new Date(n.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}}async getSession(e){try{const t=await this.client.getSession(e);return t?{id:t.id,title:t.title,createdAt:new Date(t.created_at),updatedAt:new Date(t.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}:null}catch{return null}}async getAllSessions(){console.log("🔍 DatabaseService.getAllSessions 调用:",{userId:this.userId,projectId:this.projectId});const e=await this.client.getSessions(this.userId,this.projectId);console.log("🔍 API返回的会话数据:",e);const t=e.map(n=>({id:n.id,title:n.title,createdAt:new Date(n.created_at||n.createdAt),updatedAt:new Date(n.updated_at||n.updatedAt),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}));return console.log("🔍 格式化后的会话数据:",t),t}async updateSession(e,t){return console.warn("updateSession not implemented yet"),null}async deleteSession(e){try{return await this.client.deleteSession(e),!0}catch{return!1}}async createMessage(e){var 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,x,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(y){console.warn("Failed to parse message metadata:",y),c={}}let p;if(f.toolCalls)try{p=typeof f.toolCalls=="string"?JSON.parse(f.toolCalls):f.toolCalls}catch(y){console.warn("Failed to parse top-level toolCalls:",y)}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:p,createdAt:new Date(f.created_at),originalMessage:f}}),l=new Map;i.forEach(f=>{var c;if(f.role==="tool"&&f.toolCallId){const p=((c=f.metadata)==null?void 0:c.isError)||!1;l.set(f.toolCallId,{content:f.content,error:p?f.content:void 0})}});const d=i.map(f=>{var _,j;let c;const p=f.topLevelToolCalls||((_=f.metadata)==null?void 0:_.toolCalls);f.role==="assistant"&&p&&Array.isArray(p)&&(console.log("[Database] 处理工具调用:",{messageId:f.id,sourceToolCalls:p}),c=p.map(v=>{if(v.function){let I={};try{I=typeof v.function.arguments=="string"?JSON.parse(v.function.arguments):v.function.arguments}catch(O){console.warn("Failed to parse tool call arguments:",O),I={}}const M=l.get(v.id);return{id:v.id||`tool_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,messageId:f.id,name:v.function.name,arguments:I,result:(M==null?void 0:M.content)||void 0,error:(M==null?void 0:M.error)||void 0,createdAt:f.createdAt}}return null}).filter(Boolean));const y=[],b=typeof f.reasoning=="string"&&f.reasoning.trim().length>0;f.role==="assistant"&&b&&y.push({type:"thinking",content:f.reasoning}),typeof f.content=="string"&&f.content.trim().length>0&&y.push({type:"text",content:f.content}),c&&Array.isArray(c)&&c.length>0&&c.forEach(v=>{y.push({type:"tool_call",toolCallId:v.id})});let S;try{const v=f.metadata&&f.metadata.attachments||[];Array.isArray(v)&&v.length>0&&(S=v.map((I,M)=>{const O=I.mimeType||I.mime||"application/octet-stream",L=!!(I.preview||I.url),C=O.startsWith("image/")?"image":O.startsWith("audio/")?"audio":"file",H=L?I.type||C:C==="image"?"file":C;return{id:I.id||`${f.id}_att_${M}`,messageId:f.id,type:H,name:I.name||`attachment-${M+1}`,url:I.preview||I.url||"",size:I.size||0,mimeType:O,createdAt:f.createdAt}}))}catch{}return{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,...S?{attachments:S}:{},toolCalls:c,contentSegments:y.length>0?y:(j=f.metadata)==null?void 0:j.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 p=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 y=-1;for(let b=f+1;b<d.length;b++)if(((x=d[b])==null?void 0:x.role)==="assistant"){y=b;break}if(y===-1){for(let b=f-1;b>=0;b--)if(((w=d[b])==null?void 0:w.role)==="assistant"){y=b;break}}if(y!==-1){const b=d[y],S=`【上下文摘要】
54
+ `,_=(((m=b.metadata)==null?void 0:m.contentSegments)||[]).slice(),j=_.length-1;j>=0&&_[j].type==="thinking"&&String(_[j].content||"").startsWith(S)?_[j].content=S+String(p||""):_.push({type:"thinking",content:S+String(p||"")}),b.metadata=b.metadata||{},b.metadata.contentSegments=_,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 as="RFC3986",is={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},qd="RFC1738",Jd=Array.isArray,qe=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),$n=1024,Vd=(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+=$n){const d=a.length>=$n?a.slice(l,l+$n):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===qd&&(h===40||h===41)){u[u.length]=d.charAt(g);continue}if(h<128){u[u.length]=qe[h];continue}if(h<2048){u[u.length]=qe[192|h>>6]+qe[128|h&63];continue}if(h<55296||h>=57344){u[u.length]=qe[224|h>>12]+qe[128|h>>6&63]+qe[128|h&63];continue}g+=1,h=65536+((h&1023)<<10|d.charCodeAt(g)&1023),u[u.length]=qe[240|h>>18]+qe[128|h>>12&63]+qe[128|h>>6&63]+qe[128|h&63]}i+=u.join("")}return i};function Xd(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Fo(r,e){if(Jd(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const Gd=Object.prototype.hasOwnProperty,di={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},Ve=Array.isArray,Yd=Array.prototype.push,ui=function(r,e){Yd.apply(r,Ve(e)?e:[e])},Kd=Date.prototype.toISOString,ye={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Vd,encodeValuesOnly:!1,format:as,formatter:is[as],indices:!1,serializeDate(r){return Kd.call(r)},skipNulls:!1,strictNullHandling:!1};function Qd(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const Dn={};function fi(r,e,t,n,s,a,i,l,d,u,g,h,x,w,m,f,c,p){let y=r,b=p,S=0,_=!1;for(;(b=b.get(Dn))!==void 0&&!_;){const O=b.get(r);if(S+=1,typeof O<"u"){if(O===S)throw new RangeError("Cyclic object value");_=!0}typeof b.get(Dn)>"u"&&(S=0)}if(typeof u=="function"?y=u(e,y):y instanceof Date?y=x==null?void 0:x(y):t==="comma"&&Ve(y)&&(y=Fo(y,function(O){return O instanceof Date?x==null?void 0:x(O):O})),y===null){if(a)return d&&!f?d(e,ye.encoder,c,"key",w):e;y=""}if(Qd(y)||Xd(y)){if(d){const O=f?e:d(e,ye.encoder,c,"key",w);return[(m==null?void 0:m(O))+"="+(m==null?void 0:m(d(y,ye.encoder,c,"value",w)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(y)))]}const j=[];if(typeof y>"u")return j;let v;if(t==="comma"&&Ve(y))f&&d&&(y=Fo(y,d)),v=[{value:y.length>0?y.join(",")||null:void 0}];else if(Ve(u))v=u;else{const O=Object.keys(y);v=g?O.sort(g):O}const I=l?String(e).replace(/\./g,"%2E"):String(e),M=n&&Ve(y)&&y.length===1?I+"[]":I;if(s&&Ve(y)&&y.length===0)return M+"[]";for(let O=0;O<v.length;++O){const L=v[O],C=typeof L=="object"&&typeof L.value<"u"?L.value:y[L];if(i&&C===null)continue;const H=h&&l?L.replace(/\./g,"%2E"):L,D=Ve(y)?typeof t=="function"?t(M,H):M:M+(h?"."+H:"["+H+"]");p.set(r,S);const V=new WeakMap;V.set(Dn,p),ui(j,fi(C,D,t,n,s,a,i,l,t==="comma"&&f&&Ve(y)?null:d,u,g,h,x,w,m,f,c,V))}return j}function Zd(r=ye){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||ye.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=as;if(typeof r.format<"u"){if(!Gd.call(is,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=is[t];let s=ye.filter;(typeof r.filter=="function"||Ve(r.filter))&&(s=r.filter);let a;if(r.arrayFormat&&r.arrayFormat in di?a=r.arrayFormat:"indices"in r?a=r.indices?"indices":"repeat":a=ye.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:ye.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:ye.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:ye.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:ye.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?ye.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:ye.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:ye.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:ye.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:ye.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:ye.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:ye.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:ye.strictNullHandling}}function eu(r,e={}){let t=r;const n=Zd(e);let s,a;typeof n.filter=="function"?(a=n.filter,t=a("",t)):Ve(n.filter)&&(a=n.filter,s=a);const i=[];if(typeof t!="object"||t===null)return"";const l=di[n.arrayFormat],d=l==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const u=new WeakMap;for(let x=0;x<s.length;++x){const w=s[x];n.skipNulls&&t[w]===null||ui(i,fi(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 kt="4.104.0";let Uo=!1,tr,hi,mi,ls,gi,pi,xi,yi,bi;function tu(r,e={auto:!1}){if(Uo)throw new Error(`you must \`import 'openai/shims/${r.kind}'\` before importing anything else from openai`);if(tr)throw new Error(`can't \`import 'openai/shims/${r.kind}'\` after \`import 'openai/shims/${tr}'\``);Uo=e.auto,tr=r.kind,hi=r.fetch,mi=r.FormData,ls=r.File,gi=r.ReadableStream,pi=r.getMultipartRequestOptions,xi=r.getDefaultAgent,yi=r.fileFromPath,bi=r.isFsReadStream}class ru{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function nu({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 ru(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 wi=()=>{tr||tu(nu(),{auto:!0})};wi();class K extends Error{}class je extends K{constructor(e,t,n,s){super(`${je.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 cn({message:n,cause:ds(t)});const a=t==null?void 0:t.error;return e===400?new vi(e,a,n,s):e===401?new _i(e,a,n,s):e===403?new Si(e,a,n,s):e===404?new Ci(e,a,n,s):e===409?new ji(e,a,n,s):e===422?new Ai(e,a,n,s):e===429?new Ni(e,a,n,s):e>=500?new ki(e,a,n,s):new je(e,a,n,s)}}class Fe extends je{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class cn extends je{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Es extends cn{constructor({message:e}={}){super({message:e??"Request timed out."})}}class vi extends je{}class _i extends je{}class Si extends je{}class Ci extends je{}class ji extends je{}class Ai extends je{}class Ni extends je{}class ki extends je{}class Mi extends K{constructor(){super("Could not parse response content as the length limit was reached")}}class Ei extends K{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var jr=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},ct=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;class dn{constructor(){Le.set(this,void 0),this.buffer=new Uint8Array,jr(this,Le,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=su(this.buffer,ct(this,Le,"f")))!=null;){if(a.carriage&&ct(this,Le,"f")==null){jr(this,Le,a.index,"f");continue}if(ct(this,Le,"f")!=null&&(a.index!==ct(this,Le,"f")+1||a.carriage)){s.push(this.decodeText(this.buffer.slice(0,ct(this,Le,"f")-1))),this.buffer=this.buffer.slice(ct(this,Le,"f")),jr(this,Le,null,"f");continue}const i=ct(this,Le,"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),jr(this,Le,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 K(`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 K(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new K("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
55
+ `):[]}}Le=new WeakMap;dn.NEWLINE_CHARS=new Set([`
56
+ `,"\r"]);dn.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function su(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 ou(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 Pi(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 Ge{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 au(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 je(void 0,l.error,void 0,Di(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 je(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 Ge(s,t)}static fromReadableStream(e,t){let n=!1;async function*s(){const i=new dn,l=Pi(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 Ge(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 Ge(()=>s(e),this.controller),new Ge(()=>s(t),this.controller)]}toReadableStream(){const e=this;let t;const n=new TextEncoder;return new gi({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)+`
57
+ `);s.enqueue(l)}catch(a){s.error(a)}},async cancel(){var s;await((s=t.return)==null?void 0:s.call(t))}})}}async function*au(r,e){if(!r.body)throw e.abort(),new K("Attempted to iterate over a response with no body");const t=new lu,n=new dn,s=Pi(r.body);for await(const a of iu(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*iu(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=ou(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class lu{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(`
58
+ `),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]=cu(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function cu(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}const Ii=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Ti=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&un(r),un=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",du=r=>Ti(r)||Ii(r)||bi(r);async function Oi(r,e,t){var s;if(r=await r,Ti(r))return r;if(Ii(r)){const a=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");const i=un(a)?[await a.arrayBuffer()]:[a];return new ls(i,e,t)}const n=await uu(r);if(e||(e=hu(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 ls(n,e,t)}async function uu(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(un(r))e.push(await r.arrayBuffer());else if(mu(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: ${fu(r)}`);return e}function fu(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function hu(r){var e;return Fn(r.name)||Fn(r.filename)||((e=Fn(r.path))==null?void 0:e.split(/[\\/]/).pop())}const Fn=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},mu=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Bo=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody",bt=async r=>{const e=await gu(r.body);return pi(e,r)},gu=async r=>{const e=new mi;return await Promise.all(Object.entries(r||{}).map(([t,n])=>cs(e,t,n))),e},cs=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(du(t)){const n=await Oi(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>cs(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>cs(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 pu=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},xu=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)},Ar;wi();async function Ri(r){var i;const{response:e}=r;if(r.options.stream)return at("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):Ge.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 at("response",e.status,e.url,e.headers,l),Li(l,e)}const a=await e.text();return at("response",e.status,e.url,e.headers,a),a}function Li(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 fn extends Promise{constructor(e,t=Ri){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new fn(this.responsePromise,async t=>Li(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 yu{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:a}){this.baseURL=e,this.maxRetries=Un("maxRetries",t),this.timeout=Un("timeout",n),this.httpAgent=s,this.fetch=a??hi}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Su(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${Nu()}`}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&&un(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:Bo(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&&Un("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const h=n.httpAgent??this.httpAgent??xi(g),x=n.timeout+1e3;typeof((f=h==null?void 0:h.options)==null?void 0:f.timeout)=="number"&&x>(h.options.timeout??0)&&(h.options.timeout=x),this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),l[this.idempotencyHeader]=e.idempotencyKey);const w=this.buildHeaders({options:n,headers:l,contentLength:u,retryCount:t});return{req:{method:s,...d&&{body:d},headers:w,...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 qo(a,i),qo(a,t),Bo(e.body)&&tr!=="node"&&delete a["content-type"],kr(i,"x-stainless-retry-count")===void 0&&kr(t,"x-stainless-retry-count")===void 0&&(a["x-stainless-retry-count"]=String(s)),kr(i,"x-stainless-timeout")===void 0&&kr(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 je.generate(e,t,n,s)}request(e,t=null){return new fn(this.makeRequest(e,t))}async makeRequest(e,t){var h,x;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}),at("request",i,n,a.headers),(h=n.signal)!=null&&h.aborted)throw new Fe;const d=new AbortController,u=await this.fetchWithTimeout(i,a,l,d).catch(ds);if(u instanceof Error){if((x=n.signal)!=null&&x.aborted)throw new Fe;if(t)return this.retryRequest(n,t);throw u.name==="AbortError"?new Es:new cn({cause:u})}const g=Di(u.headers);if(!u.ok){if(t&&this.shouldRetry(u)){const y=`retrying, ${t} attempts remaining`;return at(`response (error; ${y})`,u.status,i,g),this.retryRequest(n,t,g)}const w=await u.text().catch(y=>ds(y).message),m=Cu(w),f=m?void 0:w;throw at(`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 bu(this,n,e)}buildURL(e,t){const n=Au(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Fi(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 K(`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 ur(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 ${kt}`}}class $i{constructor(e,t,n,s){Ar.set(this,void 0),pu(this,Ar,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 K("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 xu(this,Ar,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Ar=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class bu extends fn{constructor(e,t,n){super(t,async s=>new n(e,s.response,await Ri(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const Di=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),wu={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},ge=r=>typeof r=="object"&&r!==null&&!Fi(r)&&Object.keys(r).every(e=>Ui(wu,e)),vu=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kt,"X-Stainless-OS":Ho(Deno.build.os),"X-Stainless-Arch":Wo(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":kt,"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":kt,"X-Stainless-OS":Ho(process.platform),"X-Stainless-Arch":Wo(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const r=_u();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":kt,"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":kt,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function _u(){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 Wo=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",Ho=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 zo;const Su=()=>zo??(zo=vu()),Cu=r=>{try{return JSON.parse(r)}catch{return}},ju=/^[a-z][a-z0-9+.-]*:/i,Au=r=>ju.test(r),ur=r=>new Promise(e=>setTimeout(e,r)),Un=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new K(`${r} must be an integer`);if(e<0)throw new K(`${r} must be a positive integer`);return e},ds=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)},Nr=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 Fi(r){if(!r)return!0;for(const e in r)return!1;return!0}function Ui(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function qo(r,e){for(const t in e){if(!Ui(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 Jo=new Set(["authorization","api-key"]);function at(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)Jo.has(l.toLowerCase())&&(i.headers[l]="REDACTED");return i}let a=null;for(const i in s)Jo.has(i.toLowerCase())&&(a??(a={...s}),a[i]="REDACTED");return a??s});console.log(`OpenAI:DEBUG:${r}`,...n)}}const Nu=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),ku=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",Mu=r=>typeof(r==null?void 0:r.get)=="function",kr=(r,e)=>{var n;const t=e.toLowerCase();if(Mu(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},Eu=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 Bn(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}class hn extends $i{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 be extends $i{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){var n;const e=this.getPaginatedItems();if(!e.length)return null;const t=(n=e[e.length-1])==null?void 0:n.id;return t?{params:{after:t}}:null}}class Q{constructor(e){this._client=e}}let Bi=class extends Q{list(e,t={},n){return ge(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,Pu,{query:t,...n})}},mn=class extends Q{constructor(){super(...arguments),this.messages=new Bi(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return ge(e)?this.list({},e):this._client.getAPIList("/chat/completions",gn,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class gn extends be{}class Pu extends be{}mn.ChatCompletionsPage=gn;mn.Messages=Bi;let pn=class extends Q{constructor(){super(...arguments),this.completions=new mn(this._client)}};pn.Completions=mn;pn.ChatCompletionsPage=gn;class Wi extends Q{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t==null?void 0:t.headers},__binaryResponse:!0})}}class Hi extends Q{create(e,t){return this._client.post("/audio/transcriptions",bt({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class zi extends Q{create(e,t){return this._client.post("/audio/translations",bt({body:e,...t,__metadata:{model:e.model}}))}}class fr extends Q{constructor(){super(...arguments),this.transcriptions=new Hi(this._client),this.translations=new zi(this._client),this.speech=new Wi(this._client)}}fr.Transcriptions=Hi;fr.Translations=zi;fr.Speech=Wi;class Ps extends Q{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return ge(e)?this.list({},e):this._client.getAPIList("/batches",Is,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class Is extends be{}Ps.BatchesPage=Is;var Be=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=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)},us,Dr,Fr,Gt,Yt,Ur,Kt,Qe,Qt,Kr,Qr,Mt,qi;class Ts{constructor(){us.add(this),this.controller=new AbortController,Dr.set(this,void 0),Fr.set(this,()=>{}),Gt.set(this,()=>{}),Yt.set(this,void 0),Ur.set(this,()=>{}),Kt.set(this,()=>{}),Qe.set(this,{}),Qt.set(this,!1),Kr.set(this,!1),Qr.set(this,!1),Mt.set(this,!1),Be(this,Dr,new Promise((e,t)=>{Be(this,Fr,e,"f"),Be(this,Gt,t,"f")}),"f"),Be(this,Yt,new Promise((e,t)=>{Be(this,Ur,e,"f"),Be(this,Kt,t,"f")}),"f"),me(this,Dr,"f").catch(()=>{}),me(this,Yt,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},me(this,us,"m",qi).bind(this))},0)}_connected(){this.ended||(me(this,Fr,"f").call(this),this._emit("connect"))}get ended(){return me(this,Qt,"f")}get errored(){return me(this,Kr,"f")}get aborted(){return me(this,Qr,"f")}abort(){this.controller.abort()}on(e,t){return(me(this,Qe,"f")[e]||(me(this,Qe,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=me(this,Qe,"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(me(this,Qe,"f")[e]||(me(this,Qe,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{Be(this,Mt,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){Be(this,Mt,!0,"f"),await me(this,Yt,"f")}_emit(e,...t){if(me(this,Qt,"f"))return;e==="end"&&(Be(this,Qt,!0,"f"),me(this,Ur,"f").call(this));const n=me(this,Qe,"f")[e];if(n&&(me(this,Qe,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!me(this,Mt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),me(this,Gt,"f").call(this,s),me(this,Kt,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!me(this,Mt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),me(this,Gt,"f").call(this,s),me(this,Kt,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Dr=new WeakMap,Fr=new WeakMap,Gt=new WeakMap,Yt=new WeakMap,Ur=new WeakMap,Kt=new WeakMap,Qe=new WeakMap,Qt=new WeakMap,Kr=new WeakMap,Qr=new WeakMap,Mt=new WeakMap,us=new WeakSet,qi=function(e){if(Be(this,Kr,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new Fe),e instanceof Fe)return Be(this,Qr,!0,"f"),this._emit("abort",e);if(e instanceof K)return this._emit("error",e);if(e instanceof Error){const t=new K(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new K(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)},Re=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},Ce,fs,Xe,Br,We,ht,Et,ft,Zr,$e,Wr,Hr,rr,Zt,er,Vo,Xo,Go,Yo,Ko,Qo,Zo;class He extends Ts{constructor(){super(...arguments),Ce.add(this),fs.set(this,[]),Xe.set(this,{}),Br.set(this,{}),We.set(this,void 0),ht.set(this,void 0),Et.set(this,void 0),ft.set(this,void 0),Zr.set(this,void 0),$e.set(this,void 0),Wr.set(this,void 0),Hr.set(this,void 0),rr.set(this,void 0)}[(fs=new WeakMap,Xe=new WeakMap,Br=new WeakMap,We=new WeakMap,ht=new WeakMap,Et=new WeakMap,ft=new WeakMap,Zr=new WeakMap,$e=new WeakMap,Wr=new WeakMap,Hr=new WeakMap,rr=new WeakMap,Ce=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 He;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=Ge.fromReadableStream(e,this.controller);for await(const i of s)G(this,Ce,"m",Zt).call(this,i);if((a=s.controller.signal)!=null&&a.aborted)throw new Fe;return this._addRun(G(this,Ce,"m",er).call(this))}toReadableStream(){return new Ge(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,a){const i=new He;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,Ce,"m",Zt).call(this,g);if((u=d.controller.signal)!=null&&u.aborted)throw new Fe;return this._addRun(G(this,Ce,"m",er).call(this))}static createThreadAssistantStream(e,t,n){const s=new He;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 He;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,Wr,"f")}currentRun(){return G(this,Hr,"f")}currentMessageSnapshot(){return G(this,We,"f")}currentRunStepSnapshot(){return G(this,rr,"f")}async finalRunSteps(){return await this.done(),Object.values(G(this,Xe,"f"))}async finalMessages(){return await this.done(),Object.values(G(this,Br,"f"))}async finalRun(){if(await this.done(),!G(this,ht,"f"))throw Error("Final run was not received.");return G(this,ht,"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,Ce,"m",Zt).call(this,d);if((l=i.controller.signal)!=null&&l.aborted)throw new Fe;return this._addRun(G(this,Ce,"m",er).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,Ce,"m",Zt).call(this,u);if((d=l.controller.signal)!=null&&d.aborted)throw new Fe;return this._addRun(G(this,Ce,"m",er).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(Bn(a)&&Bn(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(!Bn(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)}}Zt=function(e){if(!this.ended)switch(Re(this,Wr,e,"f"),G(this,Ce,"m",Go).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,Ce,"m",Zo).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,Ce,"m",Xo).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,Ce,"m",Vo).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},er=function(){if(this.ended)throw new K("stream has ended, this shouldn't happen");if(!G(this,ht,"f"))throw Error("Final run has not been received");return G(this,ht,"f")},Vo=function(e){const[t,n]=G(this,Ce,"m",Ko).call(this,e,G(this,We,"f"));Re(this,We,t,"f"),G(this,Br,"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,Et,"f")){if(G(this,ft,"f"))switch(G(this,ft,"f").type){case"text":this._emit("textDone",G(this,ft,"f").text,G(this,We,"f"));break;case"image_file":this._emit("imageFileDone",G(this,ft,"f").image_file,G(this,We,"f"));break}Re(this,Et,s.index,"f")}Re(this,ft,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(G(this,Et,"f")!==void 0){const s=e.data.content[G(this,Et,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,G(this,We,"f"));break;case"text":this._emit("textDone",s.text,G(this,We,"f"));break}}G(this,We,"f")&&this._emit("messageDone",e.data),Re(this,We,void 0,"f")}},Xo=function(e){const t=G(this,Ce,"m",Yo).call(this,e);switch(Re(this,rr,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,Zr,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(G(this,$e,"f")&&this._emit("toolCallDone",G(this,$e,"f")),Re(this,Zr,a.index,"f"),Re(this,$e,t.step_details.tool_calls[a.index],"f"),G(this,$e,"f")&&this._emit("toolCallCreated",G(this,$e,"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":Re(this,rr,void 0,"f"),e.data.step_details.type=="tool_calls"&&G(this,$e,"f")&&(this._emit("toolCallDone",G(this,$e,"f")),Re(this,$e,void 0,"f")),this._emit("runStepDone",e.data,t);break}},Go=function(e){G(this,fs,"f").push(e),this._emit("event",e)},Yo=function(e){switch(e.event){case"thread.run.step.created":return G(this,Xe,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=G(this,Xe,"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=He.accumulateDelta(t,n.delta);G(this,Xe,"f")[e.data.id]=s}return G(this,Xe,"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,Xe,"f")[e.data.id]=e.data;break}if(G(this,Xe,"f")[e.data.id])return G(this,Xe,"f")[e.data.id];throw new Error("No snapshot available")},Ko=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,Ce,"m",Qo).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")},Qo=function(e,t){return He.accumulateDelta(t,e)},Zo=function(e){switch(Re(this,Hr,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":Re(this,ht,e.data,"f"),G(this,$e,"f")&&(this._emit("toolCallDone",G(this,$e,"f")),Re(this,$e,void 0,"f"));break}};class Os extends Q{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e={},t){return ge(e)?this.list({},e):this._client.getAPIList("/assistants",Rs,{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 Rs extends be{}Os.AssistantsPage=Rs;function ea(r){return typeof r.parse=="function"}const Pt=r=>(r==null?void 0:r.role)==="assistant",Ji=r=>(r==null?void 0:r.role)==="function",Vi=r=>(r==null?void 0:r.role)==="tool";function Ls(r){return(r==null?void 0:r.$brand)==="auto-parseable-response-format"}function hr(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function Iu(r,e){return!e||!Xi(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}}))}:$s(r,e)}function $s(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new Mi;if(n.finish_reason==="content_filter")throw new Ei;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(a=>Ou(e,a)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?Tu(e,n.message.content):null}}});return{...r,choices:t}}function Tu(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 Ou(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:hr(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function Ru(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 hr(t)||(t==null?void 0:t.function.strict)||!1}function Xi(r){var e;return Ls(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>hr(t)||t.type==="function"&&t.function.strict===!0))??!1}function Lu(r){for(const e of r??[]){if(e.type!=="function")throw new K(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new K(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var Me=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Ae,hs,en,ms,gs,ps,Gi,xs;const ta=10;class Yi extends Ts{constructor(){super(...arguments),Ae.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(n=e.choices[0])==null?void 0:n.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(Ji(e)||Vi(e))&&e.content)this._emit("functionCallResult",e.content);else if(Pt(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(Pt(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 K("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),Me(this,Ae,"m",hs).call(this)}async finalMessage(){return await this.done(),Me(this,Ae,"m",en).call(this)}async finalFunctionCall(){return await this.done(),Me(this,Ae,"m",ms).call(this)}async finalFunctionCallResult(){return await this.done(),Me(this,Ae,"m",gs).call(this)}async totalUsage(){return await this.done(),Me(this,Ae,"m",ps).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=Me(this,Ae,"m",en).call(this);t&&this._emit("finalMessage",t);const n=Me(this,Ae,"m",hs).call(this);n&&this._emit("finalContent",n);const s=Me(this,Ae,"m",ms).call(this);s&&this._emit("finalFunctionCall",s);const a=Me(this,Ae,"m",gs).call(this);a!=null&&this._emit("finalFunctionCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",Me(this,Ae,"m",ps).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())),Me(this,Ae,"m",Gi).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion($s(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 x;const s="function",{function_call:a="auto",stream:i,...l}=t,d=typeof a!="string"&&(a==null?void 0:a.name),{maxChatCompletions:u=ta}=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=(x=(await this._createChatCompletion(e,{...l,function_call:a,functions:h,messages:[...this.messages]},n)).choices[0])==null?void 0:x.message;if(!f)throw new K("missing message in ChatCompletion response");if(!f.function_call)return;const{name:c,arguments:p}=f.function_call,y=g[c];if(y){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 b;try{b=ea(y)?await y.parse(p):p}catch(j){this._addMessage({role:s,name:c,content:j instanceof Error?j.message:String(j)});continue}const S=await y.function(b,this),_=Me(this,Ae,"m",xs).call(this,S);if(this._addMessage({role:s,name:c,content:_}),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=ta}=n||{},g=t.tools.map(c=>{if(hr(c)){if(!c.$callback)throw new K("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 x="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 y=(m=(await this._createChatCompletion(e,{...l,tool_choice:a,tools:x,messages:[...this.messages]},n)).choices[0])==null?void 0:m.message;if(!y)throw new K("missing message in ChatCompletion response");if(!((f=y.tool_calls)!=null&&f.length))return;for(const b of y.tool_calls){if(b.type!=="function")continue;const S=b.id,{name:_,arguments:j}=b.function,v=h[_];if(v){if(d&&d!==_){const L=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,tool_call_id:S,content:L});continue}}else{const L=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(h).map(C=>JSON.stringify(C)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:S,content:L});continue}let I;try{I=ea(v)?await v.parse(j):j}catch(L){const C=L instanceof Error?L.message:String(L);this._addMessage({role:s,tool_call_id:S,content:C});continue}const M=await v.function(I,this),O=Me(this,Ae,"m",xs).call(this,M);if(this._addMessage({role:s,tool_call_id:S,content:O}),d)return}}}}Ae=new WeakSet,hs=function(){return Me(this,Ae,"m",en).call(this).content??null},en=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Pt(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 K("stream ended without producing a ChatCompletionMessage with role=assistant")},ms=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const s=this.messages[n];if(Pt(s)&&(s!=null&&s.function_call))return s.function_call;if(Pt(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},gs=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ji(t)&&t.content!=null||Vi(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}},ps=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},Gi=function(e){if(e.n!=null&&e.n>1)throw new K("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},xs=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class ir extends Yi{static runFunctions(e,t,n){const s=new ir,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 ir,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),Pt(e)&&e.content&&this._emit("content",e.content)}}const Ki=1,Qi=2,Zi=4,el=8,tl=16,rl=32,nl=64,sl=128,ol=256,al=sl|ol,il=tl|rl|al|nl,ll=Ki|Qi|il,cl=Zi|el,$u=ll|cl,ve={STR:Ki,NUM:Qi,ARR:Zi,OBJ:el,NULL:tl,BOOL:rl,NAN:nl,INFINITY:sl,MINUS_INFINITY:ol,INF:al,SPECIAL:il,ATOM:ll,COLLECTION:cl,ALL:$u};class Du extends Error{}class Fu extends Error{}function Uu(r,e=ve.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return Bu(r.trim(),e)}const Bu=(r,e)=>{const t=r.length;let n=0;const s=x=>{throw new Du(`${x} at position ${n}`)},a=x=>{throw new Fu(`${x} 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"||ve.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||ve.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||ve.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||ve.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||ve.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||ve.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):g()),l=()=>{const x=n;let w=!1;for(n++;n<t&&(r[n]!=='"'||w&&r[n-1]==="\\");)w=r[n]==="\\"?!w:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(x,++n-Number(w)))}catch(m){a(String(m))}else if(ve.STR&e)try{return JSON.parse(r.substring(x,n-Number(w))+'"')}catch{return JSON.parse(r.substring(x,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},d=()=>{n++,h();const x={};try{for(;r[n]!=="}";){if(h(),n>=t&&ve.OBJ&e)return x;const w=l();h(),n++;try{const m=i();Object.defineProperty(x,w,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(ve.OBJ&e)return x;throw m}h(),r[n]===","&&n++}}catch{if(ve.OBJ&e)return x;s("Expected '}' at end of object")}return n++,x},u=()=>{n++;const x=[];try{for(;r[n]!=="]";)x.push(i()),h(),r[n]===","&&n++}catch{if(ve.ARR&e)return x;s("Expected ']' at end of array")}return n++,x},g=()=>{if(n===0){r==="-"&&ve.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(w){if(ve.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 x=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(ve.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(x,n))}catch{r.substring(x,n)==="-"&&ve.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(x,r.lastIndexOf("e")))}catch(m){a(String(m))}}},h=()=>{for(;n<t&&`
59
+ \r `.includes(r[n]);)n++};return i()},ra=r=>Uu(r,ve.ALL^ve.NUM);var St=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},ue=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,Ye,Ct,et,Wn,Mr,Hn,zn,qn,Er,Jn,na;class lr extends Yi{constructor(e){super(),xe.add(this),Ye.set(this,void 0),Ct.set(this,void 0),et.set(this,void 0),St(this,Ye,e,"f"),St(this,Ct,[],"f")}get currentChatCompletionSnapshot(){return ue(this,et,"f")}static fromReadableStream(e){const t=new lr(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,n){const s=new lr(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())),ue(this,xe,"m",Wn).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)ue(this,xe,"m",Hn).call(this,l);if((i=a.controller.signal)!=null&&i.aborted)throw new Fe;return this._addChatCompletion(ue(this,xe,"m",Er).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())),ue(this,xe,"m",Wn).call(this),this._connected();const s=Ge.fromReadableStream(e,this.controller);let a;for await(const l of s)a&&a!==l.id&&this._addChatCompletion(ue(this,xe,"m",Er).call(this)),ue(this,xe,"m",Hn).call(this,l),a=l.id;if((i=s.controller.signal)!=null&&i.aborted)throw new Fe;return this._addChatCompletion(ue(this,xe,"m",Er).call(this))}[(Ye=new WeakMap,Ct=new WeakMap,et=new WeakMap,xe=new WeakSet,Wn=function(){this.ended||St(this,et,void 0,"f")},Mr=function(t){let n=ue(this,Ct,"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},ue(this,Ct,"f")[t.index]=n,n)},Hn=function(t){var s,a,i,l,d,u,g,h,x,w,m,f,c,p,y;if(this.ended)return;const n=ue(this,xe,"m",na).call(this,t);this._emit("chunk",t,n);for(const b of t.choices){const S=n.choices[b.index];b.delta.content!=null&&((s=S.message)==null?void 0:s.role)==="assistant"&&((a=S.message)!=null&&a.content)&&(this._emit("content",b.delta.content,S.message.content),this._emit("content.delta",{delta:b.delta.content,snapshot:S.message.content,parsed:S.message.parsed})),b.delta.refusal!=null&&((i=S.message)==null?void 0:i.role)==="assistant"&&((l=S.message)!=null&&l.refusal)&&this._emit("refusal.delta",{delta:b.delta.refusal,snapshot:S.message.refusal}),((d=b.logprobs)==null?void 0:d.content)!=null&&((u=S.message)==null?void 0:u.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(g=b.logprobs)==null?void 0:g.content,snapshot:((h=S.logprobs)==null?void 0:h.content)??[]}),((x=b.logprobs)==null?void 0:x.refusal)!=null&&((w=S.message)==null?void 0:w.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(m=b.logprobs)==null?void 0:m.refusal,snapshot:((f=S.logprobs)==null?void 0:f.refusal)??[]});const _=ue(this,xe,"m",Mr).call(this,S);S.finish_reason&&(ue(this,xe,"m",qn).call(this,S),_.current_tool_call_index!=null&&ue(this,xe,"m",zn).call(this,S,_.current_tool_call_index));for(const j of b.delta.tool_calls??[])_.current_tool_call_index!==j.index&&(ue(this,xe,"m",qn).call(this,S),_.current_tool_call_index!=null&&ue(this,xe,"m",zn).call(this,S,_.current_tool_call_index)),_.current_tool_call_index=j.index;for(const j of b.delta.tool_calls??[]){const v=(c=S.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:(p=v.function)==null?void 0:p.name,index:j.index,arguments:v.function.arguments,parsed_arguments:v.function.parsed_arguments,arguments_delta:((y=j.function)==null?void 0:y.arguments)??""}):(v==null||v.type,void 0))}}},zn=function(t,n){var i,l,d;if(ue(this,xe,"m",Mr).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=ue(this,Ye,"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:hr(u)?u.$parseRaw(a.function.arguments):u!=null&&u.function.strict?JSON.parse(a.function.arguments):null})}else a.type},qn=function(t){var s,a;const n=ue(this,xe,"m",Mr).call(this,t);if(t.message.content&&!n.content_done){n.content_done=!0;const i=ue(this,xe,"m",Jn).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}))},Er=function(){if(this.ended)throw new K("stream has ended, this shouldn't happen");const t=ue(this,et,"f");if(!t)throw new K("request ended without sending any chunks");return St(this,et,void 0,"f"),St(this,Ct,[],"f"),Wu(t,ue(this,Ye,"f"))},Jn=function(){var n;const t=(n=ue(this,Ye,"f"))==null?void 0:n.response_format;return Ls(t)?t:null},na=function(t){var n,s,a,i;let l=ue(this,et,"f");const{choices:d,...u}=t;l?Object.assign(l,u):l=St(this,et,{...u,choices:[]},"f");for(const{delta:g,finish_reason:h,index:x,logprobs:w=null,...m}of t.choices){let f=l.choices[x];if(f||(f=l.choices[x]={finish_reason:h,index:x,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,ue(this,Ye,"f")&&Xi(ue(this,Ye,"f")))){if(h==="length")throw new Mi;if(h==="content_filter")throw new Ei}if(Object.assign(f,m),!g)continue;const{content:c,refusal:p,function_call:y,role:b,tool_calls:S,..._}=g;if(Object.assign(f.message,_),p&&(f.message.refusal=(f.message.refusal||"")+p),b&&(f.message.role=b),y&&(f.message.function_call?(y.name&&(f.message.function_call.name=y.name),y.arguments&&((a=f.message.function_call).arguments??(a.arguments=""),f.message.function_call.arguments+=y.arguments)):f.message.function_call=y),c&&(f.message.content=(f.message.content||"")+c,!f.message.refusal&&ue(this,xe,"m",Jn).call(this)&&(f.message.parsed=ra(f.message.content))),S){f.message.tool_calls||(f.message.tool_calls=[]);for(const{index:j,id:v,type:I,function:M,...O}of S){const L=(i=f.message.tool_calls)[j]??(i[j]={});Object.assign(L,O),v&&(L.id=v),I&&(L.type=I),M&&(L.function??(L.function={name:M.name??"",arguments:""})),M!=null&&M.name&&(L.function.name=M.name),M!=null&&M.arguments&&(L.function.arguments+=M.arguments,Ru(ue(this,Ye,"f"),L)&&(L.function.parsed_arguments=ra(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 Ge(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Wu(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:x,...w})=>{if(!g)throw new K(`missing finish_reason for choice ${h}`);const{content:m=null,function_call:f,tool_calls:c,...p}=u,y=u.role;if(!y)throw new K(`missing role for choice ${h}`);if(f){const{arguments:b,name:S}=f;if(b==null)throw new K(`missing function_call.arguments for choice ${h}`);if(!S)throw new K(`missing function_call.name for choice ${h}`);return{...w,message:{content:m,function_call:{arguments:b,name:S},role:y,refusal:u.refusal??null},finish_reason:g,index:h,logprobs:x}}return c?{...w,index:h,finish_reason:g,logprobs:x,message:{...p,role:y,content:m,refusal:u.refusal??null,tool_calls:c.map((b,S)=>{const{function:_,type:j,id:v,...I}=b,{arguments:M,name:O,...L}=_||{};if(v==null)throw new K(`missing choices[${h}].tool_calls[${S}].id
60
+ ${Pr(r)}`);if(j==null)throw new K(`missing choices[${h}].tool_calls[${S}].type
61
+ ${Pr(r)}`);if(O==null)throw new K(`missing choices[${h}].tool_calls[${S}].function.name
62
+ ${Pr(r)}`);if(M==null)throw new K(`missing choices[${h}].tool_calls[${S}].function.arguments
63
+ ${Pr(r)}`);return{...I,id:v,type:j,function:{...L,name:O,arguments:M}}})}}:{...w,message:{...p,content:m,role:y,refusal:u.refusal??null},finish_reason:g,index:h,logprobs:x}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Iu(d,e)}function Pr(r){return JSON.stringify(r)}class It extends lr{static fromReadableStream(e){const t=new It(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new It(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 It(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 dl=class extends Q{parse(e,t){return Lu(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=>$s(n,e))}runFunctions(e,t){return e.stream?It.runFunctions(this._client,e,t):ir.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?It.runTools(this._client,e,t):ir.runTools(this._client,e,t)}stream(e,t){return lr.createChatCompletion(this._client,e,t)}};class ys extends Q{constructor(){super(...arguments),this.completions=new dl(this._client)}}(function(r){r.Completions=dl})(ys||(ys={}));class ul extends Q{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class fl extends Q{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class xn extends Q{constructor(){super(...arguments),this.sessions=new ul(this._client),this.transcriptionSessions=new fl(this._client)}}xn.Sessions=ul;xn.TranscriptionSessions=fl;class Ds extends Q{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return ge(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Fs,{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 Fs extends be{}Ds.MessagesPage=Fs;class Us extends Q{retrieve(e,t,n,s={},a){return ge(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 ge(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Bs,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}}class Bs extends be{}Us.RunStepsPage=Bs;let mr=class extends Q{constructor(){super(...arguments),this.steps=new Us(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 ge(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Ws,{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 He.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 ur(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,n){return He.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 He.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class Ws extends be{}mr.RunsPage=Ws;mr.Steps=Us;mr.RunStepsPage=Bs;class $t extends Q{constructor(){super(...arguments),this.runs=new mr(this._client),this.messages=new Ds(this._client)}create(e={},t){return ge(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 He.createThreadAssistantStream(e,this._client.beta.threads,t)}}$t.Runs=mr;$t.RunsPage=Ws;$t.Messages=Ds;$t.MessagesPage=Fs;class Dt extends Q{constructor(){super(...arguments),this.realtime=new xn(this._client),this.chat=new ys(this._client),this.assistants=new Os(this._client),this.threads=new $t(this._client)}}Dt.Realtime=xn;Dt.Assistants=Os;Dt.AssistantsPage=Rs;Dt.Threads=$t;class hl extends Q{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class ml extends Q{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n==null?void 0:n.headers},__binaryResponse:!0})}}let yn=class extends Q{constructor(){super(...arguments),this.content=new ml(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,bt({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return ge(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Hs,{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 Hs extends be{}yn.FileListResponsesPage=Hs;yn.Content=ml;class gr extends Q{constructor(){super(...arguments),this.files=new yn(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 ge(e)?this.list({},e):this._client.getAPIList("/containers",zs,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}}class zs extends be{}gr.ContainerListResponsesPage=zs;gr.Files=yn;gr.FileListResponsesPage=Hs;class gl extends Q{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&at("Request","User defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?a:(at("response","Decoding base64 embeddings to float32 array"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(l=>{const d=l.embedding;l.embedding=Eu(d)}),i)))}}class qs extends Q{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return ge(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Js,{query:n,...s})}}class Js extends be{}qs.OutputItemListResponsesPage=Js;class pr extends Q{constructor(){super(...arguments),this.outputItems=new qs(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 ge(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Vs,{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 Vs extends be{}pr.RunListResponsesPage=Vs;pr.OutputItems=qs;pr.OutputItemListResponsesPage=Js;class xr extends Q{constructor(){super(...arguments),this.runs=new pr(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 ge(e)?this.list({},e):this._client.getAPIList("/evals",Xs,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class Xs extends be{}xr.EvalListResponsesPage=Xs;xr.Runs=pr;xr.RunListResponsesPage=Vs;let Gs=class extends Q{create(e,t){return this._client.post("/files",bt({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return ge(e)?this.list({},e):this._client.getAPIList("/files",Ys,{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 ur(t),i=await this.retrieve(e),Date.now()-a>n)throw new Es({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};class Ys extends be{}Gs.FileObjectsPage=Ys;class pl extends Q{}let xl=class extends Q{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Ks extends Q{constructor(){super(...arguments),this.graders=new xl(this._client)}}Ks.Graders=xl;class Qs extends Q{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Zs,{body:t,method:"post",...n})}retrieve(e,t={},n){return ge(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 Zs extends hn{}Qs.PermissionCreateResponsesPage=Zs;let bn=class extends Q{constructor(){super(...arguments),this.permissions=new Qs(this._client)}};bn.Permissions=Qs;bn.PermissionCreateResponsesPage=Zs;class eo extends Q{list(e,t={},n){return ge(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,to,{query:t,...n})}}class to extends be{}eo.FineTuningJobCheckpointsPage=to;class Ft extends Q{constructor(){super(...arguments),this.checkpoints=new eo(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 ge(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",ro,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return ge(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,no,{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 ro extends be{}class no extends be{}Ft.FineTuningJobsPage=ro;Ft.FineTuningJobEventsPage=no;Ft.Checkpoints=eo;Ft.FineTuningJobCheckpointsPage=to;class it extends Q{constructor(){super(...arguments),this.methods=new pl(this._client),this.jobs=new Ft(this._client),this.checkpoints=new bn(this._client),this.alpha=new Ks(this._client)}}it.Methods=pl;it.Jobs=Ft;it.FineTuningJobsPage=ro;it.FineTuningJobEventsPage=no;it.Checkpoints=bn;it.Alpha=Ks;class yl extends Q{}class so extends Q{constructor(){super(...arguments),this.graderModels=new yl(this._client)}}so.GraderModels=yl;class bl extends Q{createVariation(e,t){return this._client.post("/images/variations",bt({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",bt({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class oo extends Q{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ao,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class ao extends hn{}oo.ModelsPage=ao;class wl extends Q{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Hu(r,e){return!e||!qu(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)}:vl(r,e)}function vl(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Xu(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:zu(e,i.text)}:i);return{...s,content:a}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||_l(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 zu(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 qu(r){var e;return!!Ls((e=r.text)==null?void 0:e.format)}function Ju(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function Vu(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function Xu(r,e){const t=Vu(r.tools??[],e.name);return{...e,...e,parsed_arguments:Ju(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function _l(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 Sl extends Q{list(e,t={},n){return ge(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Yu,{query:t,...n})}}var jt=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},tt=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},At,Ir,rt,Tr,sa,oa,aa,ia;class io extends Ts{constructor(e){super(),At.add(this),Ir.set(this,void 0),rt.set(this,void 0),Tr.set(this,void 0),jt(this,Ir,e,"f")}static createResponse(e,t,n){const s=new io(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())),tt(this,At,"m",sa).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)tt(this,At,"m",oa).call(this,d,i);if((l=a.controller.signal)!=null&&l.aborted)throw new Fe;return tt(this,At,"m",aa).call(this)}[(Ir=new WeakMap,rt=new WeakMap,Tr=new WeakMap,At=new WeakSet,sa=function(){this.ended||jt(this,rt,void 0,"f")},oa=function(t,n){if(this.ended)return;const s=(i,l)=>{(n==null||l.sequence_number>n)&&this._emit(i,l)},a=tt(this,At,"m",ia).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 K(`missing output at index ${t.output_index}`);if(i.type==="message"){const l=i.content[t.content_index];if(!l)throw new K(`missing content at index ${t.content_index}`);if(l.type!=="output_text")throw new K(`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 K(`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}},aa=function(){if(this.ended)throw new K("stream has ended, this shouldn't happen");const t=tt(this,rt,"f");if(!t)throw new K("request ended without sending any events");jt(this,rt,void 0,"f");const n=Gu(t,tt(this,Ir,"f"));return jt(this,Tr,n,"f"),n},ia=function(t){let n=tt(this,rt,"f");if(!n){if(t.type!=="response.created")throw new K(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=jt(this,rt,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 K(`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 K(`missing output at index ${t.output_index}`);if(s.type==="message"){const a=s.content[t.content_index];if(!a)throw new K(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new K(`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 K(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{jt(this,rt,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=tt(this,Tr,"f");if(!e)throw new K("stream ended without producing a ChatCompletion");return e}}function Gu(r,e){return Hu(r,e)}class lo extends Q{constructor(){super(...arguments),this.inputItems=new Sl(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"&&_l(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=>vl(n,e))}stream(e,t){return io.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 Yu extends be{}lo.InputItems=Sl;class Cl extends Q{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,bt({body:t,...n}))}}class co extends Q{constructor(){super(...arguments),this.parts=new Cl(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})}}co.Parts=Cl;const Ku=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 wn extends Q{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return ge(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,vn,{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 ur(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`,uo,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class vn extends be{}class uo extends hn{}wn.VectorStoreFilesPage=vn;wn.FileContentResponsesPage=uo;class jl extends Q{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return ge(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,vn,{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 ur(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(x){for(let w of x){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 Ku(h),await this.createAndPoll(e,{file_ids:u})}}class lt extends Q{constructor(){super(...arguments),this.files=new wn(this._client),this.fileBatches=new jl(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 ge(e)?this.list({},e):this._client.getAPIList("/vector_stores",fo,{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`,ho,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class fo extends be{}class ho extends hn{}lt.VectorStoresPage=fo;lt.VectorStoreSearchResponsesPage=ho;lt.Files=wn;lt.VectorStoreFilesPage=vn;lt.FileContentResponsesPage=uo;lt.FileBatches=jl;var Al;class Z extends yu{constructor({baseURL:e=Nr("OPENAI_BASE_URL"),apiKey:t=Nr("OPENAI_API_KEY"),organization:n=Nr("OPENAI_ORG_ID")??null,project:s=Nr("OPENAI_PROJECT_ID")??null,...a}={}){if(t===void 0)throw new K("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&&ku())throw new K(`It looks like you're running in a browser-like environment.
43
64
 
44
65
  This is disabled by default, as it risks exposing your secret API credentials to attackers.
45
66
  If you understand the risks and have appropriate mitigations in place,
@@ -48,53 +69,53 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
48
69
  new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
49
70
 
50
71
  https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
51
- `);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new qi(this),this.chat=new sn(this),this.embeddings=new Ji(this),this.files=new Ds(this),this.images=new Ki(this),this.audio=new tr(this),this.moderations=new Yi(this),this.models=new Gs(this),this.fineTuning=new Ye(this),this.graders=new Vs(this),this.vectorStores=new Qe(this),this.beta=new Nt(this),this.batches=new ws(this),this.uploads=new Qs(this),this.responses=new Ys(this),this.evals=new ar(this),this.containers=new sr(this),this._options=i,this.apiKey=t,this.organization=n,this.project=s}defaultQuery(){return this._options.defaultQuery}defaultHeaders(e){return{...super.defaultHeaders(e),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(e){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(e){return Qc(e,{arrayFormat:"brackets"})}}nl=Z;Z.OpenAI=nl;Z.DEFAULT_TIMEOUT=6e5;Z.OpenAIError=Y;Z.APIError=xe;Z.APIConnectionError=Yr;Z.APIConnectionTimeoutError=ys;Z.APIUserAbortError=Me;Z.NotFoundError=ti;Z.ConflictError=ri;Z.RateLimitError=si;Z.BadRequestError=Qa;Z.AuthenticationError=Za;Z.InternalServerError=oi;Z.PermissionDeniedError=ei;Z.UnprocessableEntityError=ni;Z.toFile=ui;Z.fileFromPath=Xa;Z.Completions=qi;Z.Chat=sn;Z.ChatCompletionsPage=nn;Z.Embeddings=Ji;Z.Files=Ds;Z.FileObjectsPage=Fs;Z.Images=Ki;Z.Audio=tr;Z.Moderations=Yi;Z.Models=Gs;Z.ModelsPage=Xs;Z.FineTuning=Ye;Z.Graders=Vs;Z.VectorStores=Qe;Z.VectorStoresPage=eo;Z.VectorStoreSearchResponsesPage=to;Z.Beta=Nt;Z.Batches=ws;Z.BatchesPage=vs;Z.Uploads=Qs;Z.Responses=Ys;Z.Evals=ar;Z.EvalListResponsesPage=Ls;Z.Containers=sr;Z.ContainerListResponsesPage=Ps;class sl{constructor(e,t,n,s,o,i,l){W(this,"messages");W(this,"tools");W(this,"callback");W(this,"modelConfig");W(this,"configUrl");W(this,"abortController");W(this,"isAborted");W(this,"sessionId");this.messages=e,this.tools=t,this.callback=s,this.modelConfig=o,this.configUrl=i||"/api",this.sessionId=l||n,console.log("🔧 AiRequestHandler Constructor - configUrl:",this.configUrl,"haha"),console.log("🔧 AiRequestHandler Constructor - modelConfig.base_url:",this.modelConfig.base_url),this.abortController=new AbortController,this.isAborted=!1;debugger}async chatCompletion(){var e,t;try{if(this.isAborted)return console.log("Chat completion aborted by user"),this.messages;console.log("Using OpenAI package with base URL:",this.configUrl),console.log("API Key:",this.modelConfig.api_key?"Present":"Missing"),console.log("Config Url: ",this.configUrl);const n=new Z({apiKey:this.modelConfig.api_key,baseURL:this.configUrl,dangerouslyAllowBrowser:!0,defaultHeaders:{"x-target-url":this.modelConfig.base_url}}),s=this.buildPayLoad(),o=await n.chat.completions.create({...s,stream:!0},{signal:this.abortController.signal});return await this.handleOpenAIStreamResponse(o,this.callback),this.messages}catch(n){debugger;if(n.name==="AbortError"||n.message==="network error"||(e=n.message)!=null&&e.includes("aborted")||(t=n.message)!=null&&t.includes("cancelled")||this.isAborted)return console.log("Chat completion aborted by user"),this.messages;throw console.error("Chat completion failed:",n),console.error("Error type:",n.constructor.name),console.error("Error message:",n.message),console.error("Error stack:",n.stack),(n.message.includes("CORS")||n.message.includes("fetch"))&&console.error("This appears to be a CORS or network error. Check your base_url and API configuration."),this.callback&&this.callback("error",n),n}}async handleOpenAIStreamResponse(e,t){var s,o;const n={role:"assistant",content:"",reasoning_content:"",tool_calls:[],model_info:{model:this.modelConfig.model_name,temperature:this.modelConfig.temperature,max_tokens:this.modelConfig.max_tokens},function_calls:[]};try{console.log("Starting to process OpenAI stream...");let i=0,l=null;for await(const c of e){if(this.isAborted){console.log("Stream processing aborted");break}if(i++,c.choices&&c.choices.length>0){const m=c.choices[0].delta;if(m&&(m.content&&(n.content+=m.content,t&&t("chunk",{type:"text",content:m.content})),m.reasoning_content&&(n.reasoning_content+=m.reasoning_content,t&&t("chunk",{type:"reasoning_content",content:m.reasoning_content,accumulated:n.reasoning_content})),m.tool_calls))for(const f of m.tool_calls){if(!f){console.warn("Invalid tool call:",f);continue}let p=f.index;for((p==null||typeof p!="number")&&(p=n.tool_calls.length,console.log(`Tool call index was ${f.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:""}),f.id&&f.id!==""?l.id=f.id:(!l.id||l.id==="")&&(l.id=`call_${Date.now()}_${p}`),f.function&&(f.function.name&&(l.function.name=f.function.name),f.function.arguments&&(l.function.arguments+=f.function.arguments))}}}console.log(`OpenAI stream completed. Processed ${i} chunks.`),n.tool_calls.length>0&&(n.function_calls=n.tool_calls.map(c=>({id:c.id,name:c.function.name,arguments:c.function.arguments}))),this.messages.push(n)}catch(i){if(i.name==="AbortError"||i.message==="network error"||(s=i.message)!=null&&s.includes("aborted")||(o=i.message)!=null&&o.includes("cancelled")||this.isAborted){console.log("Stream processing aborted by user");return}throw console.error("Stream processing error:",i),t&&t("error",i),i}}buildPayLoad(){const e=this.convertToOpenAIFormat(this.messages),t={model:this.modelConfig.model_name||"gpt-3.5-turbo",messages:e,max_tokens:this.modelConfig.max_tokens||4e3,sessionId:this.sessionId};return this.tools&&this.tools.length>0&&(t.tools=this.tools),t}cleanHtmlContent(e){if(!e||typeof e!="string")return"";let t=e.replace(/<[^>]*>/g,"");return t=t.replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').replace(/&#39;/g,"'").replace(/&nbsp;/g," "),t=t.replace(/[ \t]+/g," ").replace(/\n[ \t]*/g,`
72
+ `);super({baseURL:i.baseURL,timeout:i.timeout??6e5,httpAgent:i.httpAgent,maxRetries:i.maxRetries,fetch:i.fetch}),this.completions=new hl(this),this.chat=new pn(this),this.embeddings=new gl(this),this.files=new Gs(this),this.images=new bl(this),this.audio=new fr(this),this.moderations=new wl(this),this.models=new oo(this),this.fineTuning=new it(this),this.graders=new so(this),this.vectorStores=new lt(this),this.beta=new Dt(this),this.batches=new Ps(this),this.uploads=new co(this),this.responses=new lo(this),this.evals=new xr(this),this.containers=new gr(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 eu(e,{arrayFormat:"brackets"})}}Al=Z;Z.OpenAI=Al;Z.DEFAULT_TIMEOUT=6e5;Z.OpenAIError=K;Z.APIError=je;Z.APIConnectionError=cn;Z.APIConnectionTimeoutError=Es;Z.APIUserAbortError=Fe;Z.NotFoundError=Ci;Z.ConflictError=ji;Z.RateLimitError=Ni;Z.BadRequestError=vi;Z.AuthenticationError=_i;Z.InternalServerError=ki;Z.PermissionDeniedError=Si;Z.UnprocessableEntityError=Ai;Z.toFile=Oi;Z.fileFromPath=yi;Z.Completions=hl;Z.Chat=pn;Z.ChatCompletionsPage=gn;Z.Embeddings=gl;Z.Files=Gs;Z.FileObjectsPage=Ys;Z.Images=bl;Z.Audio=fr;Z.Moderations=wl;Z.Models=oo;Z.ModelsPage=ao;Z.FineTuning=it;Z.Graders=so;Z.VectorStores=lt;Z.VectorStoresPage=fo;Z.VectorStoreSearchResponsesPage=ho;Z.Beta=Dt;Z.Batches=Ps;Z.BatchesPage=Is;Z.Uploads=co;Z.Responses=lo;Z.Evals=xr;Z.EvalListResponsesPage=Xs;Z.Containers=gr;Z.ContainerListResponsesPage=zs;class Nl{constructor(e,t,n,s,a,i,l){q(this,"messages");q(this,"tools");q(this,"callback");q(this,"modelConfig");q(this,"configUrl");q(this,"abortController");q(this,"isAborted");q(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 Z({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},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 x=h.index;for((x==null||typeof x!="number")&&(x=n.tool_calls.length,console.log(`Tool call index was ${h.index}, using ${x} instead`));n.tool_calls.length<=x;)n.tool_calls.push({id:"",type:"function",function:{name:"",arguments:""}});l=n.tool_calls[x],l.function||(l.function={name:"",arguments:""}),h.id&&h.id!==""?l.id=h.id:(!l.id||l.id==="")&&(l.id=`call_${Date.now()}_${x}`),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,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
73
  `).replace(/\n{3,}/g,`
53
74
 
54
- `).trim(),t}convertToOpenAIFormat(e){return e.map(t=>{let n=t.content||t.message||"";t.role==="assistant"&&(n=this.cleanHtmlContent(n));const s={role:t.role,content:n};if(t.role==="assistant"&&(t.tool_calls||t.function_calls)){const o=t.tool_calls||t.function_calls||[];o.length>0&&(console.log("Converting tool calls for assistant message:",o),s.tool_calls=o.map(i=>{var f,p;const l=((f=i.function)==null?void 0:f.name)||i.name,c=((p=i.function)==null?void 0:p.arguments)||i.arguments;if(!l)return console.warn("Tool call missing function name:",i),null;let d;typeof c=="string"?d=c:c&&typeof c=="object"?d=JSON.stringify(c):d="{}";try{JSON.parse(d)}catch(y){console.warn("Invalid JSON in tool call arguments, using empty object:",d,y),d="{}"}const m={id:i.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,type:i.type||"function",function:{name:l,arguments:d}};return console.log("Converted tool call:",m),m}).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 Kd{constructor(e,t,n,s,o,i="/api"){W(this,"messageManager");W(this,"modelConfig");W(this,"conversationId");W(this,"callback");W(this,"sessionId");W(this,"configUrl");this.messageManager=e,this.modelConfig=t,this.conversationId=n,this.callback=s,this.sessionId=o||n,this.configUrl=i}async processToolResult(e,t){const n=e;debugger;const s=(n.content||"").length,o=s>1e3;let i=n.content||"";if(o)try{const l=await this.generateContentSummary(n.content,n.tool_name);i=l,console.log(`[Tool Result Summary] 为工具 ${n.tool_name} 生成总结,原长度: ${s}, 总结长度: ${l.length}`)}catch(l){if(l.message==="Stream aborted by user"||l.name==="AbortError"){console.log("[Tool Result Summary] 总结生成被用户中断");return}console.error("[Tool Result Summary] 生成总结失败:",l)}return await this.messageManager.saveToolMessage({sessionId:t,role:"tool",content:n.content||"",summary:o?i:void 0,status:"completed",createdAt:new Date,metadata:{tool_call_id:n.tool_call_id,tool_name:n.tool_name,is_summarized:o,original_length:s}}),{role:"tool",tool_call_id:n.tool_call_id,content:i,metadata:{tool_name:n.tool_name,timestamp:new Date().toISOString(),content_length:s,is_summarized:o}}}async generateContentSummary(e,t){try{const n=[{id:Date.now().toString()+"_system",sessionId:this.conversationId,role:"system",content:"请帮我总结一下这个内容,对其内容进行精简,将主要信息提取出来。请用简洁明了的语言概括核心要点。",rawContent:"请帮我总结一下这个内容,对其内容进行精简,将主要信息提取出来。请用简洁明了的语言概括核心要点。",status:"completed",createdAt:new Date},{id:Date.now().toString()+"_user",sessionId:this.conversationId,role:"user",content:`请帮我对以下内容进行总结:
75
+ `).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,x;const l=((h=i.function)==null?void 0:h.name)||i.name,d=((x=i.function)==null?void 0:x.arguments)||i.arguments;if(!l)return console.warn("Tool call missing function name:",i),null;let u;typeof d=="string"?u=d:d&&typeof d=="object"?u=JSON.stringify(d):u="{}";try{JSON.parse(u)}catch(w){console.warn("Invalid JSON in tool call arguments, using empty object:",u,w),u="{}"}const 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 Qu{constructor(e,t,n,s,a,i="/api"){q(this,"messageManager");q(this,"modelConfig");q(this,"conversationId");q(this,"callback");q(this,"sessionId");q(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
76
 
56
77
  ${e}`,rawContent:`请帮我对以下内容进行总结:
57
78
 
58
- ${e}`,status:"completed",createdAt:new Date}];let s="";return await new sl(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,o,i,l,c,d,m){W(this,"messages");W(this,"conversationId");W(this,"tools");W(this,"modelConfig");W(this,"callBack");W(this,"mcpToolExecute");W(this,"configUrl");W(this,"isAborted");W(this,"currentAiRequestHandler");W(this,"toolResultProcessor");W(this,"sessionId");this.messages=e,this.conversationId=t,this.tools=n,this.modelConfig=s,this.callBack=o,this.mcpToolExecute=i,this.configUrl=c||"/api",this.sessionId=m||this.conversationId,console.log("🔧 AiClient Constructor - configUrl:",this.configUrl),this.isAborted=!1,this.currentAiRequestHandler=null,this.toolResultProcessor=new Kd(l,this.modelConfig,this.conversationId,this.callBack,this.sessionId,this.configUrl),d&&d.signal.addEventListener("abort",()=>{console.log("AiClient: External abort signal received"),this.abort()})}async start(){await this.handleToolCallRecursively(25,0)}async handleToolCallRecursively(e,t){var s;if(t>=e){this.callBack("error","Maximum rounds reached");return}if(this.isAborted){console.log("AiClient: Request aborted");return}let n=this.messages[this.messages.length-1];if(n&&n.role==="assistant")if(n.tool_calls&&n.tool_calls.length>0){if(this.isAborted){console.log("AiClient: Tool call execution aborted");return}this.callBack("tool_call",n.tool_calls);let o=[];for(const l of n.tool_calls){if(this.isAborted){console.log("AiClient: Aborted during tool execution");return}const c=((s=l.function)==null?void 0:s.name)||l.name;if(this.mcpToolExecute.toolSupportsStreaming(c)){console.log(`Using streaming execution for tool: ${c}`);const m={tool_call_id:l.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:c,content:""};try{await this.mcpToolExecute.executeStream(l,f=>{if(this.isAborted)return;console.log("chunk",f);const p=this.processChunk(f);m.content+=p,this.callBack("tool_stream_chunk",{toolCallId:l.id,chunk:p})},()=>{this.isAborted||console.log(`Stream completed for tool: ${c}`)},f=>{if(this.isAborted||f.message==="Stream aborted by user"||f.name==="AbortError"){console.log(`Tool ${c} stream aborted by user`);return}console.error(`Stream error for tool ${c}:`,f),m.content=JSON.stringify({error:f.message||"Tool execution failed"})}),m.content||(m.content=JSON.stringify({result:"Tool execution completed"}))}catch(f){if(this.isAborted||f.message==="Stream aborted by user"||f.name==="AbortError"){console.log(`Tool ${c} execution aborted by user`);return}console.error(`Failed to execute stream tool ${c}:`,f),m.content=JSON.stringify({error:f.message||"Tool execution failed"})}o.push(m)}else{console.log(`Using regular execution for tool: ${c}`);const m=await this.mcpToolExecute.execute([l]);o.push(...m)}}if(this.isAborted){console.log("AiClient: Aborted after tool execution");return}const i=await this.toolResultProcessor.processToolResult(o[0],this.conversationId);debugger;if(this.messages.push(i),this.callBack("tool_result",o),this.isAborted){console.log("AiClient: Aborted before chatCompletion after tool execution");return}if(await this.chatCompletion(),this.isAborted){console.log("AiClient: Aborted after chatCompletion after tool execution");return}await this.handleToolCallRecursively(e,t+1)}else{this.callBack("conversation_complete",n);return}else{if(this.isAborted){console.log("AiClient: Aborted before chatCompletion");return}if(await this.chatCompletion(),this.isAborted){console.log("AiClient: Aborted after chatCompletion");return}await this.handleToolCallRecursively(e,t+1)}}async chatCompletion(){if(this.isAborted){console.log("AiClient: chatCompletion aborted");return}const e=new sl(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?`
59
- `+s.content:s.content;if(s.data)return typeof s.data=="string"&&s.data.startsWith("data: ")?this.processChunk(s.data,!0):s.data;if(s.ai_stream_chunk)return typeof s.ai_stream_chunk=="string"&&s.ai_stream_chunk.startsWith("data: ")?this.processChunk(s.ai_stream_chunk,!1):s.ai_stream_chunk}}catch{return e}return""}}function ol(r,e){return function(){return r.apply(e,arguments)}}const{toString:Yd}=Object.prototype,{getPrototypeOf:ro}=Object,{iterator:un,toStringTag:al}=Symbol,fn=(r=>e=>{const t=Yd.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),Pe=r=>(r=r.toLowerCase(),e=>fn(e)===r),hn=r=>e=>typeof e===r,{isArray:Et}=Array,At=hn("undefined");function ir(r){return r!==null&&!At(r)&&r.constructor!==null&&!At(r.constructor)&&_e(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const il=Pe("ArrayBuffer");function Qd(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&il(r.buffer),e}const Zd=hn("string"),_e=hn("function"),ll=hn("number"),lr=r=>r!==null&&typeof r=="object",eu=r=>r===!0||r===!1,Pr=r=>{if(fn(r)!=="object")return!1;const e=ro(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(al in r)&&!(un in r)},tu=r=>{if(!lr(r)||ir(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},ru=Pe("Date"),nu=Pe("File"),su=Pe("Blob"),ou=Pe("FileList"),au=r=>lr(r)&&_e(r.pipe),iu=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||_e(r.append)&&((e=fn(r))==="formdata"||e==="object"&&_e(r.toString)&&r.toString()==="[object FormData]"))},lu=Pe("URLSearchParams"),[cu,du,uu,fu]=["ReadableStream","Request","Response","Headers"].map(Pe),hu=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function cr(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let n,s;if(typeof r!="object"&&(r=[r]),Et(r))for(n=0,s=r.length;n<s;n++)e.call(null,r[n],n,r);else{if(ir(r))return;const o=t?Object.getOwnPropertyNames(r):Object.keys(r),i=o.length;let l;for(n=0;n<i;n++)l=o[n],e.call(null,r[l],l,r)}}function cl(r,e){if(ir(r))return null;e=e.toLowerCase();const t=Object.keys(r);let n=t.length,s;for(;n-- >0;)if(s=t[n],e===s.toLowerCase())return s;return null}const st=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,dl=r=>!At(r)&&r!==st;function ls(){const{caseless:r,skipUndefined:e}=dl(this)&&this||{},t={},n=(s,o)=>{const i=r&&cl(t,o)||o;Pr(t[i])&&Pr(s)?t[i]=ls(t[i],s):Pr(s)?t[i]=ls({},s):Et(s)?t[i]=s.slice():(!e||!At(s))&&(t[i]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&cr(arguments[s],n);return t}const mu=(r,e,t,{allOwnKeys:n}={})=>(cr(e,(s,o)=>{t&&_e(s)?r[o]=ol(s,t):r[o]=s},{allOwnKeys:n}),r),gu=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),pu=(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)},xu=(r,e,t,n)=>{let s,o,i;const l={};if(e=e||{},r==null)return e;do{for(s=Object.getOwnPropertyNames(r),o=s.length;o-- >0;)i=s[o],(!n||n(i,r,e))&&!l[i]&&(e[i]=r[i],l[i]=!0);r=t!==!1&&ro(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},bu=(r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const n=r.indexOf(e,t);return n!==-1&&n===t},yu=r=>{if(!r)return null;if(Et(r))return r;let e=r.length;if(!ll(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},wu=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&ro(Uint8Array)),vu=(r,e)=>{const n=(r&&r[un]).call(r);let s;for(;(s=n.next())&&!s.done;){const o=s.value;e.call(r,o[0],o[1])}},_u=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},Su=Pe("HTMLFormElement"),Cu=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),ju=Pe("RegExp"),ul=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};cr(t,(s,o)=>{let i;(i=e(s,o,r))!==!1&&(n[o]=i||s)}),Object.defineProperties(r,n)},Au=r=>{ul(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+"'")})}})},ku=(r,e)=>{const t={},n=s=>{s.forEach(o=>{t[o]=!0})};return Et(r)?n(r):n(String(r).split(e)),t},Nu=()=>{},Mu=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function Eu(r){return!!(r&&_e(r.append)&&r[al]==="FormData"&&r[un])}const Iu=r=>{const e=new Array(10),t=(n,s)=>{if(lr(n)){if(e.indexOf(n)>=0)return;if(ir(n))return n;if(!("toJSON"in n)){e[s]=n;const o=Et(n)?[]:{};return cr(n,(i,l)=>{const c=t(i,s+1);!At(c)&&(o[l]=c)}),e[s]=void 0,o}}return n};return t(r,0)},Tu=Pe("AsyncFunction"),Pu=r=>r&&(lr(r)||_e(r))&&_e(r.then)&&_e(r.catch),fl=((r,e)=>r?setImmediate:e?((t,n)=>(st.addEventListener("message",({source:s,data:o})=>{s===st&&o===t&&n.length&&n.shift()()},!1),s=>{n.push(s),st.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",_e(st.postMessage)),Ou=typeof queueMicrotask<"u"?queueMicrotask.bind(st):typeof process<"u"&&process.nextTick||fl,Ru=r=>r!=null&&_e(r[un]),k={isArray:Et,isArrayBuffer:il,isBuffer:ir,isFormData:iu,isArrayBufferView:Qd,isString:Zd,isNumber:ll,isBoolean:eu,isObject:lr,isPlainObject:Pr,isEmptyObject:tu,isReadableStream:cu,isRequest:du,isResponse:uu,isHeaders:fu,isUndefined:At,isDate:ru,isFile:nu,isBlob:su,isRegExp:ju,isFunction:_e,isStream:au,isURLSearchParams:lu,isTypedArray:wu,isFileList:ou,forEach:cr,merge:ls,extend:mu,trim:hu,stripBOM:gu,inherits:pu,toFlatObject:xu,kindOf:fn,kindOfTest:Pe,endsWith:bu,toArray:yu,forEachEntry:vu,matchAll:_u,isHTMLForm:Su,hasOwnProperty:Qo,hasOwnProp:Qo,reduceDescriptors:ul,freezeMethods:Au,toObjectSet:ku,toCamelCase:Cu,noop:Nu,toFiniteNumber:Mu,findKey:cl,global:st,isContextDefined:dl,isSpecCompliantForm:Eu,toJSONObject:Iu,isAsyncFn:Tu,isThenable:Pu,setImmediate:fl,asap:Ou,isIterable:Ru};function ee(r,e,t,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=r,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}k.inherits(ee,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:k.toJSONObject(this.config),code:this.code,status:this.status}}});const hl=ee.prototype,ml={};["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=>{ml[r]={value:r}});Object.defineProperties(ee,ml);Object.defineProperty(hl,"isAxiosError",{value:!0});ee.from=(r,e,t,n,s,o)=>{const i=Object.create(hl);k.toFlatObject(r,i,function(m){return m!==Error.prototype},d=>d!=="isAxiosError");const l=r&&r.message?r.message:"Error",c=e==null&&r?r.code:e;return ee.call(i,l,c,t,n,s),r&&i.cause==null&&Object.defineProperty(i,"cause",{value:r,configurable:!0}),i.name=r&&r.name||"Error",o&&Object.assign(i,o),i};const $u=null;function cs(r){return k.isPlainObject(r)||k.isArray(r)}function gl(r){return k.endsWith(r,"[]")?r.slice(0,-2):r}function Zo(r,e,t){return r?r.concat(e).map(function(s,o){return s=gl(s),!t&&o?"["+s+"]":s}).join(t?".":""):e}function Lu(r){return k.isArray(r)&&!r.some(cs)}const Du=k.toFlatObject(k,{},null,function(e){return/^is[A-Z]/.test(e)});function mn(r,e,t){if(!k.isObject(r))throw new TypeError("target must be an object");e=e||new FormData,t=k.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,u){return!k.isUndefined(u[x])});const n=t.metaTokens,s=t.visitor||m,o=t.dots,i=t.indexes,c=(t.Blob||typeof Blob<"u"&&Blob)&&k.isSpecCompliantForm(e);if(!k.isFunction(s))throw new TypeError("visitor must be a function");function d(h){if(h===null)return"";if(k.isDate(h))return h.toISOString();if(k.isBoolean(h))return h.toString();if(!c&&k.isBlob(h))throw new ee("Blob is not supported. Use a Buffer instead.");return k.isArrayBuffer(h)||k.isTypedArray(h)?c&&typeof Blob=="function"?new Blob([h]):Buffer.from(h):h}function m(h,x,u){let g=h;if(h&&!u&&typeof h=="object"){if(k.endsWith(x,"{}"))x=n?x:x.slice(0,-2),h=JSON.stringify(h);else if(k.isArray(h)&&Lu(h)||(k.isFileList(h)||k.endsWith(x,"[]"))&&(g=k.toArray(h)))return x=gl(x),g.forEach(function(w,S){!(k.isUndefined(w)||w===null)&&e.append(i===!0?Zo([x],S,o):i===null?x:x+"[]",d(w))}),!1}return cs(h)?!0:(e.append(Zo(u,x,o),d(h)),!1)}const f=[],p=Object.assign(Du,{defaultVisitor:m,convertValue:d,isVisitable:cs});function y(h,x){if(!k.isUndefined(h)){if(f.indexOf(h)!==-1)throw Error("Circular reference detected in "+x.join("."));f.push(h),k.forEach(h,function(g,b){(!(k.isUndefined(g)||g===null)&&s.call(e,g,k.isString(b)?b.trim():b,x,p))===!0&&y(g,x?x.concat(b):[b])}),f.pop()}}if(!k.isObject(r))throw new TypeError("data must be an object");return y(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&&mn(r,this,e)}const pl=no.prototype;pl.append=function(e,t){this._pairs.push([e,t])};pl.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 Fu(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function xl(r,e,t){if(!e)return r;const n=t&&t.encode||Fu;k.isFunction(t)&&(t={serialize:t});const s=t&&t.serialize;let o;if(s?o=s(e,t):o=k.isURLSearchParams(e)?e.toString():new no(e,t).toString(n),o){const i=r.indexOf("#");i!==-1&&(r=r.slice(0,i)),r+=(r.indexOf("?")===-1?"?":"&")+o}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){k.forEach(this.handlers,function(n){n!==null&&e(n)})}}const bl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Uu=typeof URLSearchParams<"u"?URLSearchParams:no,Bu=typeof FormData<"u"?FormData:null,Wu=typeof Blob<"u"?Blob:null,Hu={isBrowser:!0,classes:{URLSearchParams:Uu,FormData:Bu,Blob:Wu},protocols:["http","https","file","blob","url","data"]},so=typeof window<"u"&&typeof document<"u",ds=typeof navigator=="object"&&navigator||void 0,qu=so&&(!ds||["ReactNative","NativeScript","NS"].indexOf(ds.product)<0),zu=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Ju=so&&window.location.href||"http://localhost",Vu=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:so,hasStandardBrowserEnv:qu,hasStandardBrowserWebWorkerEnv:zu,navigator:ds,origin:Ju},Symbol.toStringTag,{value:"Module"})),ye={...Vu,...Hu};function Gu(r,e){return mn(r,new ye.classes.URLSearchParams,{visitor:function(t,n,s,o){return ye.isNode&&k.isBuffer(t)?(this.append(n,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function Xu(r){return k.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Ku(r){const e={},t=Object.keys(r);let n;const s=t.length;let o;for(n=0;n<s;n++)o=t[n],e[o]=r[o];return e}function yl(r){function e(t,n,s,o){let i=t[o++];if(i==="__proto__")return!0;const l=Number.isFinite(+i),c=o>=t.length;return i=!i&&k.isArray(s)?s.length:i,c?(k.hasOwnProp(s,i)?s[i]=[s[i],n]:s[i]=n,!l):((!s[i]||!k.isObject(s[i]))&&(s[i]=[]),e(t,n,s[i],o)&&k.isArray(s[i])&&(s[i]=Ku(s[i])),!l)}if(k.isFormData(r)&&k.isFunction(r.entries)){const t={};return k.forEachEntry(r,(n,s)=>{e(Xu(n),s,t,0)}),t}return null}function Yu(r,e,t){if(k.isString(r))try{return(e||JSON.parse)(r),k.trim(r)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(r)}const dr={transitional:bl,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",s=n.indexOf("application/json")>-1,o=k.isObject(e);if(o&&k.isHTMLForm(e)&&(e=new FormData(e)),k.isFormData(e))return s?JSON.stringify(yl(e)):e;if(k.isArrayBuffer(e)||k.isBuffer(e)||k.isStream(e)||k.isFile(e)||k.isBlob(e)||k.isReadableStream(e))return e;if(k.isArrayBufferView(e))return e.buffer;if(k.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let l;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Gu(e,this.formSerializer).toString();if((l=k.isFileList(e))||n.indexOf("multipart/form-data")>-1){const c=this.env&&this.env.FormData;return mn(l?{"files[]":e}:e,c&&new c,this.formSerializer)}}return o||s?(t.setContentType("application/json",!1),Yu(e)):e}],transformResponse:[function(e){const t=this.transitional||dr.transitional,n=t&&t.forcedJSONParsing,s=this.responseType==="json";if(k.isResponse(e)||k.isReadableStream(e))return e;if(e&&k.isString(e)&&(n&&!this.responseType||s)){const i=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e,this.parseReviver)}catch(l){if(i)throw l.name==="SyntaxError"?ee.from(l,ee.ERR_BAD_RESPONSE,this,null,this.response):l}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ye.classes.FormData,Blob:ye.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};k.forEach(["delete","get","head","post","put","patch"],r=>{dr.headers[r]={}});const Qu=k.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"]),Zu=r=>{const e={};let t,n,s;return r&&r.split(`
60
- `).forEach(function(i){s=i.indexOf(":"),t=i.substring(0,s).trim().toLowerCase(),n=i.substring(s+1).trim(),!(!t||e[t]&&Qu[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 Pt(r){return r&&String(r).trim().toLowerCase()}function Or(r){return r===!1||r==null?r:k.isArray(r)?r.map(Or):String(r)}function ef(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 tf=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function $n(r,e,t,n,s){if(k.isFunction(n))return n.call(this,e,t);if(s&&(e=t),!!k.isString(e)){if(k.isString(n))return e.indexOf(n)!==-1;if(k.isRegExp(n))return n.test(e)}}function rf(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function nf(r,e){const t=k.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(r,n+t,{value:function(s,o,i){return this[n].call(this,e,s,o,i)},configurable:!0})})}let Se=class{constructor(e){e&&this.set(e)}set(e,t,n){const s=this;function o(l,c,d){const m=Pt(c);if(!m)throw new Error("header name must be a non-empty string");const f=k.findKey(s,m);(!f||s[f]===void 0||d===!0||d===void 0&&s[f]!==!1)&&(s[f||c]=Or(l))}const i=(l,c)=>k.forEach(l,(d,m)=>o(d,m,c));if(k.isPlainObject(e)||e instanceof this.constructor)i(e,t);else if(k.isString(e)&&(e=e.trim())&&!tf(e))i(Zu(e),t);else if(k.isObject(e)&&k.isIterable(e)){let l={},c,d;for(const m of e){if(!k.isArray(m))throw TypeError("Object iterator must return a key-value pair");l[d=m[0]]=(c=l[d])?k.isArray(c)?[...c,m[1]]:[c,m[1]]:m[1]}i(l,t)}else e!=null&&o(t,e,n);return this}get(e,t){if(e=Pt(e),e){const n=k.findKey(this,e);if(n){const s=this[n];if(!t)return s;if(t===!0)return ef(s);if(k.isFunction(t))return t.call(this,s,n);if(k.isRegExp(t))return t.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,t){if(e=Pt(e),e){const n=k.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||$n(this,this[n],n,t)))}return!1}delete(e,t){const n=this;let s=!1;function o(i){if(i=Pt(i),i){const l=k.findKey(n,i);l&&(!t||$n(n,n[l],l,t))&&(delete n[l],s=!0)}}return k.isArray(e)?e.forEach(o):o(e),s}clear(e){const t=Object.keys(this);let n=t.length,s=!1;for(;n--;){const o=t[n];(!e||$n(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){const t=this,n={};return k.forEach(this,(s,o)=>{const i=k.findKey(n,o);if(i){t[i]=Or(s),delete t[o];return}const l=e?rf(o):String(o).trim();l!==o&&delete t[o],t[l]=Or(s),n[l]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const t=Object.create(null);return k.forEach(this,(n,s)=>{n!=null&&n!==!1&&(t[s]=e&&k.isArray(n)?n.join(", "):n)}),t}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,t])=>e+": "+t).join(`
61
- `)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(s=>n.set(s)),n}static accessor(e){const n=(this[ra]=this[ra]={accessors:{}}).accessors,s=this.prototype;function o(i){const l=Pt(i);n[l]||(nf(s,i),n[l]=!0)}return k.isArray(e)?e.forEach(o):o(e),this}};Se.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);k.reduceDescriptors(Se.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(n){this[t]=n}}});k.freezeMethods(Se);function Ln(r,e){const t=this||dr,n=e||t,s=Se.from(n.headers);let o=n.data;return k.forEach(r,function(l){o=l.call(t,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function wl(r){return!!(r&&r.__CANCEL__)}function It(r,e,t){ee.call(this,r??"canceled",ee.ERR_CANCELED,e,t),this.name="CanceledError"}k.inherits(It,ee,{__CANCEL__:!0});function vl(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new ee("Request failed with status code "+t.status,[ee.ERR_BAD_REQUEST,ee.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function sf(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function of(r,e){r=r||10;const t=new Array(r),n=new Array(r);let s=0,o=0,i;return e=e!==void 0?e:1e3,function(c){const d=Date.now(),m=n[o];i||(i=d),t[s]=c,n[s]=d;let f=o,p=0;for(;f!==s;)p+=t[f++],f=f%r;if(s=(s+1)%r,s===o&&(o=(o+1)%r),d-i<e)return;const y=m&&d-m;return y?Math.round(p*1e3/y):void 0}}function af(r,e){let t=0,n=1e3/e,s,o;const i=(d,m=Date.now())=>{t=m,s=null,o&&(clearTimeout(o),o=null),r(...d)};return[(...d)=>{const m=Date.now(),f=m-t;f>=n?i(d,m):(s=d,o||(o=setTimeout(()=>{o=null,i(s)},n-f)))},()=>s&&i(s)]}const qr=(r,e,t=3)=>{let n=0;const s=of(50,250);return af(o=>{const i=o.loaded,l=o.lengthComputable?o.total:void 0,c=i-n,d=s(c),m=i<=l;n=i;const f={loaded:i,total:l,progress:l?i/l:void 0,bytes:c,rate:d||void 0,estimated:d&&l&&m?(l-i)/d:void 0,event:o,lengthComputable:l!=null,[e?"download":"upload"]:!0};r(f)},t)},na=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},sa=r=>(...e)=>k.asap(()=>r(...e)),lf=ye.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,ye.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(ye.origin),ye.navigator&&/(msie|trident)/i.test(ye.navigator.userAgent)):()=>!0,cf=ye.hasStandardBrowserEnv?{write(r,e,t,n,s,o){const i=[r+"="+encodeURIComponent(e)];k.isNumber(t)&&i.push("expires="+new Date(t).toGMTString()),k.isString(n)&&i.push("path="+n),k.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.join("; ")},read(r){const e=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(r){this.write(r,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function df(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function uf(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function _l(r,e,t){let n=!df(e);return r&&(n||t==!1)?uf(r,e):e}const oa=r=>r instanceof Se?{...r}:r;function ct(r,e){e=e||{};const t={};function n(d,m,f,p){return k.isPlainObject(d)&&k.isPlainObject(m)?k.merge.call({caseless:p},d,m):k.isPlainObject(m)?k.merge({},m):k.isArray(m)?m.slice():m}function s(d,m,f,p){if(k.isUndefined(m)){if(!k.isUndefined(d))return n(void 0,d,f,p)}else return n(d,m,f,p)}function o(d,m){if(!k.isUndefined(m))return n(void 0,m)}function i(d,m){if(k.isUndefined(m)){if(!k.isUndefined(d))return n(void 0,d)}else return n(void 0,m)}function l(d,m,f){if(f in e)return n(d,m);if(f in r)return n(void 0,d)}const c={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:l,headers:(d,m,f)=>s(oa(d),oa(m),f,!0)};return k.forEach(Object.keys({...r,...e}),function(m){const f=c[m]||s,p=f(r[m],e[m],m);k.isUndefined(p)&&f!==l||(t[m]=p)}),t}const Sl=r=>{const e=ct({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:l}=e;if(e.headers=i=Se.from(i),e.url=xl(_l(e.baseURL,e.url,e.allowAbsoluteUrls),r.params,r.paramsSerializer),l&&i.set("Authorization","Basic "+btoa((l.username||"")+":"+(l.password?unescape(encodeURIComponent(l.password)):""))),k.isFormData(t)){if(ye.hasStandardBrowserEnv||ye.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if(k.isFunction(t.getHeaders)){const c=t.getHeaders(),d=["content-type","content-length"];Object.entries(c).forEach(([m,f])=>{d.includes(m.toLowerCase())&&i.set(m,f)})}}if(ye.hasStandardBrowserEnv&&(n&&k.isFunction(n)&&(n=n(e)),n||n!==!1&&lf(e.url))){const c=s&&o&&cf.read(o);c&&i.set(s,c)}return e},ff=typeof XMLHttpRequest<"u",hf=ff&&function(r){return new Promise(function(t,n){const s=Sl(r);let o=s.data;const i=Se.from(s.headers).normalize();let{responseType:l,onUploadProgress:c,onDownloadProgress:d}=s,m,f,p,y,h;function x(){y&&y(),h&&h(),s.cancelToken&&s.cancelToken.unsubscribe(m),s.signal&&s.signal.removeEventListener("abort",m)}let u=new XMLHttpRequest;u.open(s.method.toUpperCase(),s.url,!0),u.timeout=s.timeout;function g(){if(!u)return;const w=Se.from("getAllResponseHeaders"in u&&u.getAllResponseHeaders()),v={data:!l||l==="text"||l==="json"?u.responseText:u.response,status:u.status,statusText:u.statusText,headers:w,config:r,request:u};vl(function(_){t(_),x()},function(_){n(_),x()},v),u=null}"onloadend"in u?u.onloadend=g:u.onreadystatechange=function(){!u||u.readyState!==4||u.status===0&&!(u.responseURL&&u.responseURL.indexOf("file:")===0)||setTimeout(g)},u.onabort=function(){u&&(n(new ee("Request aborted",ee.ECONNABORTED,r,u)),u=null)},u.onerror=function(S){const v=S&&S.message?S.message:"Network Error",C=new ee(v,ee.ERR_NETWORK,r,u);C.event=S||null,n(C),u=null},u.ontimeout=function(){let S=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const v=s.transitional||bl;s.timeoutErrorMessage&&(S=s.timeoutErrorMessage),n(new ee(S,v.clarifyTimeoutError?ee.ETIMEDOUT:ee.ECONNABORTED,r,u)),u=null},o===void 0&&i.setContentType(null),"setRequestHeader"in u&&k.forEach(i.toJSON(),function(S,v){u.setRequestHeader(v,S)}),k.isUndefined(s.withCredentials)||(u.withCredentials=!!s.withCredentials),l&&l!=="json"&&(u.responseType=s.responseType),d&&([p,h]=qr(d,!0),u.addEventListener("progress",p)),c&&u.upload&&([f,y]=qr(c),u.upload.addEventListener("progress",f),u.upload.addEventListener("loadend",y)),(s.cancelToken||s.signal)&&(m=w=>{u&&(n(!w||w.type?new It(null,r,u):w),u.abort(),u=null)},s.cancelToken&&s.cancelToken.subscribe(m),s.signal&&(s.signal.aborted?m():s.signal.addEventListener("abort",m)));const b=sf(s.url);if(b&&ye.protocols.indexOf(b)===-1){n(new ee("Unsupported protocol "+b+":",ee.ERR_BAD_REQUEST,r));return}u.send(o||null)})},mf=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let n=new AbortController,s;const o=function(d){if(!s){s=!0,l();const m=d instanceof Error?d:this.reason;n.abort(m instanceof ee?m:new It(m instanceof Error?m.message:m))}};let i=e&&setTimeout(()=>{i=null,o(new ee(`timeout ${e} of ms exceeded`,ee.ETIMEDOUT))},e);const l=()=>{r&&(i&&clearTimeout(i),i=null,r.forEach(d=>{d.unsubscribe?d.unsubscribe(o):d.removeEventListener("abort",o)}),r=null)};r.forEach(d=>d.addEventListener("abort",o));const{signal:c}=n;return c.unsubscribe=()=>k.asap(l),c}},gf=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},pf=async function*(r,e){for await(const t of xf(r))yield*gf(t,e)},xf=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=pf(r,e);let o=0,i,l=c=>{i||(i=!0,n&&n(c))};return new ReadableStream({async pull(c){try{const{done:d,value:m}=await s.next();if(d){l(),c.close();return}let f=m.byteLength;if(t){let p=o+=f;t(p)}c.enqueue(new Uint8Array(m))}catch(d){throw l(d),d}},cancel(c){return l(c),s.return()}},{highWaterMark:2})},ia=64*1024,{isFunction:Sr}=k,bf=(({Request:r,Response:e})=>({Request:r,Response:e}))(k.global),{ReadableStream:la,TextEncoder:ca}=k.global,da=(r,...e)=>{try{return!!r(...e)}catch{return!1}},yf=r=>{r=k.merge.call({skipUndefined:!0},bf,r);const{fetch:e,Request:t,Response:n}=r,s=e?Sr(e):typeof fetch=="function",o=Sr(t),i=Sr(n);if(!s)return!1;const l=s&&Sr(la),c=s&&(typeof ca=="function"?(h=>x=>h.encode(x))(new ca):async h=>new Uint8Array(await new t(h).arrayBuffer())),d=o&&l&&da(()=>{let h=!1;const x=new t(ye.origin,{body:new la,method:"POST",get duplex(){return h=!0,"half"}}).headers.has("Content-Type");return h&&!x}),m=i&&l&&da(()=>k.isReadableStream(new n("").body)),f={stream:m&&(h=>h.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(h=>{!f[h]&&(f[h]=(x,u)=>{let g=x&&x[h];if(g)return g.call(x);throw new ee(`Response type '${h}' is not supported`,ee.ERR_NOT_SUPPORT,u)})});const p=async h=>{if(h==null)return 0;if(k.isBlob(h))return h.size;if(k.isSpecCompliantForm(h))return(await new t(ye.origin,{method:"POST",body:h}).arrayBuffer()).byteLength;if(k.isArrayBufferView(h)||k.isArrayBuffer(h))return h.byteLength;if(k.isURLSearchParams(h)&&(h=h+""),k.isString(h))return(await c(h)).byteLength},y=async(h,x)=>{const u=k.toFiniteNumber(h.getContentLength());return u??p(x)};return async h=>{let{url:x,method:u,data:g,signal:b,cancelToken:w,timeout:S,onDownloadProgress:v,onUploadProgress:C,responseType:_,headers:T,withCredentials:N="same-origin",fetchOptions:P}=Sl(h),R=e||fetch;_=_?(_+"").toLowerCase():"text";let j=mf([b,w&&w.toAbortSignal()],S),F=null;const O=j&&j.unsubscribe&&(()=>{j.unsubscribe()});let z;try{if(C&&d&&u!=="get"&&u!=="head"&&(z=await y(T,g))!==0){let D=new t(x,{method:"POST",body:g,duplex:"half"}),B;if(k.isFormData(g)&&(B=D.headers.get("content-type"))&&T.setContentType(B),D.body){const[X,M]=na(z,qr(sa(C)));g=aa(D.body,ia,X,M)}}k.isString(N)||(N=N?"include":"omit");const H=o&&"credentials"in t.prototype,E={...P,signal:j,method:u.toUpperCase(),headers:T.normalize().toJSON(),body:g,duplex:"half",credentials:H?N:void 0};F=o&&new t(x,E);let L=await(o?R(F,P):R(x,E));const U=m&&(_==="stream"||_==="response");if(m&&(v||U&&O)){const D={};["status","statusText","headers"].forEach(K=>{D[K]=L[K]});const B=k.toFiniteNumber(L.headers.get("content-length")),[X,M]=v&&na(B,qr(sa(v),!0))||[];L=new n(aa(L.body,ia,X,()=>{M&&M(),O&&O()}),D)}_=_||"text";let $=await f[k.findKey(f,_)||"text"](L,h);return!U&&O&&O(),await new Promise((D,B)=>{vl(D,B,{data:$,headers:Se.from(L.headers),status:L.status,statusText:L.statusText,config:h,request:F})})}catch(H){throw O&&O(),H&&H.name==="TypeError"&&/Load failed|fetch/i.test(H.message)?Object.assign(new ee("Network Error",ee.ERR_NETWORK,h,F),{cause:H.cause||H}):ee.from(H,H&&H.code,h,F)}}},wf=new Map,Cl=r=>{let e=r?r.env:{};const{fetch:t,Request:n,Response:s}=e,o=[n,s,t];let i=o.length,l=i,c,d,m=wf;for(;l--;)c=o[l],d=m.get(c),d===void 0&&m.set(c,d=l?new Map:yf(e)),m=d;return d};Cl();const us={http:$u,xhr:hf,fetch:{get:Cl}};k.forEach(us,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const ua=r=>`- ${r}`,vf=r=>k.isFunction(r)||r===null||r===!1,jl={getAdapter:(r,e)=>{r=k.isArray(r)?r:[r];const{length:t}=r;let n,s;const o={};for(let i=0;i<t;i++){n=r[i];let l;if(s=n,!vf(n)&&(s=us[(l=String(n)).toLowerCase()],s===void 0))throw new ee(`Unknown adapter '${l}'`);if(s&&(k.isFunction(s)||(s=s.get(e))))break;o[l||"#"+i]=s}if(!s){const i=Object.entries(o).map(([c,d])=>`adapter ${c} `+(d===!1?"is not supported by the environment":"is not available in the build"));let l=t?i.length>1?`since :
62
- `+i.map(ua).join(`
63
- `):" "+ua(i[0]):"as no adapter specified";throw new ee("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return s},adapters:us};function Dn(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new It(null,r)}function fa(r){return Dn(r),r.headers=Se.from(r.headers),r.data=Ln.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),jl.getAdapter(r.adapter||dr.adapter,r)(r).then(function(n){return Dn(r),n.data=Ln.call(r,r.transformResponse,n),n.headers=Se.from(n.headers),n},function(n){return wl(n)||(Dn(r),n&&n.response&&(n.response.data=Ln.call(r,r.transformResponse,n.response),n.response.headers=Se.from(n.response.headers))),Promise.reject(n)})}const Al="1.12.2",gn={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{gn[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});const ha={};gn.transitional=function(e,t,n){function s(o,i){return"[Axios v"+Al+"] Transitional option '"+o+"'"+i+(n?". "+n:"")}return(o,i,l)=>{if(e===!1)throw new ee(s(i," has been removed"+(t?" in "+t:"")),ee.ERR_DEPRECATED);return t&&!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(o,i,l):!0}};gn.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function _f(r,e,t){if(typeof r!="object")throw new ee("options must be an object",ee.ERR_BAD_OPTION_VALUE);const n=Object.keys(r);let s=n.length;for(;s-- >0;){const o=n[s],i=e[o];if(i){const l=r[o],c=l===void 0||i(l,o,r);if(c!==!0)throw new ee("option "+o+" must be "+c,ee.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new ee("Unknown option "+o,ee.ERR_BAD_OPTION)}}const Rr={assertOptions:_f,validators:gn},Re=Rr.validators;let ot=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 o=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=`
64
- `+o):n.stack=o}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=ct(this.defaults,t);const{transitional:n,paramsSerializer:s,headers:o}=t;n!==void 0&&Rr.assertOptions(n,{silentJSONParsing:Re.transitional(Re.boolean),forcedJSONParsing:Re.transitional(Re.boolean),clarifyTimeoutError:Re.transitional(Re.boolean)},!1),s!=null&&(k.isFunction(s)?t.paramsSerializer={serialize:s}:Rr.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),Rr.assertOptions(t,{baseUrl:Re.spelling("baseURL"),withXsrfToken:Re.spelling("withXSRFToken")},!0),t.method=(t.method||this.defaults.method||"get").toLowerCase();let i=o&&k.merge(o.common,o[t.method]);o&&k.forEach(["delete","get","head","post","put","patch","common"],h=>{delete o[h]}),t.headers=Se.concat(i,o);const l=[];let c=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(t)===!1||(c=c&&x.synchronous,l.unshift(x.fulfilled,x.rejected))});const d=[];this.interceptors.response.forEach(function(x){d.push(x.fulfilled,x.rejected)});let m,f=0,p;if(!c){const h=[fa.bind(this),void 0];for(h.unshift(...l),h.push(...d),p=h.length,m=Promise.resolve(t);f<p;)m=m.then(h[f++],h[f++]);return m}p=l.length;let y=t;for(;f<p;){const h=l[f++],x=l[f++];try{y=h(y)}catch(u){x.call(this,u);break}}try{m=fa.call(this,y)}catch(h){return Promise.reject(h)}for(f=0,p=d.length;f<p;)m=m.then(d[f++],d[f++]);return m}getUri(e){e=ct(this.defaults,e);const t=_l(e.baseURL,e.url,e.allowAbsoluteUrls);return xl(t,e.params,e.paramsSerializer)}};k.forEach(["delete","get","head","options"],function(e){ot.prototype[e]=function(t,n){return this.request(ct(n||{},{method:e,url:t,data:(n||{}).data}))}});k.forEach(["post","put","patch"],function(e){function t(n){return function(o,i,l){return this.request(ct(l||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}ot.prototype[e]=t(),ot.prototype[e+"Form"]=t(!0)});let Sf=class kl{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let t;this.promise=new Promise(function(o){t=o});const n=this;this.promise.then(s=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](s);n._listeners=null}),this.promise.then=s=>{let o;const i=new Promise(l=>{n.subscribe(l),o=l}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},e(function(o,i,l){n.reason||(n.reason=new It(o,i,l),t(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const t=this._listeners.indexOf(e);t!==-1&&this._listeners.splice(t,1)}toAbortSignal(){const e=new AbortController,t=n=>{e.abort(n)};return this.subscribe(t),e.signal.unsubscribe=()=>this.unsubscribe(t),e.signal}static source(){let e;return{token:new kl(function(s){e=s}),cancel:e}}};function Cf(r){return function(t){return r.apply(null,t)}}function jf(r){return k.isObject(r)&&r.isAxiosError===!0}const fs={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(fs).forEach(([r,e])=>{fs[e]=r});function Nl(r){const e=new ot(r),t=ol(ot.prototype.request,e);return k.extend(t,ot.prototype,e,{allOwnKeys:!0}),k.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return Nl(ct(r,s))},t}const ce=Nl(dr);ce.Axios=ot;ce.CanceledError=It;ce.CancelToken=Sf;ce.isCancel=wl;ce.VERSION=Al;ce.toFormData=mn;ce.AxiosError=ee;ce.Cancel=ce.CanceledError;ce.all=function(e){return Promise.all(e)};ce.spread=Cf;ce.isAxiosError=jf;ce.mergeConfig=ct;ce.AxiosHeaders=Se;ce.formToJSON=r=>yl(k.isHTMLForm(r)?new FormData(r):r);ce.getAdapter=jl.getAdapter;ce.HttpStatusCode=fs;ce.default=ce;const{Axios:Kg,AxiosError:Yg,CanceledError:Qg,isCancel:Zg,CancelToken:ep,VERSION:tp,all:rp,Cancel:np,isAxiosError:sp,spread:op,toFormData:ap,AxiosHeaders:ip,HttpStatusCode:lp,formToJSON:cp,getAdapter:dp,mergeConfig:up}=ce,ma=ce.create({timeout:3e4,headers:{"Content-Type":"application/json"}});class Af{constructor(e){W(this,"mcpServers");W(this,"tools");W(this,"toolMetadata");this.mcpServers=e,this.tools=[],this.toolMetadata=new Map}async init(){await this.buildTools()}async executeStream(e,t,n,s){return new Promise(async(o,i)=>{var l,c,d,m;try{const f=((l=e.function)==null?void 0:l.name)||e.name,p=((c=e.function)==null?void 0:c.arguments)||e.arguments||{};let y=p;if(typeof p=="string")try{y=JSON.parse(p)}catch(u){console.warn("Failed to parse tool arguments:",u),y={}}const h=this.findToolInfo(f);if(!h)throw new Error(`Tool not found: ${f}`);const x=this.toolSupportsStreaming(f);if(console.log("开始调用工具:",x),x)await this.callMcpToolStream(h.serverUrl,h.originalName,y,t,()=>{n(),o()},u=>{s(new Error(u.message||"Tool execution failed")),i(u)});else{const u=await this.callMcpTool(h.serverUrl,h.originalName,y);t(JSON.stringify(u)),n(),o()}}catch(f){if(f.message==="Stream aborted by user"||f.name==="AbortError"){console.log(`Tool ${((d=e.function)==null?void 0:d.name)||e.name} stream aborted by user`),o();return}console.error(`Failed to execute stream tool ${((m=e.function)==null?void 0:m.name)||e.name}:`,f),s(new Error(f.message||"Tool execution failed")),i(f)}})}async execute(e){var n,s,o,i,l,c;console.log("开始调用工具,但是没有用流式的方式");const t=[];for(const d of e)try{const m=((n=d.function)==null?void 0:n.name)||d.name,f=((s=d.function)==null?void 0:s.arguments)||d.arguments||{};if(!m)throw new Error("Tool name is required");let p=f;if(typeof f=="string")try{p=JSON.parse(f)}catch(x){console.warn("Failed to parse tool arguments:",x),p={}}const y=this.findToolInfo(m);if(!y)throw new Error(`Tool not found: ${m}`);const h=await this.callMcpTool(y.serverUrl,y.originalName,p||{});t.push({tool_call_id:d.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:m,content:JSON.stringify(h),createdAt:new Date})}catch(m){if(m.message==="Stream aborted by user"||m.name==="AbortError"){console.log(`Tool ${((o=d.function)==null?void 0:o.name)||d.name} execution aborted by user`),t.push({tool_call_id:d.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:((i=d.function)==null?void 0:i.name)||d.name,content:JSON.stringify({result:"Tool execution aborted by user"})});continue}console.error(`Failed to execute tool ${((l=d.function)==null?void 0:l.name)||d.name}:`,m),t.push({tool_call_id:d.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name:((c=d.function)==null?void 0:c.name)||d.name,content:JSON.stringify({error:m.message||"Tool execution failed"})})}return t}findToolInfo(e){if(this.toolMetadata&&this.toolMetadata.has(e))return this.toolMetadata.get(e)??null;const t=this.tools.find(n=>{var s;return((s=n.function)==null?void 0:s.name)===e});return t&&t.originalName?{originalName:t.originalName,serverName:t.serverName,serverUrl:t.serverUrl}:null}toolSupportsStreaming(e){return!0}async callMcpToolStream(e,t,n,s,o,i){try{const l=`${e}/sse/openai/tool/call`;console.log("MCP Stream Tool Call URL:",l);const c=new AbortController,d=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:c.signal});if(!d.ok)throw new Error(`HTTP error! status: ${d.status}`);const m=d.body.getReader(),f=new TextDecoder;let p="",y=Date.now();const h=setInterval(()=>{if(Date.now()-y>12e4){clearInterval(h),m.cancel(),i(new Error("Stream read timeout: no data received for 2 minutes"));return}},1e4);try{for(;;){const{done:x,value:u}=await m.read();if(x)break;y=Date.now(),p+=f.decode(u,{stream:!0});const g=this.parseSSEEvents(p);p=g.remaining;for(const b of g.parsed)if(await this.handleSSEEvent(b,s,o,i)){clearInterval(h),m.cancel();return}}}finally{clearInterval(h),m.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(`
65
- `);let s={},o=0;for(;o<n.length;){const c=n[o].trim();if(c==="")s.data&&(s.event||(s.event="data"),t.push(s)),s={};else if(c.startsWith("event:"))s.event=c.substring(6).trim();else if(c.startsWith("data:")){const d=c.substring(5).trim();d==="[DONE]"?t.push({event:"end",data:"{}"}):s.data=d}o++}const i=e.lastIndexOf(`
79
+ ${e}`,status:"completed",createdAt:new Date}];let s="";return await new Nl(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 la{constructor(e,t,n,s,a,i,l,d,u,g){q(this,"messages");q(this,"conversationId");q(this,"tools");q(this,"modelConfig");q(this,"callBack");q(this,"mcpToolExecute");q(this,"configUrl");q(this,"isAborted");q(this,"currentAiRequestHandler");q(this,"toolResultProcessor");q(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 Qu(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 x=this.processChunk(h);g.content+=x,this.callBack("tool_stream_chunk",{toolCallId:l.id,chunk:x})},()=>{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 Nl(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?`
80
+ `+s.content:s.content;if(s.data)return typeof s.data=="string"&&s.data.startsWith("data: ")?this.processChunk(s.data,!0):s.data;if(s.ai_stream_chunk)return typeof s.ai_stream_chunk=="string"&&s.ai_stream_chunk.startsWith("data: ")?this.processChunk(s.ai_stream_chunk,!1):s.ai_stream_chunk}}catch{return e}return""}}function kl(r,e){return function(){return r.apply(e,arguments)}}const{toString:Zu}=Object.prototype,{getPrototypeOf:mo}=Object,{iterator:_n,toStringTag:Ml}=Symbol,Sn=(r=>e=>{const t=Zu.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),ze=r=>(r=r.toLowerCase(),e=>Sn(e)===r),Cn=r=>e=>typeof e===r,{isArray:Ut}=Array,Lt=Cn("undefined");function yr(r){return r!==null&&!Lt(r)&&r.constructor!==null&&!Lt(r.constructor)&&Ie(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const El=ze("ArrayBuffer");function ef(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&El(r.buffer),e}const tf=Cn("string"),Ie=Cn("function"),Pl=Cn("number"),br=r=>r!==null&&typeof r=="object",rf=r=>r===!0||r===!1,zr=r=>{if(Sn(r)!=="object")return!1;const e=mo(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Ml in r)&&!(_n in r)},nf=r=>{if(!br(r)||yr(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},sf=ze("Date"),of=ze("File"),af=ze("Blob"),lf=ze("FileList"),cf=r=>br(r)&&Ie(r.pipe),df=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||Ie(r.append)&&((e=Sn(r))==="formdata"||e==="object"&&Ie(r.toString)&&r.toString()==="[object FormData]"))},uf=ze("URLSearchParams"),[ff,hf,mf,gf]=["ReadableStream","Request","Response","Headers"].map(ze),pf=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function wr(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let n,s;if(typeof r!="object"&&(r=[r]),Ut(r))for(n=0,s=r.length;n<s;n++)e.call(null,r[n],n,r);else{if(yr(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 Il(r,e){if(yr(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 mt=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Tl=r=>!Lt(r)&&r!==mt;function bs(){const{caseless:r,skipUndefined:e}=Tl(this)&&this||{},t={},n=(s,a)=>{const i=r&&Il(t,a)||a;zr(t[i])&&zr(s)?t[i]=bs(t[i],s):zr(s)?t[i]=bs({},s):Ut(s)?t[i]=s.slice():(!e||!Lt(s))&&(t[i]=s)};for(let s=0,a=arguments.length;s<a;s++)arguments[s]&&wr(arguments[s],n);return t}const xf=(r,e,t,{allOwnKeys:n}={})=>(wr(e,(s,a)=>{t&&Ie(s)?r[a]=kl(s,t):r[a]=s},{allOwnKeys:n}),r),yf=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),bf=(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)},wf=(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&&mo(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},vf=(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},_f=r=>{if(!r)return null;if(Ut(r))return r;let e=r.length;if(!Pl(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},Sf=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&mo(Uint8Array)),Cf=(r,e)=>{const n=(r&&r[_n]).call(r);let s;for(;(s=n.next())&&!s.done;){const a=s.value;e.call(r,a[0],a[1])}},jf=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},Af=ze("HTMLFormElement"),Nf=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,s){return n.toUpperCase()+s}),ca=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),kf=ze("RegExp"),Ol=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};wr(t,(s,a)=>{let i;(i=e(s,a,r))!==!1&&(n[a]=i||s)}),Object.defineProperties(r,n)},Mf=r=>{Ol(r,(e,t)=>{if(Ie(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=r[t];if(Ie(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+"'")})}})},Ef=(r,e)=>{const t={},n=s=>{s.forEach(a=>{t[a]=!0})};return Ut(r)?n(r):n(String(r).split(e)),t},Pf=()=>{},If=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function Tf(r){return!!(r&&Ie(r.append)&&r[Ml]==="FormData"&&r[_n])}const Of=r=>{const e=new Array(10),t=(n,s)=>{if(br(n)){if(e.indexOf(n)>=0)return;if(yr(n))return n;if(!("toJSON"in n)){e[s]=n;const a=Ut(n)?[]:{};return wr(n,(i,l)=>{const d=t(i,s+1);!Lt(d)&&(a[l]=d)}),e[s]=void 0,a}}return n};return t(r,0)},Rf=ze("AsyncFunction"),Lf=r=>r&&(br(r)||Ie(r))&&Ie(r.then)&&Ie(r.catch),Rl=((r,e)=>r?setImmediate:e?((t,n)=>(mt.addEventListener("message",({source:s,data:a})=>{s===mt&&a===t&&n.length&&n.shift()()},!1),s=>{n.push(s),mt.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",Ie(mt.postMessage)),$f=typeof queueMicrotask<"u"?queueMicrotask.bind(mt):typeof process<"u"&&process.nextTick||Rl,Df=r=>r!=null&&Ie(r[_n]),E={isArray:Ut,isArrayBuffer:El,isBuffer:yr,isFormData:df,isArrayBufferView:ef,isString:tf,isNumber:Pl,isBoolean:rf,isObject:br,isPlainObject:zr,isEmptyObject:nf,isReadableStream:ff,isRequest:hf,isResponse:mf,isHeaders:gf,isUndefined:Lt,isDate:sf,isFile:of,isBlob:af,isRegExp:kf,isFunction:Ie,isStream:cf,isURLSearchParams:uf,isTypedArray:Sf,isFileList:lf,forEach:wr,merge:bs,extend:xf,trim:pf,stripBOM:yf,inherits:bf,toFlatObject:wf,kindOf:Sn,kindOfTest:ze,endsWith:vf,toArray:_f,forEachEntry:Cf,matchAll:jf,isHTMLForm:Af,hasOwnProperty:ca,hasOwnProp:ca,reduceDescriptors:Ol,freezeMethods:Mf,toObjectSet:Ef,toCamelCase:Nf,noop:Pf,toFiniteNumber:If,findKey:Il,global:mt,isContextDefined:Tl,isSpecCompliantForm:Tf,toJSONObject:Of,isAsyncFn:Rf,isThenable:Lf,setImmediate:Rl,asap:$f,isIterable:Df};function re(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(re,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 Ll=re.prototype,$l={};["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=>{$l[r]={value:r}});Object.defineProperties(re,$l);Object.defineProperty(Ll,"isAxiosError",{value:!0});re.from=(r,e,t,n,s,a)=>{const i=Object.create(Ll);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 re.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 Ff=null;function ws(r){return E.isPlainObject(r)||E.isArray(r)}function Dl(r){return E.endsWith(r,"[]")?r.slice(0,-2):r}function da(r,e,t){return r?r.concat(e).map(function(s,a){return s=Dl(s),!t&&a?"["+s+"]":s}).join(t?".":""):e}function Uf(r){return E.isArray(r)&&!r.some(ws)}const Bf=E.toFlatObject(E,{},null,function(e){return/^is[A-Z]/.test(e)});function jn(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 re("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 p=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)&&Uf(m)||(E.isFileList(m)||E.endsWith(f,"[]"))&&(p=E.toArray(m)))return f=Dl(f),p.forEach(function(b,S){!(E.isUndefined(b)||b===null)&&e.append(i===!0?da([f],S,a):i===null?f:f+"[]",u(b))}),!1}return ws(m)?!0:(e.append(da(c,f,a),u(m)),!1)}const h=[],x=Object.assign(Bf,{defaultVisitor:g,convertValue:u,isVisitable:ws});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(p,y){(!(E.isUndefined(p)||p===null)&&s.call(e,p,E.isString(y)?y.trim():y,f,x))===!0&&w(p,f?f.concat(y):[y])}),h.pop()}}if(!E.isObject(r))throw new TypeError("data must be an object");return w(r),e}function ua(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function go(r,e){this._pairs=[],r&&jn(r,this,e)}const Fl=go.prototype;Fl.append=function(e,t){this._pairs.push([e,t])};Fl.toString=function(e){const t=e?function(n){return e.call(this,n,ua)}:ua;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function Wf(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Ul(r,e,t){if(!e)return r;const n=t&&t.encode||Wf;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 go(e,t).toString(n),a){const i=r.indexOf("#");i!==-1&&(r=r.slice(0,i)),r+=(r.indexOf("?")===-1?"?":"&")+a}return r}class fa{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 Bl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Hf=typeof URLSearchParams<"u"?URLSearchParams:go,zf=typeof FormData<"u"?FormData:null,qf=typeof Blob<"u"?Blob:null,Jf={isBrowser:!0,classes:{URLSearchParams:Hf,FormData:zf,Blob:qf},protocols:["http","https","file","blob","url","data"]},po=typeof window<"u"&&typeof document<"u",vs=typeof navigator=="object"&&navigator||void 0,Vf=po&&(!vs||["ReactNative","NativeScript","NS"].indexOf(vs.product)<0),Xf=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",Gf=po&&window.location.href||"http://localhost",Yf=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:po,hasStandardBrowserEnv:Vf,hasStandardBrowserWebWorkerEnv:Xf,navigator:vs,origin:Gf},Symbol.toStringTag,{value:"Module"})),Ne={...Yf,...Jf};function Kf(r,e){return jn(r,new Ne.classes.URLSearchParams,{visitor:function(t,n,s,a){return Ne.isNode&&E.isBuffer(t)?(this.append(n,t.toString("base64")),!1):a.defaultVisitor.apply(this,arguments)},...e})}function Qf(r){return E.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function Zf(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 Wl(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]=Zf(s[i])),!l)}if(E.isFormData(r)&&E.isFunction(r.entries)){const t={};return E.forEachEntry(r,(n,s)=>{e(Qf(n),s,t,0)}),t}return null}function eh(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 vr={transitional:Bl,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(Wl(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 Kf(e,this.formSerializer).toString();if((l=E.isFileList(e))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return jn(l?{"files[]":e}:e,d&&new d,this.formSerializer)}}return a||s?(t.setContentType("application/json",!1),eh(e)):e}],transformResponse:[function(e){const t=this.transitional||vr.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"?re.from(l,re.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:Ne.classes.FormData,Blob:Ne.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=>{vr.headers[r]={}});const th=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"]),rh=r=>{const e={};let t,n,s;return r&&r.split(`
81
+ `).forEach(function(i){s=i.indexOf(":"),t=i.substring(0,s).trim().toLowerCase(),n=i.substring(s+1).trim(),!(!t||e[t]&&th[t])&&(t==="set-cookie"?e[t]?e[t].push(n):e[t]=[n]:e[t]=e[t]?e[t]+", "+n:n)}),e},ha=Symbol("internals");function zt(r){return r&&String(r).trim().toLowerCase()}function qr(r){return r===!1||r==null?r:E.isArray(r)?r.map(qr):String(r)}function nh(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 sh=r=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(r.trim());function Vn(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 oh(r){return r.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,t,n)=>t.toUpperCase()+n)}function ah(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 Te=class{constructor(e){e&&this.set(e)}set(e,t,n){const s=this;function a(l,d,u){const g=zt(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]=qr(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())&&!sh(e))i(rh(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=zt(e),e){const n=E.findKey(this,e);if(n){const s=this[n];if(!t)return s;if(t===!0)return nh(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=zt(e),e){const n=E.findKey(this,e);return!!(n&&this[n]!==void 0&&(!t||Vn(this,this[n],n,t)))}return!1}delete(e,t){const n=this;let s=!1;function a(i){if(i=zt(i),i){const l=E.findKey(n,i);l&&(!t||Vn(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||Vn(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]=qr(s),delete t[a];return}const l=e?oh(a):String(a).trim();l!==a&&delete t[a],t[l]=qr(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(`
82
+ `)}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[ha]=this[ha]={accessors:{}}).accessors,s=this.prototype;function a(i){const l=zt(i);n[l]||(ah(s,i),n[l]=!0)}return E.isArray(e)?e.forEach(a):a(e),this}};Te.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);E.reduceDescriptors(Te.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(n){this[t]=n}}});E.freezeMethods(Te);function Xn(r,e){const t=this||vr,n=e||t,s=Te.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 Hl(r){return!!(r&&r.__CANCEL__)}function Bt(r,e,t){re.call(this,r??"canceled",re.ERR_CANCELED,e,t),this.name="CanceledError"}E.inherits(Bt,re,{__CANCEL__:!0});function zl(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new re("Request failed with status code "+t.status,[re.ERR_BAD_REQUEST,re.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function ih(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function lh(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,x=0;for(;h!==s;)x+=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(x*1e3/w):void 0}}function ch(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 tn=(r,e,t=3)=>{let n=0;const s=lh(50,250);return ch(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)},ma=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},ga=r=>(...e)=>E.asap(()=>r(...e)),dh=Ne.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,Ne.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(Ne.origin),Ne.navigator&&/(msie|trident)/i.test(Ne.navigator.userAgent)):()=>!0,uh=Ne.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 fh(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function hh(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function ql(r,e,t){let n=!fh(e);return r&&(n||t==!1)?hh(r,e):e}const pa=r=>r instanceof Te?{...r}:r;function wt(r,e){e=e||{};const t={};function n(u,g,h,x){return E.isPlainObject(u)&&E.isPlainObject(g)?E.merge.call({caseless:x},u,g):E.isPlainObject(g)?E.merge({},g):E.isArray(g)?g.slice():g}function s(u,g,h,x){if(E.isUndefined(g)){if(!E.isUndefined(u))return n(void 0,u,h,x)}else return n(u,g,h,x)}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(pa(u),pa(g),h,!0)};return E.forEach(Object.keys({...r,...e}),function(g){const h=d[g]||s,x=h(r[g],e[g],g);E.isUndefined(x)&&h!==l||(t[g]=x)}),t}const Jl=r=>{const e=wt({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:a,headers:i,auth:l}=e;if(e.headers=i=Te.from(i),e.url=Ul(ql(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(Ne.hasStandardBrowserEnv||Ne.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(Ne.hasStandardBrowserEnv&&(n&&E.isFunction(n)&&(n=n(e)),n||n!==!1&&dh(e.url))){const d=s&&a&&uh.read(a);d&&i.set(s,d)}return e},mh=typeof XMLHttpRequest<"u",gh=mh&&function(r){return new Promise(function(t,n){const s=Jl(r);let a=s.data;const i=Te.from(s.headers).normalize();let{responseType:l,onUploadProgress:d,onDownloadProgress:u}=s,g,h,x,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 p(){if(!c)return;const b=Te.from("getAllResponseHeaders"in c&&c.getAllResponseHeaders()),_={data:!l||l==="text"||l==="json"?c.responseText:c.response,status:c.status,statusText:c.statusText,headers:b,config:r,request:c};zl(function(v){t(v),f()},function(v){n(v),f()},_),c=null}"onloadend"in c?c.onloadend=p:c.onreadystatechange=function(){!c||c.readyState!==4||c.status===0&&!(c.responseURL&&c.responseURL.indexOf("file:")===0)||setTimeout(p)},c.onabort=function(){c&&(n(new re("Request aborted",re.ECONNABORTED,r,c)),c=null)},c.onerror=function(S){const _=S&&S.message?S.message:"Network Error",j=new re(_,re.ERR_NETWORK,r,c);j.event=S||null,n(j),c=null},c.ontimeout=function(){let S=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const _=s.transitional||Bl;s.timeoutErrorMessage&&(S=s.timeoutErrorMessage),n(new re(S,_.clarifyTimeoutError?re.ETIMEDOUT:re.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&&([x,m]=tn(u,!0),c.addEventListener("progress",x)),d&&c.upload&&([h,w]=tn(d),c.upload.addEventListener("progress",h),c.upload.addEventListener("loadend",w)),(s.cancelToken||s.signal)&&(g=b=>{c&&(n(!b||b.type?new Bt(null,r,c):b),c.abort(),c=null)},s.cancelToken&&s.cancelToken.subscribe(g),s.signal&&(s.signal.aborted?g():s.signal.addEventListener("abort",g)));const y=ih(s.url);if(y&&Ne.protocols.indexOf(y)===-1){n(new re("Unsupported protocol "+y+":",re.ERR_BAD_REQUEST,r));return}c.send(a||null)})},ph=(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 re?g:new Bt(g instanceof Error?g.message:g))}};let i=e&&setTimeout(()=>{i=null,a(new re(`timeout ${e} of ms exceeded`,re.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}},xh=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},yh=async function*(r,e){for await(const t of bh(r))yield*xh(t,e)},bh=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()}},xa=(r,e,t,n)=>{const s=yh(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 x=a+=h;t(x)}d.enqueue(new Uint8Array(g))}catch(u){throw l(u),u}},cancel(d){return l(d),s.return()}},{highWaterMark:2})},ya=64*1024,{isFunction:Or}=E,wh=(({Request:r,Response:e})=>({Request:r,Response:e}))(E.global),{ReadableStream:ba,TextEncoder:wa}=E.global,va=(r,...e)=>{try{return!!r(...e)}catch{return!1}},vh=r=>{r=E.merge.call({skipUndefined:!0},wh,r);const{fetch:e,Request:t,Response:n}=r,s=e?Or(e):typeof fetch=="function",a=Or(t),i=Or(n);if(!s)return!1;const l=s&&Or(ba),d=s&&(typeof wa=="function"?(m=>f=>m.encode(f))(new wa):async m=>new Uint8Array(await new t(m).arrayBuffer())),u=a&&l&&va(()=>{let m=!1;const f=new t(Ne.origin,{body:new ba,method:"POST",get duplex(){return m=!0,"half"}}).headers.has("Content-Type");return m&&!f}),g=i&&l&&va(()=>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 p=f&&f[m];if(p)return p.call(f);throw new re(`Response type '${m}' is not supported`,re.ERR_NOT_SUPPORT,c)})});const x=async m=>{if(m==null)return 0;if(E.isBlob(m))return m.size;if(E.isSpecCompliantForm(m))return(await new t(Ne.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??x(f)};return async m=>{let{url:f,method:c,data:p,signal:y,cancelToken:b,timeout:S,onDownloadProgress:_,onUploadProgress:j,responseType:v,headers:I,withCredentials:M="same-origin",fetchOptions:O}=Jl(m),L=e||fetch;v=v?(v+"").toLowerCase():"text";let C=ph([y,b&&b.toAbortSignal()],S),H=null;const D=C&&C.unsubscribe&&(()=>{C.unsubscribe()});let V;try{if(j&&u&&c!=="get"&&c!=="head"&&(V=await w(I,p))!==0){let J=new t(f,{method:"POST",body:p,duplex:"half"}),ee;if(E.isFormData(p)&&(ee=J.headers.get("content-type"))&&I.setContentType(ee),J.body){const[U,N]=ma(V,tn(ga(j)));p=xa(J.body,ya,U,N)}}E.isString(M)||(M=M?"include":"omit");const X=a&&"credentials"in t.prototype,F={...O,signal:C,method:c.toUpperCase(),headers:I.normalize().toJSON(),body:p,duplex:"half",credentials:X?M:void 0};H=a&&new t(f,F);let Y=await(a?L(H,O):L(f,F));const ae=g&&(v==="stream"||v==="response");if(g&&(_||ae&&D)){const J={};["status","statusText","headers"].forEach($=>{J[$]=Y[$]});const ee=E.toFiniteNumber(Y.headers.get("content-length")),[U,N]=_&&ma(ee,tn(ga(_),!0))||[];Y=new n(xa(Y.body,ya,U,()=>{N&&N(),D&&D()}),J)}v=v||"text";let W=await h[E.findKey(h,v)||"text"](Y,m);return!ae&&D&&D(),await new Promise((J,ee)=>{zl(J,ee,{data:W,headers:Te.from(Y.headers),status:Y.status,statusText:Y.statusText,config:m,request:H})})}catch(X){throw D&&D(),X&&X.name==="TypeError"&&/Load failed|fetch/i.test(X.message)?Object.assign(new re("Network Error",re.ERR_NETWORK,m,H),{cause:X.cause||X}):re.from(X,X&&X.code,m,H)}}},_h=new Map,Vl=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=_h;for(;l--;)d=a[l],u=g.get(d),u===void 0&&g.set(d,u=l?new Map:vh(e)),g=u;return u};Vl();const _s={http:Ff,xhr:gh,fetch:{get:Vl}};E.forEach(_s,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const _a=r=>`- ${r}`,Sh=r=>E.isFunction(r)||r===null||r===!1,Xl={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,!Sh(n)&&(s=_s[(l=String(n)).toLowerCase()],s===void 0))throw new re(`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 :
83
+ `+i.map(_a).join(`
84
+ `):" "+_a(i[0]):"as no adapter specified";throw new re("There is no suitable adapter to dispatch the request "+l,"ERR_NOT_SUPPORT")}return s},adapters:_s};function Gn(r){if(r.cancelToken&&r.cancelToken.throwIfRequested(),r.signal&&r.signal.aborted)throw new Bt(null,r)}function Sa(r){return Gn(r),r.headers=Te.from(r.headers),r.data=Xn.call(r,r.transformRequest),["post","put","patch"].indexOf(r.method)!==-1&&r.headers.setContentType("application/x-www-form-urlencoded",!1),Xl.getAdapter(r.adapter||vr.adapter,r)(r).then(function(n){return Gn(r),n.data=Xn.call(r,r.transformResponse,n),n.headers=Te.from(n.headers),n},function(n){return Hl(n)||(Gn(r),n&&n.response&&(n.response.data=Xn.call(r,r.transformResponse,n.response),n.response.headers=Te.from(n.response.headers))),Promise.reject(n)})}const Gl="1.12.2",An={};["object","boolean","number","function","string","symbol"].forEach((r,e)=>{An[r]=function(n){return typeof n===r||"a"+(e<1?"n ":" ")+r}});const Ca={};An.transitional=function(e,t,n){function s(a,i){return"[Axios v"+Gl+"] Transitional option '"+a+"'"+i+(n?". "+n:"")}return(a,i,l)=>{if(e===!1)throw new re(s(i," has been removed"+(t?" in "+t:"")),re.ERR_DEPRECATED);return t&&!Ca[i]&&(Ca[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}};An.spelling=function(e){return(t,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function Ch(r,e,t){if(typeof r!="object")throw new re("options must be an object",re.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 re("option "+a+" must be "+d,re.ERR_BAD_OPTION_VALUE);continue}if(t!==!0)throw new re("Unknown option "+a,re.ERR_BAD_OPTION)}}const Jr={assertOptions:Ch,validators:An},Je=Jr.validators;let pt=class{constructor(e){this.defaults=e||{},this.interceptors={request:new fa,response:new fa}}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+=`
85
+ `+a):n.stack=a}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=wt(this.defaults,t);const{transitional:n,paramsSerializer:s,headers:a}=t;n!==void 0&&Jr.assertOptions(n,{silentJSONParsing:Je.transitional(Je.boolean),forcedJSONParsing:Je.transitional(Je.boolean),clarifyTimeoutError:Je.transitional(Je.boolean)},!1),s!=null&&(E.isFunction(s)?t.paramsSerializer={serialize:s}:Jr.assertOptions(s,{encode:Je.function,serialize:Je.function},!0)),t.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?t.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:t.allowAbsoluteUrls=!0),Jr.assertOptions(t,{baseUrl:Je.spelling("baseURL"),withXsrfToken:Je.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=Te.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,x;if(!d){const m=[Sa.bind(this),void 0];for(m.unshift(...l),m.push(...u),x=m.length,g=Promise.resolve(t);h<x;)g=g.then(m[h++],m[h++]);return g}x=l.length;let w=t;for(;h<x;){const m=l[h++],f=l[h++];try{w=m(w)}catch(c){f.call(this,c);break}}try{g=Sa.call(this,w)}catch(m){return Promise.reject(m)}for(h=0,x=u.length;h<x;)g=g.then(u[h++],u[h++]);return g}getUri(e){e=wt(this.defaults,e);const t=ql(e.baseURL,e.url,e.allowAbsoluteUrls);return Ul(t,e.params,e.paramsSerializer)}};E.forEach(["delete","get","head","options"],function(e){pt.prototype[e]=function(t,n){return this.request(wt(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(wt(l||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:a,data:i}))}}pt.prototype[e]=t(),pt.prototype[e+"Form"]=t(!0)});let jh=class Yl{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 Bt(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 Yl(function(s){e=s}),cancel:e}}};function Ah(r){return function(t){return r.apply(null,t)}}function Nh(r){return E.isObject(r)&&r.isAxiosError===!0}const Ss={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(Ss).forEach(([r,e])=>{Ss[e]=r});function Kl(r){const e=new pt(r),t=kl(pt.prototype.request,e);return E.extend(t,pt.prototype,e,{allOwnKeys:!0}),E.extend(t,e,null,{allOwnKeys:!0}),t.create=function(s){return Kl(wt(r,s))},t}const pe=Kl(vr);pe.Axios=pt;pe.CanceledError=Bt;pe.CancelToken=jh;pe.isCancel=Hl;pe.VERSION=Gl;pe.toFormData=jn;pe.AxiosError=re;pe.Cancel=pe.CanceledError;pe.all=function(e){return Promise.all(e)};pe.spread=Ah;pe.isAxiosError=Nh;pe.mergeConfig=wt;pe.AxiosHeaders=Te;pe.formToJSON=r=>Wl(E.isHTMLForm(r)?new FormData(r):r);pe.getAdapter=Xl.getAdapter;pe.HttpStatusCode=Ss;pe.default=pe;const{Axios:Zp,AxiosError:ex,CanceledError:tx,isCancel:rx,CancelToken:nx,VERSION:sx,all:ox,Cancel:ax,isAxiosError:ix,spread:lx,toFormData:cx,AxiosHeaders:dx,HttpStatusCode:ux,formToJSON:fx,getAdapter:hx,mergeConfig:mx}=pe,ja=pe.create({timeout:3e4,headers:{"Content-Type":"application/json"}});class kh{constructor(e){q(this,"mcpServers");q(this,"tools");q(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,x=((d=e.function)==null?void 0:d.arguments)||e.arguments||{};let w=x;if(typeof x=="string")try{w=JSON.parse(x)}catch(c){console.warn("Failed to parse tool arguments:",c),w={}}const m=this.findToolInfo(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 x=h;if(typeof h=="string")try{x=JSON.parse(h)}catch(f){console.warn("Failed to parse tool arguments:",f),x={}}const w=this.findToolInfo(g);if(!w)throw new Error(`Tool not found: ${g}`);const m=await this.callMcpTool(w.serverUrl,w.originalName,x||{});t.push({tool_call_id:u.id||`call_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,role:"tool",name: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 x="",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(),x+=h.decode(c,{stream:!0});const p=this.parseSSEEvents(x);x=p.remaining;for(const y of p.parsed)if(await this.handleSSEEvent(y,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(`
86
+ `);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(`
66
87
 
67
- `),l=i>=0?e.substring(i+2):e;return{parsed:t,remaining:l}}async handleSSEEvent(e,t,n,s){try{const o=JSON.parse(e.data);switch(e.event){case"start":return console.log("Stream started:",o),!1;case"data":if(console.log("Stream data:",o),o.choices&&o.choices.length>0){const i=o.choices[0];if(i.delta){const l=i.delta;l.content&&l.content?t(l.content):l.function_call&&l.function_call.arguments&&t(l.function_call.arguments)}}else o.chunk&&t(o.chunk);return!1;case"end":return console.log("Stream completed:",o),n(),!0;case"error":return console.error("Stream error:",o),s(new Error(o.error||"Stream error")),!0;default:return console.warn("Unknown SSE event:",e.event,o),!1}}catch(o){return console.error("Failed to parse SSE event:",o),s(new Error(o.message||"SSE parse error")),!0}}async callMcpTool(e,t,n){try{const s={jsonrpc:"2.0",id:`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,method:"tools/call",params:{name:t,arguments:n||{}}},o=`${e}`;console.log("MCP Tool Call URL:",o);const i=await ma.post(o,s);if(i.data.error)throw new Error(`MCP tool call failed: ${i.data.error.message}`);return i.data.result}catch(s){throw console.error(`Failed to call MCP tool ${t}:`,s),s}}async buildTools(){var e;try{this.tools=[];for(const t of this.mcpServers)try{const n={jsonrpc:"2.0",id:`req_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,method:"tools/list",params:{}},s=`${t.url}`;console.log("MCP Tools List URL:",s);const o=await ma.post(s,n);if(o.data.error)throw new Error(`MCP tools/list failed: ${o.data.error.message}`);const l=(((e=o.data.result)==null?void 0:e.tools)||[]).map(c=>{const d={type:"function",function:{name:`${t.name}_${c.name}`,description:c.description,parameters:c.input_schema||c.inputSchema||c.parameters||{}}};return this.toolMetadata=this.toolMetadata||new Map,this.toolMetadata.set(`${t.name}_${c.name}`,{originalName:c.name,serverName:t.name,serverUrl:t.url,supportsStreaming:!0}),d});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 Ml{constructor(e,t,n,s=null,o,i){W(this,"conversationId");W(this,"userId");W(this,"conversation");W(this,"mcpServers");W(this,"messages");W(this,"tools");W(this,"mcpToolsExecute");W(this,"modelConfig");W(this,"currentThread");W(this,"isAborted");W(this,"messageManager");W(this,"configUrl");W(this,"sessionId");this.conversationId=e,this.userId=t,this.conversation=null,this.mcpServers=[],this.messages=[],this.tools=[],this.mcpToolsExecute=null,this.modelConfig=s,this.messageManager=n,this.configUrl=o||"/api",this.sessionId=i||e,console.log("🔧 AiServer Constructor - configUrl:",this.configUrl),this.currentThread=null,this.isAborted=!1}async init(){var e;try{const t=await Ar.getDetails(this.conversationId);this.conversation=t.data.conversation,console.log("AiServer - Conversation:",this.conversation),console.log("AiServer - API Key:",(e=this.modelConfig)!=null&&e.api_key?"Present":"Missing");const n=await re.getMcpConfigs(this.userId);console.log("mcpResponse",n);const o=(Array.isArray(n)?n:[]).filter(i=>i.enabled);this.mcpServers=o.map((i,l)=>({id:i.id||`mcp-server-${l}`,name:i.name,url:i.command,config:i.config||{}})),this.mcpToolsExecute=new Af(this.mcpServers),await this.mcpToolsExecute.init(),this.tools=this.mcpToolsExecute.getTools()}catch(t){throw console.error("AiServer init failed:",t),t}}callback(e,t){switch(e){case"chunk":console.log("Received chunk:",t);break;case"tool_call":console.log("Tool call:",t);break;case"error":console.error("AI Client error:",t);break;case"complete":console.log("AI response complete:",t);break;default:console.log("Unknown callback type:",e,t)}}async sendMessage(e){var t,n;try{if(console.log("AiServer sendMessage called with:",e),console.log("Message type:",typeof e),console.log("Message length:",e==null?void 0:e.length),!this.conversation)return this.sendMessageDirect(e);console.log("Processing user message:",e);const i=((await Ar.getMessages(this.conversationId,{limit:2})).data.messages||[]).sort((y,h)=>{const x=new Date(y.created_at||y.timestamp||0),u=new Date(h.created_at||h.timestamp||0),g=isNaN(x.getTime())?0:x.getTime(),b=isNaN(u.getTime())?0:u.getTime();return g-b});this.messages=[];let l="";try{const y=await fetch(`/api/system-context/active?userId=${this.userId}`);y.ok&&(l=(await y.json()).content||"")}catch(y){console.log("Failed to load system context:",y)}this.conversation&&this.conversation.global_prompt&&(l?l=this.conversation.global_prompt+`
88
+ `),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 ja.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 ja.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 Ql{constructor(e,t,n,s=null,a,i){q(this,"conversationId");q(this,"userId");q(this,"conversation");q(this,"mcpServers");q(this,"messages");q(this,"tools");q(this,"mcpToolsExecute");q(this,"modelConfig");q(this,"currentThread");q(this,"isAborted");q(this,"messageManager");q(this,"configUrl");q(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 $r.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 ie.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 kh(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 $r.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),p=isNaN(f.getTime())?0:f.getTime(),y=isNaN(c.getTime())?0:c.getTime();return p-y});this.messages=[];let l="";try{const w=await fetch(`/api/system-context/active?userId=${this.userId}`);w.ok&&(l=(await w.json()).content||"")}catch(w){console.log("Failed to load system context:",w)}this.conversation&&this.conversation.global_prompt&&(l?l=this.conversation.global_prompt+`
68
89
 
69
- `+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 c=i.slice(-2);this.messages.push(...c),console.log("Messages prepared for AI:",this.messages.map(y=>({role:y.role,content:(y.content||y.message||"").substring(0,50)+"...",created_at:y.created_at})));const d=`thread_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,m=new AbortController,f=new Yo(this.messages,this.conversationId,this.tools,this.modelConfig,(y,h)=>this.callback(y,h),this.mcpToolsExecute,this.messageManager,this.configUrl,m,this.sessionId),p={id:d,aiClient:f,abortController:m,isRunning:!0,startTime:Date.now()};this.currentThread=p,console.log(`AiServer: Created request thread ${d}`);try{if(this.isAborted||!p.isRunning){console.log(`AiServer: Thread ${d} was aborted before start`);return}await f.start(),console.log(`AiServer: Thread ${d} completed successfully`)}catch(y){if(this.isAborted||!p.isRunning){console.log(`AiServer: Thread ${d} was aborted during execution`);return}if(y.message==="Stream aborted by user"||y.name==="AbortError"){console.log(`AiServer: Thread ${d} aborted by user`);return}throw console.error(`AiServer: Thread ${d} failed:`,y),y}finally{((t=this.currentThread)==null?void 0:t.id)===d&&(this.currentThread.isRunning=!1,this.currentThread=null,console.log(`AiServer: Thread ${d} cleaned up`))}}catch(s){if(s.message==="Stream aborted by user"||s.name==="AbortError"||this.isAborted){console.log("sendMessage aborted by user");return}throw console.error("sendMessage failed:",s),console.error("Error details:",(n=s.response)==null?void 0:n.data),this.callback("error",s),s}}async sendMessageDirect(e){var t;try{console.log("AiServer sendMessageDirect called with:",e),this.messages=[{role:"user",content:e}],console.log("Messages prepared for AI:",this.messages);const n=`direct_thread_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=new AbortController,o=new Yo(this.messages,this.conversationId,[],this.modelConfig,(l,c)=>this.callback(l,c),null,this.messageManager,this.configUrl,s,this.sessionId),i={id:n,aiClient:o,abortController:s,isRunning:!0,startTime:Date.now()};this.currentThread=i,console.log(`AiServer: Created direct thread ${n}`);try{if(this.isAborted||!i.isRunning){console.log(`AiServer: Direct thread ${n} was aborted before start`);return}await o.start(),console.log(`AiServer: Direct thread ${n} completed successfully`)}catch(l){if(this.isAborted||!i.isRunning){console.log(`AiServer: Direct thread ${n} was aborted during execution`);return}throw console.error(`AiServer: Direct thread ${n} failed:`,l),l}finally{((t=this.currentThread)==null?void 0:t.id)===n&&(this.currentThread.isRunning=!1,this.currentThread=null,console.log(`AiServer: Direct thread ${n} cleaned up`))}}catch(n){throw console.error("sendMessageDirect failed:",n),this.callback("error",n),n}}async getMessages(e={}){try{const t=await Ar.getMessages(this.conversationId,e);return this.messages=t.data.messages||[],t.data}catch(t){throw console.error("getMessages failed:",t),t}}async addMessage(e,t="user"){try{return{message:await this.messageManager.saveMessage({content:e,role:t,sessionId:this.conversationId,createdAt:new Date})}}catch(n){throw console.error("addMessage failed:",n),n}}abort(){console.log("AiServer: Abort called"),this.isAborted=!0;debugger;this.currentThread?(console.log(`AiServer: Aborting thread ${this.currentThread.id}`),this.currentThread.isRunning=!1,this.currentThread.abortController.signal.aborted||(this.currentThread.abortController.abort(),console.log(`AiServer: Thread ${this.currentThread.id} AbortController aborted`)),this.currentThread.aiClient&&(this.currentThread.aiClient.abort(),console.log(`AiServer: Thread ${this.currentThread.id} AI client aborted`)),this.currentThread=null,console.log("AiServer: Thread reference cleared")):console.log("AiServer: No active thread to abort")}isRequestAborted(){return this.isAborted}resetAbortState(){this.isAborted=!1,this.currentThread&&(this.currentThread.isRunning=!1,this.currentThread=null)}}class El{constructor(e){W(this,"pendingSaves",new Set);W(this,"savedMessages",new Map);W(this,"databaseService");this.databaseService=e}async saveUserMessage(e){var n;const t=`${e.sessionId}-${e.role}-${e.content}-${(n=e.createdAt)==null?void 0:n.getTime()}`;if(this.pendingSaves.has(t)){for(;this.pendingSaves.has(t);)await new Promise(o=>setTimeout(o,10));const s=this.savedMessages.get(t);if(s)return s}this.pendingSaves.add(t);try{const s=await this.databaseService.createMessage(e);return this.savedMessages.set(t,s),s}finally{this.pendingSaves.delete(t)}}async saveAssistantMessage(e){var n,s;const t=`${e.sessionId}-${e.role}-${JSON.stringify(((n=e.metadata)==null?void 0:n.toolCalls)||[])}-${(s=e.createdAt)==null?void 0:s.getTime()}`;if(this.pendingSaves.has(t)){for(;this.pendingSaves.has(t);)await new Promise(i=>setTimeout(i,10));const o=this.savedMessages.get(t);if(o)return o}this.pendingSaves.add(t);try{const o=await this.databaseService.createMessage(e);return this.savedMessages.set(t,o),o}finally{this.pendingSaves.delete(t)}}async saveToolMessage(e){var n;const t=`${e.sessionId}-${e.role}-${e.content}-${(n=e.createdAt)==null?void 0:n.getTime()}`;if(this.pendingSaves.has(t)){for(;this.pendingSaves.has(t);)await new Promise(o=>setTimeout(o,10));const s=this.savedMessages.get(t);if(s)return s}this.pendingSaves.add(t);try{const s=await this.databaseService.createMessage(e);return this.savedMessages.set(t,s),s}finally{this.pendingSaves.delete(t)}}async saveMessage(e){switch(e.role){case"user":return this.saveUserMessage(e);case"assistant":return this.saveAssistantMessage(e);case"tool":return this.saveToolMessage(e);default:return this.databaseService.createMessage(e)}}clearCache(){this.savedMessages.clear()}getCacheStats(){return{pendingCount:this.pendingSaves.size,cachedCount:this.savedMessages.size}}}class kf 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 Il{constructor(e,t,n,s){W(this,"currentAiClient",null);W(this,"currentSessionId",null);W(this,"dbService");W(this,"messageManager");W(this,"userId");W(this,"configUrl");this.userId=e,this.dbService=new kf(e,t),this.messageManager=n,this.configUrl=s||"/api",console.log("🔧 ChatService Constructor - configUrl:",this.configUrl)}async sendMessage(e,t,n=[],s={},o){var i,l,c,d,m;try{if(this.currentSessionId=e,!await this.dbService.getSession(e))throw new Error("Session not found");let p;if(o)p=o;else{const x=await this.getChatConfig();p={model_name:x.model,temperature:x.temperature,max_tokens:16e3,api_key:x.apiKey,base_url:x.baseUrl}}const y=new Ml(e,this.userId,this.messageManager,p,this.configUrl,e);let h=3;for(;h>0;)try{await y.init();break}catch(x){if(h--,h===0)throw new Error(`AI服务初始化失败: ${x instanceof Error?x.message:"未知错误"}`);await new Promise(u=>setTimeout(u,1e3))}y.callback=(x,u)=>{var g,b,w,S,v,C,_,T;try{switch(x){case"chunk":const N=typeof u=="string"?u:u.content||u.accumulated||"";(g=s.onChunk)==null||g.call(s,{type:"text",content:N,accumulated:N});break;case"summary_chunk":const P=typeof u=="string"?u:u.content||u.accumulated||"";(b=s.onChunk)==null||b.call(s,{type:"text",content:P,accumulated:P});break;case"tool_call":(w=s.onToolCall)==null||w.call(s,u);break;case"tool_result":(S=s.onToolResult)==null||S.call(s,u);break;case"tool_stream_chunk":(v=s.onToolStreamChunk)==null||v.call(s,u);break;case"complete":debugger;break;case"conversation_complete":(C=s.onComplete)==null||C.call(s,u);break;case"error":const R=u instanceof Error?u.message:typeof u=="string"?u:"AI响应出错";(_=s.onError)==null||_.call(s,new Error(R));break;default:console.warn("Unknown AI response type:",x)}}catch(N){console.error("Callback error:",N),(T=s.onError)==null||T.call(s,new Error(`处理AI响应时出错: ${N instanceof Error?N.message:"未知错误"}`))}},this.currentAiClient=y,await y.sendMessage(t)}catch(f){if(f.message==="Stream aborted by user"||f.name==="AbortError"){console.log("Message sending aborted by user");return}if((i=f.message)!=null&&i.includes("ERR_INCOMPLETE_CHUNKED_ENCODING")||(l=f.message)!=null&&l.includes("net::ERR_")||(c=f.message)!=null&&c.includes("Failed to fetch")){console.log("Network connection error during streaming:",f.message),(d=s.onError)==null||d.call(s,new Error("网络连接中断,请检查网络状态后重试"));return}throw console.error("Failed to send message:",f),(m=s.onError)==null||m.call(s,f instanceof Error?f:new Error(String(f))),f}}async abortCurrentConversation(){if(console.log("🛑 ChatService: 中止当前对话"),this.currentSessionId)try{console.log(`🛑 ChatService: 调用服务端停止接口,会话ID: ${this.currentSessionId}`);const t=await(await fetch(`${this.configUrl}/chat/stop`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({session_id:this.currentSessionId})})).json();t.success?console.log(`✅ ChatService: 服务端停止成功 - ${t.message}`):console.warn(`⚠️ ChatService: 服务端停止失败 - ${t.message||"未知错误"}`);debugger;this.currentAiClient&&(console.log("🔄 ChatService: 尝试客户端停止作为备用方案"),this.currentAiClient.abort()),this.currentAiClient=null,this.currentSessionId=null}catch(e){console.error("❌ ChatService: 调用服务端停止接口失败:",e),this.currentAiClient&&(console.log("🔄 ChatService: 尝试客户端停止作为备用方案"),this.currentAiClient.abort()),this.currentAiClient=null,this.currentSessionId=null}else console.log("⚠️ ChatService: 没有活动的会话可以中止"),this.currentAiClient&&(console.log("🔄 ChatService: 尝试停止当前AI客户端"),this.currentAiClient.abort(),this.currentAiClient=null)}async getChatConfig(){return await this.dbService.getUserConfig("chatConfig")||{model:"gpt-3.5-turbo",temperature:.7,maxTokens:4e3,apiKey:"",baseUrl:"https://api.openai.com/v1"}}}function Nf({set:r,get:e,client:t,getUserIdParam:n}){return async function(o,i=[]){var b;const{currentSessionId:l,selectedModelId:c,aiModelConfigs:d,chatConfig:m,isLoading:f,isStreaming:p,activeSystemContext:y,selectedAgentId:h,agents:x}=e();if(!l)throw new Error("No active session");if(f||p){console.log("Message sending already in progress, ignoring duplicate request");return}let u=null,g=null;if(h){if(g=x.find(w=>w.id===h),!g||g.enabled===!1)throw new Error("选择的智能体不可用")}else if(c){if(u=d.find(w=>w.id===c),!u||!u.enabled)throw new Error("选择的模型不可用")}else throw new Error("请先选择一个模型或智能体");try{const w=new Date,S={id:`temp_user_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:l,role:"user",content:o,status:"completed",createdAt:w,metadata:{...i.length>0?{attachments:i}:{},model:g?`[Agent] ${g.name}`:u.model_name,...u?{modelConfig:{id:u.id,name:u.name,base_url:u.base_url,model_name:u.model_name}}:{}}};r(R=>{R.messages.push(S),R.isLoading=!0,R.isStreaming=!0});const v=new Date(w.getTime()+1),C={id:`temp_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:l,role:"assistant",content:"",status:"streaming",createdAt:v,metadata:{model:g?`[Agent] ${g.name}`:u.model_name,...u?{modelConfig:{id:u.id,name:u.name,base_url:u.base_url,model_name:u.model_name}}:{},toolCalls:[],contentSegments:[{content:"",type:"text"}],currentSegmentIndex:0}};r(R=>{R.messages.push(C),R.streamingMessageId=C.id});const _=g?{session_id:l,message:o,agent_id:g.id,system_context:(y==null?void 0:y.content)||m.systemPrompt||"",attachments:i||[]}:{session_id:l,message:o,model_config:{model:u.model_name,base_url:u.base_url,api_key:u.api_key||"",temperature:m.temperature,max_tokens:m.maxTokens},system_context:(y==null?void 0:y.content)||m.systemPrompt||"",attachments:i||[]};console.log("🚀 开始调用后端流式聊天API:",_);const T=g?await t.streamAgentChat(l,o,g.id,n()):await t.streamChat(l,o,u,n());if(!T)throw new Error("No response received");const N=T.getReader(),P=new TextDecoder;try{for(;;){const{done:R,value:j}=await N.read();if(R){console.log("✅ 流式响应完成");break}const O=P.decode(j,{stream:!0}).split(`
70
- `);for(const z of O)if(z.trim()!==""&&z.startsWith("data: ")){const H=z.slice(6);if(H==="[DONE]"){console.log("✅ 收到完成信号");break}try{const E=JSON.parse(H);if(E.type==="chunk")E.content&&r(L=>{const U=L.messages.find($=>$.id===C.id);if(U&&U.metadata){const $=typeof E.content=="string"?E.content:typeof E=="string"?E:E.content||"",D=U.metadata.currentSegmentIndex||0,B=U.metadata.contentSegments||[];B[D]&&B[D].type==="text"?B[D].content+=$:(B.push({content:$,type:"text"}),U.metadata.currentSegmentIndex=B.length-1),U.content=B.filter(X=>X.type==="text").map(X=>X.content).join("")}});else if(E.type==="thinking")E.content&&r(L=>{const U=L.messages.find($=>$.id===C.id);if(U&&U.metadata){const $=typeof E.content=="string"?E.content:typeof E=="string"?E:E.content||"",D=U.metadata.contentSegments||[],B=D.length-1;B>=0&&D[B].type==="thinking"?(D[B].content+=$,U.metadata.currentSegmentIndex=B):(D.push({content:$,type:"thinking"}),U.metadata.currentSegmentIndex=D.length-1),U.content=D.filter(X=>X.type==="text").map(X=>X.content).join("")}});else if(E.type==="content")r(L=>{const U=L.messages.find($=>$.id===C.id);if(U&&U.metadata){const $=typeof E.content=="string"?E.content:typeof E=="string"?E:E.content||"",D=U.metadata.currentSegmentIndex||0,B=U.metadata.contentSegments||[];B[D]&&B[D].type==="text"?B[D].content+=$:(B.push({content:$,type:"text"}),U.metadata.currentSegmentIndex=B.length-1),U.content=B.filter(X=>X.type==="text").map(X=>X.content).join("")}});else if(E.type==="tools_start"){console.log("🔧 收到工具调用:",E.data),console.log("🔧 工具调用数据类型:",typeof E.data,"是否为数组:",Array.isArray(E.data));const L=D=>{var X,M,K;console.log("🔧 [DEBUG] 原始工具调用数据:",D),console.log("🔧 [DEBUG] tc.function:",D.function),console.log("🔧 [DEBUG] tc.function?.name:",(X=D.function)==null?void 0:X.name),console.log("🔧 [DEBUG] tc.name:",D.name);const B={id:D.id||D.tool_call_id||`tool_${Date.now()}_${Math.random()}`,messageId:C.id,name:((M=D.function)==null?void 0:M.name)||D.name||"unknown_tool",arguments:((K=D.function)==null?void 0:K.arguments)||D.arguments||"{}",result:D.result||"",error:D.error||void 0,createdAt:D.createdAt||D.created_at||new Date};return console.log("🔧 [DEBUG] 转换后的工具调用:",B),B};console.log("🔧 [DEBUG] tools_start 原始数据:",E.data);const U=E.data.tool_calls||E.data,$=Array.isArray(U)?U:[U];console.log("🔧 [DEBUG] 提取的工具调用数组:",$),r(D=>{const B=D.messages.findIndex(X=>X.id===C.id);if(console.log("🔧 查找消息索引:",B,"消息ID:",C.id),B!==-1){const X=D.messages[B];console.log("🔧 找到消息,当前metadata:",X.metadata),X.metadata||(X.metadata={}),X.metadata.toolCalls||(X.metadata.toolCalls=[]);const M=X.metadata.contentSegments||[];console.log("🔧 处理工具调用数组,长度:",$.length),$.forEach(K=>{const A=L(K);console.log("🔧 添加转换后的工具调用:",A),X.metadata.toolCalls.push(A),M.push({content:"",type:"tool_call",toolCallId:A.id})}),M.push({content:"",type:"text"}),X.metadata.currentSegmentIndex=M.length-1,console.log("🔧 更新后的toolCalls:",X.metadata.toolCalls)}else console.log("🔧 ❌ 未找到对应的消息")})}else if(E.type==="tools_end"){console.log("🔧 收到工具结果:",E.data),console.log("🔧 工具结果数据类型:",typeof E.data);const L=Array.isArray(E.data)?E.data:[E.data];r(U=>{const $=U.messages.findIndex(D=>D.id===C.id);if($!==-1){const D=U.messages[$];D.metadata&&D.metadata.toolCalls&&(L.forEach(B=>{var K,A,q,J;const X=B.tool_call_id||B.id||B.toolCallId;if(!X){console.warn("⚠️ 工具结果缺少工具调用ID:",B);return}console.log("🔍 查找工具调用:",X,"在消息中:",(A=(K=D.metadata)==null?void 0:K.toolCalls)==null?void 0:A.map(V=>V.id));const M=D.metadata.toolCalls.find(V=>V.id===X);if(M){console.log("✅ 找到工具调用,更新最终结果:",M.id);const V=B.result||B.content||B.output||"";B.success===!1||B.is_error===!0?(M.error=B.error||V||"工具执行失败",console.log("❌ 工具执行失败:",{id:M.id,name:B.name||M.name,error:M.error,success:B.success,is_error:B.is_error})):((!M.result||M.result.trim()==="")&&(M.result=V),M.error&&delete M.error,console.log("✅ 工具执行成功,最终结果已更新:",{id:M.id,name:B.name||M.name,resultLength:M.result.length,success:B.success,is_stream:B.is_stream}))}else console.log("❌ 未找到对应的工具调用:",X),console.log("📋 当前可用的工具调用ID:",(J=(q=D.metadata)==null?void 0:q.toolCalls)==null?void 0:J.map(V=>V.id))}),D.updatedAt=new Date)}})}else if(E.type==="tools_stream"){console.log("🔧 收到工具流式数据:",E.data);const L=E.data;r(U=>{const $=U.messages.findIndex(D=>D.id===C.id);if($!==-1){const D=U.messages[$];if(D.metadata&&D.metadata.toolCalls){const B=L.toolCallId||L.tool_call_id||L.id;if(!B){console.warn("⚠️ 工具流式数据缺少工具调用ID:",L);return}console.log("🔍 查找工具调用进行流式更新:",B);const X=D.metadata.toolCalls.find(M=>M.id===B);if(X){const M=L.content||L.chunk||L.data||"";L.is_error||!L.success?(X.error=M||"工具执行出错",console.log("❌ 工具流式执行出错:",{id:X.id,error:X.error,success:L.success,is_error:L.is_error})):(X.result=(X.result||"")+M,console.log("🔧 工具流式数据已更新:",{id:X.id,name:L.name,chunkLength:M.length,totalLength:X.result.length,success:L.success,is_stream:L.is_stream})),D.updatedAt=new Date}}}})}else{if(E.type==="error")throw new Error(E.message||((b=E.data)==null?void 0:b.message)||"Stream error");if(E.type==="cancelled"){console.log("⚠️ 流式会话已被取消");break}else if(E.type==="done"){console.log("✅ 收到完成信号");break}}}catch(E){console.warn("解析流式数据失败:",E,"data:",H)}}}}finally{N.releaseLock(),r(R=>{R.isLoading=!1,R.isStreaming=!1,R.streamingMessageId=null})}console.log("✅ 消息发送完成")}catch(w){throw console.error("❌ 发送消息失败:",w),r(S=>{const v=S.messages.findIndex(C=>{var _;return(_=C.id)==null?void 0:_.startsWith("temp_")});v!==-1&&S.messages.splice(v,1),S.isLoading=!1,S.isStreaming=!1,S.streamingMessageId=null,S.error=w instanceof Error?w.message:"Failed to send message"}),w}}}function Mf({set:r,get:e,client:t,getUserIdParam:n}){const s=o=>({id:o.id,name:o.name,url:o.url,iconUrl:o.icon_url??void 0,createdAt:new Date(o.created_at),updatedAt:new Date(o.updated_at??o.created_at)});return{loadApplications:async()=>{try{console.log("[Store] loadApplications: start");const o=n(),l=(await t.getApplications(o)||[]).map(s);r(c=>{c.applications=l}),console.log("[Store] loadApplications: loaded",l.length,"items")}catch(o){console.error("Failed to load applications:",o),r(i=>{i.applications=[]})}},createApplication:async(o,i,l)=>{try{const c=await t.createApplication({name:o,url:i,icon_url:l??null,user_id:n()}),d=s(c);r(m=>{m.applications=[d,...m.applications]})}catch(c){console.error("Failed to create application:",c),r(d=>{d.error=c instanceof Error?c.message:"Failed to create application"})}},updateApplication:async(o,i)=>{try{const l={};i.name!==void 0&&(l.name=i.name),i.url!==void 0&&(l.url=i.url),i.iconUrl!==void 0&&(l.icon_url=i.iconUrl??null);const c=await t.updateApplication(o,l),d=s(c);r(m=>{m.applications=m.applications.map(f=>f.id===o?d:f)})}catch(l){console.error("Failed to update application:",l),r(c=>{c.error=l instanceof Error?l.message:"Failed to update application"})}},deleteApplication:async o=>{try{await t.deleteApplication(o),r(i=>{i.applications=i.applications.filter(l=>l.id!==o),i.mcpConfigs=i.mcpConfigs.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(c=>c!==o):[]})),i.systemContexts=i.systemContexts.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(c=>c!==o):[]})),i.agents=i.agents.map(l=>({...l,app_ids:Array.isArray(l.app_ids)?l.app_ids.filter(c=>c!==o):[]}))})}catch(i){console.error("Failed to delete application:",i),r(l=>{l.error=i instanceof Error?i.message:"Failed to delete application"})}},setSelectedApplication:o=>{console.log("[Store] setSelectedApplication:",o);const i=e().selectedApplicationId;console.log("[Store] setSelectedApplication - before:",{oldId:i,newId:o}),r(c=>({...c,selectedApplicationId:o}));const l=e().selectedApplicationId;console.log("[Store] setSelectedApplication - after:",{oldId:i,newId:l})},setMcpAppAssociation:(o,i)=>{r(l=>{l.mcpConfigs=l.mcpConfigs.map(c=>c.id===o?{...c,app_ids:Array.isArray(i)?i:[]}:c)})},setSystemContextAppAssociation:(o,i)=>{r(l=>{l.systemContexts=l.systemContexts.map(c=>c.id===o?{...c,app_ids:Array.isArray(i)?i:[]}:c)});try{(async()=>await t.updateSystemContext(o,{name:void 0,content:void 0,app_ids:Array.isArray(i)?i:[]}))()}catch{}},setAgentAppAssociation:(o,i)=>{r(l=>{l.agents=l.agents.map(c=>c.id===o?{...c,app_ids:Array.isArray(i)?i:[]}:c)});try{(async()=>await t.updateAgent(o,{app_ids:Array.isArray(i)?i:[]}))()}catch{}}}}function Ef({set:r,get:e,client:t,getUserIdParam:n}){return{loadAiModelConfigs:async()=>{try{const s=n(),i=(await t.getAiModelConfigs(s)).map(l=>({id:l.id,name:l.name,base_url:l.base_url,api_key:l.api_key,model_name:l.model,enabled:l.enabled,createdAt:new Date(l.created_at),updatedAt:new Date(l.created_at)}));r(l=>{l.aiModelConfigs=i})}catch(s){console.error("Failed to load AI model configs:",s),r(o=>{o.error=s instanceof Error?s.message:"Failed to load AI model configs"})}},updateAiModelConfig:async s=>{try{const o=n(),l=e().aiModelConfigs.find(d=>d.id===s.id)?"update":"create",c={id:s.id||crypto.randomUUID(),name:s.name,provider:"openai",model:s.model_name,api_key:s.api_key,base_url:s.base_url,enabled:s.enabled,user_id:o};l==="update"?await t.updateAiModelConfig(s.id,c):await t.createAiModelConfig(c),await e().loadAiModelConfigs()}catch(o){console.error("Failed to update AI model config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to update AI model config"})}},deleteAiModelConfig:async s=>{try{await t.deleteAiModelConfig(s),r(o=>{o.aiModelConfigs=o.aiModelConfigs.filter(i=>i.id!==s)})}catch(o){console.error("Failed to delete AI model config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to delete AI model config"})}},setSelectedModel:s=>{r(o=>{o.selectedModelId=s,s&&(o.selectedAgentId=null)})}}}function If({set:r,get:e,client:t,getUserIdParam:n}){return{loadMcpConfigs:async()=>{var s;try{const o=n(),i=await t.getMcpConfigs(o);console.log("🔍 [后端返回] loadMcpConfigs 返回的数据:",i),console.log("🔍 [后端返回] 第一个配置的 app_ids:",(s=i==null?void 0:i[0])==null?void 0:s.app_ids),r(l=>{l.mcpConfigs=i})}catch(o){console.error("Failed to load MCP configs:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to load MCP configs"})}},updateMcpConfig:async s=>{try{const o=n();console.log("🔍 updateMcpConfig 调用:",{userId:o,configId:s.id,configName:s.name});let i=null;if(s.id){const d={id:s.id,name:s.name,command:s.command,type:s.type,args:s.args??void 0,env:s.env??void 0,cwd:s.cwd??void 0,enabled:s.enabled,userId:o,app_ids:Array.isArray(s.app_ids)?s.app_ids:void 0};console.log("🔍 updateMcpConfig 更新数据:",d),i=await t.updateMcpConfig(s.id,d)}else{const d={name:s.name,command:s.command,type:s.type,args:s.args??void 0,env:s.env??void 0,cwd:s.cwd??void 0,enabled:s.enabled,user_id:o,app_ids:Array.isArray(s.app_ids)?s.app_ids:void 0};i=await t.createMcpConfig(d)}const l=(i==null?void 0:i.id)??s.id,c=Array.isArray(i==null?void 0:i.app_ids)?i.app_ids:Array.isArray(s.app_ids)?s.app_ids:[];return r(d=>{d.mcpConfigs=d.mcpConfigs.map(m=>m.id===l?{...m,app_ids:c}:m)}),await e().loadMcpConfigs(),i}catch(o){return console.error("Failed to update MCP config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to update MCP config"}),null}},deleteMcpConfig:async s=>{try{await t.deleteMcpConfig(s),r(o=>{o.mcpConfigs=o.mcpConfigs.filter(i=>i.id!==s)})}catch(o){console.error("Failed to delete MCP config:",o),r(i=>{i.error=o instanceof Error?o.message:"Failed to delete MCP config"})}}}}function Tf({set:r}){return{updateChatConfig:async e=>{r(t=>{t.chatConfig={...t.chatConfig,...e}})}}}function zr(r,e){const t=r||re,n=e==null?void 0:e.userId,s=e==null?void 0:e.projectId,o=e==null?void 0:e.configUrl,i=n||"default-user",l=s||"default-project",c=o||"/api",d=()=>i,m=()=>({userId:i,projectId:l}),f=new bs(i,l,t),p=new El(f),y=new Il(i,l,p,c);return console.log("chatService:",y),vc()(Rc(Bc((h,x)=>({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 被调用"),h(S=>{S.isLoading=!0,S.error=null}),console.log("🔍 loadSessions isLoading 设置为 true");const{userId:u,projectId:g}=m();console.log("🔍 loadSessions 调用 client.getSessions",{userId:u,projectId:g,customUserId:n,customProjectId:s});const b=await t.getSessions(u,g);console.log("🔍 loadSessions 返回结果:",b),h(S=>{S.sessions=b,S.isLoading=!1});const w=x();if(b.length>0&&!w.currentSessionId){const S=localStorage.getItem(`lastSessionId_${u}_${g}`);let v=null;S&&(v=b.find(C=>C.id===S)),v||(v=[...b].sort((C,_)=>new Date(_.createdAt).getTime()-new Date(C.createdAt).getTime())[0]),v&&(console.log("🔍 自动选择会话:",v.id),setTimeout(()=>{x().selectSession(v.id)},0))}console.log("🔍 loadSessions 完成")}catch(u){console.error("🔍 loadSessions 错误:",u),h(g=>{g.error=u instanceof Error?u.message:"Failed to load sessions",g.isLoading=!1})}},createSession:async(u="New Chat")=>{try{const{userId:g,projectId:b}=m();console.log("🔍 createSession 使用参数:",{userId:g,projectId:b,title:u}),console.log("🔍 createSession 自定义参数:",{customUserId:n,customProjectId:s}),console.log("🔍 createSession 最终使用的参数:",{userId:g,projectId:b,isCustomUserId:!!n,isCustomProjectId:!!s});const w={id:crypto.randomUUID(),title:u,user_id:g,project_id:b},S=await t.createSession(w);console.log("✅ createSession API调用成功:",S);const v={id:S.id,title:S.title,createdAt:new Date(S.created_at),updatedAt:new Date(S.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null};return h(C=>{C.sessions.unshift(v),C.currentSessionId=v.id,C.currentSession=v,C.messages=[],C.error=null}),localStorage.setItem(`lastSessionId_${g}_${b}`,v.id),console.log("🔍 保存新创建的会话ID到 localStorage:",v.id),v.id}catch(g){throw console.error("❌ createSession 失败:",g),h(b=>{b.error=g instanceof Error?g.message:"Failed to create session"}),g}},selectSession:async u=>{try{h(w=>{w.isLoading=!0,w.error=null});const g=await f.getSession(u),b=await f.getSessionMessages(u,{limit:10,offset:0});if(h(w=>{w.currentSessionId=u,w.currentSession=g,w.messages=b,w.isLoading=!1,w.hasMoreMessages=b.length===10,g||(w.error="Session not found")}),g){const{userId:w,projectId:S}=m();localStorage.setItem(`lastSessionId_${w}_${S}`,u),console.log("🔍 保存会话ID到 localStorage:",u)}}catch(g){console.error("Failed to select session:",g),h(b=>{b.error=g instanceof Error?g.message:"Failed to select session",b.isLoading=!1})}},updateSession:async(u,g)=>{try{const b=await f.updateSession(u,g);h(w=>{const S=w.sessions.findIndex(v=>v.id===u);S!==-1&&b&&(w.sessions[S]=b),w.currentSessionId===u&&(w.currentSession=b)})}catch(b){console.error("Failed to update session:",b),h(w=>{w.error=b instanceof Error?b.message:"Failed to update session"})}},deleteSession:async u=>{try{await f.deleteSession(u),h(g=>{g.sessions=g.sessions.filter(b=>b.id!==u),g.currentSessionId===u&&(g.currentSessionId=null,g.currentSession=null,g.messages=[])})}catch(g){console.error("Failed to delete session:",g),h(b=>{b.error=g instanceof Error?g.message:"Failed to delete session"})}},loadMessages:async u=>{try{h(b=>{b.isLoading=!0,b.error=null});const g=await f.getSessionMessages(u,{limit:10,offset:0});h(b=>{b.messages=g,b.isLoading=!1,b.hasMoreMessages=g.length===10})}catch(g){console.error("Failed to load messages:",g),h(b=>{b.error=g instanceof Error?g.message:"Failed to load messages",b.isLoading=!1})}},loadMoreMessages:async u=>{try{const b=x().messages.length,w=await f.getSessionMessages(u,{limit:10,offset:b});h(S=>{const v=new Set(S.messages.map(_=>_.id)),C=w.filter(_=>!v.has(_.id));S.messages=[...C,...S.messages],S.hasMoreMessages=w.length===10})}catch(g){console.error("Failed to load more messages:",g),h(b=>{b.error=g instanceof Error?g.message:"Failed to load more messages"})}},sendMessage:Nf({set:h,get:x,client:t,getUserIdParam:d}),updateMessage:async(u,g)=>{try{const b=await f.updateMessage(u,g);h(w=>{const S=w.messages.findIndex(v=>v.id===u);S!==-1&&b&&(w.messages[S]=b)})}catch(b){console.error("Failed to update message:",b),h(w=>{w.error=b instanceof Error?b.message:"Failed to update message"})}},deleteMessage:async u=>{try{await f.deleteMessage(u),h(g=>{g.messages=g.messages.filter(b=>b.id!==u)})}catch(g){console.error("Failed to delete message:",g),h(b=>{b.error=g instanceof Error?g.message:"Failed to delete message"})}},startStreaming:u=>{h(g=>{g.isStreaming=!0,g.streamingMessageId=u})},updateStreamingMessage:u=>{h(g=>{if(g.streamingMessageId){const b=g.messages.findIndex(w=>w.id===g.streamingMessageId);b!==-1&&(g.messages[b].content=u)}})},stopStreaming:()=>{h(u=>{u.isStreaming=!1,u.streamingMessageId=null})},abortCurrentConversation:async()=>{const{currentSessionId:u}=x();if(u)try{await t.stopChat(u),console.log("✅ 成功停止当前对话")}catch(g){console.error("❌ 停止对话失败:",g)}h(g=>{g.isStreaming=!1,g.streamingMessageId=null,g.isLoading=!1})},toggleSidebar:()=>{h(u=>{u.sidebarOpen=!u.sidebarOpen})},setTheme:u=>{h(g=>{g.theme=u})},...Tf({set:h}),...If({set:h,get:x,client:t,getUserIdParam:d}),...Mf({set:h,get:x,client:t,getUserIdParam:d}),...Ef({set:h,get:x,client:t,getUserIdParam:d}),loadAgents:async()=>{var u;try{const g=await t.getAgents(d());console.log("🔍 [后端返回] loadAgents 返回的数据:",g),console.log("🔍 [后端返回] 第一个智能体的 app_ids:",(u=g==null?void 0:g[0])==null?void 0:u.app_ids),h(b=>{b.agents=g||[]})}catch(g){console.error("Failed to load agents:",g),h(b=>{b.agents=[],b.error=g instanceof Error?g.message:"Failed to load agents"})}},setSelectedAgent:u=>{h(g=>{g.selectedAgentId=u,u&&(g.selectedModelId=null)})},loadSystemContexts:async()=>{try{const u=await t.getSystemContexts(d()),g=await t.getActiveSystemContext(d());h(b=>{const w=(u||[]).map(S=>({...S,isActive:!1}));if(g&&g.context){const S=g.context,v=w.findIndex(C=>C.id===S.id);v!==-1?(w[v].isActive=!0,b.activeSystemContext={...w[v]}):b.activeSystemContext=null}else b.activeSystemContext=null;b.systemContexts=w})}catch(u){console.error("Failed to load system contexts:",u),h(g=>{g.systemContexts=[],g.activeSystemContext=null})}},createSystemContext:async(u,g,b)=>{try{const w=await t.createSystemContext({name:u,content:g,user_id:d(),app_ids:Array.isArray(b)?b:void 0});return h(S=>{S.systemContexts.push(w)}),w}catch(w){return console.error("Failed to create system context:",w),h(S=>{S.error=w instanceof Error?w.message:"Failed to create system context"}),null}},updateSystemContext:async(u,g,b,w)=>{try{const S=await t.updateSystemContext(u,{name:g,content:b,app_ids:Array.isArray(w)?w:void 0});return h(v=>{const C=v.systemContexts.findIndex(_=>_.id===u);C!==-1&&(v.systemContexts[C]=S)}),S}catch(S){return console.error("Failed to update system context:",S),h(v=>{v.error=S instanceof Error?S.message:"Failed to update system context"}),null}},deleteSystemContext:async u=>{try{await t.deleteSystemContext(u),h(g=>{var b;g.systemContexts=g.systemContexts.filter(w=>w.id!==u),((b=g.activeSystemContext)==null?void 0:b.id)===u&&(g.activeSystemContext=null)})}catch(g){console.error("Failed to delete system context:",g),h(b=>{b.error=g instanceof Error?g.message:"Failed to delete system context"})}},activateSystemContext:async u=>{try{await t.activateSystemContext(u,d()),h(g=>{const b=g.systemContexts.find(w=>w.id===u);b&&(g.systemContexts.forEach(w=>{w.isActive=w.id===u}),g.activeSystemContext={...b,isActive:!0})})}catch(g){console.error("Failed to activate system context:",g),h(b=>{b.error=g instanceof Error?g.message:"Failed to activate system context"})}},setError:u=>{h(g=>{g.error=u})},clearError:()=>{h(u=>{u.error=null})}}),{name:"chat-store-with-backend",partialize:h=>({theme:h.theme,sidebarOpen:h.sidebarOpen,chatConfig:h.chatConfig,selectedModelId:h.selectedModelId})})))}const dt=zr();function Pf(r,e,t){return zr(t,{userId:r,projectId:e})}const pn=I.createContext(null),Of=({children:r,userId:e,projectId:t,customApiClient:n})=>{const s=I.useMemo(()=>e||t||n?(console.log("🏪 创建自定义store:",{userId:e,projectId:t,hasCustomApiClient:!!n}),Pf(e||"default-user",t||"default-project",n)):(console.log("🏪 使用默认store"),dt),[e,t,n]);return a.jsx(pn.Provider,{value:{store:s,userId:e,projectId:t,apiClient:n},children:r})},Tl=()=>{const r=I.useContext(pn);if(!r)throw new Error("useChatStoreContext must be used within a ChatStoreProvider");return r.store},ut=()=>Tl()(),Rf=()=>{const r=I.useContext(pn);return r?{userId:r.userId,projectId:r.projectId}:{userId:void 0,projectId:void 0}},$f=()=>{const r=I.useContext(pn);return r==null?void 0:r.apiClient},_t=({content:r,isStreaming:e=!1,className:t="",onApplyCode:n})=>{const[s,o]=I.useState(new Set),i=I.useCallback(async f=>{try{await navigator.clipboard.writeText(f)}catch(p){console.error("Failed to copy code:",p)}},[]),l=I.useCallback(f=>{o(p=>{const y=new Set(p);return y.has(f)?y.delete(f):y.add(f),y})},[]),c=I.useMemo(()=>f=>{if(!f)return"";let p=f;const y=/\$\$([\s\S]*?)\$\$/g;p=p.replace(y,(S,v)=>`<div class="math-block">${v.trim()}</div>`);const h=/\$([^$]+)\$/g;p=p.replace(h,(S,v)=>`<span class="math-inline">${v}</span>`);const x=/\|(.+)\|\n\|[-\s|:]+\|\n((?:\|.+\|\n?)*)/g;if(p=p.replace(x,(S,v,C)=>{const _=v.split("|").map(P=>P.trim()).filter(P=>P),T=C.trim().split(`
71
- `).map(P=>P.split("|").map(R=>R.trim()).filter(R=>R));let N="<table>";return _.length>0&&(N+="<thead><tr>",_.forEach(P=>{N+=`<th>${P}</th>`}),N+="</tr></thead>"),T.length>0&&(N+="<tbody>",T.forEach(P=>{P.length>0&&(N+="<tr>",P.forEach(R=>{N+=`<td>${R}</td>`}),N+="</tr>")}),N+="</tbody>"),N+="</table>",e?`<div class="streaming-table-wrapper">
90
+ `+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 la(this.messages,this.conversationId,this.tools,this.modelConfig,(w,m)=>this.callback(w,m),this.mcpToolsExecute,this.messageManager,this.configUrl,g,this.sessionId),x={id:u,aiClient:h,abortController:g,isRunning:!0,startTime:Date.now()};this.currentThread=x,console.log(`AiServer: Created request thread ${u}`);try{if(this.isAborted||!x.isRunning){console.log(`AiServer: Thread ${u} was aborted before start`);return}await h.start(),console.log(`AiServer: Thread ${u} completed successfully`)}catch(w){if(this.isAborted||!x.isRunning){console.log(`AiServer: Thread ${u} was aborted during execution`);return}if(w.message==="Stream aborted by user"||w.name==="AbortError"){console.log(`AiServer: Thread ${u} aborted by user`);return}throw console.error(`AiServer: Thread ${u} failed:`,w),w}finally{((t=this.currentThread)==null?void 0:t.id)===u&&(this.currentThread.isRunning=!1,this.currentThread=null,console.log(`AiServer: Thread ${u} cleaned up`))}}catch(s){if(s.message==="Stream aborted by user"||s.name==="AbortError"||this.isAborted){console.log("sendMessage aborted by user");return}throw console.error("sendMessage failed:",s),console.error("Error details:",(n=s.response)==null?void 0:n.data),this.callback("error",s),s}}async sendMessageDirect(e){var t;try{console.log("AiServer sendMessageDirect called with:",e),this.messages=[{role:"user",content:e}],console.log("Messages prepared for AI:",this.messages);const n=`direct_thread_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,s=new AbortController,a=new la(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 $r.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 Zl{constructor(e){q(this,"pendingSaves",new Set);q(this,"savedMessages",new Map);q(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 Mh extends Ms{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 ec{constructor(e,t,n,s){q(this,"currentAiClient",null);q(this,"currentSessionId",null);q(this,"dbService");q(this,"messageManager");q(this,"userId");q(this,"configUrl");this.userId=e,this.dbService=new Mh(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 x;if(a)x=a;else{const f=await this.getChatConfig();x={model_name:f.model,temperature:f.temperature,api_key:f.apiKey,base_url:f.baseUrl}}const w=new Ql(e,this.userId,this.messageManager,x,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 p,y,b,S,_,j,v,I;try{switch(f){case"chunk":const M=typeof c=="string"?c:c.content||c.accumulated||"";(p=s.onChunk)==null||p.call(s,{type:"text",content:M,accumulated:M});break;case"summary_chunk":const O=typeof c=="string"?c:c.content||c.accumulated||"";(y=s.onChunk)==null||y.call(s,{type:"text",content:O,accumulated:O});break;case"tool_call":(b=s.onToolCall)==null||b.call(s,c);break;case"tool_result":(S=s.onToolResult)==null||S.call(s,c);break;case"tool_stream_chunk":(_=s.onToolStreamChunk)==null||_.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(M){console.error("Callback error:",M),(I=s.onError)==null||I.call(s,new Error(`处理AI响应时出错: ${M instanceof Error?M.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,apiKey:"",baseUrl:"https://api.openai.com/v1"}}}function Eh({set:r,get:e,client:t,getUserIdParam:n}){return async function(a,i=[]){var y;const{currentSessionId:l,selectedModelId:d,aiModelConfigs:u,chatConfig:g,isLoading:h,isStreaming:x,activeSystemContext:w,selectedAgentId:m,agents:f}=e();if(!l)throw new Error("No active session");if(h||x){console.log("Message sending already in progress, ignoring duplicate request");return}let c=null,p=null;if(m){if(p=f.find(b=>b.id===m),!p||p.enabled===!1)throw new Error("选择的智能体不可用")}else if(d){if(c=u.find(b=>b.id===d),!c||!c.enabled)throw new Error("选择的模型不可用")}else throw new Error("请先选择一个模型或智能体");try{const b=F=>new Promise((Y,ae)=>{const W=new FileReader;W.onload=()=>Y(String(W.result)),W.onerror=ae,W.readAsDataURL(F)}),S=F=>new Promise((Y,ae)=>{const W=new FileReader;W.onload=()=>Y(String(W.result)),W.onerror=ae,W.readAsText(F)}),_=async F=>{const Y=F.type.startsWith("image/"),ae=F.type.startsWith("audio/"),W=Y||ae?await b(F):URL.createObjectURL(F);return{id:`att_${Date.now()}_${Math.random().toString(36).slice(2,8)}`,messageId:"temp",type:Y?"image":ae?"audio":"file",name:F.name,url:W,size:F.size,mimeType:F.type,createdAt:new Date}},j=async F=>{const Y=F.type.startsWith("image/"),ae=F.type.startsWith("text/")||F.type==="application/json",W=F.type==="application/pdf"||/\.pdf$/i.test(F.name),J=F.type==="application/vnd.openxmlformats-officedocument.wordprocessingml.document"||/\.docx$/i.test(F.name),ee=5*1024*1024;if(Y){const U=await b(F);return{name:F.name,mimeType:F.type,size:F.size,type:"image",dataUrl:U}}if(ae){const U=await S(F);return{name:F.name,mimeType:F.type,size:F.size,type:"file",text:U}}if((W||J)&&F.size<=ee){const U=await b(F);return{name:F.name,mimeType:W?"application/pdf":"application/vnd.openxmlformats-officedocument.wordprocessingml.document",size:F.size,type:"file",dataUrl:U}}return{name:F.name,mimeType:F.type,size:F.size,type:"file"}},v=await Promise.all((i||[]).map(_)),I=await Promise.all((i||[]).map(j)),M=new Date,O={id:`temp_user_${Date.now()}_${Math.random().toString(36).slice(2,9)}`,sessionId:l,role:"user",content:a,status:"completed",createdAt:M,metadata:{...v.length>0?{attachments:v}:{},model:p?`[Agent] ${p.name}`:c.model_name,...c?{modelConfig:{id:c.id,name:c.name,base_url:c.base_url,model_name:c.model_name}}:{}}};r(F=>{F.messages.push(O),F.isLoading=!0,F.isStreaming=!0});const L=new Date(M.getTime()+1),C={id:`temp_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:l,role:"assistant",content:"",status:"streaming",createdAt:L,metadata:{model:p?`[Agent] ${p.name}`:c.model_name,...c?{modelConfig:{id:c.id,name:c.name,base_url:c.base_url,model_name:c.model_name}}:{},toolCalls:[],contentSegments:[{content:"",type:"text"}],currentSegmentIndex:0}};r(F=>{F.messages.push(C),F.streamingMessageId=C.id});const H=p?{session_id:l,message:a,agent_id:p.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},system_context:(w==null?void 0:w.content)||g.systemPrompt||"",attachments:I||[]};console.log("🚀 开始调用后端流式聊天API:",H);const D=p?await t.streamAgentChat(l,a,p.id,n(),I):await t.streamChat(l,a,c,n(),I);if(!D)throw new Error("No response received");const V=D.getReader(),X=new TextDecoder;try{for(;;){const{done:F,value:Y}=await V.read();if(F){console.log("✅ 流式响应完成");break}const W=X.decode(Y,{stream:!0}).split(`
91
+ `);for(const J of W)if(J.trim()!==""&&J.startsWith("data: ")){const ee=J.slice(6);if(ee==="[DONE]"){console.log("✅ 收到完成信号");break}try{const U=JSON.parse(ee);if(typeof U=="string"&&U==="[DONE]"){console.log("✅ 收到完成信号");break}if(U.type==="chunk")U.content&&r(N=>{const $=N.messages.find(A=>A.id===C.id);if($&&$.metadata){const A=typeof U.content=="string"?U.content:typeof U=="string"?U:U.content||"",k=$.metadata.currentSegmentIndex||0,P=$.metadata.contentSegments||[];P[k]&&P[k].type==="text"?P[k].content+=A:(P.push({content:A,type:"text"}),$.metadata.currentSegmentIndex=P.length-1),$.content=P.filter(R=>R.type==="text").map(R=>R.content).join("")}});else if(U.type==="thinking")U.content&&r(N=>{const $=N.messages.find(A=>A.id===C.id);if($&&$.metadata){const A=typeof U.content=="string"?U.content:typeof U=="string"?U:U.content||"",k=$.metadata.contentSegments||[],P=k.length-1;P>=0&&k[P].type==="thinking"?(k[P].content+=A,$.metadata.currentSegmentIndex=P):(k.push({content:A,type:"thinking"}),$.metadata.currentSegmentIndex=k.length-1),$.content=k.filter(R=>R.type==="text").map(R=>R.content).join("")}});else if(U.type==="context_summarized"||U.type==="context_summarized_start"||U.type==="context_summarized_stream"||U.type==="context_summarized_end"){const N=U.data||{},$="【上下文摘要】\\n";r(A=>{const k=A.messages.find(z=>z.id===C.id);if(!k||!k.metadata)return;const P=k.metadata.contentSegments||[],R=()=>{const z=P.length-1;return z>=0&&P[z].type==="thinking"&&String(P[z].content||"").startsWith($)?z:(P.push({content:$,type:"thinking"}),k.metadata.contentSegments=P,k.metadata.currentSegmentIndex=P.length-1,P.length-1)};if(U.type==="context_summarized_start")R();else if(U.type==="context_summarized_stream"){const z=R(),ne=N.content||N.chunk||N.data||"";P[z].content+=String(ne),k.metadata.currentSegmentIndex=z}else if(U.type==="context_summarized_end"||U.type==="context_summarized"){const z=R(),ne=typeof N.full_summary=="string"&&N.full_summary.length>0?N.full_summary:N.summary_preview||"";P[z].content=$+String(ne),k.metadata.contentSegments=P,k.metadata.currentSegmentIndex=z}k.updatedAt=new Date})}else if(U.type==="content")r(N=>{const $=N.messages.find(A=>A.id===C.id);if($&&$.metadata){const A=typeof U.content=="string"?U.content:typeof U=="string"?U:U.content||"",k=$.metadata.currentSegmentIndex||0,P=$.metadata.contentSegments||[];P[k]&&P[k].type==="text"?P[k].content+=A:(P.push({content:A,type:"text"}),$.metadata.currentSegmentIndex=P.length-1),$.content=P.filter(R=>R.type==="text").map(R=>R.content).join("")}});else if(U.type==="tools_start"){console.log("🔧 收到工具调用:",U.data),console.log("🔧 工具调用数据类型:",typeof U.data,"是否为数组:",Array.isArray(U.data));const N=k=>{var R,z,ne;console.log("🔧 [DEBUG] 原始工具调用数据:",k),console.log("🔧 [DEBUG] tc.function:",k.function),console.log("🔧 [DEBUG] tc.function?.name:",(R=k.function)==null?void 0:R.name),console.log("🔧 [DEBUG] tc.name:",k.name);const P={id:k.id||k.tool_call_id||`tool_${Date.now()}_${Math.random()}`,messageId:C.id,name:((z=k.function)==null?void 0:z.name)||k.name||"unknown_tool",arguments:((ne=k.function)==null?void 0:ne.arguments)||k.arguments||"{}",result:k.result||"",error:k.error||void 0,createdAt:k.createdAt||k.created_at||new Date};return console.log("🔧 [DEBUG] 转换后的工具调用:",P),P};console.log("🔧 [DEBUG] tools_start 原始数据:",U.data);const $=U.data.tool_calls||U.data,A=Array.isArray($)?$:[$];console.log("🔧 [DEBUG] 提取的工具调用数组:",A),r(k=>{const P=k.messages.findIndex(R=>R.id===C.id);if(console.log("🔧 查找消息索引:",P,"消息ID:",C.id),P!==-1){const R=k.messages[P];console.log("🔧 找到消息,当前metadata:",R.metadata),R.metadata||(R.metadata={}),R.metadata.toolCalls||(R.metadata.toolCalls=[]);const z=R.metadata.contentSegments||[];console.log("🔧 处理工具调用数组,长度:",A.length),A.forEach(ne=>{const B=N(ne);console.log("🔧 添加转换后的工具调用:",B),R.metadata.toolCalls.push(B),z.push({content:"",type:"tool_call",toolCallId:B.id})}),z.push({content:"",type:"text"}),R.metadata.currentSegmentIndex=z.length-1,console.log("🔧 更新后的toolCalls:",R.metadata.toolCalls)}else console.log("🔧 ❌ 未找到对应的消息")})}else if(U.type==="tools_end"){console.log("🔧 收到工具结果:",U.data),console.log("🔧 工具结果数据类型:",typeof U.data);const N=Array.isArray(U.data)?U.data:[U.data];r($=>{const A=$.messages.findIndex(k=>k.id===C.id);if(A!==-1){const k=$.messages[A];k.metadata&&k.metadata.toolCalls&&(N.forEach(P=>{var ne,B,se,we;const R=P.tool_call_id||P.id||P.toolCallId;if(!R){console.warn("⚠️ 工具结果缺少工具调用ID:",P);return}console.log("🔍 查找工具调用:",R,"在消息中:",(B=(ne=k.metadata)==null?void 0:ne.toolCalls)==null?void 0:B.map(le=>le.id));const z=k.metadata.toolCalls.find(le=>le.id===R);if(z){console.log("✅ 找到工具调用,更新最终结果:",z.id);const le=P.result||P.content||P.output||"";P.success===!1||P.is_error===!0?(z.error=P.error||le||"工具执行失败",console.log("❌ 工具执行失败:",{id:z.id,name:P.name||z.name,error:z.error,success:P.success,is_error:P.is_error})):((!z.result||z.result.trim()==="")&&(z.result=le),z.error&&delete z.error,console.log("✅ 工具执行成功,最终结果已更新:",{id:z.id,name:P.name||z.name,resultLength:z.result.length,success:P.success,is_stream:P.is_stream}))}else console.log("❌ 未找到对应的工具调用:",R),console.log("📋 当前可用的工具调用ID:",(we=(se=k.metadata)==null?void 0:se.toolCalls)==null?void 0:we.map(le=>le.id))}),k.updatedAt=new Date)}})}else if(U.type==="tools_stream"){console.log("🔧 收到工具流式数据:",U.data);const N=U.data;r($=>{const A=$.messages.findIndex(k=>k.id===C.id);if(A!==-1){const k=$.messages[A];if(k.metadata&&k.metadata.toolCalls){const P=N.toolCallId||N.tool_call_id||N.id;if(!P){console.warn("⚠️ 工具流式数据缺少工具调用ID:",N);return}console.log("🔍 查找工具调用进行流式更新:",P);const R=k.metadata.toolCalls.find(z=>z.id===P);if(R){const z=N.content||N.chunk||N.data||"";N.is_error||!N.success?(R.error=z||"工具执行出错",console.log("❌ 工具流式执行出错:",{id:R.id,error:R.error,success:N.success,is_error:N.is_error})):(R.result=(R.result||"")+z,console.log("🔧 工具流式数据已更新:",{id:R.id,name:N.name,chunkLength:z.length,totalLength:R.result.length,success:N.success,is_stream:N.is_stream})),k.updatedAt=new Date}}}})}else{if(U.type==="error")throw new Error(U.message||((y=U.data)==null?void 0:y.message)||"Stream error");if(U.type==="cancelled"){console.log("⚠️ 流式会话已被取消");break}else if(U.type==="done"){console.log("✅ 收到完成信号");break}}}catch(U){console.warn("解析流式数据失败:",U,"data:",ee)}}}}finally{V.releaseLock(),r(F=>{F.isLoading=!1,F.isStreaming=!1,F.streamingMessageId=null})}console.log("✅ 消息发送完成")}catch(b){throw console.error("❌ 发送消息失败:",b),r(S=>{const _=S.messages.findIndex(j=>{var v;return(v=j.id)==null?void 0:v.startsWith("temp_")});_!==-1&&S.messages.splice(_,1),S.isLoading=!1,S.isStreaming=!1,S.streamingMessageId=null,S.error=b instanceof Error?b.message:"Failed to send message"}),b}}}function Ph({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 Ih({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=>{r(a=>{a.selectedModelId=s,s&&(a.selectedAgentId=null)})}}}function Th({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 Oh({set:r}){return{updateChatConfig:async e=>{r(t=>{t.chatConfig={...t.chatConfig,...e}})}}}function rn(r,e){const t=r||ie,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 Ms(i,l,t),x=new Zl(h),w=new ec(i,l,x,d);return console.log("chatService:",w),Jc()(ad(fd((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,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(S=>{S.isLoading=!0,S.error=null}),console.log("🔍 loadSessions isLoading 设置为 true");const{userId:c,projectId:p}=g();console.log("🔍 loadSessions 调用 client.getSessions",{userId:c,projectId:p,customUserId:n,customProjectId:s});const y=await t.getSessions(c,p);console.log("🔍 loadSessions 返回结果:",y),m(S=>{S.sessions=y,S.isLoading=!1});const b=f();if(y.length>0&&!b.currentSessionId){const S=localStorage.getItem(`lastSessionId_${c}_${p}`);let _=null;S&&(_=y.find(j=>j.id===S)),_||(_=[...y].sort((j,v)=>new Date(v.createdAt).getTime()-new Date(j.createdAt).getTime())[0]),_&&(console.log("🔍 自动选择会话:",_.id),setTimeout(()=>{f().selectSession(_.id)},0))}console.log("🔍 loadSessions 完成")}catch(c){console.error("🔍 loadSessions 错误:",c),m(p=>{p.error=c instanceof Error?c.message:"Failed to load sessions",p.isLoading=!1})}},createSession:async(c="New Chat")=>{try{const{userId:p,projectId:y}=g();console.log("🔍 createSession 使用参数:",{userId:p,projectId:y,title:c}),console.log("🔍 createSession 自定义参数:",{customUserId:n,customProjectId:s}),console.log("🔍 createSession 最终使用的参数:",{userId:p,projectId:y,isCustomUserId:!!n,isCustomProjectId:!!s});const b={id:crypto.randomUUID(),title:c,user_id:p,project_id:y},S=await t.createSession(b);console.log("✅ createSession API调用成功:",S);const _={id:S.id,title:S.title,createdAt:new Date(S.created_at),updatedAt:new Date(S.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null};return m(j=>{j.sessions.unshift(_),j.currentSessionId=_.id,j.currentSession=_,j.messages=[],j.error=null}),localStorage.setItem(`lastSessionId_${p}_${y}`,_.id),console.log("🔍 保存新创建的会话ID到 localStorage:",_.id),_.id}catch(p){throw console.error("❌ createSession 失败:",p),m(y=>{y.error=p instanceof Error?p.message:"Failed to create session"}),p}},selectSession:async c=>{try{m(b=>{b.isLoading=!0,b.error=null});const p=await h.getSession(c),y=await h.getSessionMessages(c,{limit:10,offset:0});if(m(b=>{b.currentSessionId=c,b.currentSession=p,b.messages=y,b.isLoading=!1,b.hasMoreMessages=y.length===10,p||(b.error="Session not found")}),p){const{userId:b,projectId:S}=g();localStorage.setItem(`lastSessionId_${b}_${S}`,c),console.log("🔍 保存会话ID到 localStorage:",c)}}catch(p){console.error("Failed to select session:",p),m(y=>{y.error=p instanceof Error?p.message:"Failed to select session",y.isLoading=!1})}},updateSession:async(c,p)=>{try{const y=await h.updateSession(c,p);m(b=>{const S=b.sessions.findIndex(_=>_.id===c);S!==-1&&y&&(b.sessions[S]=y),b.currentSessionId===c&&(b.currentSession=y)})}catch(y){console.error("Failed to update session:",y),m(b=>{b.error=y instanceof Error?y.message:"Failed to update session"})}},deleteSession:async c=>{try{await h.deleteSession(c),m(p=>{p.sessions=p.sessions.filter(y=>y.id!==c),p.currentSessionId===c&&(p.currentSessionId=null,p.currentSession=null,p.messages=[])})}catch(p){console.error("Failed to delete session:",p),m(y=>{y.error=p instanceof Error?p.message:"Failed to delete session"})}},loadMessages:async c=>{try{m(y=>{y.isLoading=!0,y.error=null});const p=await h.getSessionMessages(c,{limit:10,offset:0});m(y=>{y.messages=p,y.isLoading=!1,y.hasMoreMessages=p.length===10})}catch(p){console.error("Failed to load messages:",p),m(y=>{y.error=p instanceof Error?p.message:"Failed to load messages",y.isLoading=!1})}},loadMoreMessages:async c=>{try{const y=f().messages.length,b=await h.getSessionMessages(c,{limit:10,offset:y});m(S=>{const _=new Set(S.messages.map(v=>v.id)),j=b.filter(v=>!_.has(v.id));S.messages=[...j,...S.messages],S.hasMoreMessages=b.length===10})}catch(p){console.error("Failed to load more messages:",p),m(y=>{y.error=p instanceof Error?p.message:"Failed to load more messages"})}},sendMessage:Eh({set:m,get:f,client:t,getUserIdParam:u}),updateMessage:async(c,p)=>{try{const y=await h.updateMessage(c,p);m(b=>{const S=b.messages.findIndex(_=>_.id===c);S!==-1&&y&&(b.messages[S]=y)})}catch(y){console.error("Failed to update message:",y),m(b=>{b.error=y instanceof Error?y.message:"Failed to update message"})}},deleteMessage:async c=>{try{await h.deleteMessage(c),m(p=>{p.messages=p.messages.filter(y=>y.id!==c)})}catch(p){console.error("Failed to delete message:",p),m(y=>{y.error=p instanceof Error?p.message:"Failed to delete message"})}},startStreaming:c=>{m(p=>{p.isStreaming=!0,p.streamingMessageId=c})},updateStreamingMessage:c=>{m(p=>{if(p.streamingMessageId){const y=p.messages.findIndex(b=>b.id===p.streamingMessageId);y!==-1&&(p.messages[y].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(p){console.error("❌ 停止对话失败:",p)}m(p=>{p.isStreaming=!1,p.streamingMessageId=null,p.isLoading=!1})},toggleSidebar:()=>{m(c=>{c.sidebarOpen=!c.sidebarOpen})},setTheme:c=>{m(p=>{p.theme=c})},...Oh({set:m}),...Th({set:m,get:f,client:t,getUserIdParam:u}),...Ph({set:m,get:f,client:t,getUserIdParam:u}),...Ih({set:m,get:f,client:t,getUserIdParam:u}),loadAgents:async()=>{var c;try{const p=await t.getAgents(u());console.log("🔍 [后端返回] loadAgents 返回的数据:",p),console.log("🔍 [后端返回] 第一个智能体的 app_ids:",(c=p==null?void 0:p[0])==null?void 0:c.app_ids),m(y=>{y.agents=p||[]})}catch(p){console.error("Failed to load agents:",p),m(y=>{y.agents=[],y.error=p instanceof Error?p.message:"Failed to load agents"})}},setSelectedAgent:c=>{m(p=>{p.selectedAgentId=c,c&&(p.selectedModelId=null)})},loadSystemContexts:async()=>{try{const c=await t.getSystemContexts(u()),p=await t.getActiveSystemContext(u());m(y=>{const b=(c||[]).map(S=>({...S,isActive:!1}));if(p&&p.context){const S=p.context,_=b.findIndex(j=>j.id===S.id);_!==-1?(b[_].isActive=!0,y.activeSystemContext={...b[_]}):y.activeSystemContext=null}else y.activeSystemContext=null;y.systemContexts=b})}catch(c){console.error("Failed to load system contexts:",c),m(p=>{p.systemContexts=[],p.activeSystemContext=null})}},createSystemContext:async(c,p,y)=>{try{const b=await t.createSystemContext({name:c,content:p,user_id:u(),app_ids:Array.isArray(y)?y:void 0});return m(S=>{S.systemContexts.push(b)}),b}catch(b){return console.error("Failed to create system context:",b),m(S=>{S.error=b instanceof Error?b.message:"Failed to create system context"}),null}},updateSystemContext:async(c,p,y,b)=>{try{const S=await t.updateSystemContext(c,{name:p,content:y,app_ids:Array.isArray(b)?b:void 0});return m(_=>{const j=_.systemContexts.findIndex(v=>v.id===c);j!==-1&&(_.systemContexts[j]=S)}),S}catch(S){return console.error("Failed to update system context:",S),m(_=>{_.error=S instanceof Error?S.message:"Failed to update system context"}),null}},deleteSystemContext:async c=>{try{await t.deleteSystemContext(c),m(p=>{var y;p.systemContexts=p.systemContexts.filter(b=>b.id!==c),((y=p.activeSystemContext)==null?void 0:y.id)===c&&(p.activeSystemContext=null)})}catch(p){console.error("Failed to delete system context:",p),m(y=>{y.error=p instanceof Error?p.message:"Failed to delete system context"})}},activateSystemContext:async c=>{try{await t.activateSystemContext(c,u()),m(p=>{const y=p.systemContexts.find(b=>b.id===c);y&&(p.systemContexts.forEach(b=>{b.isActive=b.id===c}),p.activeSystemContext={...y,isActive:!0})})}catch(p){console.error("Failed to activate system context:",p),m(y=>{y.error=p instanceof Error?p.message:"Failed to activate system context"})}},setError:c=>{m(p=>{p.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 vt=rn();function Rh(r,e,t){return rn(t,{userId:r,projectId:e})}const Nn=T.createContext(null),Lh=({children:r,userId:e,projectId:t,customApiClient:n})=>{const s=T.useMemo(()=>e||t||n?(console.log("🏪 创建自定义store:",{userId:e,projectId:t,hasCustomApiClient:!!n}),Rh(e||"default-user",t||"default-project",n)):(console.log("🏪 使用默认store"),vt),[e,t,n]);return o.jsx(Nn.Provider,{value:{store:s,userId:e,projectId:t,apiClient:n},children:r})},tc=()=>{const r=T.useContext(Nn);if(!r)throw new Error("useChatStoreContext must be used within a ChatStoreProvider");return r.store},_t=()=>tc()(),rc=()=>{const r=T.useContext(Nn);return r?{userId:r.userId,projectId:r.projectId}:{userId:void 0,projectId:void 0}},nc=()=>{const r=T.useContext(Nn);return r==null?void 0:r.apiClient},gt=({content:r,isStreaming:e=!1,className:t="",onApplyCode:n})=>{const[s,a]=T.useState(new Set),i=T.useCallback(async h=>{try{await navigator.clipboard.writeText(h)}catch(x){console.error("Failed to copy code:",x)}},[]),l=T.useCallback(h=>{a(x=>{const w=new Set(x);return w.has(h)?w.delete(h):w.add(h),w})},[]),d=T.useMemo(()=>h=>{if(!h)return"";let x=h;const w=/\$\$([\s\S]*?)\$\$/g;x=x.replace(w,(S,_)=>`<div class="math-block">${_.trim()}</div>`);const m=/\$([^$]+)\$/g;x=x.replace(m,(S,_)=>`<span class="math-inline">${_}</span>`);const f=/\|(.+)\|\n\|[-\s|:]+\|\n((?:\|.+\|\n?)*)/g;if(x=x.replace(f,(S,_,j)=>{const v=_.split("|").map(O=>O.trim()).filter(O=>O),I=j.trim().split(`
92
+ `).map(O=>O.split("|").map(L=>L.trim()).filter(L=>L));let M="<table>";return v.length>0&&(M+="<thead><tr>",v.forEach(O=>{M+=`<th>${O}</th>`}),M+="</tr></thead>"),I.length>0&&(M+="<tbody>",I.forEach(O=>{O.length>0&&(M+="<tr>",O.forEach(L=>{M+=`<td>${L}</td>`}),M+="</tr>")}),M+="</tbody>"),M+="</table>",e?`<div class="streaming-table-wrapper">
72
93
  <div class="streaming-table-indicator">● 正在生成表格...</div>
73
- ${N}
74
- </div>`:N}),e){const S=/\|(.+)\|\n\|[-\s|:]+\|(?:\n(?:\|.+\|)*)?$/,v=p.match(S);if(v){const[C,_]=v,T=_.split("|").map(F=>F.trim()).filter(F=>F),R=C.split(`
75
- `).slice(2).map(F=>F.split("|").map(O=>O.trim()).filter(O=>O)).filter(F=>F.length>0);let j='<div class="streaming-table-wrapper">';j+='<div class="streaming-table-indicator">● 正在生成表格...</div>',j+='<table class="streaming-table">',T.length>0&&(j+="<thead><tr>",T.forEach(F=>{j+=`<th>${F}</th>`}),j+="</tr></thead>"),R.length>0&&(j+="<tbody>",R.forEach(F=>{j+="<tr>",F.forEach(O=>{j+=`<td>${O}</td>`}),j+="</tr>"}),j+="</tbody>"),j+="</table></div>",p=p.replace(S,j)}}const u=/```(\w+)?\n?([\s\S]*?)```/g;let g=0;if(p=p.replace(u,(S,v,C)=>{const _=v||"text",T=d(C.trim()),N=`code-block-${g++}`,P=s.has(N),R=C.trim();return`<div class="code-block ${P?"expanded":""}" data-block-id="${N}">
94
+ ${M}
95
+ </div>`:M}),e){const S=/\|(.+)\|\n\|[-\s|:]+\|(?:\n(?:\|.+\|)*)?$/,_=x.match(S);if(_){const[j,v]=_,I=v.split("|").map(H=>H.trim()).filter(H=>H),L=j.split(`
96
+ `).slice(2).map(H=>H.split("|").map(D=>D.trim()).filter(D=>D)).filter(H=>H.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(H=>{C+=`<th>${H}</th>`}),C+="</tr></thead>"),L.length>0&&(C+="<tbody>",L.forEach(H=>{C+="<tr>",H.forEach(D=>{C+=`<td>${D}</td>`}),C+="</tr>"}),C+="</tbody>"),C+="</table></div>",x=x.replace(S,C)}}const c=/```(\w+)?\n?([\s\S]*?)```/g;let p=0;if(x=x.replace(c,(S,_,j)=>{const v=_||"text",I=u(j.trim()),M=`code-block-${p++}`,O=s.has(M),L=j.trim();return`<div class="code-block ${O?"expanded":""}" data-block-id="${M}">
76
97
  <div class="code-header">
77
- <span class="code-language">${_}</span>
98
+ <span class="code-language">${v}</span>
78
99
  <div class="code-actions">
79
- <button class="code-action-btn copy-btn" data-code="${encodeURIComponent(R)}" title="复制代码">
100
+ <button class="code-action-btn copy-btn" data-code="${encodeURIComponent(L)}" title="复制代码">
80
101
  <span class="icon">复制</span>
81
102
  </button>
82
- <button class="code-action-btn apply-btn" data-code="${encodeURIComponent(R)}" data-language="${_}" title="应用代码">
103
+ <button class="code-action-btn apply-btn" data-code="${encodeURIComponent(L)}" data-language="${v}" title="应用代码">
83
104
  <span class="icon">应用</span>
84
105
  </button>
85
- <button class="code-action-btn expand-btn" data-block-id="${N}" title="${P?"收起":"展开"}">
86
- <span class="icon">${P?"收起":"展开"}</span>
106
+ <button class="code-action-btn expand-btn" data-block-id="${M}" title="${O?"收起":"展开"}">
107
+ <span class="icon">${O?"收起":"展开"}</span>
87
108
  </button>
88
109
  </div>
89
110
  </div>
90
111
  <div class="code-content">
91
- <pre><code>${T}</code></pre>
112
+ <pre><code>${I}</code></pre>
92
113
  </div>
93
- </div>`}),p=p.replace(/`([^`\n]+)`/g,"<code>$1</code>"),e){const S=/```(\w+)?\n?([\s\S]*?)$/,v=p.match(S);if(v&&!v[0].includes("```",3)){const[,C,_]=v,T=C||"text",N=d(_);p=p.replace(S,`<div class="code-block streaming-code">
94
- <div class="code-header">${T} <span class="streaming-indicator">● 正在输入...</span></div>
95
- <pre><code>${N}</code></pre>
96
- </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 w=0;return p=p.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g,S=>{const v=`__PROTECTED_HTML_${w++}__`;return b.push(S),v}),p=p.replace(/<[^>]+>/g,S=>{const v=`__PROTECTED_HTML_${w++}__`;return b.push(S),v}),p=p.replace(/\n\n/g,"</p><p>"),p=p.replace(/\n/g,"<br>"),b.forEach((S,v)=>{p=p.replace(`__PROTECTED_HTML_${v}__`,S)}),p&&!p.startsWith("<")&&(p=`<p>${p}</p>`),p},[e,s,n]),d=(f,p)=>f.replace(/</g,"&lt;").replace(/>/g,"&gt;"),m=I.useCallback(f=>{const y=f.target.closest("button");if(y){if(y.classList.contains("copy-btn")){const h=decodeURIComponent(y.getAttribute("data-code")||"");i(h)}else if(y.classList.contains("apply-btn")){const h=decodeURIComponent(y.getAttribute("data-code")||""),x=y.getAttribute("data-language")||"text";n==null||n(h,x)}else if(y.classList.contains("expand-btn")){const h=y.getAttribute("data-block-id");h&&l(h)}}},[i,n,l]);return a.jsxs("div",{className:`markdown-renderer ${t}`,onClick:m,children:[a.jsx("div",{dangerouslySetInnerHTML:{__html:c(r)}}),e&&a.jsx("span",{className:"streaming-cursor"})]})};function Pl(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=Pl(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Lf(){for(var r,e,t=0,n="",s=arguments.length;t<s;t++)(r=arguments[t])&&(e=Pl(r))&&(n&&(n+=" "),n+=e);return n}const oo="-",Df=r=>{const e=Uf(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:i=>{const l=i.split(oo);return l[0]===""&&l.length!==1&&l.shift(),Ol(l,e)||Ff(i)},getConflictingClassGroupIds:(i,l)=>{const c=t[i]||[];return l&&n[i]?[...c,...n[i]]:c}}},Ol=(r,e)=>{var i;if(r.length===0)return e.classGroupId;const t=r[0],n=e.nextPart.get(t),s=n?Ol(r.slice(1),n):void 0;if(s)return s;if(e.validators.length===0)return;const o=r.join(oo);return(i=e.validators.find(({validator:l})=>l(o)))==null?void 0:i.classGroupId},ga=/^\[(.+)\]$/,Ff=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}},Uf=r=>{const{theme:e,prefix:t}=r,n={nextPart:new Map,validators:[]};return Wf(Object.entries(r.classGroups),t).forEach(([o,i])=>{hs(i,n,o,e)}),n},hs=(r,e,t,n)=>{r.forEach(s=>{if(typeof s=="string"){const o=s===""?e:pa(e,s);o.classGroupId=t;return}if(typeof s=="function"){if(Bf(s)){hs(s(n),e,t,n);return}e.validators.push({validator:s,classGroupId:t});return}Object.entries(s).forEach(([o,i])=>{hs(i,pa(e,o),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},Bf=r=>r.isThemeGetter,Wf=(r,e)=>e?r.map(([t,n])=>{const s=n.map(o=>typeof o=="string"?e+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([i,l])=>[e+i,l])):o);return[t,s]}):r,Hf=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,n=new Map;const s=(o,i)=>{t.set(o,i),e++,e>r&&(e=0,n=t,t=new Map)};return{get(o){let i=t.get(o);if(i!==void 0)return i;if((i=n.get(o))!==void 0)return s(o,i),i},set(o,i){t.has(o)?t.set(o,i):s(o,i)}}},Rl="!",qf=r=>{const{separator:e,experimentalParseClassName:t}=r,n=e.length===1,s=e[0],o=e.length,i=l=>{const c=[];let d=0,m=0,f;for(let u=0;u<l.length;u++){let g=l[u];if(d===0){if(g===s&&(n||l.slice(u,u+o)===e)){c.push(l.slice(m,u)),m=u+o;continue}if(g==="/"){f=u;continue}}g==="["?d++:g==="]"&&d--}const p=c.length===0?l:l.substring(m),y=p.startsWith(Rl),h=y?p.substring(1):p,x=f&&f>m?f-m:void 0;return{modifiers:c,hasImportantModifier:y,baseClassName:h,maybePostfixModifierPosition:x}};return t?l=>t({className:l,parseClassName:i}):i},zf=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},Jf=r=>({cache:Hf(r.cacheSize),parseClassName:qf(r),...Df(r)}),Vf=/\s+/,Gf=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:s}=e,o=[],i=r.trim().split(Vf);let l="";for(let c=i.length-1;c>=0;c-=1){const d=i[c],{modifiers:m,hasImportantModifier:f,baseClassName:p,maybePostfixModifierPosition:y}=t(d);let h=!!y,x=n(h?p.substring(0,y):p);if(!x){if(!h){l=d+(l.length>0?" "+l:l);continue}if(x=n(p),!x){l=d+(l.length>0?" "+l:l);continue}h=!1}const u=zf(m).join(":"),g=f?u+Rl:u,b=g+x;if(o.includes(b))continue;o.push(b);const w=s(x,h);for(let S=0;S<w.length;++S){const v=w[S];o.push(g+v)}l=d+(l.length>0?" "+l:l)}return l};function Xf(){let r=0,e,t,n="";for(;r<arguments.length;)(e=arguments[r++])&&(t=$l(e))&&(n&&(n+=" "),n+=t);return n}const $l=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=$l(r[n]))&&(t&&(t+=" "),t+=e);return t};function Kf(r,...e){let t,n,s,o=i;function i(c){const d=e.reduce((m,f)=>f(m),r());return t=Jf(d),n=t.cache.get,s=t.cache.set,o=l,l(c)}function l(c){const d=n(c);if(d)return d;const m=Gf(c,t);return s(c,m),m}return function(){return o(Xf.apply(null,arguments))}}const oe=r=>{const e=t=>t[r]||[];return e.isThemeGetter=!0,e},Ll=/^\[(?:([a-z-]+):)?(.+)\]$/i,Yf=/^\d+\/\d+$/,Qf=new Set(["px","full","screen"]),Zf=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,eh=/\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$/,th=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,rh=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,nh=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Be=r=>St(r)||Qf.has(r)||Yf.test(r),Ve=r=>Tt(r,"length",uh),St=r=>!!r&&!Number.isNaN(Number(r)),Fn=r=>Tt(r,"number",St),Ot=r=>!!r&&Number.isInteger(Number(r)),sh=r=>r.endsWith("%")&&St(r.slice(0,-1)),te=r=>Ll.test(r),Ge=r=>Zf.test(r),oh=new Set(["length","size","percentage"]),ah=r=>Tt(r,oh,Dl),ih=r=>Tt(r,"position",Dl),lh=new Set(["image","url"]),ch=r=>Tt(r,lh,hh),dh=r=>Tt(r,"",fh),Rt=()=>!0,Tt=(r,e,t)=>{const n=Ll.exec(r);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):t(n[2]):!1},uh=r=>eh.test(r)&&!th.test(r),Dl=()=>!1,fh=r=>rh.test(r),hh=r=>nh.test(r),mh=()=>{const r=oe("colors"),e=oe("spacing"),t=oe("blur"),n=oe("brightness"),s=oe("borderColor"),o=oe("borderRadius"),i=oe("borderSpacing"),l=oe("borderWidth"),c=oe("contrast"),d=oe("grayscale"),m=oe("hueRotate"),f=oe("invert"),p=oe("gap"),y=oe("gradientColorStops"),h=oe("gradientColorStopPositions"),x=oe("inset"),u=oe("margin"),g=oe("opacity"),b=oe("padding"),w=oe("saturate"),S=oe("scale"),v=oe("sepia"),C=oe("skew"),_=oe("space"),T=oe("translate"),N=()=>["auto","contain","none"],P=()=>["auto","hidden","clip","visible","scroll"],R=()=>["auto",te,e],j=()=>[te,e],F=()=>["",Be,Ve],O=()=>["auto",St,te],z=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],H=()=>["solid","dashed","dotted","double","none"],E=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],L=()=>["start","end","center","between","around","evenly","stretch"],U=()=>["","0",te],$=()=>["auto","avoid","all","avoid-page","page","left","right","column"],D=()=>[St,te];return{cacheSize:500,separator:":",theme:{colors:[Rt],spacing:[Be,Ve],blur:["none","",Ge,te],brightness:D(),borderColor:[r],borderRadius:["none","","full",Ge,te],borderSpacing:j(),borderWidth:F(),contrast:D(),grayscale:U(),hueRotate:D(),invert:U(),gap:j(),gradientColorStops:[r],gradientColorStopPositions:[sh,Ve],inset:R(),margin:R(),opacity:D(),padding:j(),saturate:D(),scale:D(),sepia:U(),skew:D(),space:j(),translate:j()},classGroups:{aspect:[{aspect:["auto","square","video",te]}],container:["container"],columns:[{columns:[Ge]}],"break-after":[{"break-after":$()}],"break-before":[{"break-before":$()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...z(),te]}],overflow:[{overflow:P()}],"overflow-x":[{"overflow-x":P()}],"overflow-y":[{"overflow-y":P()}],overscroll:[{overscroll:N()}],"overscroll-x":[{"overscroll-x":N()}],"overscroll-y":[{"overscroll-y":N()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[x]}],"inset-x":[{"inset-x":[x]}],"inset-y":[{"inset-y":[x]}],start:[{start:[x]}],end:[{end:[x]}],top:[{top:[x]}],right:[{right:[x]}],bottom:[{bottom:[x]}],left:[{left:[x]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ot,te]}],basis:[{basis:R()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",te]}],grow:[{grow:U()}],shrink:[{shrink:U()}],order:[{order:["first","last","none",Ot,te]}],"grid-cols":[{"grid-cols":[Rt]}],"col-start-end":[{col:["auto",{span:["full",Ot,te]},te]}],"col-start":[{"col-start":O()}],"col-end":[{"col-end":O()}],"grid-rows":[{"grid-rows":[Rt]}],"row-start-end":[{row:["auto",{span:[Ot,te]},te]}],"row-start":[{"row-start":O()}],"row-end":[{"row-end":O()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",te]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",te]}],gap:[{gap:[p]}],"gap-x":[{"gap-x":[p]}],"gap-y":[{"gap-y":[p]}],"justify-content":[{justify:["normal",...L()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...L(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...L(),"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:[u]}],mx:[{mx:[u]}],my:[{my:[u]}],ms:[{ms:[u]}],me:[{me:[u]}],mt:[{mt:[u]}],mr:[{mr:[u]}],mb:[{mb:[u]}],ml:[{ml:[u]}],"space-x":[{"space-x":[_]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[_]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",te,e]}],"min-w":[{"min-w":[te,e,"min","max","fit"]}],"max-w":[{"max-w":[te,e,"none","full","min","max","fit","prose",{screen:[Ge]},Ge]}],h:[{h:[te,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[te,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[te,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[te,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Ge,Ve]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Fn]}],"font-family":[{font:[Rt]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",te]}],"line-clamp":[{"line-clamp":["none",St,Fn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Be,te]}],"list-image":[{"list-image":["none",te]}],"list-style-type":[{list:["none","disc","decimal",te]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[r]}],"placeholder-opacity":[{"placeholder-opacity":[g]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[r]}],"text-opacity":[{"text-opacity":[g]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...H(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Be,Ve]}],"underline-offset":[{"underline-offset":["auto",Be,te]}],"text-decoration-color":[{decoration:[r]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:j()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",te]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",te]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[g]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...z(),ih]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",ah]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},ch]}],"bg-color":[{bg:[r]}],"gradient-from-pos":[{from:[h]}],"gradient-via-pos":[{via:[h]}],"gradient-to-pos":[{to:[h]}],"gradient-from":[{from:[y]}],"gradient-via":[{via:[y]}],"gradient-to":[{to:[y]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[l]}],"border-w-x":[{"border-x":[l]}],"border-w-y":[{"border-y":[l]}],"border-w-s":[{"border-s":[l]}],"border-w-e":[{"border-e":[l]}],"border-w-t":[{"border-t":[l]}],"border-w-r":[{"border-r":[l]}],"border-w-b":[{"border-b":[l]}],"border-w-l":[{"border-l":[l]}],"border-opacity":[{"border-opacity":[g]}],"border-style":[{border:[...H(),"hidden"]}],"divide-x":[{"divide-x":[l]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[l]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[g]}],"divide-style":[{divide:H()}],"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:["",...H()]}],"outline-offset":[{"outline-offset":[Be,te]}],"outline-w":[{outline:[Be,Ve]}],"outline-color":[{outline:[r]}],"ring-w":[{ring:F()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[r]}],"ring-opacity":[{"ring-opacity":[g]}],"ring-offset-w":[{"ring-offset":[Be,Ve]}],"ring-offset-color":[{"ring-offset":[r]}],shadow:[{shadow:["","inner","none",Ge,dh]}],"shadow-color":[{shadow:[Rt]}],opacity:[{opacity:[g]}],"mix-blend":[{"mix-blend":[...E(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":E()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[n]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",Ge,te]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[m]}],invert:[{invert:[f]}],saturate:[{saturate:[w]}],sepia:[{sepia:[v]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[t]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[m]}],"backdrop-invert":[{"backdrop-invert":[f]}],"backdrop-opacity":[{"backdrop-opacity":[g]}],"backdrop-saturate":[{"backdrop-saturate":[w]}],"backdrop-sepia":[{"backdrop-sepia":[v]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[i]}],"border-spacing-x":[{"border-spacing-x":[i]}],"border-spacing-y":[{"border-spacing-y":[i]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",te]}],duration:[{duration:D()}],ease:[{ease:["linear","in","out","in-out",te]}],delay:[{delay:D()}],animate:[{animate:["none","spin","ping","pulse","bounce",te]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[Ot,te]}],"translate-x":[{"translate-x":[T]}],"translate-y":[{"translate-y":[T]}],"skew-x":[{"skew-x":[C]}],"skew-y":[{"skew-y":[C]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",te]}],accent:[{accent:["auto",r]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",te]}],"caret-color":[{caret:[r]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":j()}],"scroll-mx":[{"scroll-mx":j()}],"scroll-my":[{"scroll-my":j()}],"scroll-ms":[{"scroll-ms":j()}],"scroll-me":[{"scroll-me":j()}],"scroll-mt":[{"scroll-mt":j()}],"scroll-mr":[{"scroll-mr":j()}],"scroll-mb":[{"scroll-mb":j()}],"scroll-ml":[{"scroll-ml":j()}],"scroll-p":[{"scroll-p":j()}],"scroll-px":[{"scroll-px":j()}],"scroll-py":[{"scroll-py":j()}],"scroll-ps":[{"scroll-ps":j()}],"scroll-pe":[{"scroll-pe":j()}],"scroll-pt":[{"scroll-pt":j()}],"scroll-pr":[{"scroll-pr":j()}],"scroll-pb":[{"scroll-pb":j()}],"scroll-pl":[{"scroll-pl":j()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",te]}],fill:[{fill:[r,"none"]}],"stroke-w":[{stroke:[Be,Ve,Fn]}],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"]}}},gh=Kf(mh);let Cr;const ph=new Uint8Array(16);function xh(){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(ph)}const ge=[];for(let r=0;r<256;++r)ge.push((r+256).toString(16).slice(1));function bh(r,e=0){return ge[r[e+0]]+ge[r[e+1]]+ge[r[e+2]]+ge[r[e+3]]+"-"+ge[r[e+4]]+ge[r[e+5]]+"-"+ge[r[e+6]]+ge[r[e+7]]+"-"+ge[r[e+8]]+ge[r[e+9]]+"-"+ge[r[e+10]]+ge[r[e+11]]+ge[r[e+12]]+ge[r[e+13]]+ge[r[e+14]]+ge[r[e+15]]}const yh=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),xa={randomUUID:yh};function wh(r,e,t){if(xa.randomUUID&&!r)return xa.randomUUID();r=r||{};const n=r.random||(r.rng||xh)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,bh(n)}const Fl=6048e5,vh=864e5,jr=43200,ba=1440,ya=Symbol.for("constructDateFrom");function He(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 me(r,e){return He(e||r,r)}let _h={};function ur(){return _h}function Qt(r,e){var l,c,d,m;const t=ur(),n=(e==null?void 0:e.weekStartsOn)??((c=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:c.weekStartsOn)??t.weekStartsOn??((m=(d=t.locale)==null?void 0:d.options)==null?void 0:m.weekStartsOn)??0,s=me(r,e==null?void 0:e.in),o=s.getDay(),i=(o<n?7:0)+o-n;return s.setDate(s.getDate()-i),s.setHours(0,0,0,0),s}function Jr(r,e){return Qt(r,{...e,weekStartsOn:1})}function Ul(r,e){const t=me(r,e==null?void 0:e.in),n=t.getFullYear(),s=He(t,0);s.setFullYear(n+1,0,4),s.setHours(0,0,0,0);const o=Jr(s),i=He(t,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=Jr(i);return t.getTime()>=o.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function Vr(r){const e=me(r),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+r-+t}function xn(r,...e){const t=He.bind(null,r||e.find(n=>typeof n=="object"));return e.map(t)}function wa(r,e){const t=me(r,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function Sh(r,e,t){const[n,s]=xn(t==null?void 0:t.in,r,e),o=wa(n),i=wa(s),l=+o-Vr(o),c=+i-Vr(i);return Math.round((l-c)/vh)}function Ch(r,e){const t=Ul(r,e),n=He(r,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),Jr(n)}function $r(r,e){const t=+me(r)-+me(e);return t<0?-1:t>0?1:t}function jh(r){return He(r,Date.now())}function Ah(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function kh(r){return!(!Ah(r)&&typeof r!="number"||isNaN(+me(r)))}function Nh(r,e,t){const[n,s]=xn(t==null?void 0:t.in,r,e),o=n.getFullYear()-s.getFullYear(),i=n.getMonth()-s.getMonth();return o*12+i}function Mh(r){return e=>{const n=(r?Math[r]:Math.trunc)(e);return n===0?0:n}}function Eh(r,e){return+me(r)-+me(e)}function Ih(r,e){const t=me(r,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Th(r,e){const t=me(r,e==null?void 0:e.in),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function Ph(r,e){const t=me(r,e==null?void 0:e.in);return+Ih(t,e)==+Th(t,e)}function Oh(r,e,t){const[n,s,o]=xn(t==null?void 0:t.in,r,r,e),i=$r(s,o),l=Math.abs(Nh(s,o));if(l<1)return 0;s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-i*l);let c=$r(s,o)===-i;Ph(n)&&l===1&&$r(n,o)===1&&(c=!1);const d=i*(l-+c);return d===0?0:d}function Rh(r,e,t){const n=Eh(r,e)/1e3;return Mh(t==null?void 0:t.roundingMethod)(n)}function $h(r,e){const t=me(r,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}const Lh={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"}},Dh=(r,e,t)=>{let n;const s=Lh[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 Un(r){return(e={})=>{const t=e.width?String(e.width):r.defaultWidth;return r.formats[t]||r.formats[r.defaultWidth]}}const Fh={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Uh={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Bh={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Wh={date:Un({formats:Fh,defaultWidth:"full"}),time:Un({formats:Uh,defaultWidth:"full"}),dateTime:Un({formats:Bh,defaultWidth:"full"})},Hh={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},qh=(r,e,t,n)=>Hh[r];function $t(r){return(e,t)=>{const n=t!=null&&t.context?String(t.context):"standalone";let s;if(n==="formatting"&&r.formattingValues){const i=r.defaultFormattingWidth||r.defaultWidth,l=t!=null&&t.width?String(t.width):i;s=r.formattingValues[l]||r.formattingValues[i]}else{const i=r.defaultWidth,l=t!=null&&t.width?String(t.width):r.defaultWidth;s=r.values[l]||r.values[i]}const o=r.argumentCallback?r.argumentCallback(e):e;return s[o]}}const zh={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Jh={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Vh={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"]},Gh={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"]},Xh={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"}},Kh={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"}},Yh=(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"},Qh={ordinalNumber:Yh,era:$t({values:zh,defaultWidth:"wide"}),quarter:$t({values:Jh,defaultWidth:"wide",argumentCallback:r=>r-1}),month:$t({values:Vh,defaultWidth:"wide"}),day:$t({values:Gh,defaultWidth:"wide"}),dayPeriod:$t({values:Xh,defaultWidth:"wide",formattingValues:Kh,defaultFormattingWidth:"wide"})};function Lt(r){return(e,t={})=>{const n=t.width,s=n&&r.matchPatterns[n]||r.matchPatterns[r.defaultMatchWidth],o=e.match(s);if(!o)return null;const i=o[0],l=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],c=Array.isArray(l)?em(l,f=>f.test(i)):Zh(l,f=>f.test(i));let d;d=r.valueCallback?r.valueCallback(c):c,d=t.valueCallback?t.valueCallback(d):d;const m=e.slice(i.length);return{value:d,rest:m}}}function Zh(r,e){for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&e(r[t]))return t}function em(r,e){for(let t=0;t<r.length;t++)if(e(r[t]))return t}function tm(r){return(e,t={})=>{const n=e.match(r.matchPattern);if(!n)return null;const s=n[0],o=e.match(r.parsePattern);if(!o)return null;let i=r.valueCallback?r.valueCallback(o[0]):o[0];i=t.valueCallback?t.valueCallback(i):i;const l=e.slice(s.length);return{value:i,rest:l}}}const rm=/^(\d+)(th|st|nd|rd)?/i,nm=/\d+/i,sm={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},om={any:[/^b/i,/^(a|c)/i]},am={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},im={any:[/1/i,/2/i,/3/i,/4/i]},lm={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},cm={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]},dm={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},um={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]},fm={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},hm={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}},mm={ordinalNumber:tm({matchPattern:rm,parsePattern:nm,valueCallback:r=>parseInt(r,10)}),era:Lt({matchPatterns:sm,defaultMatchWidth:"wide",parsePatterns:om,defaultParseWidth:"any"}),quarter:Lt({matchPatterns:am,defaultMatchWidth:"wide",parsePatterns:im,defaultParseWidth:"any",valueCallback:r=>r+1}),month:Lt({matchPatterns:lm,defaultMatchWidth:"wide",parsePatterns:cm,defaultParseWidth:"any"}),day:Lt({matchPatterns:dm,defaultMatchWidth:"wide",parsePatterns:um,defaultParseWidth:"any"}),dayPeriod:Lt({matchPatterns:fm,defaultMatchWidth:"any",parsePatterns:hm,defaultParseWidth:"any"})},Bl={code:"en-US",formatDistance:Dh,formatLong:Wh,formatRelative:qh,localize:Qh,match:mm,options:{weekStartsOn:0,firstWeekContainsDate:1}};function gm(r,e){const t=me(r,e==null?void 0:e.in);return Sh(t,$h(t))+1}function pm(r,e){const t=me(r,e==null?void 0:e.in),n=+Jr(t)-+Ch(t);return Math.round(n/Fl)+1}function Wl(r,e){var m,f,p,y;const t=me(r,e==null?void 0:e.in),n=t.getFullYear(),s=ur(),o=(e==null?void 0:e.firstWeekContainsDate)??((f=(m=e==null?void 0:e.locale)==null?void 0:m.options)==null?void 0:f.firstWeekContainsDate)??s.firstWeekContainsDate??((y=(p=s.locale)==null?void 0:p.options)==null?void 0:y.firstWeekContainsDate)??1,i=He((e==null?void 0:e.in)||r,0);i.setFullYear(n+1,0,o),i.setHours(0,0,0,0);const l=Qt(i,e),c=He((e==null?void 0:e.in)||r,0);c.setFullYear(n,0,o),c.setHours(0,0,0,0);const d=Qt(c,e);return+t>=+l?n+1:+t>=+d?n:n-1}function xm(r,e){var l,c,d,m;const t=ur(),n=(e==null?void 0:e.firstWeekContainsDate)??((c=(l=e==null?void 0:e.locale)==null?void 0:l.options)==null?void 0:c.firstWeekContainsDate)??t.firstWeekContainsDate??((m=(d=t.locale)==null?void 0:d.options)==null?void 0:m.firstWeekContainsDate)??1,s=Wl(r,e),o=He((e==null?void 0:e.in)||r,0);return o.setFullYear(s,0,n),o.setHours(0,0,0,0),Qt(o,e)}function bm(r,e){const t=me(r,e==null?void 0:e.in),n=+Qt(t,e)-+xm(t,e);return Math.round(n/Fl)+1}function ne(r,e){const t=r<0?"-":"",n=Math.abs(r).toString().padStart(e,"0");return t+n}const Xe={y(r,e){const t=r.getFullYear(),n=t>0?t:1-t;return ne(e==="yy"?n%100:n,e.length)},M(r,e){const t=r.getMonth();return e==="M"?String(t+1):ne(t+1,2)},d(r,e){return ne(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 ne(r.getHours()%12||12,e.length)},H(r,e){return ne(r.getHours(),e.length)},m(r,e){return ne(r.getMinutes(),e.length)},s(r,e){return ne(r.getSeconds(),e.length)},S(r,e){const t=e.length,n=r.getMilliseconds(),s=Math.trunc(n*Math.pow(10,t-3));return ne(s,e.length)}},pt={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 Xe.y(r,e)},Y:function(r,e,t,n){const s=Wl(r,n),o=s>0?s:1-s;if(e==="YY"){const i=o%100;return ne(i,2)}return e==="Yo"?t.ordinalNumber(o,{unit:"year"}):ne(o,e.length)},R:function(r,e){const t=Ul(r);return ne(t,e.length)},u:function(r,e){const t=r.getFullYear();return ne(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 ne(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 ne(n,2);case"qo":return t.ordinalNumber(n,{unit:"quarter"});case"qqq":return t.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(n,{width:"wide",context:"standalone"})}},M:function(r,e,t){const n=r.getMonth();switch(e){case"M":case"MM":return Xe.M(r,e);case"Mo":return t.ordinalNumber(n+1,{unit:"month"});case"MMM":return t.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(n,{width:"wide",context:"formatting"})}},L:function(r,e,t){const n=r.getMonth();switch(e){case"L":return String(n+1);case"LL":return ne(n+1,2);case"Lo":return t.ordinalNumber(n+1,{unit:"month"});case"LLL":return t.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(n,{width:"wide",context:"standalone"})}},w:function(r,e,t,n){const s=bm(r,n);return e==="wo"?t.ordinalNumber(s,{unit:"week"}):ne(s,e.length)},I:function(r,e,t){const n=pm(r);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):ne(n,e.length)},d:function(r,e,t){return e==="do"?t.ordinalNumber(r.getDate(),{unit:"date"}):Xe.d(r,e)},D:function(r,e,t){const n=gm(r);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):ne(n,e.length)},E:function(r,e,t){const n=r.getDay();switch(e){case"E":case"EE":case"EEE":return t.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(n,{width:"short",context:"formatting"});case"EEEE":default:return t.day(n,{width:"wide",context:"formatting"})}},e:function(r,e,t,n){const s=r.getDay(),o=(s-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(o);case"ee":return ne(o,2);case"eo":return t.ordinalNumber(o,{unit:"day"});case"eee":return t.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(s,{width:"short",context:"formatting"});case"eeee":default:return t.day(s,{width:"wide",context:"formatting"})}},c:function(r,e,t,n){const s=r.getDay(),o=(s-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(o);case"cc":return ne(o,e.length);case"co":return t.ordinalNumber(o,{unit:"day"});case"ccc":return t.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(s,{width:"narrow",context:"standalone"});case"cccccc":return t.day(s,{width:"short",context:"standalone"});case"cccc":default:return t.day(s,{width:"wide",context:"standalone"})}},i:function(r,e,t){const n=r.getDay(),s=n===0?7:n;switch(e){case"i":return String(s);case"ii":return ne(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=pt.noon:n===0?s=pt.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=pt.evening:n>=12?s=pt.afternoon:n>=4?s=pt.morning:s=pt.night,e){case"B":case"BB":case"BBB":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(r,e,t){if(e==="ho"){let n=r.getHours()%12;return n===0&&(n=12),t.ordinalNumber(n,{unit:"hour"})}return Xe.h(r,e)},H:function(r,e,t){return e==="Ho"?t.ordinalNumber(r.getHours(),{unit:"hour"}):Xe.H(r,e)},K:function(r,e,t){const n=r.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):ne(n,e.length)},k:function(r,e,t){let n=r.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):ne(n,e.length)},m:function(r,e,t){return e==="mo"?t.ordinalNumber(r.getMinutes(),{unit:"minute"}):Xe.m(r,e)},s:function(r,e,t){return e==="so"?t.ordinalNumber(r.getSeconds(),{unit:"second"}):Xe.s(r,e)},S:function(r,e){return Xe.S(r,e)},X:function(r,e,t){const n=r.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return Sa(n);case"XXXX":case"XX":return tt(n);case"XXXXX":case"XXX":default:return tt(n,":")}},x:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"x":return Sa(n);case"xxxx":case"xx":return tt(n);case"xxxxx":case"xxx":default:return tt(n,":")}},O:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+_a(n,":");case"OOOO":default:return"GMT"+tt(n,":")}},z:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+_a(n,":");case"zzzz":default:return"GMT"+tt(n,":")}},t:function(r,e,t){const n=Math.trunc(+r/1e3);return ne(n,e.length)},T:function(r,e,t){return ne(+r,e.length)}};function _a(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=Math.trunc(n/60),o=n%60;return o===0?t+String(s):t+String(s)+e+ne(o,2)}function Sa(r,e){return r%60===0?(r>0?"-":"+")+ne(Math.abs(r)/60,2):tt(r,e)}function tt(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=ne(Math.trunc(n/60),2),o=ne(n%60,2);return t+s+e+o}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"})}},Hl=(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"})}},ym=(r,e)=>{const t=r.match(/(P+)(p+)?/)||[],n=t[1],s=t[2];if(!s)return Ca(r,e);let o;switch(n){case"P":o=e.dateTime({width:"short"});break;case"PP":o=e.dateTime({width:"medium"});break;case"PPP":o=e.dateTime({width:"long"});break;case"PPPP":default:o=e.dateTime({width:"full"});break}return o.replace("{{date}}",Ca(n,e)).replace("{{time}}",Hl(s,e))},wm={p:Hl,P:ym},vm=/^D+$/,_m=/^Y+$/,Sm=["D","DD","YY","YYYY"];function Cm(r){return vm.test(r)}function jm(r){return _m.test(r)}function Am(r,e,t){const n=km(r,e,t);if(console.warn(n),Sm.includes(r))throw new RangeError(n)}function km(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 Nm=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Mm=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Em=/^'([^]*?)'?$/,Im=/''/g,Tm=/[a-zA-Z]/;function ao(r,e,t){var m,f,p,y;const n=ur(),s=n.locale??Bl,o=n.firstWeekContainsDate??((f=(m=n.locale)==null?void 0:m.options)==null?void 0:f.firstWeekContainsDate)??1,i=n.weekStartsOn??((y=(p=n.locale)==null?void 0:p.options)==null?void 0:y.weekStartsOn)??0,l=me(r,t==null?void 0:t.in);if(!kh(l))throw new RangeError("Invalid time value");let c=e.match(Mm).map(h=>{const x=h[0];if(x==="p"||x==="P"){const u=wm[x];return u(h,s.formatLong)}return h}).join("").match(Nm).map(h=>{if(h==="''")return{isToken:!1,value:"'"};const x=h[0];if(x==="'")return{isToken:!1,value:Pm(h)};if(va[x])return{isToken:!0,value:h};if(x.match(Tm))throw new RangeError("Format string contains an unescaped latin alphabet character `"+x+"`");return{isToken:!1,value:h}});s.localize.preprocessor&&(c=s.localize.preprocessor(l,c));const d={firstWeekContainsDate:o,weekStartsOn:i,locale:s};return c.map(h=>{if(!h.isToken)return h.value;const x=h.value;(jm(x)||Cm(x))&&Am(x,e,String(r));const u=va[x[0]];return u(l,x,s.localize,d)}).join("")}function Pm(r){const e=r.match(Em);return e?e[1].replace(Im,"'"):r}function Om(r,e,t){const n=ur(),s=(t==null?void 0:t.locale)??n.locale??Bl,o=2520,i=$r(r,e);if(isNaN(i))throw new RangeError("Invalid time value");const l=Object.assign({},t,{addSuffix:t==null?void 0:t.addSuffix,comparison:i}),[c,d]=xn(t==null?void 0:t.in,...i>0?[e,r]:[r,e]),m=Rh(d,c),f=(Vr(d)-Vr(c))/1e3,p=Math.round((m-f)/60);let y;if(p<2)return t!=null&&t.includeSeconds?m<5?s.formatDistance("lessThanXSeconds",5,l):m<10?s.formatDistance("lessThanXSeconds",10,l):m<20?s.formatDistance("lessThanXSeconds",20,l):m<40?s.formatDistance("halfAMinute",0,l):m<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 h=Math.round(p/60);return s.formatDistance("aboutXHours",h,l)}else{if(p<o)return s.formatDistance("xDays",1,l);if(p<jr){const h=Math.round(p/ba);return s.formatDistance("xDays",h,l)}else if(p<jr*2)return y=Math.round(p/jr),s.formatDistance("aboutXMonths",y,l)}if(y=Oh(d,c),y<12){const h=Math.round(p/jr);return s.formatDistance("xMonths",h,l)}else{const h=y%12,x=Math.trunc(y/12);return h<3?s.formatDistance("aboutXYears",x,l):h<9?s.formatDistance("overXYears",x,l):s.formatDistance("almostXYears",x+1,l)}}function Rm(r,e){return Om(r,jh(r),e)}function Ne(...r){return gh(Lf(r))}function $m(){return wh()}function ql(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 Lm(r){if(!r)return"时间未知";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"时间未知":Rm(e,{addSuffix:!0})}function Dm(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 Fm(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 Um(r,e){return r.length<=e?r:r.slice(0,e)+"..."}function Bm(r){return r.replace(/<[^>]*>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').trim()}function Wm(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function Hm(r){try{return new URL(r),!0}catch{return!1}}function ms(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=>ms(e));if(typeof r=="object"){const e={};for(const t in r)r.hasOwnProperty(t)&&(e[t]=ms(r[t]));return e}return r}function qm(r,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function zm(r,e){let t;return(...n)=>{t||(r(...n),t=!0,setTimeout(()=>t=!1,e))}}function zl(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 Jl(r){return r.slice((r.lastIndexOf(".")-1>>>0)+2)}function Jm(r){const e=["jpg","jpeg","png","gif","bmp","webp","svg"],t=Jl(r).toLowerCase();return e.includes(t)}function Vm(){const r=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6366f1"];return r[Math.floor(Math.random()*r.length)]}async function Gm(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){return console.error("Failed to copy text to clipboard:",e),!1}}function Xm(r,e,t="text/plain"){const n=new Blob([r],{type:t}),s=URL.createObjectURL(n),o=document.createElement("a");o.href=s,o.download=e,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(s)}function Km(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Ym(){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 Qm extends Error{constructor(t,n="UNKNOWN_ERROR",s=500){super(t);W(this,"code");W(this,"statusCode");this.name="AppError",this.code=n,this.statusCode=s}}async function Zm(r,e=3,t=1e3){let n;for(let s=1;s<=e;s++)try{return await r()}catch(o){if(n=o,s===e)break;await new Promise(i=>setTimeout(i,t*s))}throw n}const eg={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)}}},Vl=({attachment:r,customRenderer:e,className:t})=>{if(e)return a.jsx("div",{children:e(r)});const n=r.type==="image",s=r.type==="audio",o=()=>n?a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}):s?a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3"})}):a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})});return a.jsxs("div",{className:Ne("inline-flex items-center gap-2 p-2 bg-muted rounded-lg border max-w-sm",t),children:[a.jsx("div",{className:"flex-shrink-0 text-muted-foreground",children:o()}),a.jsxs("div",{className:"flex-1 min-w-0",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("span",{className:"text-sm font-medium truncate",children:r.name}),a.jsx("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:zl(r.size)})]}),r.mimeType&&a.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:r.mimeType})]}),a.jsx("div",{className:"flex-shrink-0",children:n?a.jsx("button",{onClick:()=>window.open(r.url,"_blank"),className:"p-1 hover:bg-background rounded transition-colors",title:"View image",children:a.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]})}):a.jsx("a",{href:r.url,download:r.name,className:"p-1 hover:bg-background rounded transition-colors inline-block",title:"Download file",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})})}),n&&a.jsx("div",{className:"w-full mt-2",children:a.jsx("img",{src:r.url,alt:r.name,className:"max-w-full h-auto rounded border",style:{maxHeight:"200px"},loading:"lazy"})}),s&&a.jsx("div",{className:"w-full mt-2",children:a.jsxs("audio",{controls:!0,className:"w-full",preload:"metadata",children:[a.jsx("source",{src:r.url,type:r.mimeType}),"Your browser does not support the audio element."]})})]})},gs=({toolCall:r,allMessages:e=[],className:t})=>{const[n,s]=I.useState(!1);console.log("🔍 ToolCallRenderer - 开始查找工具结果消息"),console.log("🔍 当前工具调用ID:",r.id),console.log("🔍 所有消息数量:",e.length),console.log("🔍 所有消息:",e.map(v=>{var C;return{id:v.id,role:v.role,tool_call_id:v.tool_call_id||v.toolCallId,metadata:v.metadata,content:((C=v.content)==null?void 0:C.substring(0,100))+"..."}}));const o=e.find(v=>{var T,N;if(v.role!=="tool")return!1;const C=v.tool_call_id||v.toolCallId,_=((T=v.metadata)==null?void 0:T.tool_call_id)||((N=v.metadata)==null?void 0:N.toolCallId);return C===r.id||_===r.id});console.log("🔍 找到的工具结果消息:",o),console.log("🎨 ToolCallRenderer - 工具调用:",r.id,"结果:",r.result,"工具消息:",o==null?void 0:o.content);const i=r.result||(o==null?void 0:o.content),l=!!r.error,c=!!i,m=(()=>{if(!r.arguments)return{};if(typeof r.arguments=="object")return r.arguments;if(typeof r.arguments=="string")try{return JSON.parse(r.arguments)}catch(v){return console.warn("Failed to parse tool arguments:",r.arguments,v),{}}return{}})(),f=m&&Object.keys(m).length>0,p=(v,C="")=>{const _={};for(const T in v)if(v.hasOwnProperty(T)){const N=v[T],P=C?`${C}.${T}`:T;N!==null&&typeof N=="object"&&!Array.isArray(N)?Object.assign(_,p(N,P)):_[P]=N}return _},h=(()=>{if(!f)return"";const v=p(m),C=Object.keys(v);let _=`| 参数 | 值 |
114
+ </div>`}),x=x.replace(/`([^`\n]+)`/g,"<code>$1</code>"),e){const S=/```(\w+)?\n?([\s\S]*?)$/,_=x.match(S);if(_&&!_[0].includes("```",3)){const[,j,v]=_,I=j||"text",M=u(v);x=x.replace(S,`<div class="code-block streaming-code">
115
+ <div class="code-header">${I} <span class="streaming-indicator">● 正在输入...</span></div>
116
+ <pre><code>${M}</code></pre>
117
+ </div>`)}}x=x.replace(/^### (.*$)/gm,"<h3>$1</h3>"),x=x.replace(/^## (.*$)/gm,"<h2>$1</h2>"),x=x.replace(/^# (.*$)/gm,"<h1>$1</h1>"),x=x.replace(/^\* (.*$)/gm,"<li>• $1</li>"),x=x.replace(/^\d+\. (.*$)/gm,"<li>$1</li>"),x=x.replace(/\*\*(.*?)\*\*/g,"<strong>$1</strong>"),x=x.replace(/\*(.*?)\*/g,"<em>$1</em>"),x=x.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" target="_blank" rel="noopener noreferrer">$1</a>'),x=x.replace(/^> (.*$)/gm,"<blockquote>$1</blockquote>"),x=x.replace(/^---$/gm,"<hr>");const y=[];let b=0;return x=x.replace(/<[^>]+>[\s\S]*?<\/[^>]+>/g,S=>{const _=`__PROTECTED_HTML_${b++}__`;return y.push(S),_}),x=x.replace(/<[^>]+>/g,S=>{const _=`__PROTECTED_HTML_${b++}__`;return y.push(S),_}),x=x.replace(/\n\n/g,"</p><p>"),x=x.replace(/\n/g,"<br>"),y.forEach((S,_)=>{x=x.replace(`__PROTECTED_HTML_${_}__`,S)}),x&&!x.startsWith("<")&&(x=`<p>${x}</p>`),x},[e,s,n]),u=(h,x)=>h.replace(/</g,"&lt;").replace(/>/g,"&gt;"),g=T.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 sc(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=sc(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function $h(){for(var r,e,t=0,n="",s=arguments.length;t<s;t++)(r=arguments[t])&&(e=sc(r))&&(n&&(n+=" "),n+=e);return n}const xo="-",Dh=r=>{const e=Uh(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:i=>{const l=i.split(xo);return l[0]===""&&l.length!==1&&l.shift(),oc(l,e)||Fh(i)},getConflictingClassGroupIds:(i,l)=>{const d=t[i]||[];return l&&n[i]?[...d,...n[i]]:d}}},oc=(r,e)=>{var i;if(r.length===0)return e.classGroupId;const t=r[0],n=e.nextPart.get(t),s=n?oc(r.slice(1),n):void 0;if(s)return s;if(e.validators.length===0)return;const a=r.join(xo);return(i=e.validators.find(({validator:l})=>l(a)))==null?void 0:i.classGroupId},Aa=/^\[(.+)\]$/,Fh=r=>{if(Aa.test(r)){const e=Aa.exec(r)[1],t=e==null?void 0:e.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},Uh=r=>{const{theme:e,prefix:t}=r,n={nextPart:new Map,validators:[]};return Wh(Object.entries(r.classGroups),t).forEach(([a,i])=>{Cs(i,n,a,e)}),n},Cs=(r,e,t,n)=>{r.forEach(s=>{if(typeof s=="string"){const a=s===""?e:Na(e,s);a.classGroupId=t;return}if(typeof s=="function"){if(Bh(s)){Cs(s(n),e,t,n);return}e.validators.push({validator:s,classGroupId:t});return}Object.entries(s).forEach(([a,i])=>{Cs(i,Na(e,a),t,n)})})},Na=(r,e)=>{let t=r;return e.split(xo).forEach(n=>{t.nextPart.has(n)||t.nextPart.set(n,{nextPart:new Map,validators:[]}),t=t.nextPart.get(n)}),t},Bh=r=>r.isThemeGetter,Wh=(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,Hh=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)}}},ac="!",zh=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 p=l[c];if(u===0){if(p===s&&(n||l.slice(c,c+a)===e)){d.push(l.slice(g,c)),g=c+a;continue}if(p==="/"){h=c;continue}}p==="["?u++:p==="]"&&u--}const x=d.length===0?l:l.substring(g),w=x.startsWith(ac),m=w?x.substring(1):x,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},qh=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},Jh=r=>({cache:Hh(r.cacheSize),parseClassName:zh(r),...Dh(r)}),Vh=/\s+/,Xh=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:s}=e,a=[],i=r.trim().split(Vh);let l="";for(let d=i.length-1;d>=0;d-=1){const u=i[d],{modifiers:g,hasImportantModifier:h,baseClassName:x,maybePostfixModifierPosition:w}=t(u);let m=!!w,f=n(m?x.substring(0,w):x);if(!f){if(!m){l=u+(l.length>0?" "+l:l);continue}if(f=n(x),!f){l=u+(l.length>0?" "+l:l);continue}m=!1}const c=qh(g).join(":"),p=h?c+ac:c,y=p+f;if(a.includes(y))continue;a.push(y);const b=s(f,m);for(let S=0;S<b.length;++S){const _=b[S];a.push(p+_)}l=u+(l.length>0?" "+l:l)}return l};function Gh(){let r=0,e,t,n="";for(;r<arguments.length;)(e=arguments[r++])&&(t=ic(e))&&(n&&(n+=" "),n+=t);return n}const ic=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=ic(r[n]))&&(t&&(t+=" "),t+=e);return t};function Yh(r,...e){let t,n,s,a=i;function i(d){const u=e.reduce((g,h)=>h(g),r());return t=Jh(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=Xh(d,t);return s(d,g),g}return function(){return a(Gh.apply(null,arguments))}}const he=r=>{const e=t=>t[r]||[];return e.isThemeGetter=!0,e},lc=/^\[(?:([a-z-]+):)?(.+)\]$/i,Kh=/^\d+\/\d+$/,Qh=new Set(["px","full","screen"]),Zh=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,em=/\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$/,tm=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,rm=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,nm=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Ke=r=>Tt(r)||Qh.has(r)||Kh.test(r),nt=r=>Wt(r,"length",um),Tt=r=>!!r&&!Number.isNaN(Number(r)),Yn=r=>Wt(r,"number",Tt),qt=r=>!!r&&Number.isInteger(Number(r)),sm=r=>r.endsWith("%")&&Tt(r.slice(0,-1)),oe=r=>lc.test(r),st=r=>Zh.test(r),om=new Set(["length","size","percentage"]),am=r=>Wt(r,om,cc),im=r=>Wt(r,"position",cc),lm=new Set(["image","url"]),cm=r=>Wt(r,lm,hm),dm=r=>Wt(r,"",fm),Jt=()=>!0,Wt=(r,e,t)=>{const n=lc.exec(r);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):t(n[2]):!1},um=r=>em.test(r)&&!tm.test(r),cc=()=>!1,fm=r=>rm.test(r),hm=r=>nm.test(r),mm=()=>{const r=he("colors"),e=he("spacing"),t=he("blur"),n=he("brightness"),s=he("borderColor"),a=he("borderRadius"),i=he("borderSpacing"),l=he("borderWidth"),d=he("contrast"),u=he("grayscale"),g=he("hueRotate"),h=he("invert"),x=he("gap"),w=he("gradientColorStops"),m=he("gradientColorStopPositions"),f=he("inset"),c=he("margin"),p=he("opacity"),y=he("padding"),b=he("saturate"),S=he("scale"),_=he("sepia"),j=he("skew"),v=he("space"),I=he("translate"),M=()=>["auto","contain","none"],O=()=>["auto","hidden","clip","visible","scroll"],L=()=>["auto",oe,e],C=()=>[oe,e],H=()=>["",Ke,nt],D=()=>["auto",Tt,oe],V=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],X=()=>["solid","dashed","dotted","double","none"],F=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],Y=()=>["start","end","center","between","around","evenly","stretch"],ae=()=>["","0",oe],W=()=>["auto","avoid","all","avoid-page","page","left","right","column"],J=()=>[Tt,oe];return{cacheSize:500,separator:":",theme:{colors:[Jt],spacing:[Ke,nt],blur:["none","",st,oe],brightness:J(),borderColor:[r],borderRadius:["none","","full",st,oe],borderSpacing:C(),borderWidth:H(),contrast:J(),grayscale:ae(),hueRotate:J(),invert:ae(),gap:C(),gradientColorStops:[r],gradientColorStopPositions:[sm,nt],inset:L(),margin:L(),opacity:J(),padding:C(),saturate:J(),scale:J(),sepia:ae(),skew:J(),space:C(),translate:C()},classGroups:{aspect:[{aspect:["auto","square","video",oe]}],container:["container"],columns:[{columns:[st]}],"break-after":[{"break-after":W()}],"break-before":[{"break-before":W()}],"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:[...V(),oe]}],overflow:[{overflow:O()}],"overflow-x":[{"overflow-x":O()}],"overflow-y":[{"overflow-y":O()}],overscroll:[{overscroll:M()}],"overscroll-x":[{"overscroll-x":M()}],"overscroll-y":[{"overscroll-y":M()}],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",qt,oe]}],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",oe]}],grow:[{grow:ae()}],shrink:[{shrink:ae()}],order:[{order:["first","last","none",qt,oe]}],"grid-cols":[{"grid-cols":[Jt]}],"col-start-end":[{col:["auto",{span:["full",qt,oe]},oe]}],"col-start":[{"col-start":D()}],"col-end":[{"col-end":D()}],"grid-rows":[{"grid-rows":[Jt]}],"row-start-end":[{row:["auto",{span:[qt,oe]},oe]}],"row-start":[{"row-start":D()}],"row-end":[{"row-end":D()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",oe]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",oe]}],gap:[{gap:[x]}],"gap-x":[{"gap-x":[x]}],"gap-y":[{"gap-y":[x]}],"justify-content":[{justify:["normal",...Y()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...Y(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...Y(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[y]}],px:[{px:[y]}],py:[{py:[y]}],ps:[{ps:[y]}],pe:[{pe:[y]}],pt:[{pt:[y]}],pr:[{pr:[y]}],pb:[{pb:[y]}],pl:[{pl:[y]}],m:[{m:[c]}],mx:[{mx:[c]}],my:[{my:[c]}],ms:[{ms:[c]}],me:[{me:[c]}],mt:[{mt:[c]}],mr:[{mr:[c]}],mb:[{mb:[c]}],ml:[{ml:[c]}],"space-x":[{"space-x":[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",oe,e]}],"min-w":[{"min-w":[oe,e,"min","max","fit"]}],"max-w":[{"max-w":[oe,e,"none","full","min","max","fit","prose",{screen:[st]},st]}],h:[{h:[oe,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[oe,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[oe,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[oe,e,"auto","min","max","fit"]}],"font-size":[{text:["base",st,nt]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",Yn]}],"font-family":[{font:[Jt]}],"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",oe]}],"line-clamp":[{"line-clamp":["none",Tt,Yn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Ke,oe]}],"list-image":[{"list-image":["none",oe]}],"list-style-type":[{list:["none","disc","decimal",oe]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[r]}],"placeholder-opacity":[{"placeholder-opacity":[p]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[r]}],"text-opacity":[{"text-opacity":[p]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...X(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Ke,nt]}],"underline-offset":[{"underline-offset":["auto",Ke,oe]}],"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",oe]}],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",oe]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[p]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...V(),im]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",am]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},cm]}],"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":[p]}],"border-style":[{border:[...X(),"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":[p]}],"divide-style":[{divide:X()}],"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:["",...X()]}],"outline-offset":[{"outline-offset":[Ke,oe]}],"outline-w":[{outline:[Ke,nt]}],"outline-color":[{outline:[r]}],"ring-w":[{ring:H()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[r]}],"ring-opacity":[{"ring-opacity":[p]}],"ring-offset-w":[{"ring-offset":[Ke,nt]}],"ring-offset-color":[{"ring-offset":[r]}],shadow:[{shadow:["","inner","none",st,dm]}],"shadow-color":[{shadow:[Jt]}],opacity:[{opacity:[p]}],"mix-blend":[{"mix-blend":[...F(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":F()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[n]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",st,oe]}],grayscale:[{grayscale:[u]}],"hue-rotate":[{"hue-rotate":[g]}],invert:[{invert:[h]}],saturate:[{saturate:[b]}],sepia:[{sepia:[_]}],"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":[p]}],"backdrop-saturate":[{"backdrop-saturate":[b]}],"backdrop-sepia":[{"backdrop-sepia":[_]}],"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",oe]}],duration:[{duration:J()}],ease:[{ease:["linear","in","out","in-out",oe]}],delay:[{delay:J()}],animate:[{animate:["none","spin","ping","pulse","bounce",oe]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[S]}],"scale-x":[{"scale-x":[S]}],"scale-y":[{"scale-y":[S]}],rotate:[{rotate:[qt,oe]}],"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",oe]}],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",oe]}],"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",oe]}],fill:[{fill:[r,"none"]}],"stroke-w":[{stroke:[Ke,nt,Yn]}],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"]}}},gm=Yh(mm);let Rr;const pm=new Uint8Array(16);function xm(){if(!Rr&&(Rr=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!Rr))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Rr(pm)}const Se=[];for(let r=0;r<256;++r)Se.push((r+256).toString(16).slice(1));function ym(r,e=0){return Se[r[e+0]]+Se[r[e+1]]+Se[r[e+2]]+Se[r[e+3]]+"-"+Se[r[e+4]]+Se[r[e+5]]+"-"+Se[r[e+6]]+Se[r[e+7]]+"-"+Se[r[e+8]]+Se[r[e+9]]+"-"+Se[r[e+10]]+Se[r[e+11]]+Se[r[e+12]]+Se[r[e+13]]+Se[r[e+14]]+Se[r[e+15]]}const bm=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),ka={randomUUID:bm};function wm(r,e,t){if(ka.randomUUID&&!r)return ka.randomUUID();r=r||{};const n=r.random||(r.rng||xm)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,ym(n)}const dc=6048e5,vm=864e5,Lr=43200,Ma=1440,Ea=Symbol.for("constructDateFrom");function Ze(r,e){return typeof r=="function"?r(e):r&&typeof r=="object"&&Ea in r?r[Ea](e):r instanceof Date?new r.constructor(e):new Date(e)}function _e(r,e){return Ze(e||r,r)}let _m={};function _r(){return _m}function cr(r,e){var l,d,u,g;const t=_r(),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=_e(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 nn(r,e){return cr(r,{...e,weekStartsOn:1})}function uc(r,e){const t=_e(r,e==null?void 0:e.in),n=t.getFullYear(),s=Ze(t,0);s.setFullYear(n+1,0,4),s.setHours(0,0,0,0);const a=nn(s),i=Ze(t,0);i.setFullYear(n,0,4),i.setHours(0,0,0,0);const l=nn(i);return t.getTime()>=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function sn(r){const e=_e(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 kn(r,...e){const t=Ze.bind(null,r||e.find(n=>typeof n=="object"));return e.map(t)}function Pa(r,e){const t=_e(r,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function Sm(r,e,t){const[n,s]=kn(t==null?void 0:t.in,r,e),a=Pa(n),i=Pa(s),l=+a-sn(a),d=+i-sn(i);return Math.round((l-d)/vm)}function Cm(r,e){const t=uc(r,e),n=Ze(r,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),nn(n)}function Vr(r,e){const t=+_e(r)-+_e(e);return t<0?-1:t>0?1:t}function jm(r){return Ze(r,Date.now())}function Am(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function Nm(r){return!(!Am(r)&&typeof r!="number"||isNaN(+_e(r)))}function km(r,e,t){const[n,s]=kn(t==null?void 0:t.in,r,e),a=n.getFullYear()-s.getFullYear(),i=n.getMonth()-s.getMonth();return a*12+i}function Mm(r){return e=>{const n=(r?Math[r]:Math.trunc)(e);return n===0?0:n}}function Em(r,e){return+_e(r)-+_e(e)}function Pm(r,e){const t=_e(r,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Im(r,e){const t=_e(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 Tm(r,e){const t=_e(r,e==null?void 0:e.in);return+Pm(t,e)==+Im(t,e)}function Om(r,e,t){const[n,s,a]=kn(t==null?void 0:t.in,r,r,e),i=Vr(s,a),l=Math.abs(km(s,a));if(l<1)return 0;s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-i*l);let d=Vr(s,a)===-i;Tm(n)&&l===1&&Vr(n,a)===1&&(d=!1);const u=i*(l-+d);return u===0?0:u}function Rm(r,e,t){const n=Em(r,e)/1e3;return Mm(t==null?void 0:t.roundingMethod)(n)}function Lm(r,e){const t=_e(r,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}const $m={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"}},Dm=(r,e,t)=>{let n;const s=$m[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 Kn(r){return(e={})=>{const t=e.width?String(e.width):r.defaultWidth;return r.formats[t]||r.formats[r.defaultWidth]}}const Fm={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Um={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},Bm={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Wm={date:Kn({formats:Fm,defaultWidth:"full"}),time:Kn({formats:Um,defaultWidth:"full"}),dateTime:Kn({formats:Bm,defaultWidth:"full"})},Hm={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},zm=(r,e,t,n)=>Hm[r];function Vt(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 qm={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},Jm={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},Vm={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"]},Xm={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"]},Gm={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"}},Ym={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"}},Km=(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"},Qm={ordinalNumber:Km,era:Vt({values:qm,defaultWidth:"wide"}),quarter:Vt({values:Jm,defaultWidth:"wide",argumentCallback:r=>r-1}),month:Vt({values:Vm,defaultWidth:"wide"}),day:Vt({values:Xm,defaultWidth:"wide"}),dayPeriod:Vt({values:Gm,defaultWidth:"wide",formattingValues:Ym,defaultFormattingWidth:"wide"})};function Xt(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)?eg(l,h=>h.test(i)):Zm(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 Zm(r,e){for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&e(r[t]))return t}function eg(r,e){for(let t=0;t<r.length;t++)if(e(r[t]))return t}function tg(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 rg=/^(\d+)(th|st|nd|rd)?/i,ng=/\d+/i,sg={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},og={any:[/^b/i,/^(a|c)/i]},ag={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},ig={any:[/1/i,/2/i,/3/i,/4/i]},lg={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},cg={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]},dg={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},ug={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]},fg={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},hg={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}},mg={ordinalNumber:tg({matchPattern:rg,parsePattern:ng,valueCallback:r=>parseInt(r,10)}),era:Xt({matchPatterns:sg,defaultMatchWidth:"wide",parsePatterns:og,defaultParseWidth:"any"}),quarter:Xt({matchPatterns:ag,defaultMatchWidth:"wide",parsePatterns:ig,defaultParseWidth:"any",valueCallback:r=>r+1}),month:Xt({matchPatterns:lg,defaultMatchWidth:"wide",parsePatterns:cg,defaultParseWidth:"any"}),day:Xt({matchPatterns:dg,defaultMatchWidth:"wide",parsePatterns:ug,defaultParseWidth:"any"}),dayPeriod:Xt({matchPatterns:fg,defaultMatchWidth:"any",parsePatterns:hg,defaultParseWidth:"any"})},fc={code:"en-US",formatDistance:Dm,formatLong:Wm,formatRelative:zm,localize:Qm,match:mg,options:{weekStartsOn:0,firstWeekContainsDate:1}};function gg(r,e){const t=_e(r,e==null?void 0:e.in);return Sm(t,Lm(t))+1}function pg(r,e){const t=_e(r,e==null?void 0:e.in),n=+nn(t)-+Cm(t);return Math.round(n/dc)+1}function hc(r,e){var g,h,x,w;const t=_e(r,e==null?void 0:e.in),n=t.getFullYear(),s=_r(),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=(x=s.locale)==null?void 0:x.options)==null?void 0:w.firstWeekContainsDate)??1,i=Ze((e==null?void 0:e.in)||r,0);i.setFullYear(n+1,0,a),i.setHours(0,0,0,0);const l=cr(i,e),d=Ze((e==null?void 0:e.in)||r,0);d.setFullYear(n,0,a),d.setHours(0,0,0,0);const u=cr(d,e);return+t>=+l?n+1:+t>=+u?n:n-1}function xg(r,e){var l,d,u,g;const t=_r(),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=hc(r,e),a=Ze((e==null?void 0:e.in)||r,0);return a.setFullYear(s,0,n),a.setHours(0,0,0,0),cr(a,e)}function yg(r,e){const t=_e(r,e==null?void 0:e.in),n=+cr(t,e)-+xg(t,e);return Math.round(n/dc)+1}function de(r,e){const t=r<0?"-":"",n=Math.abs(r).toString().padStart(e,"0");return t+n}const ot={y(r,e){const t=r.getFullYear(),n=t>0?t:1-t;return de(e==="yy"?n%100:n,e.length)},M(r,e){const t=r.getMonth();return e==="M"?String(t+1):de(t+1,2)},d(r,e){return de(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 de(r.getHours()%12||12,e.length)},H(r,e){return de(r.getHours(),e.length)},m(r,e){return de(r.getMinutes(),e.length)},s(r,e){return de(r.getSeconds(),e.length)},S(r,e){const t=e.length,n=r.getMilliseconds(),s=Math.trunc(n*Math.pow(10,t-3));return de(s,e.length)}},Nt={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ia={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 ot.y(r,e)},Y:function(r,e,t,n){const s=hc(r,n),a=s>0?s:1-s;if(e==="YY"){const i=a%100;return de(i,2)}return e==="Yo"?t.ordinalNumber(a,{unit:"year"}):de(a,e.length)},R:function(r,e){const t=uc(r);return de(t,e.length)},u:function(r,e){const t=r.getFullYear();return de(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 de(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 de(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 ot.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 de(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=yg(r,n);return e==="wo"?t.ordinalNumber(s,{unit:"week"}):de(s,e.length)},I:function(r,e,t){const n=pg(r);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):de(n,e.length)},d:function(r,e,t){return e==="do"?t.ordinalNumber(r.getDate(),{unit:"date"}):ot.d(r,e)},D:function(r,e,t){const n=gg(r);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):de(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 de(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 de(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 de(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=Nt.noon:n===0?s=Nt.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=Nt.evening:n>=12?s=Nt.afternoon:n>=4?s=Nt.morning:s=Nt.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 ot.h(r,e)},H:function(r,e,t){return e==="Ho"?t.ordinalNumber(r.getHours(),{unit:"hour"}):ot.H(r,e)},K:function(r,e,t){const n=r.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):de(n,e.length)},k:function(r,e,t){let n=r.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):de(n,e.length)},m:function(r,e,t){return e==="mo"?t.ordinalNumber(r.getMinutes(),{unit:"minute"}):ot.m(r,e)},s:function(r,e,t){return e==="so"?t.ordinalNumber(r.getSeconds(),{unit:"second"}):ot.s(r,e)},S:function(r,e){return ot.S(r,e)},X:function(r,e,t){const n=r.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return Oa(n);case"XXXX":case"XX":return ut(n);case"XXXXX":case"XXX":default:return ut(n,":")}},x:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"x":return Oa(n);case"xxxx":case"xx":return ut(n);case"xxxxx":case"xxx":default:return ut(n,":")}},O:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Ta(n,":");case"OOOO":default:return"GMT"+ut(n,":")}},z:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Ta(n,":");case"zzzz":default:return"GMT"+ut(n,":")}},t:function(r,e,t){const n=Math.trunc(+r/1e3);return de(n,e.length)},T:function(r,e,t){return de(+r,e.length)}};function Ta(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+de(a,2)}function Oa(r,e){return r%60===0?(r>0?"-":"+")+de(Math.abs(r)/60,2):ut(r,e)}function ut(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=de(Math.trunc(n/60),2),a=de(n%60,2);return t+s+e+a}const Ra=(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"})}},mc=(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"})}},bg=(r,e)=>{const t=r.match(/(P+)(p+)?/)||[],n=t[1],s=t[2];if(!s)return Ra(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}}",Ra(n,e)).replace("{{time}}",mc(s,e))},wg={p:mc,P:bg},vg=/^D+$/,_g=/^Y+$/,Sg=["D","DD","YY","YYYY"];function Cg(r){return vg.test(r)}function jg(r){return _g.test(r)}function Ag(r,e,t){const n=Ng(r,e,t);if(console.warn(n),Sg.includes(r))throw new RangeError(n)}function Ng(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 kg=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Mg=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Eg=/^'([^]*?)'?$/,Pg=/''/g,Ig=/[a-zA-Z]/;function yo(r,e,t){var g,h,x,w;const n=_r(),s=n.locale??fc,a=n.firstWeekContainsDate??((h=(g=n.locale)==null?void 0:g.options)==null?void 0:h.firstWeekContainsDate)??1,i=n.weekStartsOn??((w=(x=n.locale)==null?void 0:x.options)==null?void 0:w.weekStartsOn)??0,l=_e(r,t==null?void 0:t.in);if(!Nm(l))throw new RangeError("Invalid time value");let d=e.match(Mg).map(m=>{const f=m[0];if(f==="p"||f==="P"){const c=wg[f];return c(m,s.formatLong)}return m}).join("").match(kg).map(m=>{if(m==="''")return{isToken:!1,value:"'"};const f=m[0];if(f==="'")return{isToken:!1,value:Tg(m)};if(Ia[f])return{isToken:!0,value:m};if(f.match(Ig))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;(jg(f)||Cg(f))&&Ag(f,e,String(r));const c=Ia[f[0]];return c(l,f,s.localize,u)}).join("")}function Tg(r){const e=r.match(Eg);return e?e[1].replace(Pg,"'"):r}function Og(r,e,t){const n=_r(),s=(t==null?void 0:t.locale)??n.locale??fc,a=2520,i=Vr(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]=kn(t==null?void 0:t.in,...i>0?[e,r]:[r,e]),g=Rm(u,d),h=(sn(u)-sn(d))/1e3,x=Math.round((g-h)/60);let w;if(x<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):x===0?s.formatDistance("lessThanXMinutes",1,l):s.formatDistance("xMinutes",x,l);if(x<45)return s.formatDistance("xMinutes",x,l);if(x<90)return s.formatDistance("aboutXHours",1,l);if(x<Ma){const m=Math.round(x/60);return s.formatDistance("aboutXHours",m,l)}else{if(x<a)return s.formatDistance("xDays",1,l);if(x<Lr){const m=Math.round(x/Ma);return s.formatDistance("xDays",m,l)}else if(x<Lr*2)return w=Math.round(x/Lr),s.formatDistance("aboutXMonths",w,l)}if(w=Om(u,d),w<12){const m=Math.round(x/Lr);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 Rg(r,e){return Og(r,jm(r),e)}function Ee(...r){return gm($h(r))}function Lg(){return wm()}function gc(r){if(!r)return"--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"--:--":yo(e,"HH:mm")}function $g(r){if(!r)return"时间未知";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"时间未知":Rg(e,{addSuffix:!0})}function Dg(r){if(!r)return"----/--/--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/--":yo(e,"yyyy-MM-dd")}function Fg(r){if(!r)return"----/--/-- --:--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/-- --:--:--":yo(e,"yyyy-MM-dd HH:mm:ss")}function Ug(r,e){return r.length<=e?r:r.slice(0,e)+"..."}function Bg(r){return r.replace(/<[^>]*>/g,"").replace(/&nbsp;/g," ").replace(/&amp;/g,"&").replace(/&lt;/g,"<").replace(/&gt;/g,">").replace(/&quot;/g,'"').trim()}function Wg(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function Hg(r){try{return new URL(r),!0}catch{return!1}}function js(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=>js(e));if(typeof r=="object"){const e={};for(const t in r)r.hasOwnProperty(t)&&(e[t]=js(r[t]));return e}return r}function zg(r,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function qg(r,e){let t;return(...n)=>{t||(r(...n),t=!0,setTimeout(()=>t=!1,e))}}function pc(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 xc(r){return r.slice((r.lastIndexOf(".")-1>>>0)+2)}function Jg(r){const e=["jpg","jpeg","png","gif","bmp","webp","svg"],t=xc(r).toLowerCase();return e.includes(t)}function Vg(){const r=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6366f1"];return r[Math.floor(Math.random()*r.length)]}async function Xg(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){return console.error("Failed to copy text to clipboard:",e),!1}}function Gg(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 Yg(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Kg(){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 Qg extends Error{constructor(t,n="UNKNOWN_ERROR",s=500){super(t);q(this,"code");q(this,"statusCode");this.name="AppError",this.code=n,this.statusCode=s}}async function Zg(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 ep={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)}}},yc=({attachment:r,isUser:e=!1,customRenderer:t,className:n})=>{if(t)return o.jsx("div",{children:t(r)});const s=r.type==="image",a=r.type==="audio",i=()=>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:"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"})}):a?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:Ee("p-2 bg-muted rounded-lg border max-w-sm",n),children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx("div",{className:"flex-shrink-0 text-muted-foreground",children:i()}),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:pc(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:s?o.jsx("button",{onClick:()=>r.url&&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"})]})}):!e&&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"})})})})]}),s&&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 object-contain",style:{maxHeight:"200px"},loading:"lazy"})}),a&&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."]})})]})},As=({toolCall:r,allMessages:e=[],className:t})=>{const[n,s]=T.useState(!1);console.log("🔍 ToolCallRenderer - 开始查找工具结果消息"),console.log("🔍 当前工具调用ID:",r.id),console.log("🔍 所有消息数量:",e.length),console.log("🔍 所有消息:",e.map(_=>{var j;return{id:_.id,role:_.role,tool_call_id:_.tool_call_id||_.toolCallId,metadata:_.metadata,content:((j=_.content)==null?void 0:j.substring(0,100))+"..."}}));const a=e.find(_=>{var I,M;if(_.role!=="tool")return!1;const j=_.tool_call_id||_.toolCallId,v=((I=_.metadata)==null?void 0:I.tool_call_id)||((M=_.metadata)==null?void 0:M.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(_){return console.warn("Failed to parse tool arguments:",r.arguments,_),{}}return{}})(),h=g&&Object.keys(g).length>0,x=(_,j="")=>{const v={};for(const I in _)if(_.hasOwnProperty(I)){const M=_[I],O=j?`${j}.${I}`:I;M!==null&&typeof M=="object"&&!Array.isArray(M)?Object.assign(v,x(M,O)):v[O]=M}return v},m=(()=>{if(!h)return"";const _=x(g),j=Object.keys(_);let v=`| 参数 | 值 |
97
118
  |------|------|
98
- `;return C.forEach(T=>{const N=v[T];let P;typeof N=="string"?P=N.replace(/\n/g,"<br>").replace(/\|/g,"\\|"):Array.isArray(N)?P=`[${N.join(", ")}]`.replace(/\|/g,"\\|"):P=JSON.stringify(N).replace(/\|/g,"\\|"),_+=`| ${T} | ${P} |
99
- `}),_})(),u=(()=>{if(!c)return null;if(i&&typeof i=="object")return i;if(typeof i=="string")try{const v=JSON.parse(i);if(v&&typeof v=="object")return v}catch{return null}return null})(),g=!!(u&&typeof u=="object"),b=v=>{if(v===null)return"null";if(Array.isArray(v)){if(v.length===0)return"array []";const C=v[0],_=b(C);return _==="object"?"object []":`${_}[]`}switch(typeof v){case"string":return"string";case"number":return Number.isInteger(v)?"integer":"number";case"boolean":return"boolean";case"object":return"object";default:return typeof v}},w=(v,C="",_="")=>{const T=[];if(v==null)return T;if(Array.isArray(v)){const N={path:_||C||"list",name:C||"list",type:b(v),value:v,children:v.map((P,R)=>{const j=`${_||C||"list"}[${R}]`,F=b(P);return{path:j,name:`[${R}]`,type:F,value:P,children:F==="object"||Array.isArray(P)?w(P,`[${R}]`,j):[]}})};return T.push(N),T}return typeof v=="object"&&Object.keys(v).forEach(N=>{const P=v[N],R=_?`${_}.${N}`:N,j=b(P),F=j==="object"||Array.isArray(P)?w(P,N,R):[];T.push({path:R,name:N,type:j,value:P,children:F})}),T},S=({data:v})=>{const C=Array.isArray(v)?w(v,"list","list"):w(v,"",""),[_,T]=I.useState(()=>new Set(C.filter(j=>j.children.length>0).map(j=>j.path))),N=j=>{T(F=>{const O=new Set(F);return O.has(j)?O.delete(j):O.add(j),O})},P=j=>{if(j===null)return"null";if(Array.isArray(j))return`数组(${j.length})`;if(typeof j=="object")return"对象";if(typeof j=="string")return j;try{return JSON.stringify(j)}catch{return String(j)}},R=(j,F)=>j.map(O=>{const z=O.children&&O.children.length>0,H=_.has(O.path),E=z?H?"▾":"▸":"",L=P(O.value);return a.jsxs(I.Fragment,{children:[a.jsxs("tr",{children:[a.jsxs("td",{style:{paddingLeft:F*16},children:[z?a.jsx("button",{type:"button",onClick:()=>N(O.path),className:"mr-2 text-gray-600 dark:text-gray-300 hover:text-black dark:hover:text-white","aria-label":H?"收起":"展开",children:E}):a.jsx("span",{className:"mr-4"}),O.name]}),a.jsx("td",{style:{whiteSpace:"normal",wordBreak:"break-word"},children:L})]}),z&&H&&R(O.children,F+1)]},O.path)});return a.jsx("div",{className:"border-l-4 border-green-400 dark:border-green-500 rounded-lg overflow-hidden bg-green-50/50 dark:bg-green-900/20 mb-2",children:a.jsx("div",{className:"markdown-renderer",children:a.jsxs("table",{children:[a.jsx("thead",{children:a.jsxs("tr",{children:[a.jsx("th",{children:"字段"}),a.jsx("th",{children:"值"})]})}),a.jsx("tbody",{children:R(C,0)})]})})})};return a.jsxs("div",{className:"tool-call-renderer tool-call-container",children:[a.jsxs("div",{className:"tool-header",children:[a.jsxs("span",{className:"tool-name",children:["@",r.name]}),l&&a.jsx("span",{className:"status-badge status-error",children:"错误"}),c&&!l&&a.jsx("span",{className:"status-badge status-success",children:"完成"}),!c&&!l&&a.jsx("span",{className:"status-badge status-pending",children:"等待中"}),(f||c||l)&&a.jsx("button",{onClick:()=>s(!n),className:"toggle-button",children:n?"收起详情":"查看详情"})]}),n&&a.jsxs("div",{className:"details-container",children:[f&&a.jsx("div",{children:h&&a.jsx("div",{className:"border-l-4 border-blue-400 dark:border-blue-500 rounded-lg overflow-hidden bg-blue-50/50 dark:bg-blue-900/20 mb-4",children:a.jsx(_t,{content:h})})}),c&&a.jsxs("div",{children:[a.jsx("div",{className:"details-title",children:"结果:"}),g?a.jsx(S,{data:u}):a.jsx(_t,{content:typeof i=="string"?i:JSON.stringify(i)})]}),l&&a.jsxs("div",{children:[a.jsx("div",{className:"details-title",children:"错误:"}),a.jsx("div",{className:"status-badge status-error",style:{display:"block",padding:"0.5rem"},children:r.error})]}),a.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400 border-t border-gray-200 dark:border-gray-700 pt-2",children:["执行时间: ",(()=>{const v=new Date(r.createdAt);return isNaN(v.getTime())?"时间未知":v.toLocaleString()})()]})]})]})},tg=({message:r,isLast:e=!1,isStreaming:t=!1,onEdit:n,onDelete:s,allMessages:o=[],customRenderer:i})=>{var _,T,N,P,R,j,F;console.log("🚀🚀🚀 MessageItem 组件被调用!消息ID:",r.id,"角色:",r.role),console.log("🚀🚀🚀 完整消息对象:",r);const[l,c]=I.useState(!1),[d,m]=I.useState(r.content),f=(O,z)=>{navigator.clipboard.writeText(O).then(()=>{console.log("代码已复制到剪贴板:",{code:O,language:z})}).catch(H=>{console.error("复制失败:",H)})},[p,y]=I.useState(!1),h=r.role==="user",x=r.role==="assistant",u=r.role==="system",g=r.role==="tool";if(g)return null;if(i!=null&&i.renderMessage)return a.jsx("div",{children:i.renderMessage(r)});const b=()=>{n&&d.trim()!==r.content&&n(r.id,d.trim()),c(!1)},w=()=>{m(r.content),c(!1)},S=async()=>{try{await navigator.clipboard.writeText(r.content)}catch(O){console.error("Failed to copy message:",O)}},v=((_=r.metadata)==null?void 0:_.attachments)||[],C=r.toolCalls||((T=r.metadata)==null?void 0:T.toolCalls)||[];return console.log("🔧 工具调用数据:",{顶层toolCalls:r.toolCalls,"metadata.toolCalls":(N=r.metadata)==null?void 0:N.toolCalls,最终toolCalls长度:C.length,消息ID:r.id,contentSegments:(P=r.metadata)==null?void 0:P.contentSegments,contentSegments长度:((j=(R=r.metadata)==null?void 0:R.contentSegments)==null?void 0:j.length)||0}),a.jsxs("div",{className:Ne("group relative rounded-lg transition-colors",!x&&"flex gap-3 px-4 py-4",x&&"px-4 py-2",h&&"bg-user-message",u&&"bg-muted border-l-4 border-primary",g&&"bg-blue-50 dark:bg-blue-950/20 border-l-4 border-blue-500","hover:bg-opacity-80"),onMouseEnter:()=>y(!0),onMouseLeave:()=>y(!1),children:[!x&&a.jsx("div",{className:"flex-shrink-0",children:a.jsx("div",{className:Ne("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium",h&&"bg-primary text-primary-foreground",u&&"bg-muted text-muted-foreground",g&&"bg-blue-500 text-white"),children:h?"U":g?"T":"S"})}),a.jsxs("div",{className:"flex-1 min-w-0",children:[!x&&a.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[a.jsx("span",{className:"text-sm font-medium",children:h?"You":g?"Tool Result":"System"}),a.jsx("span",{className:"text-xs text-muted-foreground",children:ql(r.createdAt)}),((F=r.metadata)==null?void 0:F.model)&&a.jsx("span",{className:"text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded",children:r.metadata.model})]}),v.length>0&&a.jsx("div",{className:"mb-3 space-y-2",children:v.map(O=>a.jsx(Vl,{attachment:O,customRenderer:i==null?void 0:i.renderAttachment},O.id))}),l?a.jsxs("div",{className:"space-y-2",children:[a.jsx("textarea",{value:d,onChange:O=>m(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}),a.jsxs("div",{className:"flex gap-2",children:[a.jsx("button",{onClick:b,className:"px-3 py-1 text-sm bg-primary text-primary-foreground rounded hover:bg-primary/90",children:"Save"}),a.jsx("button",{onClick:w,className:"px-3 py-1 text-sm bg-muted text-muted-foreground rounded hover:bg-muted/80",children:"Cancel"})]})]}):a.jsx("div",{className:"space-y-3",children:(()=>{var E;const O=((E=r.metadata)==null?void 0:E.contentSegments)||[],z=r.content&&r.content.trim().length>0,H=t&&e;return O.length>0?(console.log("🎨 使用分段渲染,分段数量:",O.length),console.log("🎨 分段详情:",O),a.jsx("div",{className:"space-y-0.5",children:O.map((L,U)=>{if(console.log(`🎨 渲染分段 ${U}:`,L),L.type==="text")return console.log(`🎨 渲染文本分段 ${U}:`,L.content),a.jsx("div",{className:"prose prose-sm max-w-none",children:a.jsx(_t,{content:L.content,isStreaming:H&&U===O.length-1,onApplyCode:f})},`segment-${U}`);if(L.type==="tool_call"){console.log(`🎨 渲染工具调用分段 ${U}:`,L);const $=C.find(D=>D.id===L.toolCallId);if(console.log(`🎨 查找工具调用 ${L.toolCallId}:`,$),$)return console.log("🎨 找到工具调用,开始渲染:",$),a.jsx("div",{children:a.jsx(gs,{toolCall:$,allMessages:o})},`tool-${$.id}`);console.log(`🎨 ❌ 未找到工具调用 ${L.toolCallId}`)}else if(L.type==="thinking")return console.log(`🎨 渲染思考分段 ${U}:`,L.content),a.jsxs("details",{className:"group border border-gray-200 dark:border-gray-700 rounded-md bg-muted px-3 py-2",children:[a.jsx("summary",{className:"cursor-pointer text-xs text-gray-500 dark:text-gray-400 select-none",children:"思考过程"}),a.jsx("div",{className:"mt-1",children:a.jsx(_t,{content:L.content||"",isStreaming:H&&U===O.length-1,onApplyCode:f,className:"thinking not-prose"})})]},`thinking-${U}`);return null})})):(console.log("🎨 使用传统渲染方式"),console.log("🎨 hasContent:",z),console.log("🎨 toolCalls.length:",C.length),a.jsxs("div",{className:"space-y-0.5",children:[z&&a.jsx("div",{className:"prose prose-sm max-w-none",children:a.jsx(_t,{content:r.content,isStreaming:H,onApplyCode:f})}),C.length>0&&a.jsxs("div",{className:"space-y-0.5",children:[a.jsx("div",{className:"text-sm text-muted-foreground font-medium",children:"工具调用:"}),C.map(L=>(console.log("🎨 传统方式渲染工具调用:",L),a.jsx("div",{children:a.jsx(gs,{toolCall:L,allMessages:o})},`tool-${L.id}`)))]})]}))})()}),r.tokensUsed&&a.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Tokens used: ",r.tokensUsed]})]}),p&&!l&&a.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 bg-background border rounded-md shadow-sm opacity-0 group-hover:opacity-100 transition-opacity",children:[a.jsx("button",{onClick:S,className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Copy message",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}),h&&n&&a.jsx("button",{onClick:()=>c(!0),className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Edit message",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}),s&&a.jsx("button",{onClick:()=>s(r.id),className:"p-1.5 hover:bg-destructive/10 rounded text-muted-foreground hover:text-destructive transition-colors",title:"Delete message",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})})]})]})},Gl=I.memo(tg,(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)),Xl=({size:r="md",className:e})=>{const t={sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"};return a.jsx("div",{className:Ne("animate-spin rounded-full border-2 border-current border-t-transparent",t[r],e),role:"status","aria-label":"Loading",children:a.jsx("span",{className:"sr-only",children:"Loading..."})})},io=({messages:r,isLoading:e=!1,isStreaming:t=!1,hasMore:n=!1,onLoadMore:s,onMessageEdit:o,onMessageDelete:i,customRenderer:l})=>{const c=I.useRef(null),d=I.useRef(null),[m,f]=I.useState(!0),[p,y]=I.useState(!0),h=()=>{const b=c.current;return b?b.scrollHeight-b.scrollTop-b.clientHeight<=40:!0},x=(b=!0)=>{var w;(w=d.current)==null||w.scrollIntoView({behavior:b?"smooth":"auto"})};I.useEffect(()=>{t&&m&&x(!0)},[r,t,m]),I.useEffect(()=>{y(h())},[r,t]),I.useEffect(()=>{t&&p&&f(!0),t||f(!1)},[t,p]);const u=()=>{const b=h();y(b),b||f(!1)},g=()=>{x(!0),f(!0)};return r.length===0&&!e?a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 mx-auto bg-muted rounded-full flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Start a conversation"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Send a message to begin your chat with AI"})]})]})}):a.jsxs("div",{className:"flex flex-col h-full relative",children:[a.jsxs("div",{ref:c,onScroll:u,className:"flex-1 overflow-y-auto px-4 py-6 space-y-1",style:{willChange:"scroll-position",transform:"translateZ(0)"},children:[n&&a.jsx("div",{className:"flex justify-center mb-2",children:a.jsx("button",{type:"button",onClick:s,className:"text-sm px-3 py-1 rounded border border-border text-foreground hover:bg-accent",children:"加载更多"})}),r.map((b,w)=>a.jsx(Gl,{message:b,isLast:w===r.length-1,isStreaming:t&&w===r.length-1,onEdit:o,onDelete:i,allMessages:r,customRenderer:l},b.id)),e&&a.jsx("div",{className:"flex justify-start",children:a.jsxs("div",{className:"flex items-center space-x-2 bg-muted px-4 py-3 rounded-lg max-w-xs",children:[a.jsx(Xl,{size:"sm"}),a.jsx("span",{className:"text-sm text-muted-foreground",children:"AI is thinking..."})]})}),a.jsx("div",{ref:d})]}),!p&&a.jsxs("button",{type:"button","aria-label":"回到底部",title:"回到底部",onClick:g,className:"absolute bottom-4 right-4 z-10 flex items-center gap-2 rounded-full bg-primary text-primary-foreground px-4 py-2 shadow-md hover:bg-primary/90",children:[a.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[a.jsx("path",{d:"M12 5v12"}),a.jsx("path",{d:"M19 12l-7 7-7-7"})]}),a.jsx("span",{className:"text-sm",children:"回到底部"})]})]})},lo=({onSend:r,onStop:e,disabled:t=!1,isStreaming:n=!1,placeholder:s="Type your message...",maxLength:o=4e3,allowAttachments:i=!1,supportedFileTypes:l=["image/*","text/*","application/pdf"],showModelSelector:c=!1,selectedModelId:d=null,availableModels:m=[],onModelChange:f,selectedAgentId:p=null,availableAgents:y=[],onAgentChange:h})=>{const[x,u]=I.useState(""),[g,b]=I.useState([]),[w,S]=I.useState(!1),v=I.useRef(null),C=I.useRef(null);I.useEffect(()=>{console.log("InputArea - isStreaming 状态变化:",{isStreaming:n,disabled:t,onStop:!!e,timestamp:new Date().toISOString()})},[n,t,e]);const _=I.useCallback(()=>{const E=v.current;if(E){E.style.height="auto";const L=E.scrollHeight,U=200;E.style.height=`${Math.min(L,U)}px`}},[]),T=E=>{const L=E.target.value;L.length<=o&&(u(L),_())},N=E=>{E.key==="Enter"&&!E.shiftKey&&(E.preventDefault(),P())},P=()=>{const E=x.trim();if(!(!E&&g.length===0)&&!t){if(c&&!d&&!p){alert("请先选择一个模型或智能体");return}r(E,g),u(""),b([]),v.current&&(v.current.style.height="auto")}},R=E=>{const L=Array.from(E.target.files||[]);b(U=>[...U,...L]),C.current&&(C.current.value="")},j=E=>{b(L=>L.filter((U,$)=>$!==E))},F=E=>{E.preventDefault(),i&&!t&&S(!0)},O=E=>{E.preventDefault(),S(!1)},z=E=>{if(E.preventDefault(),S(!1),!i||t)return;const L=Array.from(E.dataTransfer.files);b(U=>[...U,...L])},H=E=>{if(E===0)return"0 Bytes";const L=1024,U=["Bytes","KB","MB","GB"],$=Math.floor(Math.log(E)/Math.log(L));return parseFloat((E/Math.pow(L,$)).toFixed(2))+" "+U[$]};return a.jsxs("div",{className:"border-t bg-background p-4",children:[c&&a.jsx("div",{className:"mb-3",children:m.length>0||y.length>0?a.jsxs("select",{value:p?`agent:${p}`:d||"",onChange:E=>{const L=E.target.value;if(L.startsWith("agent:")){const U=L.replace("agent:","");h==null||h(U),f==null||f(null)}else f==null||f(L||null),h==null||h(null)},disabled:t,className:Ne("w-80 max-w-full px-3 py-2 border border-input bg-background rounded-md","text-sm text-foreground placeholder:text-muted-foreground","focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent","disabled:opacity-50 disabled:cursor-not-allowed"),children:[a.jsx("option",{value:"",children:"请选择模型或智能体..."}),y&&y.filter(E=>E.enabled).length>0&&a.jsx("optgroup",{label:"智能体",children:y.filter(E=>E.enabled).map(E=>a.jsxs("option",{value:`agent:${E.id}`,children:["[Agent] ",E.name]},E.id))}),m&&m.filter(E=>E.enabled).length>0&&a.jsx("optgroup",{label:"模型",children:m.filter(E=>E.enabled).map(E=>a.jsxs("option",{value:E.id,children:[E.name," (",E.model_name,")"]},E.id))})]}):a.jsx("div",{className:"w-80 max-w-full px-3 py-2 border border-input bg-muted rounded-md text-sm text-muted-foreground",children:"暂无可用模型或智能体,请先在右上角配置"})}),g.length>0&&a.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:g.map((E,L)=>a.jsxs("div",{className:"flex items-center gap-2 bg-muted px-3 py-2 rounded-lg text-sm",children:[a.jsx("svg",{className:"w-4 h-4 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})}),a.jsx("span",{className:"truncate max-w-32",children:E.name}),a.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",H(E.size),")"]}),a.jsx("button",{onClick:()=>j(L),className:"text-muted-foreground hover:text-destructive transition-colors",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},L))}),a.jsxs("div",{className:Ne("relative flex items-end gap-2 p-3 border rounded-lg transition-colors","focus-within:border-primary",w&&"border-primary bg-primary/5",t&&"opacity-50 cursor-not-allowed"),onDragOver:F,onDragLeave:O,onDrop:z,children:[i&&a.jsx("button",{onClick:()=>{var E;return(E=C.current)==null?void 0:E.click()},disabled:t,className:"flex-shrink-0 p-2 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Attach files",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}),a.jsx("textarea",{ref:v,value:x,onChange:T,onKeyDown:N,placeholder:s,disabled:t,className:Ne("flex-1 resize-none bg-transparent border-none outline-none","placeholder:text-muted-foreground","disabled:cursor-not-allowed"),rows:1,style:{minHeight:"24px",maxHeight:"200px"}}),a.jsxs("div",{className:"flex-shrink-0 text-xs text-muted-foreground",children:[x.length,"/",o]}),n?a.jsx("button",{onClick:()=>{console.log("停止按钮被点击",{onStop:e,disabled:t}),e&&e()},disabled:!1,className:Ne("flex-shrink-0 p-2 rounded-md transition-colors","bg-red-500 text-white hover:bg-red-600","disabled:opacity-50 disabled:cursor-not-allowed"),title:"停止生成",style:{backgroundColor:"#ef4444",color:"white"},children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 6h12v12H6z"})})}):a.jsx("button",{onClick:P,disabled:t||n||!x.trim()&&g.length===0,className:Ne("flex-shrink-0 p-2 rounded-md transition-colors","disabled:opacity-50 disabled:cursor-not-allowed",(x.trim()||g.length>0)&&!t&&!n?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground"),title:c&&!d?"请先选择AI模型":"Send message",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"})})}),i&&a.jsx("input",{ref:C,type:"file",multiple:!0,accept:l.join(","),onChange:R,className:"hidden"})]}),w&&i&&a.jsx("div",{className:"absolute inset-0 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center",children:a.jsxs("div",{className:"text-center",children:[a.jsx("svg",{className:"w-8 h-8 mx-auto text-primary mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"})}),a.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to attach"})]})})]})},Kl=({className:r="w-5 h-5"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Yl=({className:r="w-5 h-5"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 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"})}),Ql=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"})}),Zl=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"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"})}),rg=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),ng=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),ec=({className:r="w-5 h-5"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})}),sg=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"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"})}),og=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"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"})}),ag=({className:r="w-4 h-4"})=>a.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})}),bn=({isOpen:r,title:e,message:t,confirmText:n="确认",cancelText:s="取消",onConfirm:o,onCancel:i,type:l="danger"})=>{if(!r)return null;const c=()=>{switch(l){case"danger":return"bg-red-600 hover:bg-red-700 text-white";case"warning":return"bg-yellow-600 hover:bg-yellow-700 text-white";default:return"bg-blue-600 hover:bg-blue-700 text-white"}};return a.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4",children:a.jsx("div",{className:"bg-card rounded-lg shadow-lg w-full max-w-sm border border-border animate-breathing-border",children:a.jsxs("div",{className:"p-6",children:[a.jsx("h3",{className:"text-lg font-medium text-foreground mb-2",children:e}),a.jsx("p",{className:"text-muted-foreground text-sm mb-6",children:t}),a.jsxs("div",{className:"flex gap-3",children:[a.jsx("button",{onClick:i,className:"flex-1 px-4 py-2 text-sm border border-border rounded-md hover:bg-accent transition-colors",children:s}),a.jsx("button",{onClick:o,className:`flex-1 px-4 py-2 text-sm rounded-md transition-colors ${c()}`,children:n})]})]})})})},yn=()=>{const[r,e]=I.useState({isOpen:!1,title:"",message:"",confirmText:"确认",cancelText:"取消",type:"danger"}),t=I.useCallback(i=>{e({isOpen:!0,title:i.title,message:i.message,confirmText:i.confirmText||"确认",cancelText:i.cancelText||"取消",type:i.type||"danger",onConfirm:i.onConfirm,onCancel:i.onCancel})},[]),n=I.useCallback(()=>{e(i=>({...i,isOpen:!1}))},[]),s=I.useCallback(()=>{var i;(i=r.onConfirm)==null||i.call(r),n()},[r.onConfirm,n]),o=I.useCallback(()=>{var i;(i=r.onCancel)==null||i.call(r),n()},[r.onCancel,n]);return{dialogState:r,showConfirmDialog:t,hideConfirmDialog:n,handleConfirm:s,handleCancel:o}},ig=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})=>{let n=null;try{n=ut()}catch{}const s=t?t():n;if(!s)throw new Error("SessionList must be used within a ChatStoreProvider or receive a store prop");const{sessions:o,currentSession:i,createSession:l,selectSession:c,deleteSession:d,updateSession:m}=s,[f,p]=I.useState(null),[y,h]=I.useState(""),[x,u]=I.useState(!1),[g,b]=I.useState(!1),{dialogState:w,showConfirmDialog:S,handleConfirm:v,handleCancel:C}=yn();I.useEffect(()=>{if(r)b(!0),requestAnimationFrame(()=>{u(!0)});else{u(!1);const O=setTimeout(()=>{b(!1)},300);return()=>clearTimeout(O)}},[r]);const _=async()=>{try{await l(),e==null||e()}catch(O){console.error("Failed to create session:",O)}},T=async O=>{try{await c(O),e==null||e()}catch(z){console.error("Failed to select session:",z)}},N=async O=>{const z=o.find(H=>H.id===O);S({title:"删除确认",message:`确定要删除会话 "${(z==null?void 0:z.title)||"Untitled"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{try{await d(O)}catch(H){console.error("Failed to delete session:",H)}}})},P=(O,z)=>{p(O),h(z)},R=async()=>{if(f&&y.trim())try{await m(f,{title:y.trim()}),p(null),h("")}catch(O){console.error("Failed to update session:",O)}},j=()=>{p(null),h("")},F=O=>{O.key==="Enter"?R():O.key==="Escape"&&j()};return g?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:`fixed inset-0 bg-black/50 backdrop-blur-sm z-40 transition-opacity duration-300 ${x?"opacity-100":"opacity-0"}`,onClick:e}),a.jsx("div",{className:`fixed left-0 top-0 h-full w-80 sm:w-96 bg-card z-50 transform transition-all duration-300 ease-in-out ${x?"translate-x-0":"-translate-x-full"} shadow-xl breathing-border`,children:a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"会话列表"}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{onClick:_,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"新建会话",children:a.jsx(Kl,{className:"w-5 h-5"})}),e&&a.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto",children:o.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground",children:[a.jsx(ec,{className:"w-12 h-12 mb-4 opacity-50"}),a.jsx("p",{className:"text-sm",children:"还没有会话"}),a.jsx("button",{onClick:_,className:"mt-2 px-4 py-2 text-sm bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"创建第一个会话"})]}):a.jsx("div",{className:"p-2 space-y-1",children:o.map(O=>a.jsxs("div",{className:`group relative flex items-center p-3 rounded-lg cursor-pointer transition-colors ${(i==null?void 0:i.id)===O.id?"bg-accent border border-border":"hover:bg-accent/50"}`,onClick:()=>T(O.id),children:[a.jsx("div",{className:"flex-1 min-w-0",children:f===O.id?a.jsx("input",{type:"text",value:y,onChange:z=>h(z.target.value),onBlur:R,onKeyDown:F,className:"w-full px-2 py-1 text-sm bg-background border border-border rounded focus:outline-none focus:ring-2 focus:ring-ring",autoFocus:!0,onClick:z=>z.stopPropagation()}):a.jsxs(a.Fragment,{children:[a.jsx("h3",{className:"text-sm font-medium text-foreground truncate",children:O.title}),a.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:ig(O.updatedAt)})]})}),f!==O.id&&a.jsxs("div",{className:"relative",children:[a.jsx("button",{className:"p-1 text-muted-foreground hover:text-foreground opacity-0 group-hover:opacity-100 transition-opacity",onClick:z=>{z.stopPropagation();const H=z.currentTarget.nextElementSibling;H&&H.classList.toggle("hidden")},children:a.jsx(Yl,{className:"w-4 h-4"})}),a.jsx("div",{className:"hidden absolute right-0 z-10 mt-1 w-32 bg-popover border border-border rounded-md shadow-lg",children:a.jsxs("div",{className:"py-1",children:[a.jsxs("button",{onClick:z=>{z.stopPropagation(),P(O.id,O.title);const H=z.currentTarget.closest(".absolute");H&&H.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-popover-foreground hover:bg-accent",children:[a.jsx(Ql,{className:"w-4 h-4 mr-2"}),"重命名"]}),a.jsxs("button",{onClick:z=>{z.stopPropagation(),N(O.id);const H=z.currentTarget.closest(".absolute");H&&H.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-destructive hover:bg-destructive/10",children:[a.jsx(Zl,{className:"w-4 h-4 mr-2"}),"删除"]})]})})]})]},O.id))})}),a.jsx(bn,{isOpen:w.isOpen,title:w.title,message:w.message,confirmText:w.confirmText,cancelText:w.cancelText,type:w.type,onConfirm:v,onCancel:C})]})})]}):null},tc=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",ja=r=>r==="system"?tc():r,Bn=r=>{if(typeof window>"u")return;const e=window.document.documentElement;e.classList.remove("light","dark"),e.classList.add(r);const t=document.querySelector('meta[name="theme-color"]');t&&t.setAttribute("content",r==="dark"?"#0f172a":"#ffffff")},Aa=()=>typeof window>"u"?"system":localStorage.getItem("theme")||"system",lg=r=>{typeof window>"u"||localStorage.setItem("theme",r)},rc=()=>{const[r,e]=I.useState(()=>Aa()),[t,n]=I.useState(()=>ja(Aa())),s=i=>{e(i),lg(i);const l=ja(i);n(l),Bn(l)},o=()=>{let i;switch(r){case"light":i="dark";break;case"dark":i="system";break;case"system":i="light";break;default:i="system"}s(i)};return I.useEffect(()=>{if(r!=="system")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),l=()=>{const c=tc();n(c),Bn(c)};return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[r]),I.useEffect(()=>{Bn(t)},[t]),{theme:r,actualTheme:t,setTheme:s,toggleTheme:o}},uo=({className:r=""})=>{const{theme:e,toggleTheme:t}=rc(),n=()=>{switch(e){case"light":return a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"})});case"dark":return a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"})});case"system":return a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})});default:return null}},s=()=>{switch(e){case"light":return"Light mode";case"dark":return"Dark mode";case"system":return"System theme";default:return"Toggle theme"}};return a.jsx("button",{onClick:t,className:`p-2 hover:bg-muted rounded-lg transition-colors ${r}`,title:s(),"aria-label":s(),children:n()})},cg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"})}),ka=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),dg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),ug=({open:r,config:e,onClose:t})=>{const[n,s]=I.useState([]),[o,i]=I.useState(!1),[l,c]=I.useState(null),[d,m]=I.useState(null),[f,p]=I.useState(!1),[y,h]=I.useState({name:"",envJson:"",enabled:!1}),[x,u]=I.useState(null),[g,b]=I.useState({});return I.useEffect(()=>{(async()=>{if(!(!r||!(e!=null&&e.id))){i(!0),c(null);try{const S=await re.getMcpConfigProfiles(e.id);s(Array.isArray(S)?S:[])}catch(S){c((S==null?void 0:S.message)||"获取配置档案失败")}finally{i(!1)}}})()},[r,e==null?void 0:e.id]),r?a.jsxs("div",{className:"modal-container",children:[a.jsxs("div",{className:"modal-content w-full max-w-3xl max-h-[85vh] overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(cg,{}),a.jsxs("h3",{className:"text-lg font-semibold text-foreground",children:["配置档案 - ",e==null?void 0:e.name]})]}),a.jsx("button",{onClick:()=>t(),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(ka,{})})]}),a.jsxs("div",{className:"p-4 overflow-y-auto",style:{maxHeight:"calc(85vh - 100px)"},children:[a.jsxs("div",{className:"flex items-center justify-between mb-3",children:[a.jsx("span",{className:"text-sm text-muted-foreground",children:"已保存的配置档案"}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{if(e!=null&&e.id){i(!0);try{const w=await re.getMcpConfigProfiles(e.id);s(Array.isArray(w)?w:[])}finally{i(!1)}}},children:"刷新列表"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:async()=>{if(!(e!=null&&e.id))return;let w;try{const S=await re.getMcpConfigResource(e.id),v=S&&S.config||{};v&&typeof v=="object"&&(w=v)}catch{}h({name:`配置_${new Date().toLocaleString("zh-CN")}`,envJson:"",enabled:!1}),b(w||{}),m(null),p(!0)},children:"新增配置档案"})]})]}),o?a.jsx("div",{className:"text-xs text-muted-foreground",children:"加载中..."}):l?a.jsx("div",{className:"text-xs text-destructive",children:l}):n.length===0?a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案,点击右上角“新增配置档案”。"}):a.jsx("div",{className:"space-y-2",children:n.map(w=>a.jsx("div",{className:"px-2 py-2 border border-border rounded-md",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"text-sm text-foreground font-medium",children:w.name}),w.enabled&&a.jsx("span",{className:"px-2 py-0.5 text-[10px] rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200",children:"已启用"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{if(e!=null&&e.id)try{await re.activateMcpConfigProfile(e.id,w.id);const S=await re.getMcpConfigProfiles(e.id);s(Array.isArray(S)?S:[])}catch{}},children:"激活"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{m(w.id),h({name:w.name||"",envJson:(()=>{try{return JSON.stringify(w.env||{},null,2)}catch{return""}})(),enabled:!!w.enabled});const S=w.env||{},v={};Object.keys(S||{}).forEach(C=>{const _=S[C];if(typeof _=="string"){const T=_.trim();try{v[C]=JSON.parse(T)}catch{T.includes(",")?v[C]=T.split(",").map(N=>N.trim()).filter(Boolean):v[C]=T}}else v[C]=_}),b(v),p(!0)},children:"编辑"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-destructive text-destructive-foreground rounded-md hover:bg-destructive/80",onClick:async()=>{if(!(!(e!=null&&e.id)||!window.confirm(`确定删除配置档案 “${w.name}” 吗?`)))try{await re.deleteMcpConfigProfile(e.id,w.id);const v=await re.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[])}catch(v){console.error("删除配置档案失败:",v)}},children:"删除"})]})]})},w.id))})]})]}),f&&a.jsxs("div",{className:"modal-container z-[100]",children:[a.jsx("div",{className:"fixed inset-0 bg-black/40 backdrop-blur-sm",onClick:()=>{p(!1),u(null)}}),a.jsx("div",{className:"fixed inset-0 flex items-center justify-center p-4",children:a.jsxs("div",{className:"modal-content w-full max-w-2xl transform overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx(dg,{}),a.jsx("h3",{className:"text-base font-semibold text-foreground",children:d?"编辑配置档案":"新增配置档案"})]}),a.jsx("button",{onClick:()=>{p(!1),u(null)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(ka,{})})]}),a.jsxs("div",{className:"p-4",children:[x&&a.jsx("div",{className:"mb-2 text-xs text-destructive",children:x}),a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),a.jsx("input",{type:"text",value:y.name,onChange:w=>h({...y,name:w.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md"})]}),a.jsx("div",{children:g&&Object.keys(g).length>0&&a.jsxs("div",{className:"mb-3",children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"动态参数"}),a.jsx("div",{className:"grid grid-cols-1 gap-3",children:Object.keys(g).map(w=>{const S=g[w],v=typeof S,C=Array.isArray(S);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:w}),v==="boolean"?a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",checked:!!S,onChange:_=>b({...g,[w]:_.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("span",{className:"ml-2 text-xs",children:String(S)})]}):C?a.jsx("input",{type:"text",value:S.join(", "),onChange:_=>b({...g,[w]:_.target.value.split(",").map(T=>T.trim()).filter(Boolean)}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"}):v==="object"&&S!==null?a.jsx("textarea",{value:(()=>{try{return JSON.stringify(S,null,2)}catch{return String(S)}})(),onChange:_=>{try{const T=JSON.parse(_.target.value);b({...g,[w]:T})}catch{b({...g,[w]:_.target.value})}},rows:4,className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md font-mono text-xs"}):a.jsx("input",{type:v==="number"?"number":"text",value:S??"",onChange:_=>b({...g,[w]:v==="number"?Number(_.target.value):_.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},w)})})]})})]}),a.jsxs("div",{className:"mt-4 flex items-center justify-end gap-2",children:[a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:()=>{p(!1),u(null)},children:"取消"}),a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:async()=>{u(null);try{if(!(e!=null&&e.id))throw new Error("缺少配置ID");let w=null;if(g&&Object.keys(g).length>0)w=g;else{const C=(y.envJson||"").trim();if(C)try{const _=JSON.parse(C);_&&typeof _=="object"&&(w=_)}catch{throw new Error("env JSON 格式错误")}}let v=null;if(w&&typeof w=="object"){v={};for(const C of Object.keys(w)){const _=w[C];Array.isArray(_)?v[C]=_.join(","):typeof _=="boolean"||typeof _=="number"?v[C]=String(_):_==null?v[C]="":typeof _=="object"?v[C]=JSON.stringify(_):v[C]=String(_)}}if(d)if(await re.updateMcpConfigProfile(e.id,d,{name:y.name,env:v,enabled:y.enabled})){const _=await re.getMcpConfigProfiles(e.id);s(Array.isArray(_)?_:[]),p(!1),m(null)}else throw new Error("更新失败");else{const C=await re.createMcpConfigProfile(e.id,{name:y.name,env:v,enabled:y.enabled});if(C&&(C.id||C.success)){const _=await re.getMcpConfigProfiles(e.id);s(Array.isArray(_)?_:[]),p(!1)}else throw new Error("创建失败")}}catch(w){u((w==null?void 0:w.message)||"保存失败")}},children:"保存"})]})]})]})})]})]}):null},Na=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"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"})}),fg=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),hg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),mg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),gg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"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=ut()}catch{t=dt()}const{mcpConfigs:n,updateMcpConfig:s,deleteMcpConfig:o,loadMcpConfigs:i,applications:l,setMcpAppAssociation:c}=t,{dialogState:d,showConfirmDialog:m,handleConfirm:f,handleCancel:p}=yn(),[y,h]=I.useState(!1),[x,u]=I.useState(null),[g,b]=I.useState({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),[w,S]=I.useState(!1),[v,C]=I.useState(null),[_,T]=I.useState({}),[N,P]=I.useState([]),[R,j]=I.useState(""),[F,O]=I.useState(!1),[z,H]=I.useState(null),[E,L]=I.useState([]);I.useEffect(()=>{const A="__mcpManagerInitAt__",q=window[A]||0,J=Date.now();if(!(typeof q=="number"&&J-q<1e3)){window[A]=J,i();try{(t.loadApplications??(()=>{}))()}catch{}}},[i]);const U=async A=>{H(A),O(!0);try{const q=await re.getMcpConfigProfiles(A.id);P(Array.isArray(q)?q:[])}catch{console.error("加载配置档案失败")}finally{}},$=()=>{b({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),u(null),h(!1),T({}),P([]),j(""),L([])},D=async A=>{var V,le;if(A.preventDefault(),!g.name.trim()||!g.command.trim())return;const q={name:g.name.trim(),command:g.command.trim(),type:g.type,enabled:g.enabled,cwd:(V=g.cwd)!=null&&V.trim()?g.cwd.trim():void 0,args:(le=g.argsInput)!=null&&le.trim()?g.argsInput.split(",").map(Fe=>Fe.trim()).filter(Boolean):void 0,createdAt:new Date,updatedAt:new Date,app_ids:E},J=await s(q);J!=null&&J.id&&(c==null||c(J.id,E)),$()},B=async A=>{var V,le;if(A.preventDefault(),!x||!g.name.trim()||!g.command.trim())return;const q={...x,name:g.name.trim(),command:g.command.trim(),type:g.type,enabled:g.enabled,cwd:(V=g.cwd)!=null&&V.trim()?g.cwd.trim():void 0,args:(le=g.argsInput)!=null&&le.trim()?g.argsInput.split(",").map(Fe=>Fe.trim()).filter(Boolean):void 0,updatedAt:new Date,app_ids:E},J=await s(q);J!=null&&J.id&&(c==null||c(J.id,E)),$()},X=A=>{u(A),b({name:A.name,command:A.command,type:A.type||"stdio",enabled:A.enabled,cwd:A.cwd||"",argsInput:Array.isArray(A.args)?A.args.join(", "):""}),h(!0),T({}),C(null),S(!1),L(Array.isArray(A.app_ids)?A.app_ids:[])},M=async A=>{const q=n.find(J=>J.id===A);m({title:"删除 MCP 服务器",message:`确定要删除服务器 "${(q==null?void 0:q.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:()=>o(A)})},K=async A=>{const q={...A,enabled:!A.enabled,updatedAt:new Date};await s(q)};return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),a.jsxs("div",{className:"fixed right-0 top-0 h-full w-[520px] sm:w-[560px] bg-card z-50 shadow-xl breathing-border flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Na,{}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"MCP 服务器管理"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx(fg,{})})]}),a.jsxs("div",{className:"p-4 flex-1 overflow-y-auto",children:[!y&&a.jsxs("button",{onClick:()=>h(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx(hg,{}),a.jsx("span",{children:"添加 MCP 服务器"})]}),y&&a.jsxs("form",{onSubmit:x?B:D,className:"mb-6 p-4 bg-muted rounded-lg",children:[a.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:x?"编辑服务器":"添加新服务器"}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"服务器名称"}),a.jsx("input",{type:"text",value:g.name,onChange:A=>b({...g,name:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: File System",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"关联应用(多选)"}),a.jsxs("div",{className:"space-y-2 max-h-32 overflow-y-auto p-2 border rounded-md",children:[(l||[]).map(A=>a.jsxs("label",{className:"flex items-center space-x-2",children:[a.jsx("input",{type:"checkbox",checked:E.includes(A.id),onChange:q=>{const J=q.target.checked;L(V=>J?[...V,A.id]:V.filter(le=>le!==A.id))}}),a.jsx("span",{children:A.name})]},A.id)),(l||[]).length===0&&a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无应用,可在“应用管理”中创建。"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"协议类型"}),a.jsxs("select",{value:g.type,onChange:A=>b({...g,type:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",children:[a.jsx("option",{value:"stdio",children:"Stdio (标准输入输出)"}),a.jsx("option",{value:"http",children:"HTTP (网络协议)"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:g.type==="http"?"URL地址":"命令"}),a.jsx("input",{type:"text",value:g.command,onChange:A=>b({...g,command:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:g.type==="http"?"https://api.example.com/mcp":"npx @modelcontextprotocol/server-filesystem /path/to/allowed/files",required:!0}),g.type==="stdio"&&a.jsx(a.Fragment,{})]}),g.type==="stdio"&&a.jsxs("div",{className:"space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"可执行地址(cwd)"}),a.jsx("input",{type:"text",value:g.cwd,onChange:A=>b({...g,cwd:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"/absolute/path/to/executable"}),a.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"为空则使用当前页面的工作目录"}),a.jsx("div",{className:"mt-2 flex gap-2",children:a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{var A,q;if(g.command.trim()){S(!0),C(null);try{const J=await re.getMcpConfigResourceByCommand({type:g.type,command:g.command.trim(),args:(A=g.argsInput)!=null&&A.trim()?g.argsInput.split(",").map(V=>V.trim()).filter(Boolean):void 0,env:void 0,cwd:(q=g.cwd)!=null&&q.trim()?g.cwd.trim():void 0,alias:null});if(J&&J.success&&J.config){const V=J.config;if(T(V),x!=null&&x.id)try{const le=await re.getMcpConfigProfiles(x.id);P(Array.isArray(le)?le:[])}catch{}}else C("无法获取服务器可配置参数")}catch(J){C((J==null?void 0:J.message)||"获取配置失败")}finally{S(!1)}}},children:w?"获取中…":"获取配置"})})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"启动参数(args,逗号分隔)"}),a.jsx("input",{type:"text",value:g.argsInput,onChange:A=>b({...g,argsInput:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"--flag, value, --opt"}),a.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:"将自动转换为参数数组"})]})]}),a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",id:"enabled",checked:g.enabled,onChange:A=>b({...g,enabled:A.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此服务器"})]}),g.type==="stdio"&&Object.keys(_).length>0&&a.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-foreground",children:"服务器可配置参数(动态解析)"}),w&&a.jsx("span",{className:"text-xs text-muted-foreground",children:"解析中…"})]}),v&&a.jsx("p",{className:"text-xs text-red-600 mb-2",children:v}),a.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[Object.keys(_).map(A=>{const q=_[A],J=typeof q,V=Array.isArray(q);return a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:A}),J==="boolean"?a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",checked:!!q,onChange:le=>T({..._,[A]:le.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("span",{className:"ml-2 text-xs",children:String(q)})]}):V?a.jsx("input",{type:"text",value:q.join(", "),onChange:le=>T({..._,[A]:le.target.value.split(",").map(Fe=>Fe.trim()).filter(Boolean)}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"}):a.jsx("input",{type:J==="number"?"number":"text",value:q??"",onChange:le=>T({..._,[A]:J==="number"?Number(le.target.value):le.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},A)}),(x==null?void 0:x.id)&&a.jsxs("div",{className:"mt-2 p-2 border border-dashed rounded-md",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("input",{type:"text",value:R,onChange:A=>j(A.target.value),className:"flex-1 px-2 py-1 border border-input bg-background text-foreground rounded-md",placeholder:"配置档案名称(例如:开发环境)"}),a.jsx("button",{type:"button",className:"px-3 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:async()=>{var A,q;if(x!=null&&x.id)try{await re.createMcpConfigProfile(x.id,{name:R||`配置-${new Date().toLocaleString()}`,env:Object.keys(_).reduce((V,le)=>{const Fe=_[le];return V[le]=typeof Fe=="string"?Fe:String(Fe),V},{}),args:(A=g.argsInput)!=null&&A.trim()?g.argsInput.split(",").map(V=>V.trim()).filter(Boolean):void 0,cwd:(q=g.cwd)!=null&&q.trim()?g.cwd.trim():void 0,enabled:!1});const J=await re.getMcpConfigProfiles(x.id);P(Array.isArray(J)?J:[]),j("")}catch(J){console.error("保存配置档案失败:",J),C("保存配置档案失败")}},children:"保存为配置档案"})]}),N.length>0&&a.jsxs("div",{className:"mt-3 space-y-2",children:[a.jsx("div",{className:"text-xs text-muted-foreground",children:"已有配置档案:"}),N.map(A=>{const q=Array.isArray(A.args)?A.args.join(", "):"",J=A.env?Object.keys(A.env):[];return a.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"text-xs text-foreground font-medium",children:A.name}),A.enabled&&a.jsx("span",{className:"px-2 py-0.5 text-[10px] rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200",children:"已启用"})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{try{await re.activateMcpConfigProfile(x.id,A.id);const V=await re.getMcpConfigProfiles(x.id);P(Array.isArray(V)?V:[])}catch{}},children:"激活"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-blue-600 text-white rounded-md hover:bg-blue-700",onClick:()=>{b(V=>({...V,argsInput:Array.isArray(A.args)?A.args.join(", "):V.argsInput,cwd:A.cwd??V.cwd})),T(A.env||{})},children:"应用到表单"})]})]}),a.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),A.cwd||"未设置"]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"args:"}),q||"未设置"]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-muted-foreground",children:["env(",J.length,"):"]}),J.length===0?"未设置":a.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:J.map(V=>a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-muted-foreground",children:V}),a.jsx("span",{className:"text-foreground",children:String(A.env[V])})]},V))})]})]})]},A.id)})]})]})]})]})]}),(x==null?void 0:x.id)&&!y&&a.jsxs("div",{className:"mt-4 p-3 border border-border rounded-md bg-card",children:[a.jsxs("div",{className:"flex items-center justify-between mb-2",children:[a.jsx("span",{className:"text-sm font-medium text-foreground",children:"配置档案列表"}),a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{try{const A=await re.getMcpConfigProfiles(x.id);P(Array.isArray(A)?A:[])}catch{}},children:"刷新"})]}),N.length===0?a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案"}):a.jsx("div",{className:"space-y-2",children:N.map(A=>{const q=Array.isArray(A.args)?A.args.join(", "):"",J=A.env?Object.keys(A.env):[];return a.jsxs("div",{className:"px-2 py-1 border border-border rounded-md",children:[a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsxs("div",{className:"flex items-center gap-2",children:[a.jsx("div",{className:"text-xs text-foreground font-medium",children:A.name}),A.enabled&&a.jsx("span",{className:"px-2 py-0.5 text-[10px] rounded-full bg-green-100 text-green-700 dark:bg-green-900 dark:text-green-200",children:"已启用"})]}),a.jsx("div",{className:"flex items-center gap-2",children:a.jsx("button",{type:"button",className:"px-2 py-1 text-xs bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80",onClick:async()=>{try{await re.activateMcpConfigProfile(x.id,A.id);const V=await re.getMcpConfigProfiles(x.id);P(Array.isArray(V)?V:[])}catch{}},children:"激活"})})]}),a.jsxs("div",{className:"mt-2 grid grid-cols-1 gap-2 text-xs text-foreground",children:[a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),A.cwd||"未设置"]}),a.jsxs("div",{children:[a.jsx("span",{className:"text-muted-foreground",children:"args:"}),q||"未设置"]}),a.jsxs("div",{children:[a.jsxs("span",{className:"text-muted-foreground",children:["env(",J.length,"):"]}),J.length===0?"未设置":a.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:J.map(V=>a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("span",{className:"text-muted-foreground",children:V}),a.jsx("span",{className:"text-foreground",children:String(A.env[V])})]},V))})]})]})]},A.id)})})]}),a.jsxs("div",{className:"flex space-x-3 mt-6",children:[a.jsx("button",{type:"submit",className:"px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500",children:x?"更新":"添加"}),a.jsx("button",{type:"button",onClick:$,className:"px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 focus:outline-none focus:ring-2 focus:ring-ring",children:"取消"})]})]}),a.jsx("div",{className:"space-y-3",children:n.length===0?a.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[a.jsx(Na,{}),a.jsx("p",{className:"mt-2",children:"暂无 MCP 服务器配置"}),a.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个服务器"})]}):n.map(A=>a.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border border-border rounded-lg",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("div",{className:`w-3 h-3 rounded-full ${A.enabled?"bg-green-500":"bg-gray-400"}`}),a.jsxs("div",{children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("h4",{className:"font-medium text-foreground",children:A.name}),a.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${A.type==="http"?"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200":"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"}`,children:A.type==="http"?"HTTP":"Stdio"})]}),a.jsx("p",{className:"text-sm text-muted-foreground",children:A.command})]})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{onClick:()=>K(A),className:`px-3 py-1 text-xs rounded-full ${A.enabled?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-secondary text-secondary-foreground"}`,children:A.enabled?"已启用":"已禁用"}),a.jsx("button",{onClick:()=>U(A),className:"p-2 text-muted-foreground hover:text-indigo-600 transition-colors",title:"查看配置档案",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3 7.5l7.5 3 7.5-3M3 7.5V18l7.5 3 7.5-3V7.5M10.5 10.5V21"})})}),a.jsx("button",{onClick:()=>X(A),className:"p-2 text-muted-foreground hover:text-blue-600 transition-colors",title:"编辑",children:a.jsx(gg,{})}),a.jsx("button",{onClick:()=>M(A.id),className:"p-2 text-muted-foreground hover:text-red-600 transition-colors",title:"删除",children:a.jsx(mg,{})})]})]},A.id))})]})]}),a.jsx(ug,{open:F,config:z,onClose:()=>{O(!1),H(null)}}),a.jsx(bn,{isOpen:d.isOpen,title:d.title,message:d.message,confirmText:d.confirmText,cancelText:d.cancelText,type:d.type,onConfirm:f,onCancel:p})]})},Ma=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})}),pg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),xg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),bg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})}),yg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"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=ut()}catch{t=dt()}const{aiModelConfigs:n,loadAiModelConfigs:s,updateAiModelConfig:o,deleteAiModelConfig:i}=t,[l,c]=I.useState(!1),[d,m]=I.useState(null),[f,p]=I.useState({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),{dialogState:y,showConfirmDialog:h,handleConfirm:x,handleCancel:u}=yn();I.useEffect(()=>{const _="__aiModelManagerInitAt__",T=window[_]||0,N=Date.now();typeof T=="number"&&N-T<1e3||(window[_]=N,s())},[s]);const g=()=>{p({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),m(null),c(!1)},b=async _=>{if(_.preventDefault(),!f.name.trim()||!f.base_url.trim()||!f.api_key.trim()||!f.model_name.trim())return;const T={id:Math.random().toString(36).substr(2,9),name:f.name.trim(),base_url:f.base_url.trim(),api_key:f.api_key.trim(),model_name:f.model_name.trim(),enabled:f.enabled,createdAt:new Date,updatedAt:new Date};await o(T),g()},w=async _=>{if(_.preventDefault(),!d||!f.name.trim()||!f.base_url.trim()||!f.api_key.trim()||!f.model_name.trim())return;const T={...d,name:f.name.trim(),base_url:f.base_url.trim(),api_key:f.api_key.trim(),model_name:f.model_name.trim(),enabled:f.enabled,updatedAt:new Date};await o(T),g()},S=_=>{m(_),p({name:_.name,base_url:_.base_url,api_key:_.api_key,model_name:_.model_name,enabled:_.enabled}),c(!0)},v=async _=>{const T=n.find(N=>N.id===_);h({title:"删除确认",message:`确定要删除AI模型配置 "${(T==null?void 0:T.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{await i(_)}})},C=async _=>{const T={..._,enabled:!_.enabled,updatedAt:new Date};await o(T)};return a.jsxs("div",{className:"modal-container",children:[a.jsxs("div",{className:"modal-content w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Ma,{}),a.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"AI 模型管理"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(pg,{})})]}),a.jsxs("div",{className:"p-6 overflow-y-auto max-h-[calc(80vh-120px)]",children:[!l&&a.jsxs("button",{onClick:()=>c(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx(xg,{}),a.jsx("span",{children:"添加 AI 模型"})]}),l&&a.jsxs("form",{onSubmit:d?w:b,className:"mb-6 p-4 bg-muted rounded-lg",children:[a.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:d?"编辑 AI 模型":"添加 AI 模型"}),a.jsxs("div",{className:"space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),a.jsx("input",{type:"text",value:f.name,onChange:_=>p({...f,name:_.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: OpenAI GPT-4",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"Base URL"}),a.jsx("input",{type:"url",value:f.base_url,onChange:_=>p({...f,base_url:_.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: https://api.openai.com/v1",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"API Key"}),a.jsx("input",{type:"password",value:f.api_key,onChange:_=>p({...f,api_key:_.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"输入API密钥",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"模型名称"}),a.jsx("input",{type:"text",value:f.model_name,onChange:_=>p({...f,model_name:_.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: gpt-4",required:!0})]}),a.jsxs("div",{className:"flex items-center",children:[a.jsx("input",{type:"checkbox",id:"enabled",checked:f.enabled,onChange:_=>p({...f,enabled:_.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),a.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-foreground",children:"启用此模型"})]})]}),a.jsxs("div",{className:"flex space-x-3 mt-6",children:[a.jsx("button",{type:"submit",className:"px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500",children:d?"更新":"添加"}),a.jsx("button",{type:"button",onClick:g,className:"px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 focus:outline-none focus:ring-2 focus:ring-ring",children:"取消"})]})]}),a.jsx("div",{className:"space-y-3",children:n.length===0?a.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[a.jsx(Ma,{}),a.jsx("p",{className:"mt-2",children:"暂无 AI 模型配置"}),a.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个模型"})]}):n.map(_=>a.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border border-border rounded-lg hover:shadow-md transition-shadow",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("div",{className:`w-3 h-3 rounded-full ${_.enabled?"bg-green-500":"bg-gray-400"}`}),a.jsxs("div",{children:[a.jsx("h4",{className:"font-medium text-foreground",children:_.name}),a.jsxs("p",{className:"text-sm text-muted-foreground",children:[_.base_url," - ",_.model_name]})]})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{onClick:()=>C(_),className:`px-3 py-1 text-xs rounded-full transition-colors ${_.enabled?"bg-green-100 text-green-800 hover:bg-green-200 dark:bg-green-900 dark:text-green-200":"bg-secondary text-secondary-foreground hover:bg-secondary/80"}`,children:_.enabled?"已启用":"已禁用"}),a.jsx("button",{onClick:()=>S(_),className:"p-2 text-muted-foreground hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded transition-colors",title:"编辑",children:a.jsx(bg,{})}),a.jsx("button",{onClick:()=>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:a.jsx(yg,{})})]})]},_.id))})]})]}),a.jsx(bn,{isOpen:y.isOpen,title:y.title,message:y.message,confirmText:y.confirmText,cancelText:y.cancelText,type:y.type,onConfirm:x,onCancel:u})]})},Ea=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})}),wg=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),vg=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"})}),_g=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),Sg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})}),Cg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"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"})}),jg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),mo=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=ut()}catch{t=dt()}const{systemContexts:n,activeSystemContext:s,loadSystemContexts:o,createSystemContext:i,updateSystemContext:l,deleteSystemContext:c,activateSystemContext:d,applications:m,loadApplications:f}=t,[p,y]=I.useState("list"),[h,x]=I.useState(null),[u,g]=I.useState({name:"",content:""}),[b,w]=I.useState(!1),[S,v]=I.useState(!1),[C,_]=I.useState([]),{dialogState:T,showConfirmDialog:N,handleConfirm:P,handleCancel:R}=yn();I.useEffect(()=>{const $="__systemContextEditorInitAt__",D=window[$]||0,B=Date.now();if(typeof D=="number"&&B-D<1e3)return;window[$]=B,(async()=>{w(!0);try{await o();try{await(f==null?void 0:f())}catch{}}catch(M){console.error("Failed to load system contexts:",M)}finally{w(!1)}})()},[o]);const j=()=>{g({name:"",content:""}),x(null),y("create")},F=$=>{g({name:$.name,content:$.content}),x($),_(Array.isArray($.app_ids)?$.app_ids:[]),y("edit")},O=async()=>{if(!u.name.trim()||!u.content.trim()){alert("请填写名称和内容");return}v(!0);try{p==="create"?await i(u.name,u.content,C):p==="edit"&&h&&await l(h.id,u.name,u.content,C),y("list")}catch($){console.error("Failed to save system context:",$),alert("保存失败,请重试")}finally{v(!1)}},z=async $=>{N({title:"删除确认",message:`确定要删除上下文 "${$.name}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{try{await c($.id)}catch(D){console.error("Failed to delete system context:",D),alert("删除失败,请重试")}}})},H=async $=>{try{await d($.id),await o()}catch(D){console.error("Failed to activate system context:",D),alert("激活失败,请重试")}},E=$=>{$.ctrlKey&&$.key==="s"&&($.preventDefault(),p!=="list"&&O())},L=()=>a.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[a.jsx("div",{className:"mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:a.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:[a.jsx("strong",{children:"系统上下文"}),"将作为每次对话的系统提示词,支持 Markdown 格式。 您可以创建多个上下文配置,但同一时间只能激活一个。"]})}),a.jsx("div",{className:"flex-1 overflow-y-auto",children:b?a.jsx("div",{className:"flex items-center justify-center h-32",children:a.jsx("div",{className:"text-muted-foreground",children:"加载中..."})}):n.length===0?a.jsxs("div",{className:"flex flex-col items-center justify-center h-32 text-muted-foreground",children:[a.jsx(Ea,{}),a.jsx("p",{className:"mt-2",children:"暂无系统上下文配置"}),a.jsx("p",{className:"text-sm",children:'点击"新建"按钮创建第一个配置'})]}):a.jsx("div",{className:"space-y-3",children:n.map($=>a.jsx("div",{className:`p-4 border rounded-lg transition-colors ${$.isActive?"border-green-500 bg-green-50 dark:bg-green-900/20":"border-border bg-card"}`,children:a.jsxs("div",{className:"flex items-start justify-between",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("h3",{className:"font-medium text-foreground",children:$.name}),$.isActive&&a.jsxs("span",{className:"inline-flex items-center px-2 py-1 text-xs font-medium bg-green-100 text-green-800 rounded-full dark:bg-green-800 dark:text-green-100",children:[a.jsx(jg,{}),a.jsx("span",{className:"ml-1",children:"已激活"})]})]}),a.jsxs("p",{className:"mt-1 text-sm text-muted-foreground line-clamp-2",children:[$.content.substring(0,100),$.content.length>100&&"..."]}),a.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["创建时间: ",new Date($.createdAt).toLocaleString()]})]}),a.jsxs("div",{className:"flex items-center space-x-2 ml-4",children:[!$.isActive&&a.jsx("button",{onClick:()=>H($),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"激活"}),a.jsx("button",{onClick:()=>F($),className:"p-2 text-muted-foreground hover:text-blue-600 hover:bg-accent rounded transition-colors",children:a.jsx(Sg,{})}),a.jsx("button",{onClick:()=>z($),className:"p-2 text-muted-foreground hover:text-red-600 hover:bg-accent rounded transition-colors",children:a.jsx(Cg,{})})]})]})},$.id))})})]}),U=()=>a.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[a.jsxs("div",{className:"mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:[a.jsx("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:p==="create"?"创建新的系统上下文配置":"编辑系统上下文配置"}),a.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300 mt-2",children:"提示:使用 Ctrl+S 快速保存"})]}),a.jsxs("div",{className:"flex-1 flex flex-col space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"配置名称"}),a.jsx("input",{type:"text",value:u.name,onChange:$=>g({...u,name:$.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-lg focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如:编程助手、翻译专家、创意写作等"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"关联应用(多选)"}),a.jsxs("div",{className:"space-y-2 max-h-32 overflow-y-auto p-2 border rounded-md",children:[(m||[]).map($=>a.jsxs("label",{className:"flex items-center space-x-2",children:[a.jsx("input",{type:"checkbox",checked:C.includes($.id),onChange:D=>{const B=D.target.checked;_(X=>B?[...X,$.id]:X.filter(M=>M!==$.id))}}),a.jsx("span",{children:$.name})]},$.id)),(m||[]).length===0&&a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无应用,可在“应用管理”中创建。"})]})]}),a.jsxs("div",{className:"flex-1 flex flex-col",children:[a.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[a.jsx("label",{className:"block text-sm font-medium text-foreground",children:"Markdown 内容"}),a.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.content.length," 字符"]})]}),a.jsx("textarea",{value:u.content,onChange:$=>g({...u,content:$.target.value}),onKeyDown:E,className:"flex-1 w-full px-4 py-3 border border-input bg-background text-foreground rounded-lg focus:outline-none focus:ring-2 focus:ring-ring resize-none font-mono text-sm",placeholder:"请输入系统上下文内容,支持 Markdown 格式...\\n\\n例如:\\n# AI 助手角色设定\\n\\n你是一个专业的编程助手,具有以下特点:\\n- 提供准确、简洁的代码解决方案\\n- 遵循最佳实践和代码规范\\n- 耐心解答技术问题\\n\\n## 回答风格\\n- 使用中文回答\\n- 代码示例要完整可运行\\n- 提供必要的解释说明",spellCheck:!1})]}),a.jsxs("div",{className:"text-xs text-muted-foreground",children:[a.jsx("p",{children:"• 支持标准 Markdown 语法:标题、列表、代码块、链接等"}),a.jsx("p",{children:"• 内容将在每次对话开始时自动发送给 AI"}),a.jsx("p",{children:"• 留空则使用默认系统提示词"})]})]})]});return a.jsxs("div",{className:"modal-container",children:[a.jsxs("div",{className:"modal-content w-full max-w-4xl max-h-[90vh] overflow-hidden",children:[a.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Ea,{}),a.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"系统上下文设置"})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[p==="list"?a.jsxs("button",{onClick:j,className:"flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 transition-colors",children:[a.jsx(_g,{}),a.jsx("span",{children:"新建"})]}):a.jsxs(a.Fragment,{children:[a.jsxs("button",{onClick:O,disabled:S,className:"flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[a.jsx(vg,{}),a.jsx("span",{children:S?"保存中...":"保存"})]}),a.jsx("button",{onClick:()=>y("list"),className:"px-4 py-2 text-secondary-foreground border border-border rounded-md hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring transition-colors",children:"取消"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(wg,{})})]})]}),p==="list"?L():U()]}),a.jsx(bn,{isOpen:T.isOpen,title:T.title,message:T.message,confirmText:T.confirmText,cancelText:T.cancelText,type:T.type,onConfirm:P,onCancel:R})]})},Ia=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6M9 16h6M6 8h12a2 2 0 012 2v8a2 2 0 01-2 2H6a2 2 0 01-2-2v-8a2 2 0 012-2z"})}),Ta=()=>a.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),Ag=()=>a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),kg=()=>a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),nc=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=ut()}catch{t=dt()}const{aiModelConfigs:n,loadAiModelConfigs:s,mcpConfigs:o,loadMcpConfigs:i,systemContexts:l,loadSystemContexts:c,applications:d,loadApplications:m}=t,{userId:f}=Rf(),p=f||"custom_user_123",h=$f()||re,[x,u]=I.useState([]),[g,b]=I.useState(!1),[w,S]=I.useState(!1),[v,C]=I.useState(null),[_,T]=I.useState(null),[N,P]=I.useState({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),[R,j]=I.useState([]),F=I.useRef(!1),O=async()=>{b(!0);try{await Promise.all([s(),i(),c(),m?m():Promise.resolve(),t.loadAgents?t.loadAgents():Promise.resolve()]);const M=t.agents&&Array.isArray(t.agents)?t.agents:await h.getAgents(p),K=Array.isArray(M)?M:[];u(K)}catch(M){console.error("加载智能体失败",M)}finally{b(!1)}},z=async M=>{for(let A=0;A<3;A++)try{t.loadAgents&&await t.loadAgents();const q=await h.getAgents(p),J=Array.isArray(q)?q:[];if(u(J),M&&Array.isArray(J)&&J.some(V=>V.id===M)||!M)break;await new Promise(V=>setTimeout(V,250))}catch(q){console.warn("刷新智能体列表失败,重试中…",q),await new Promise(J=>setTimeout(J,250))}};I.useEffect(()=>{const M="__agentManagerInitAt__",K=window[M]||0,A=Date.now();typeof K=="number"&&A-K<1e3||(window[M]=A,O())},[]);const H=()=>{P({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),S(!1),T(null),j([])};I.useEffect(()=>{if(F.current){F.current=!1;return}P(M=>{const K={...M};return K.mcp_config_ids=[],K.system_context_id=void 0,K})},[R]);const E=async M=>{var K;if(M.preventDefault(),!(!N.name.trim()||!N.ai_model_config_id))try{const A=await h.createAgent({name:N.name.trim(),description:((K=N.description)==null?void 0:K.trim())||void 0,ai_model_config_id:N.ai_model_config_id,mcp_config_ids:N.mcp_config_ids,system_context_id:N.system_context_id,user_id:p,enabled:!0,app_ids:R});A&&A.id&&u(q=>q.some(V=>V.id===A.id)?q.map(V=>V.id===A.id?{...V,...A}:V):[A,...q]),await z(A==null?void 0:A.id),H()}catch(A){console.error("创建智能体失败",A),alert("创建失败,请重试")}},L=async M=>{if(M.preventDefault(),!!_)try{const K=await h.updateAgent(_.id,{name:N.name,description:N.description,ai_model_config_id:N.ai_model_config_id,mcp_config_ids:N.mcp_config_ids,system_context_id:N.system_context_id,enabled:!0,app_ids:R});u(A=>A.map(q=>q.id===_.id?{...q,...K,name:N.name,description:N.description,ai_model_config_id:N.ai_model_config_id,mcp_config_ids:N.mcp_config_ids,system_context_id:N.system_context_id,enabled:!0}:q)),await z(_.id),H()}catch(K){console.error("更新智能体失败",K),alert("更新失败,请重试")}},U=async M=>{try{await h.deleteAgent(M),u(K=>K.filter(A=>A.id!==M)),await z()}catch(K){console.error("删除智能体失败",K),alert("删除失败,请重试")}},$=M=>{T(M),S(!0),P({name:M.name,description:M.description||"",ai_model_config_id:M.ai_model_config_id,mcp_config_ids:Array.isArray(M.mcp_config_ids)?M.mcp_config_ids:[],system_context_id:M.system_context_id}),F.current=!0,j(Array.isArray(M.app_ids)?M.app_ids:[])},D=M=>{const K=n.find(A=>A.id===M);return K?`${K.name}(${K.model_name})`:M},B=M=>{if(!M)return"未选择";const K=l.find(A=>A.id===M);return K?K.name:M},X=M=>M.map(A=>{const q=o.find(J=>J.id===A);return q?q.name:A}).join(",");return a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:r}),a.jsxs("div",{className:"fixed right-0 top-0 h-full w-[520px] sm:w-[560px] bg-card z-50 shadow-xl breathing-border flex flex-col",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx(Ia,{}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"智能体管理"})]}),a.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx(Ta,{})})]}),a.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[!w&&a.jsxs("button",{onClick:()=>S(!0),className:"w-full p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx(Ag,{}),a.jsx("span",{children:"新增智能体"})]}),w&&a.jsxs("form",{onSubmit:_?L:E,className:"p-4 bg-muted rounded-lg space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"关联应用(多选)"}),a.jsxs("div",{className:"space-y-2 max-h-32 overflow-y-auto p-2 border rounded-md",children:[(d||[]).map(M=>a.jsxs("label",{className:"flex items-center space-x-2",children:[a.jsx("input",{type:"checkbox",checked:R.includes(M.id),onChange:K=>{const A=K.target.checked;j(q=>A?[...q,M.id]:q.filter(J=>J!==M.id))}}),a.jsx("span",{children:M.name})]},M.id)),(d||[]).length===0&&a.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无应用,可在“应用管理”中创建。"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),a.jsx("input",{type:"text",value:N.name,onChange:M=>P({...N,name:M.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如:项目助理",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"描述"}),a.jsx("textarea",{value:N.description,onChange:M=>P({...N,description:M.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"智能体用途说明",rows:3})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择模型(单选)"}),a.jsxs("select",{value:N.ai_model_config_id,onChange:M=>P({...N,ai_model_config_id:M.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",required:!0,children:[a.jsx("option",{value:"",children:"请选择模型"}),n.map(M=>a.jsxs("option",{value:M.id,children:[M.name,"(",M.model_name,")"]},M.id))]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 MCP 配置(多选)"}),a.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 border rounded-md",children:[(R.length?o.filter(M=>Array.isArray(M.app_ids)&&M.app_ids.some(K=>R.includes(K))):o).map(M=>a.jsxs("label",{className:"flex items-center space-x-2",children:[a.jsx("input",{type:"checkbox",checked:N.mcp_config_ids.includes(M.id),onChange:K=>{const A=K.target.checked;P(q=>({...q,mcp_config_ids:A?[...q.mcp_config_ids,M.id]:q.mcp_config_ids.filter(J=>J!==M.id)}))}}),a.jsx("span",{children:M.name})]},M.id)),R.length>0&&o.filter(M=>Array.isArray(M.app_ids)&&M.app_ids.some(K=>R.includes(K))).length===0&&a.jsx("div",{className:"text-xs text-muted-foreground",children:"所选应用下暂无 MCP 配置"})]})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择系统上下文"}),a.jsxs("select",{value:N.system_context_id||"",onChange:M=>P({...N,system_context_id:M.target.value||void 0}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",children:[a.jsx("option",{value:"",children:"不使用"}),(R.length?l.filter(M=>Array.isArray(M.app_ids)&&M.app_ids.some(K=>R.includes(K))):l).map(M=>a.jsx("option",{value:M.id,children:M.name},M.id)),R.length>0&&l.filter(M=>Array.isArray(M.app_ids)&&M.app_ids.some(K=>R.includes(K))).length===0&&a.jsx("option",{value:"",disabled:!0,children:"所选应用下暂无系统上下文"})]})]}),a.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[a.jsx("button",{type:"button",onClick:H,className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"取消"}),a.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:"保存"})]})]}),a.jsx("div",{children:g?a.jsx("div",{className:"text-muted-foreground",children:"加载中..."}):x.length===0?a.jsx("div",{className:"text-muted-foreground",children:"暂无智能体配置"}):a.jsx("div",{className:"space-y-3",children:x.map(M=>a.jsxs("div",{className:"p-4 border rounded-lg flex items-start justify-between",children:[a.jsxs("div",{className:"flex-1",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("h3",{className:"font-medium text-foreground",children:M.name}),!M.enabled&&a.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-muted text-muted-foreground",children:"未启用"})]}),M.description&&a.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:M.description}),a.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["模型:",D(M.ai_model_config_id)]}),a.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["系统上下文:",B(M.system_context_id)]}),a.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["MCP配置:",X(M.mcp_config_ids||[])]})]}),a.jsxs("div",{className:"flex items-center space-x-2 ml-4",children:[a.jsx("button",{onClick:()=>C(M),className:"px-3 py-1 text-sm bg-muted text-foreground rounded hover:bg-accent transition-colors",children:"详情"}),a.jsx("button",{onClick:()=>$(M),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"编辑"}),a.jsxs("button",{onClick:()=>U(M.id),className:"px-3 py-1 text-sm bg-destructive text-destructive-foreground rounded hover:bg-destructive/90 transition-colors flex items-center space-x-1",children:[a.jsx(kg,{}),a.jsx("span",{children:"删除"})]})]})]},M.id))})})]}),v&&a.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[a.jsx("div",{className:"fixed inset-0 bg-black/50",onClick:()=>C(null)}),a.jsxs("div",{className:"relative bg-card border border-border rounded-lg shadow-xl w-[520px] p-6",children:[a.jsxs("div",{className:"flex items-center justify-between mb-4",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx(Ia,{}),a.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"智能体详情"})]}),a.jsx("button",{onClick:()=>C(null),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:a.jsx(Ta,{})})]}),a.jsxs("div",{className:"space-y-2",children:[a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"名称:"}),v.name]}),v.description&&a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"描述:"}),v.description]}),a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"模型:"}),D(v.ai_model_config_id)]}),a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"系统上下文:"}),B(v.system_context_id)]}),a.jsxs("p",{children:[a.jsx("span",{className:"text-muted-foreground",children:"MCP配置:"}),X(v.mcp_config_ids||[])]}),a.jsxs("p",{className:"text-xs text-muted-foreground",children:["创建时间:",v.created_at?new Date(v.created_at).toLocaleString():"-"]})]}),a.jsx("div",{className:"mt-4 flex justify-end space-x-2",children:a.jsx("button",{onClick:()=>C(null),className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"关闭"})})]})]})]})]})},sc=({isOpen:r,onClose:e,manageOnly:t=!1,title:n,layout:s="modal",onApplicationSelect:o})=>{let i;try{i=ut()}catch{i=dt()}const{applications:l,loadApplications:c,createApplication:d,updateApplication:m,deleteApplication:f}=i,p=I.useRef(new Map),[y,h]=I.useState(!!t),[x,u]=I.useState(!1),[g,b]=I.useState(null),[w,S]=I.useState({name:"",url:"",iconUrl:""});I.useEffect(()=>{try{console.log("[ApplicationsPanel] useEffect -> loadApplications"),c==null||c()}catch(j){console.error("[ApplicationsPanel] loadApplications error:",j)}},[c]);const v=()=>{b(null),S({name:"",url:"",iconUrl:""}),u(!1)},C=async j=>{j.preventDefault(),w.name.trim()&&(g?await(m==null?void 0:m(g,{name:w.name.trim(),url:w.url.trim(),iconUrl:w.iconUrl.trim()||void 0})):await(d==null?void 0:d(w.name.trim(),w.url.trim(),w.iconUrl.trim()||void 0)),v())},_=j=>{console.log("[ApplicationsPanel] closeAppWindow:",j);const F=p.current.get(j);F&&!F.closed&&F.close(),p.current.delete(j)},T=j=>{console.log("[ApplicationsPanel] handleAppClick - 应用被点击:",{id:j.id,name:j.name,url:j.url}),o?(console.log("[ApplicationsPanel] 调用 onApplicationSelect 回调"),o(j)):console.log("[ApplicationsPanel] ⚠️ 未提供 onApplicationSelect 回调"),e&&(console.log("[ApplicationsPanel] 关闭应用列表面板"),e())};if(!(s==="modal"?!!r:!0))return null;const P=t?!0:y,R=n??(P?"应用管理":"应用列表");return s==="modal"?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"fixed inset-0 bg-black/50 backdrop-blur-sm z-40",onClick:e}),a.jsxs("div",{className:"fixed left-1/2 top-1/2 -translate-x-1/2 -translate-y-1/2 w-[90vw] max-w-4xl h-[85vh] bg-card z-50 shadow-xl breathing-border flex flex-col rounded-lg",children:[a.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("span",{className:"inline-block w-2.5 h-2.5 rounded-full bg-blue-500"}),a.jsx("h2",{className:"text-lg font-semibold text-foreground",children:R})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&a.jsx("button",{onClick:()=>{h(!y),u(!1),v()},className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent transition-colors",children:P?"浏览模式":"管理模式"}),!P&&p.current.size>0&&a.jsx("button",{className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",onClick:()=>{p.current.forEach((j,F)=>_(F))},children:"关闭全部"}),a.jsx("button",{onClick:e,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"关闭",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-6",children:P?a.jsxs("div",{className:"space-y-4",children:[!x&&a.jsxs("button",{type:"button",onClick:()=>u(!0),className:"w-full p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M12 6v12m6-6H6"})}),a.jsx("span",{children:"新增应用"})]}),x&&a.jsxs("form",{onSubmit:C,className:"p-4 bg-muted rounded-lg space-y-4",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"名称"}),a.jsx("input",{type:"text",value:w.name,onChange:j=>S({...w,name:j.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如:Jira、GitHub",required:!0})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"URL"}),a.jsx("input",{type:"text",value:w.url,onChange:j=>S({...w,url:j.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"https://app.example.com"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"图标URL"}),a.jsx("input",{type:"text",value:w.iconUrl,onChange:j=>S({...w,iconUrl:j.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"https://app.example.com/icon.png"})]}),a.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[a.jsx("button",{type:"button",className:"px-3 py-2 rounded bg-muted hover:bg-accent",onClick:v,children:"取消"}),a.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:g?"保存":"创建"})]})]}),a.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(j=>a.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center overflow-hidden shrink-0",children:j.iconUrl?a.jsx("img",{src:j.iconUrl,alt:j.name,className:"w-full h-full object-cover"}):a.jsx("span",{className:"text-white text-sm font-bold",children:j.name.charAt(0).toUpperCase()})}),a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-medium text-foreground",children:j.name}),j.url&&a.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:j.url})]})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{className:"px-2 py-1 text-xs bg-muted rounded hover:bg-accent",onClick:()=>{b(j.id),u(!0),S({name:j.name,url:j.url||"",iconUrl:j.iconUrl||""})},children:"编辑"}),a.jsx("button",{className:"px-2 py-1 text-xs bg-destructive text-destructive-foreground rounded hover:bg-destructive/90",onClick:()=>f==null?void 0:f(j.id),children:"删除"})]})]},j.id)),(l==null?void 0:l.length)===0&&a.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[a.jsx("svg",{className:"w-16 h-16 mx-auto mb-3 opacity-30",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm",children:"暂无应用,点击上方按钮添加"})]})]})]}):a.jsxs("div",{className:"grid grid-cols-4 md:grid-cols-5 lg:grid-cols-6 gap-6",children:[l==null?void 0:l.map(j=>{const F=p.current.has(j.id);return a.jsxs("div",{className:"relative group/item",children:[a.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>T(j),title:j.url||"",children:[a.jsxs("div",{className:`relative w-16 h-16 rounded-full flex items-center justify-center overflow-hidden transition-all ${F?"ring-2 ring-green-500 ring-offset-2 ring-offset-background scale-110":"bg-gradient-to-br from-blue-500/20 to-purple-500/20 group-hover/item:scale-105"}`,children:[j.iconUrl?a.jsx("img",{src:j.iconUrl,alt:j.name,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:a.jsx("span",{className:"text-white text-xl font-bold",children:j.name.charAt(0).toUpperCase()})}),F&&a.jsx("div",{className:"absolute -top-1 -right-1 w-5 h-5 bg-green-500 rounded-full border-2 border-background flex items-center justify-center",children:a.jsx("div",{className:"w-2 h-2 bg-white rounded-full animate-pulse"})})]}),a.jsx("div",{className:"text-xs font-medium text-foreground text-center truncate w-full px-1",children:j.name})]}),F&&a.jsx("button",{onClick:O=>{O.stopPropagation(),_(j.id)},className:"absolute top-0 left-0 w-5 h-5 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover/item:opacity-100 transition-opacity z-10",title:"关闭",children:a.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},j.id)}),((l==null?void 0:l.length)??0)===0&&a.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-20 text-center",children:[a.jsx("svg",{className:"w-20 h-20 text-muted-foreground/30 mb-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),a.jsx("button",{onClick:()=>h(!0),className:"text-sm text-blue-500 hover:text-blue-600 underline",children:"点击切换到管理模式添加应用"})]})]})})]})]}):a.jsxs("div",{className:"flex flex-col h-full",children:[a.jsxs("div",{className:"flex items-center justify-between p-3 border-b border-border bg-card/50",children:[a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("span",{className:"inline-block w-2 h-2 rounded-full bg-blue-500"}),a.jsx("span",{className:"text-sm font-medium text-foreground",children:R})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[!t&&a.jsx("button",{onClick:()=>{h(!y),u(!1),v()},className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent transition-colors",children:P?"浏览模式":"管理模式"}),!P&&p.current.size>0&&a.jsx("button",{className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent",onClick:()=>{p.current.forEach((j,F)=>_(F))},children:"关闭全部"}),e&&a.jsx("button",{onClick:e,className:"p-1.5 text-muted-foreground hover:text-foreground hover:bg-accent rounded transition-colors",title:"关闭",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]})]}),a.jsx("div",{className:"flex-1 overflow-y-auto p-4",children:P?a.jsxs(a.Fragment,{children:[a.jsx("div",{className:"mb-4 flex items-center justify-between",children:a.jsx("button",{type:"button",onClick:()=>{b(null),S({name:"",url:"",iconUrl:""}),u(j=>!j)},className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:x?"取消":"新增应用"})}),x&&a.jsxs("form",{onSubmit:j=>{var H,E,L;j.preventDefault();const F=((H=w.name)==null?void 0:H.trim())||"",O=((E=w.url)==null?void 0:E.trim())||"",z=((L=w.iconUrl)==null?void 0:L.trim())||void 0;F&&(g?m==null||m(g,{name:F,url:O,iconUrl:z}):d==null||d(F,O,z),u(!1),v())},className:"p-4 bg-muted rounded-lg space-y-3",children:[a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"名称"}),a.jsx("input",{value:w.name,onChange:j=>S({...w,name:j.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"例如:飞书"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"URL"}),a.jsx("input",{value:w.url,onChange:j=>S({...w,url:j.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://example.com"})]}),a.jsxs("div",{children:[a.jsx("label",{className:"block text-xs font-medium text-foreground mb-1",children:"图标地址"}),a.jsx("input",{value:w.iconUrl,onChange:j=>S({...w,iconUrl:j.target.value}),className:"w-full px-2 py-1 text-sm rounded border border-border bg-background",placeholder:"https://.../icon.png"})]}),a.jsxs("div",{className:"flex justify-end space-x-2",children:[a.jsx("button",{type:"button",onClick:()=>{u(!1),v(),b(null)},className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",children:"取消"}),a.jsx("button",{type:"submit",className:"px-3 py-1.5 text-sm rounded bg-primary text-primary-foreground hover:opacity-90",children:g?"保存":"创建"})]})]}),a.jsxs("div",{className:"space-y-2",children:[l==null?void 0:l.map(j=>a.jsxs("div",{className:"flex items-center justify-between p-3 rounded border border-border hover:bg-muted transition-colors",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("div",{className:"w-10 h-10 rounded-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center overflow-hidden shrink-0",children:j.iconUrl?a.jsx("img",{src:j.iconUrl,alt:j.name,className:"w-full h-full object-cover"}):a.jsx("span",{className:"text-white text-sm font-bold",children:j.name.charAt(0).toUpperCase()})}),a.jsxs("div",{children:[a.jsx("div",{className:"text-sm font-medium text-foreground",children:j.name}),j.url&&a.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:j.url})]})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{className:"px-2 py-1 text-xs rounded bg-background hover:bg-accent",onClick:()=>{u(!0),b(j.id),S({name:j.name||"",url:j.url||"",iconUrl:j.iconUrl||""})},children:"编辑"}),a.jsx("button",{className:"px-2 py-1 text-xs rounded bg-destructive text-destructive-foreground hover:opacity-90",onClick:()=>f==null?void 0:f(j.id),children:"删除"})]})]},j.id)),((l==null?void 0:l.length)??0)===0&&a.jsxs("div",{className:"flex flex-col items-center justify-center py-10 text-center",children:[a.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用,点击上方按钮添加。"})]})]})]}):a.jsxs("div",{className:"grid grid-cols-3 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[l==null?void 0:l.map(j=>{const F=p.current.has(j.id);return a.jsxs("div",{className:"relative group/item",children:[a.jsxs("button",{className:"w-full flex flex-col items-center space-y-2 p-2 rounded-lg transition-all hover:bg-muted",onClick:()=>T(j),title:j.url||"",children:[a.jsx("div",{className:`relative w-14 h-14 rounded-full flex items-center justify-center overflow-hidden transition-all ${F?"ring-2 ring-green-500 ring-offset-2 ring-offset-background scale-105":"bg-gradient-to-br from-blue-500/20 to-purple-500/20 group-hover/item:scale-105"}`,children:j.iconUrl?a.jsx("img",{src:j.iconUrl,alt:j.name,className:"w-full h-full object-cover"}):a.jsx("div",{className:"w-full h-full bg-gradient-to-br from-blue-500 to-purple-500 flex items-center justify-center",children:a.jsx("span",{className:"text-white text-lg font-bold",children:j.name.charAt(0).toUpperCase()})})}),a.jsx("div",{className:"text-xs font-medium text-foreground truncate max-w-full",children:j.name}),j.url&&a.jsx("div",{className:"text-[10px] text-muted-foreground truncate max-w-full",children:j.url})]}),F&&a.jsx("button",{onClick:O=>{O.stopPropagation(),_(j.id)},className:"absolute top-0 left-0 w-4 h-4 bg-red-500 hover:bg-red-600 rounded-full flex items-center justify-center opacity-0 group-hover/item:opacity-100 transition-opacity z-10",title:"关闭",children:a.jsx("svg",{className:"w-3 h-3 text-white",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:3,d:"M6 18L18 6M6 6l12 12"})})})]},j.id)}),((l==null?void 0:l.length)??0)===0&&a.jsxs("div",{className:"col-span-full flex flex-col items-center justify-center py-10 text-center",children:[a.jsx("svg",{className:"w-16 h-16 text-muted-foreground/30 mb-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,d:"M20 7l-8-4-8 4m16 0l-8 4m8-4v10l-8 4m0-10L4 7m8 4v10M4 7v10l8 4"})}),a.jsx("div",{className:"text-sm text-muted-foreground mb-2",children:"暂无应用"}),a.jsx("button",{onClick:()=>h(!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:o=!0,showAiModelManager:i=!0,showSystemContextEditor:l=!0,showAgentManager:c=!0,onApplicationSelect:d})=>{const m=I.useMemo(()=>{if(e)return e;if(t)return`http://localhost:${t}/api`},[e,t]),f=I.useMemo(()=>{if(m)return new Xt(m)},[m]);return a.jsx(Of,{userId:n,projectId:s,customApiClient:f,children:a.jsx(Ng,{className:r,showMcpManager:o,showAiModelManager:i,showSystemContextEditor:l,showAgentManager:c,onApplicationSelect:d})})},Ng=({className:r,showMcpManager:e,showAiModelManager:t,showSystemContextEditor:n,showAgentManager:s,onApplicationSelect:o})=>{const i=Tl(),{currentSession:l,messages:c,isLoading:d,isStreaming:m,hasMoreMessages:f,error:p,loadSessions:y,sendMessage:h,clearError:x,aiModelConfigs:u,selectedModelId:g,setSelectedModel:b,loadAiModelConfigs:w,agents:S,selectedAgentId:v,setSelectedAgent:C,loadAgents:_,abortCurrentConversation:T,loadMoreMessages:N}=i(),P=I.useRef(null),[R,j]=I.useState(!1),[F,O]=I.useState(!1),[z,H]=I.useState(!1),[E,L]=I.useState(!1),[U,$]=I.useState(!1),[D,B]=I.useState(!1);I.useEffect(()=>{(window.__standaloneChatInterfaceDidInit__??!1)||(window.__standaloneChatInterfaceDidInit__=!0,y(),w(),_())},[y,w,_]),I.useEffect(()=>{P.current&&P.current.scrollIntoView({behavior:"smooth"})},[c,m]);const X=async(M,K)=>{try{await h(M,K)}catch(A){console.error("Failed to send message:",A)}};return a.jsxs("div",{className:Ne("flex flex-col h-screen bg-background text-foreground",r),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("button",{onClick:()=>j(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),l&&a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:l.title})})]}),a.jsxs("div",{className:"flex items-center gap-2",children:[o&&a.jsx("button",{onClick:()=>{console.log("[StandaloneChat] open ApplicationsPanel button clicked"),B(!0)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:a.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[a.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),a.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),e&&a.jsx("button",{onClick:()=>O(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP服务管理",children:a.jsxs("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:[a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.594 3.94c.09-.542.56-.94 1.11-.94h2.593c.55 0 1.02.398 1.11.94l.213 1.281c.063.374.313.686.645.87.074.04.147.083.22.127.324.196.72.257 1.075.124l1.217-.456a1.125 1.125 0 011.37.49l1.296 2.247a1.125 1.125 0 01-.26 1.431l-1.003.827c-.293.24-.438.613-.431.992a6.759 6.759 0 010 .255c-.007.378.138.75.43.99l1.005.828c.424.35.534.954.26 1.43l-1.298 2.247a1.125 1.125 0 01-1.369.491l-1.217-.456c-.355-.133-.75-.072-1.076.124a6.57 6.57 0 01-.22.128c-.331.183-.581.495-.644.869l-.213 1.28c-.09.543-.56.941-1.11.941h-2.594c-.55 0-1.02-.398-1.11-.94l-.213-1.281c-.062-.374-.312-.686-.644-.87a6.52 6.52 0 01-.22-.127c-.325-.196-.72-.257-1.076-.124l-1.217.456a1.125 1.125 0 01-1.369-.49l-1.297-2.247a1.125 1.125 0 01.26-1.431l1.004-.827c.292-.24.437-.613.43-.992a6.932 6.932 0 010-.255c.007-.378-.138-.75-.43-.99l-1.004-.828a1.125 1.125 0 01-.26-1.43l1.297-2.247a1.125 1.125 0 011.37-.491l1.216.456c.356.133.751.072 1.076-.124.072-.044.146-.087.22-.128.332-.183.582-.495.644-.869l.214-1.281z"}),a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]})}),t&&a.jsx("button",{onClick:()=>H(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI配置管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9.813 15.904L9 18.75l-.813-2.846a4.5 4.5 0 00-3.09-3.09L2.25 12l2.846-.813a4.5 4.5 0 003.09-3.09L9 5.25l.813 2.846a4.5 4.5 0 003.09 3.09L15.75 12l-2.846.813a4.5 4.5 0 00-3.09 3.09zM18.259 8.715L18 9.75l-.259-1.035a3.375 3.375 0 00-2.455-2.456L14.25 6l1.036-.259a3.375 3.375 0 002.455-2.456L18 2.25l.259 1.035a3.375 3.375 0 002.456 2.456L21.75 6l-1.035.259a3.375 3.375 0 00-2.456 2.456zM16.894 20.567L16.5 21.75l-.394-1.183a2.25 2.25 0 00-1.423-1.423L13.5 18.75l1.183-.394a2.25 2.25 0 001.423-1.423l.394-1.183.394 1.183a2.25 2.25 0 001.423 1.423l1.183.394-1.183.394a2.25 2.25 0 00-1.423 1.423z"})})}),n&&a.jsx("button",{onClick:()=>L(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"System Prompt编辑器",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M19.5 14.25v-2.625a3.375 3.375 0 00-3.375-3.375h-1.5A1.125 1.125 0 0113.5 7.125v-1.5a3.375 3.375 0 00-3.375-3.375H8.25m0 12.75h7.5m-7.5 3H12M10.5 2.25H5.625c-.621 0-1.125.504-1.125 1.125v17.25c0 .621.504 1.125 1.125 1.125h12.75c.621 0 1.125-.504 1.125-1.125V11.25a9 9 0 00-9-9z"})})}),s&&a.jsx("button",{onClick:()=>$(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M9 12h6M9 16h6M6 8h12a2 2 0 012 2v8a2 2 0 01-2 2H6a2 2 0 01-2-2v-8a2 2 0 012-2z"})})}),a.jsx(uo,{})]})]}),p&&a.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:a.jsxs("div",{className:"flex items中心 justify-between",children:[a.jsx("p",{className:"text-sm text-destructive",children:p}),a.jsx("button",{onClick:x,className:"text-destructive hover:text-destructive/80 transition-colors",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),a.jsx("div",{className:"flex-1 flex overflow-hidden",children:a.jsxs("div",{className:"flex-1 overflow-hidden",children:[l?a.jsx(io,{messages:c,isLoading:d,isStreaming:m,hasMore:f,onLoadMore:()=>l&&N(l.id)}):a.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:a.jsxs("div",{className:"text-center",children:[a.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 opacity-50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})}),a.jsx("p",{className:"text-lg mb-2",children:"欢迎使用AI聊天助手"}),a.jsx("p",{className:"text-sm",children:"点击左上角按钮创建新会话开始对话"})]})}),a.jsx("div",{ref:P})]})}),l&&a.jsx(lo,{onSend:X,onStop:T,disabled:d||m,isStreaming:m,selectedModelId:g,availableModels:u,onModelChange:b,showModelSelector:!0,selectedAgentId:v,availableAgents:S,onAgentChange:C}),a.jsx(co,{isOpen:R,onClose:()=>j(!1),store:i}),a.jsx(sc,{isOpen:D,onClose:()=>B(!1),title:"应用列表",layout:"modal",onApplicationSelect:o}),F&&a.jsx(fo,{onClose:()=>O(!1),store:i}),z&&a.jsx(ho,{onClose:()=>H(!1),store:i}),s&&U&&a.jsx(nc,{onClose:()=>$(!1),store:i}),E&&a.jsx(mo,{onClose:()=>L(!1),store:i})]})};class Mg{constructor(e,t,n,s,o=!0,i=!0,l=!0,c=!0,d){W(this,"userId");W(this,"projectId");W(this,"configUrl");W(this,"apiClient");W(this,"store");W(this,"className");W(this,"showMcpManager");W(this,"showAiModelManager");W(this,"showSystemContextEditor");W(this,"showAgentManager");W(this,"onApplicationSelect");this.userId=e,this.projectId=t,this.configUrl=n||"/api",this.className=s,this.showMcpManager=o,this.showAiModelManager=i,this.showSystemContextEditor=l,this.showAgentManager=c,this.onApplicationSelect=d,console.log("🔧 AiChat Constructor - configUrl:",this.configUrl),console.log("🔧 AiChat Constructor - Module Controls:",{showMcpManager:this.showMcpManager,showAiModelManager:this.showAiModelManager,showSystemContextEditor:this.showSystemContextEditor,showAgentManager:this.showAgentManager,hasApplicationSelectCallback:!!this.onApplicationSelect}),this.apiClient=new Xt(this.configUrl),this.store=zr(this.apiClient,{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl})}render(){return I.createElement(Eg,{className:this.className,userId:this.userId,projectId:this.projectId,configUrl:this.configUrl,showMcpManager:this.showMcpManager,showAiModelManager:this.showAiModelManager,showSystemContextEditor:this.showSystemContextEditor,showAgentManager:this.showAgentManager,onApplicationSelect:this.onApplicationSelect})}getConfig(){return{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl,className:this.className,showMcpManager:this.showMcpManager,showAiModelManager:this.showAiModelManager,showSystemContextEditor:this.showSystemContextEditor,showAgentManager:this.showAgentManager,onApplicationSelect:this.onApplicationSelect}}updateConfig(e){e.userId&&(this.userId=e.userId),e.projectId&&(this.projectId=e.projectId),e.configUrl&&(this.configUrl=e.configUrl,this.apiClient=new Xt(this.configUrl),this.store=zr(this.apiClient,{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl})),e.className!==void 0&&(this.className=e.className),e.showMcpManager!==void 0&&(this.showMcpManager=e.showMcpManager),e.showAiModelManager!==void 0&&(this.showAiModelManager=e.showAiModelManager),e.showSystemContextEditor!==void 0&&(this.showSystemContextEditor=e.showSystemContextEditor),e.showAgentManager!==void 0&&(this.showAgentManager=e.showAgentManager),e.onApplicationSelect!==void 0&&(this.onApplicationSelect=e.onApplicationSelect)}getStore(){return this.store}getApiClient(){return this.apiClient}getSelectedApplication(){var s;const e=this.store.getState(),t=e.selectedApplicationId;if(console.log("[AiChat] getSelectedApplication called:",{id:t,applicationsCount:(s=e.applications)==null?void 0:s.length}),!t)return null;const n=e.applications.find(o=>o.id===t)||null;return console.log("[AiChat] getSelectedApplication result:",n),n}getSelectedApplicationUrl(){const e=this.getSelectedApplication();return e?e.url:null}subscribeSelectedApplication(e){console.log("[AiChat] subscribeSelectedApplication: 设置订阅"),console.log("[AiChat] store 对象:",this.store),console.log("[AiChat] store.subscribe 类型:",typeof this.store.subscribe);let t=this.store.getState().selectedApplicationId;console.log("[AiChat] 初始 previousId:",t);const n=this.store.subscribe(s=>{const o=s.selectedApplicationId;if(console.log("[AiChat] store.subscribe 被触发, currentId:",o,"previousId:",t),o!==t){console.log("[AiChat] selectedApplicationId 变化检测到:",{old:t,new:o}),t=o;const i=this.getSelectedApplication();console.log("[AiChat] 准备调用 listener,app:",i),e(i)}});return console.log("[AiChat] 首次调用 listener"),e(this.getSelectedApplication()),()=>{console.log("[AiChat] 取消订阅"),n()}}}const Eg=({className:r,userId:e,projectId:t,configUrl:n,showMcpManager:s,showAiModelManager:o,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:c})=>a.jsx(go,{className:r,apiBaseUrl:n,userId:e,projectId:t,showMcpManager:s,showAiModelManager:o,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:c}),Ig=({className:r,onMessageSend:e,customRenderer:t})=>{const{currentSession:n,messages:s,isLoading:o,isStreaming:i,hasMoreMessages:l,error:c,loadSessions:d,loadMoreMessages:m,sendMessage:f,clearError:p,aiModelConfigs:y,selectedModelId:h,setSelectedModel:x,loadAiModelConfigs:u,agents:g,selectedAgentId:b,setSelectedAgent:w,loadAgents:S,abortCurrentConversation:v}=ut(),C=I.useRef(null),[_,T]=I.useState(!1),[N,P]=I.useState(!1),[R,j]=I.useState(!1),[F,O]=I.useState(!1),[z,H]=I.useState(!1),[E,L]=I.useState(!1);I.useEffect(()=>{(window.__chatInterfaceDidInit__??!1)||(window.__chatInterfaceDidInit__=!0,d(),u(),S())},[d,u,S]),I.useEffect(()=>{C.current&&C.current.scrollIntoView({behavior:"smooth"})},[s,i]);const U=async($,D)=>{try{await f($,D),e==null||e($,[])}catch(B){console.error("Failed to send message:",B)}};return a.jsxs("div",{className:Ne("flex flex-col h-screen bg-background text-foreground",r),children:[a.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[a.jsxs("div",{className:"flex items-center space-x-3",children:[a.jsx("button",{onClick:()=>T(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),n&&a.jsx("div",{className:"flex-1 min-w-0",children:a.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:n.title})})]}),a.jsxs("div",{className:"flex items-center space-x-2",children:[a.jsx("button",{onClick:()=>L(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开应用列表",children:a.jsxs("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:[a.jsx("path",{d:"M4 5h6v14H4z",strokeWidth:"2"}),a.jsx("path",{d:"M12 5h8v14h-8z",strokeWidth:"2"})]})}),a.jsx("button",{onClick:()=>P(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP 服务器管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"})})}),a.jsx("button",{onClick:()=>H(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"智能体管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6M9 16h6M6 8h12a2 2 0 012 2v8a2 2 0 01-2 2H6a2 2 0 01-2-2v-8a2 2 0 012-2z"})})}),a.jsx("button",{onClick:()=>j(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI 模型管理",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})})}),a.jsx("button",{onClick:()=>O(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"系统上下文设置",children:a.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})}),a.jsx(uo,{})]})]}),c&&a.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:a.jsxs("div",{className:"flex items-center justify-between",children:[a.jsx("p",{className:"text-sm text-destructive",children:c}),a.jsx("button",{onClick:p,className:"text-destructive hover:text-destructive/80 transition-colors",children:a.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),a.jsx("div",{className:"flex flex-1 overflow-hidden",children:a.jsxs("div",{className:"flex-1 overflow-hidden",children:[n?a.jsx(io,{messages:s,isLoading:o,isStreaming:i,hasMore:l,onLoadMore:()=>n&&m(n.id),customRenderer:t}):a.jsx("div",{className:"flex items-center justify-center h-full",children:a.jsxs("div",{className:"text-center",children:[a.jsx("h2",{className:"text-xl font-semibold text-muted-foreground mb-2",children:"欢迎使用 AI 聊天"}),a.jsx("p",{className:"text-muted-foreground mb-4",children:"点击左上角按钮选择会话,或创建新的会话开始对话"}),a.jsx("button",{onClick:()=>T(!0),className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"打开会话列表"})]})}),a.jsx("div",{ref:C})]})}),n&&a.jsx("div",{className:"border-t border-border",children:a.jsx(lo,{onSend:U,onStop:v,disabled:o,isStreaming:i,placeholder:"输入消息...",showModelSelector:!0,selectedModelId:h,availableModels:y,onModelChange:x,selectedAgentId:b,availableAgents:g,onAgentChange:w})}),a.jsx(co,{isOpen:_,onClose:()=>T(!1)}),N&&a.jsx(fo,{onClose:()=>P(!1)}),z&&a.jsx(nc,{onClose:()=>H(!1)}),R&&a.jsx(ho,{onClose:()=>j(!1)}),F&&a.jsx(mo,{onClose:()=>O(!1)}),a.jsx(sc,{isOpen:E,onClose:()=>L(!1),title:"应用列表",layout:"modal"})]})};class Tg extends I.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("ErrorBoundary caught an error:",e,t)}render(){var e;return this.state.hasError?this.props.fallback?this.props.fallback:a.jsx("div",{className:"flex items-center justify-center h-full p-8",children:a.jsxs("div",{className:"text-center space-y-4",children:[a.jsx("div",{className:"w-16 h-16 mx-auto bg-destructive/10 rounded-full flex items-center justify-center",children:a.jsx("svg",{className:"w-8 h-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:a.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"})})}),a.jsxs("div",{children:[a.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Something went wrong"}),a.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),a.jsx("button",{onClick:()=>this.setState({hasError:!1,error:void 0}),className:"mt-4 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"Try again"})]})]})}):this.props.children}}const Pg="1.0.0";exports.AiChat=Mg;exports.AiModelManager=ho;exports.AiServer=Ml;exports.ApiClient=Xt;exports.AppError=Qm;exports.AttachmentRenderer=Vl;exports.ChatIcon=ec;exports.ChatInterface=Ig;exports.ChatService=Il;exports.CheckIcon=rg;exports.ChevronDownIcon=ag;exports.CopyIcon=sg;exports.DatabaseService=bs;exports.DotsVerticalIcon=Yl;exports.ErrorBoundary=Tg;exports.InputArea=lo;exports.LoadingSpinner=Xl;exports.MarkdownRenderer=_t;exports.McpManager=fo;exports.MessageItem=Gl;exports.MessageList=io;exports.MessageManager=El;exports.PencilIcon=Ql;exports.PlayIcon=og;exports.PlusIcon=Kl;exports.SessionList=co;exports.StandaloneChatInterface=go;exports.SystemContextEditor=mo;exports.ThemeToggle=uo;exports.ToolCallRenderer=gs;exports.TrashIcon=Zl;exports.XIcon=ng;exports.apiClient=re;exports.cleanHtmlContent=Bm;exports.cn=Ne;exports.conversationsApi=Ar;exports.copyToClipboard=Gm;exports.debounce=qm;exports.deepClone=ms;exports.default=go;exports.downloadFile=Xm;exports.formatDate=Dm;exports.formatDateTime=Fm;exports.formatFileSize=zl;exports.formatRelativeTime=Lm;exports.formatTime=ql;exports.generateId=$m;exports.generateRandomColor=Vm;exports.getFileExtension=Jl;exports.getOS=Ym;exports.isImageFile=Jm;exports.isMobile=Km;exports.isValidEmail=Wm;exports.isValidUrl=Hm;exports.retry=Zm;exports.storage=eg;exports.throttle=zm;exports.truncateText=Um;exports.useChatStore=dt;exports.useTheme=rc;exports.version=Pg;
119
+ `;return j.forEach(I=>{const M=_[I];let O;typeof M=="string"?O=M.replace(/\n/g,"<br>").replace(/\|/g,"\\|"):Array.isArray(M)?O=`[${M.join(", ")}]`.replace(/\|/g,"\\|"):O=JSON.stringify(M).replace(/\|/g,"\\|"),v+=`| ${I} | ${O} |
120
+ `}),v})(),c=(()=>{if(!d)return null;if(i&&typeof i=="object")return i;if(typeof i=="string")try{const _=JSON.parse(i);if(_&&typeof _=="object")return _}catch{return null}return null})(),p=!!(c&&typeof c=="object"),y=_=>{if(_===null)return"null";if(Array.isArray(_)){if(_.length===0)return"array []";const j=_[0],v=y(j);return v==="object"?"object []":`${v}[]`}switch(typeof _){case"string":return"string";case"number":return Number.isInteger(_)?"integer":"number";case"boolean":return"boolean";case"object":return"object";default:return typeof _}},b=(_,j="",v="")=>{const I=[];if(_==null)return I;if(Array.isArray(_)){const M={path:v||j||"list",name:j||"list",type:y(_),value:_,children:_.map((O,L)=>{const C=`${v||j||"list"}[${L}]`,H=y(O);return{path:C,name:`[${L}]`,type:H,value:O,children:H==="object"||Array.isArray(O)?b(O,`[${L}]`,C):[]}})};return I.push(M),I}return typeof _=="object"&&Object.keys(_).forEach(M=>{const O=_[M],L=v?`${v}.${M}`:M,C=y(O),H=C==="object"||Array.isArray(O)?b(O,M,L):[];I.push({path:L,name:M,type:C,value:O,children:H})}),I},S=({data:_})=>{const j=Array.isArray(_)?b(_,"list","list"):b(_,"",""),[v,I]=T.useState(()=>new Set(j.filter(C=>C.children.length>0).map(C=>C.path))),M=C=>{I(H=>{const D=new Set(H);return D.has(C)?D.delete(C):D.add(C),D})},O=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,H)=>C.map(D=>{const V=D.children&&D.children.length>0,X=v.has(D.path),F=V?X?"▾":"▸":"",Y=O(D.value);return o.jsxs(T.Fragment,{children:[o.jsxs("tr",{children:[o.jsxs("td",{style:{paddingLeft:H*16},children:[V?o.jsx("button",{type:"button",onClick:()=>M(D.path),className:"mr-2 text-gray-600 dark:text-gray-300 hover:text-black dark:hover:text-white","aria-label":X?"收起":"展开",children:F}):o.jsx("span",{className:"mr-4"}),D.name]}),o.jsx("td",{style:{whiteSpace:"normal",wordBreak:"break-word"},children:Y})]}),V&&X&&L(D.children,H+1)]},D.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(gt,{content:m})})}),d&&o.jsxs("div",{children:[o.jsx("div",{className:"details-title",children:"结果:"}),p?o.jsx(S,{data:c}):o.jsx(gt,{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 _=new Date(r.createdAt);return isNaN(_.getTime())?"时间未知":_.toLocaleString()})()]})]})]})},tp=({message:r,isLast:e=!1,isStreaming:t=!1,onEdit:n,onDelete:s,allMessages:a=[],customRenderer:i})=>{var v,I,M,O,L,C,H,D,V,X;console.log("🚀🚀🚀 MessageItem 组件被调用!消息ID:",r.id,"角色:",r.role),console.log("🚀🚀🚀 完整消息对象:",r);const[l,d]=T.useState(!1),[u,g]=T.useState(r.content),h=(F,Y)=>{navigator.clipboard.writeText(F).then(()=>{console.log("代码已复制到剪贴板:",{code:F,language:Y})}).catch(ae=>{console.error("复制失败:",ae)})},[x,w]=T.useState(!1),m=r.role==="user",f=r.role==="assistant",c=r.role==="system",p=r.role==="tool";if(p)return null;if(i!=null&&i.renderMessage)return o.jsx("div",{children:i.renderMessage(r)});const y=()=>{n&&u.trim()!==r.content&&n(r.id,u.trim()),d(!1)},b=()=>{g(r.content),d(!1)},S=async()=>{try{await navigator.clipboard.writeText(r.content)}catch(F){console.error("Failed to copy message:",F)}},_=((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":(M=r.metadata)==null?void 0:M.toolCalls,最终toolCalls长度:j.length,消息ID:r.id,contentSegments:(O=r.metadata)==null?void 0:O.contentSegments,contentSegments长度:((C=(L=r.metadata)==null?void 0:L.contentSegments)==null?void 0:C.length)||0}),o.jsxs("div",{className:Ee("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",p&&"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:Ee("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",p&&"bg-blue-500 text-white"),children:m?"U":p?"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":p?"Tool Result":"System"}),o.jsx("span",{className:"text-xs text-muted-foreground",children:gc(r.createdAt)}),((H=r.metadata)==null?void 0:H.model)&&o.jsx("span",{className:"text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded",children:r.metadata.model})]}),((D=r.metadata)==null?void 0:D.type)==="session_summary"&&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((V=r.metadata)==null?void 0:V.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(gt,{content:(r.rawContent||((X=r.metadata)==null?void 0:X.summary)||"").toString(),isStreaming:!1,onApplyCode:()=>{}})})]})]}),_.length>0&&o.jsx("div",{className:"mb-3 space-y-2",children:_.map(F=>o.jsx(yc,{attachment:F,isUser:m,customRenderer:i==null?void 0:i.renderAttachment},F.id))}),l?o.jsxs("div",{className:"space-y-2",children:[o.jsx("textarea",{value:u,onChange:F=>g(F.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:y,className:"px-3 py-1 text-sm bg-primary text-primary-foreground rounded hover:bg-primary/90",children:"Save"}),o.jsx("button",{onClick:b,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 W;const F=((W=r.metadata)==null?void 0:W.contentSegments)||[],Y=r.content&&r.content.trim().length>0,ae=t&&e;return F.length>0?(console.log("🎨 使用分段渲染,分段数量:",F.length),console.log("🎨 分段详情:",F),o.jsx("div",{className:"space-y-0.5",children:F.map((J,ee)=>{if(console.log(`🎨 渲染分段 ${ee}:`,J),J.type==="text")return console.log(`🎨 渲染文本分段 ${ee}:`,J.content),o.jsx("div",{className:"prose prose-sm max-w-none",children:o.jsx(gt,{content:J.content,isStreaming:ae&&ee===F.length-1,onApplyCode:h})},`segment-${ee}`);if(J.type==="tool_call"){console.log(`🎨 渲染工具调用分段 ${ee}:`,J);const U=j.find(N=>N.id===J.toolCallId);if(console.log(`🎨 查找工具调用 ${J.toolCallId}:`,U),U)return console.log("🎨 找到工具调用,开始渲染:",U),o.jsx("div",{children:o.jsx(As,{toolCall:U,allMessages:a})},`tool-${U.id}`);console.log(`🎨 ❌ 未找到工具调用 ${J.toolCallId}`)}else if(J.type==="thinking")return console.log(`🎨 渲染思考分段 ${ee}:`,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(gt,{content:J.content||"",isStreaming:ae&&ee===F.length-1,onApplyCode:h,className:"thinking not-prose"})})]},`thinking-${ee}`);return null})})):(console.log("🎨 使用传统渲染方式"),console.log("🎨 hasContent:",Y),console.log("🎨 toolCalls.length:",j.length),o.jsxs("div",{className:"space-y-0.5",children:[Y&&o.jsx("div",{className:"prose prose-sm max-w-none",children:o.jsx(gt,{content:r.content,isStreaming:ae,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(As,{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]})]}),x&&!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:S,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"})})})]})]})},bc=T.memo(tp,(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)),wc=({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:Ee("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..."})})},bo=({messages:r,isLoading:e=!1,isStreaming:t=!1,hasMore:n=!1,onLoadMore:s,onMessageEdit:a,onMessageDelete:i,customRenderer:l})=>{const d=T.useRef(null),u=T.useRef(null),[g,h]=T.useState(!0),[x,w]=T.useState(!0),m=()=>{const y=d.current;return y?y.scrollHeight-y.scrollTop-y.clientHeight<=40:!0},f=(y=!0)=>{var b;(b=u.current)==null||b.scrollIntoView({behavior:y?"smooth":"auto"})};T.useEffect(()=>{t&&g&&f(!0)},[r,t,g]),T.useEffect(()=>{w(m())},[r,t]),T.useEffect(()=>{t&&x&&h(!0),t||h(!1)},[t,x]);const c=()=>{const y=m();w(y),y||h(!1)},p=()=>{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(y=>{var b;return!((b=y==null?void 0:y.metadata)!=null&&b.hidden)}).map((y,b,S)=>o.jsx(bc,{message:y,isLast:b===S.length-1,isStreaming:t&&b===S.length-1,onEdit:a,onDelete:i,allMessages:r,customRenderer:l},y.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(wc,{size:"sm"}),o.jsx("span",{className:"text-sm text-muted-foreground",children:"AI is thinking..."})]})}),o.jsx("div",{ref:u})]}),!x&&o.jsxs("button",{type:"button","aria-label":"回到底部",title:"回到底部",onClick:p,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:"回到底部"})]})]})},wo=({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:x=null,availableAgents:w=[],onAgentChange:m})=>{const[f,c]=T.useState(""),[p,y]=T.useState([]),[b,S]=T.useState(null),[_,j]=T.useState(!1),v=T.useRef(null),I=T.useRef(null),[M,O]=T.useState(!1),L=T.useRef(null),C=T.useRef(0),H=20,D=20*1024*1024,V=50*1024*1024,X=x?(w||[]).find(B=>B.id===x):null,F=u?(g||[]).find(B=>B.id===u):null,Y=g&&g.length>0||w&&w.length>0,ae=X?`Agent: ${X.name}`:F?`Model: ${F.name}`:"选择 AI";T.useEffect(()=>{console.log("InputArea - isStreaming 状态变化:",{isStreaming:n,disabled:t,onStop:!!e,timestamp:new Date().toISOString()})},[n,t,e]);const W=T.useCallback(()=>{const B=v.current;if(B){B.style.height="auto";const se=B.scrollHeight,we=200;B.style.height=`${Math.min(se,we)}px`}},[]);T.useEffect(()=>{if(!M)return;const B=se=>{L.current&&(L.current.contains(se.target)||O(!1))};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[M]),T.useEffect(()=>{if(!i||t)return;const B=fe=>{const Ue=fe.dataTransfer;if(!Ue)return!1;try{if(Ue.types&&Array.from(Ue.types).includes("Files")||Ue.files&&Ue.files.length>0)return!0}catch{}return!1},se=fe=>{if(B(fe)){fe.preventDefault(),fe.stopPropagation(),j(!0);try{fe.dataTransfer.dropEffect="copy"}catch{}}},we=fe=>{B(fe)&&(fe.preventDefault(),fe.stopPropagation(),C.current+=1,j(!0))},le=fe=>{B(fe)&&(fe.preventDefault(),fe.stopPropagation(),C.current=Math.max(0,C.current-1),C.current===0&&j(!1))},Oe=fe=>{if(!B(fe))return;fe.preventDefault(),fe.stopPropagation(),C.current=0,j(!1);const Ue=fe.dataTransfer,ke=Array.from(Ue.files||[]);ke.length>0&&y(Ht=>[...Ht,...ke])};return window.addEventListener("dragover",se),window.addEventListener("dragenter",we),window.addEventListener("dragleave",le),window.addEventListener("drop",Oe),()=>{window.removeEventListener("dragover",se),window.removeEventListener("dragenter",we),window.removeEventListener("dragleave",le),window.removeEventListener("drop",Oe)}},[i,t]);const J=B=>{const se=B.target.value;se.length<=a&&(c(se),W())},ee=T.useCallback(B=>{!B||B.length===0||y(se=>{const we=se.reduce((ke,Ht)=>ke+((Ht==null?void 0:Ht.size)||0),0),le=[],Oe=[];let fe=we,Ue=se.length;for(const ke of B)if(ke){if(ke.size>D){le.push(`${ke.name} 超过单文件上限(${ne(D)})`);continue}if(Ue+1>H){le.push(`${ke.name} 超过数量上限(${H} 个)`);continue}if(fe+ke.size>V){le.push(`${ke.name} 导致总大小超限(${ne(V)})`);continue}Oe.push(ke),fe+=ke.size,Ue+=1}return le.length>0?S(`部分文件未添加:${le.join(";")}。限制:单文件≤${ne(D)},总计≤${ne(V)},最多 ${H} 个。`):S(null),Oe.length>0?[...se,...Oe]:se})},[]),U=B=>{B.key==="Enter"&&!B.shiftKey&&(B.preventDefault(),$())},N=B=>{try{if(!i||t)return;const se=B.clipboardData,we=[];if(se&&se.items&&se.items.length>0)for(let le=0;le<se.items.length;le++){const Oe=se.items[le];if(Oe.kind==="file"){const fe=Oe.getAsFile();fe&&fe.size>0&&we.push(fe)}}if(we.length===0&&se&&se.files&&se.files.length>0)for(let le=0;le<se.files.length;le++){const Oe=se.files[le];Oe&&Oe.size>0&&we.push(Oe)}we.length>0&&ee(we)}catch{}},$=()=>{const B=f.trim();if(!(!B&&p.length===0)&&!t){if(d&&!u&&!x){alert("请先选择一个模型或智能体");return}r(B,p),c(""),y([]),v.current&&(v.current.style.height="auto")}},A=B=>{const se=Array.from(B.target.files||[]);ee(se),I.current&&(I.current.value="")},k=B=>{y(se=>se.filter((we,le)=>le!==B))},P=B=>{B.preventDefault(),i&&!t&&j(!0)},R=B=>{B.preventDefault(),j(!1)},z=B=>{if(B.preventDefault(),j(!1),!i||t)return;const se=Array.from(B.dataTransfer.files);ee(se)},ne=B=>{if(B===0)return"0 Bytes";const se=1024,we=["Bytes","KB","MB","GB"],le=Math.floor(Math.log(B)/Math.log(se));return parseFloat((B/Math.pow(se,le)).toFixed(2))+" "+we[le]};return o.jsxs("div",{className:"border-t bg-background p-3 sm:p-4",children:[p.length>0&&o.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:p.map((B,se)=>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:B.name}),o.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",ne(B.size),")"]}),o.jsx("button",{onClick:()=>k(se),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"})})})]},se))}),b&&o.jsx("div",{className:"-mt-2 mb-3 text-xs text-destructive",children:b}),o.jsxs("div",{className:Ee("relative flex items-end gap-3 p-3 border rounded-lg transition-colors","focus-within:border-primary",_&&"border-primary bg-primary/5",t&&"opacity-50 cursor-not-allowed"),onDragOver:P,onDragLeave:R,onDrop:z,children:[d&&Y&&o.jsxs("div",{className:"absolute -top-3 left-3 z-10",ref:L,children:[o.jsxs("button",{type:"button",onClick:()=>O(B=>!B),disabled:t,className:Ee("px-2 py-0.5 rounded-full border bg-background text-xs shadow-sm","hover:bg-accent hover:text-accent-foreground transition-colors","disabled:opacity-50 disabled:cursor-not-allowed"),title:"选择模型或智能体",children:[ae,o.jsx("span",{className:"ml-1",children:"▾"})]}),M&&o.jsxs("div",{className:"absolute left-0 bottom-full mb-2 w-64 max-h-64 overflow-auto bg-popover text-popover-foreground border rounded-md shadow-lg",children:[w&&w.filter(B=>B.enabled).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-2 py-1 text-[11px] uppercase tracking-wide text-muted-foreground",children:"智能体"}),(w||[]).filter(B=>B.enabled).map(B=>o.jsxs("button",{className:Ee("w-full text-left px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground",x===B.id&&"bg-accent/40"),onClick:()=>{m==null||m(B.id),h==null||h(null),O(!1)},children:["[Agent] ",B.name]},B.id))]}),g&&g.filter(B=>B.enabled).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"px-2 py-1 text-[11px] uppercase tracking-wide text-muted-foreground border-t",children:"模型"}),(g||[]).filter(B=>B.enabled).map(B=>o.jsxs("button",{className:Ee("w-full text-left px-3 py-1.5 text-sm hover:bg-accent hover:text-accent-foreground",u===B.id&&"bg-accent/40"),onClick:()=>{h==null||h(B.id),m==null||m(null),O(!1)},children:[B.name," (",B.model_name,")"]},B.id))]}),o.jsx("div",{className:"border-t"}),o.jsx("button",{className:"w-full text-left px-3 py-1.5 text-sm text-muted-foreground hover:bg-accent hover:text-accent-foreground",onClick:()=>{h==null||h(null),m==null||m(null),O(!1)},children:"清除选择"})]})]}),i&&o.jsx("button",{onClick:()=>{var B;return(B=I.current)==null?void 0:B.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:f,onChange:J,onKeyDown:U,onPaste:N,placeholder:s,disabled:t,className:Ee("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-[11px] sm:text-xs text-muted-foreground tabular-nums",children:[f.length,"/",a]}),n?o.jsx("button",{onClick:()=>{console.log("停止按钮被点击",{onStop:e,disabled:t}),e&&e()},disabled:!1,className:Ee("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:$,disabled:t||n||!f.trim()&&p.length===0,className:Ee("flex-shrink-0 p-2 rounded-md transition-colors","disabled:opacity-50 disabled:cursor-not-allowed",(f.trim()||p.length>0)&&!t&&!n?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground"),title:d&&!u&&!x?"请先选择模型或智能体":"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:A,className:"hidden"})]}),_&&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"}),o.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["单文件≤",ne(D),",总计≤",ne(V),",最多 ",H," 个"]})]})})]})},vc=({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"})}),_c=({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"})}),Sc=({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"})}),Cc=({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"})}),rp=({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"})}),np=({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"})}),jc=({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"})}),sp=({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"})}),op=({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"})}),ap=({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"})}),Mn=({isOpen:r,title:e,message:t,confirmText:n="确认",cancelText:s="取消",onConfirm:a,onCancel:i,type:l="danger"})=>{if(!r)return null;const d=()=>{switch(l){case"danger":return"bg-red-600 hover:bg-red-700 text-white";case"warning":return"bg-yellow-600 hover:bg-yellow-700 text-white";default:return"bg-blue-600 hover:bg-blue-700 text-white"}};return 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}),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,className:`flex-1 px-4 py-2 text-sm rounded-md transition-colors ${d()}`,children:n})]})]})})})},En=()=>{const[r,e]=T.useState({isOpen:!1,title:"",message:"",confirmText:"确认",cancelText:"取消",type:"danger"}),t=T.useCallback(i=>{e({isOpen:!0,title:i.title,message:i.message,confirmText:i.confirmText||"确认",cancelText:i.cancelText||"取消",type:i.type||"danger",onConfirm:i.onConfirm,onCancel:i.onCancel})},[]),n=T.useCallback(()=>{e(i=>({...i,isOpen:!1}))},[]),s=T.useCallback(()=>{var i;(i=r.onConfirm)==null||i.call(r),n()},[r.onConfirm,n]),a=T.useCallback(()=>{var i;(i=r.onCancel)==null||i.call(r),n()},[r.onCancel,n]);return{dialogState:r,showConfirmDialog:t,hideConfirmDialog:n,handleConfirm:s,handleCancel:a}},ip=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")},vo=({isOpen:r=!0,onClose:e,store:t})=>{let n=null;try{n=_t()}catch{}const s=t?t():n;if(!s)throw new Error("SessionList must be used within a ChatStoreProvider or receive a store prop");const{sessions:a,currentSession:i,createSession:l,selectSession:d,deleteSession:u,updateSession:g}=s,[h,x]=T.useState(null),[w,m]=T.useState(""),[f,c]=T.useState(!1),[p,y]=T.useState(!1),{dialogState:b,showConfirmDialog:S,handleConfirm:_,handleCancel:j}=En();T.useEffect(()=>{if(r)y(!0),requestAnimationFrame(()=>{c(!0)});else{c(!1);const D=setTimeout(()=>{y(!1)},300);return()=>clearTimeout(D)}},[r]);const v=async()=>{try{await l(),e==null||e()}catch(D){console.error("Failed to create session:",D)}},I=async D=>{try{await d(D),e==null||e()}catch(V){console.error("Failed to select session:",V)}},M=async D=>{const V=a.find(X=>X.id===D);S({title:"删除确认",message:`确定要删除会话 "${(V==null?void 0:V.title)||"Untitled"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{try{await u(D)}catch(X){console.error("Failed to delete session:",X)}}})},O=(D,V)=>{x(D),m(V)},L=async()=>{if(h&&w.trim())try{await g(h,{title:w.trim()}),x(null),m("")}catch(D){console.error("Failed to update session:",D)}},C=()=>{x(null),m("")},H=D=>{D.key==="Enter"?L():D.key==="Escape"&&C()};return p?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:`fixed inset-0 bg-black/50 backdrop-blur-sm z-40 transition-opacity duration-300 ${f?"opacity-100":"opacity-0"}`,onClick:e}),o.jsx("div",{className:`fixed left-0 top-0 h-full w-80 sm:w-96 bg-card z-50 transform transition-all duration-300 ease-in-out ${f?"translate-x-0":"-translate-x-full"} shadow-xl breathing-border`,children:o.jsxs("div",{className:"flex flex-col h-full",children:[o.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[o.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"会话列表"}),o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("button",{onClick:v,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"新建会话",children:o.jsx(vc,{className:"w-5 h-5"})}),e&&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:a.length===0?o.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-muted-foreground",children:[o.jsx(jc,{className:"w-12 h-12 mb-4 opacity-50"}),o.jsx("p",{className:"text-sm",children:"还没有会话"}),o.jsx("button",{onClick:v,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:a.map(D=>o.jsxs("div",{className:`group relative flex items-center p-3 rounded-lg cursor-pointer transition-colors ${(i==null?void 0:i.id)===D.id?"bg-accent border border-border":"hover:bg-accent/50"}`,onClick:()=>I(D.id),children:[o.jsx("div",{className:"flex-1 min-w-0",children:h===D.id?o.jsx("input",{type:"text",value:w,onChange:V=>m(V.target.value),onBlur:L,onKeyDown:H,className:"w-full px-2 py-1 text-sm bg-background border border-border rounded focus:outline-none focus:ring-2 focus:ring-ring",autoFocus:!0,onClick:V=>V.stopPropagation()}):o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-sm font-medium text-foreground truncate",children:D.title}),o.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:ip(D.updatedAt)})]})}),h!==D.id&&o.jsxs("div",{className:"relative",children:[o.jsx("button",{className:"p-1 text-muted-foreground hover:text-foreground opacity-0 group-hover:opacity-100 transition-opacity",onClick:V=>{V.stopPropagation();const X=V.currentTarget.nextElementSibling;X&&X.classList.toggle("hidden")},children:o.jsx(_c,{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:V=>{V.stopPropagation(),O(D.id,D.title);const X=V.currentTarget.closest(".absolute");X&&X.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-popover-foreground hover:bg-accent",children:[o.jsx(Sc,{className:"w-4 h-4 mr-2"}),"重命名"]}),o.jsxs("button",{onClick:V=>{V.stopPropagation(),M(D.id);const X=V.currentTarget.closest(".absolute");X&&X.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-destructive hover:bg-destructive/10",children:[o.jsx(Cc,{className:"w-4 h-4 mr-2"}),"删除"]})]})})]})]},D.id))})}),o.jsx(Mn,{isOpen:b.isOpen,title:b.title,message:b.message,confirmText:b.confirmText,cancelText:b.cancelText,type:b.type,onConfirm:_,onCancel:j})]})})]}):null},Ac=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",La=r=>r==="system"?Ac():r,Qn=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",lp=r=>{typeof window>"u"||localStorage.setItem("theme",r)},Nc=()=>{const[r,e]=T.useState(()=>$a()),[t,n]=T.useState(()=>La($a())),s=i=>{e(i),lp(i);const l=La(i);n(l),Qn(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 T.useEffect(()=>{if(r!=="system")return;const i=window.matchMedia("(prefers-color-scheme: dark)"),l=()=>{const d=Ac();n(d),Qn(d)};return i.addEventListener("change",l),()=>i.removeEventListener("change",l)},[r]),T.useEffect(()=>{Qn(t)},[t]),{theme:r,actualTheme:t,setTheme:s,toggleTheme:a}},_o=({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()})},cp={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},dp=()=>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"})}),Da=()=>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"})}),up=()=>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"})}),fp=({open:r,config:e,onClose:t})=>{const[n,s]=T.useState([]),[a,i]=T.useState(!1),[l,d]=T.useState(null),[u,g]=T.useState(null),[h,x]=T.useState(!1),[w,m]=T.useState({name:"",envJson:"",enabled:!1}),[f,c]=T.useState(null),[p,y]=T.useState({});if(T.useEffect(()=>{(async()=>{if(!(!r||!(e!=null&&e.id))){i(!0),d(null);try{const S=await ie.getMcpConfigProfiles(e.id);s(Array.isArray(S)?S:[])}catch(S){d((S==null?void 0:S.message)||"获取配置档案失败")}finally{i(!1)}}})()},[r,e==null?void 0:e.id]),!r)return null;try{const b={id:e==null?void 0:e.id,name:e==null?void 0:e.name,type:e==null?void 0:e.type,command:e==null?void 0:e.command,cwd:e==null?void 0:e.cwd,args:e==null?void 0:e.args};typeof window<"u"}catch{}return 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(dp,{}),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(Da,{})})]}),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 b=e.args;if(!b)return"—";if(Array.isArray(b))return b.map(S=>String(S)).join(", ");if(typeof b=="string"){try{const S=JSON.parse(b);if(Array.isArray(S))return S.map(_=>String(_)).join(", ")}catch{}return b}return String(b)})()})]})]})]}),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 b=await ie.getMcpConfigProfiles(e.id);s(Array.isArray(b)?b:[])}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 b;try{const S=await ie.getMcpConfigResource(e.id),_=S&&S.config||{};_&&typeof _=="object"&&(b=_)}catch{}m({name:`配置_${new Date().toLocaleString("zh-CN")}`,envJson:"",enabled:!1}),y(b||{}),g(null),x(!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(b=>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:b.name,children:b.name}),b.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 ie.activateMcpConfigProfile(e.id,b.id);const S=await ie.getMcpConfigProfiles(e.id);s(Array.isArray(S)?S:[])}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(b.id),m({name:b.name||"",envJson:(()=>{try{return JSON.stringify(b.env||{},null,2)}catch{return""}})(),enabled:!!b.enabled});const S=b.env||{},_={};Object.keys(S||{}).forEach(j=>{const v=S[j];if(typeof v=="string"){const I=v.trim();try{_[j]=JSON.parse(I)}catch{I.includes(",")?_[j]=I.split(",").map(M=>M.trim()).filter(Boolean):_[j]=I}}else _[j]=v}),y(_),x(!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(`确定删除配置档案 “${b.name}” 吗?`)))try{await ie.deleteMcpConfigProfile(e.id,b.id);const _=await ie.getMcpConfigProfiles(e.id);s(Array.isArray(_)?_:[])}catch(_){console.error("删除配置档案失败:",_)}},children:"删除"})]})]})},b.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:()=>{x(!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(up,{}),o.jsx("h3",{className:"text-base font-semibold text-foreground",children:u?"编辑配置档案":"新增配置档案"})]}),o.jsx("button",{onClick:()=>{x(!1),c(null)},className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(Da,{})})]}),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:b=>m({...w,name:b.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md"})]}),o.jsx("div",{children:p&&Object.keys(p).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(p).map(b=>{const S=p[b],_=typeof S,j=Array.isArray(S);return o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:b}),_==="boolean"?o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",checked:!!S,onChange:v=>y({...p,[b]: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(S)})]}):j?o.jsx("input",{type:"text",value:S.join(", "),onChange:v=>y({...p,[b]: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"}):_==="object"&&S!==null?o.jsx("textarea",{value:(()=>{try{return JSON.stringify(S,null,2)}catch{return String(S)}})(),onChange:v=>{try{const I=JSON.parse(v.target.value);y({...p,[b]:I})}catch{y({...p,[b]: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:_==="number"?"number":"text",value:S??"",onChange:v=>y({...p,[b]:_==="number"?Number(v.target.value):v.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},b)})})]})})]}),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:()=>{x(!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 b=null;if(p&&Object.keys(p).length>0)b=p;else{const j=(w.envJson||"").trim();if(j)try{const v=JSON.parse(j);v&&typeof v=="object"&&(b=v)}catch{throw new Error("env JSON 格式错误")}}let _=null;if(b&&typeof b=="object"){_={};for(const j of Object.keys(b)){const v=b[j];Array.isArray(v)?_[j]=v.join(","):typeof v=="boolean"||typeof v=="number"?_[j]=String(v):v==null?_[j]="":typeof v=="object"?_[j]=JSON.stringify(v):_[j]=String(v)}}if(u)if(await ie.updateMcpConfigProfile(e.id,u,{name:w.name,env:_,enabled:w.enabled})){const v=await ie.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[]),x(!1),g(null)}else throw new Error("更新失败");else{const j=await ie.createMcpConfigProfile(e.id,{name:w.name,env:_,enabled:w.enabled});if(j&&(j.id||j.success)){const v=await ie.getMcpConfigProfiles(e.id);s(Array.isArray(v)?v:[]),x(!1)}else throw new Error("创建失败")}}catch(b){c((b==null?void 0:b.message)||"保存失败")}},children:"保存"})]})]})]})})]})]})},hp={BASE_URL:"/",DEV:!1,MODE:"production",PROD:!0,SSR:!1},Fa=()=>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"})}),mp=()=>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"})}),gp=()=>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"})}),pp=()=>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"})}),xp=()=>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"})}),So=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=_t()}catch{t=vt()}const{mcpConfigs:n,updateMcpConfig:s,deleteMcpConfig:a,loadMcpConfigs:i,applications:l,setMcpAppAssociation:d}=t,{dialogState:u,showConfirmDialog:g,handleConfirm:h,handleCancel:x}=En(),[w,m]=T.useState(!1),[f,c]=T.useState(null),[p,y]=T.useState({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),[b,S]=T.useState(!1),[_,j]=T.useState(null),[v,I]=T.useState({}),[M,O]=T.useState([]),[L,C]=T.useState(""),[H,D]=T.useState(!1),[V,X]=T.useState(null),[F,Y]=T.useState([]);T.useEffect(()=>{const A="__mcpManagerInitAt__",k=window[A]||0,P=Date.now();if(!(typeof k=="number"&&P-k<1e3)){window[A]=P,i();try{(t.loadApplications??(()=>{}))()}catch{}}},[i]);const ae=async A=>{X(A),D(!0);try{const k=await ie.getMcpConfigProfiles(A.id);O(Array.isArray(k)?k:[])}catch{console.error("加载配置档案失败")}finally{}},W=()=>{y({name:"",command:"",type:"stdio",enabled:!0,cwd:"",argsInput:""}),c(null),m(!1),I({}),O([]),C(""),Y([])},J=async A=>{var R,z;if(A.preventDefault(),!p.name.trim()||!p.command.trim())return;const k={name:p.name.trim(),command:p.command.trim(),type:p.type,enabled:p.enabled,cwd:(R=p.cwd)!=null&&R.trim()?p.cwd.trim():void 0,args:(z=p.argsInput)!=null&&z.trim()?p.argsInput.split(",").map(ne=>ne.trim()).filter(Boolean):void 0,createdAt:new Date,updatedAt:new Date,app_ids:F},P=await s(k);P!=null&&P.id&&(d==null||d(P.id,F)),W()},ee=async A=>{var R,z;if(A.preventDefault(),!f||!p.name.trim()||!p.command.trim())return;const k={...f,name:p.name.trim(),command:p.command.trim(),type:p.type,enabled:p.enabled,cwd:(R=p.cwd)!=null&&R.trim()?p.cwd.trim():void 0,args:(z=p.argsInput)!=null&&z.trim()?p.argsInput.split(",").map(ne=>ne.trim()).filter(Boolean):void 0,updatedAt:new Date,app_ids:F},P=await s(k);P!=null&&P.id&&(d==null||d(P.id,F)),W()},U=A=>{c(A);let k="";const P=A.args;if(Array.isArray(P))k=P.map(R=>String(R)).join(", ");else if(typeof P=="string"&&P.trim()!=="")try{const R=JSON.parse(P);Array.isArray(R)?k=R.map(z=>String(z)).join(", "):k=P}catch{k=P}y({name:A.name,command:A.command,type:A.type||"stdio",enabled:A.enabled,cwd:A.cwd||"",argsInput:k}),m(!0),I({}),j(null),S(!1),Y(Array.isArray(A.app_ids)?A.app_ids:[])},N=async A=>{const k=n.find(P=>P.id===A);g({title:"删除 MCP 服务器",message:`确定要删除服务器 "${(k==null?void 0:k.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:()=>a(A)})},$=async A=>{const k={...A,enabled:!A.enabled,updatedAt:new Date};await s(k)};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(Fa,{}),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(mp,{})})]}),o.jsxs("div",{className:"p-4 flex-1 overflow-y-auto overflow-x-hidden",children:[!w&&o.jsxs("button",{onClick:()=>m(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-border rounded-lg hover:border-blue-500 transition-colors flex items-center justify-center space-x-2 text-muted-foreground hover:text-blue-600",children:[o.jsx(gp,{}),o.jsx("span",{children:"添加 MCP 服务器"})]}),w&&o.jsxs("form",{onSubmit:f?ee:J,className:"mb-6 p-4 bg-muted rounded-lg",children:[o.jsx("h3",{className:"text-lg font-medium text-foreground mb-4",children:f?"编辑服务器":"添加新服务器"}),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:p.name,onChange:A=>y({...p,name:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"例如: File System",required:!0})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"关联应用(多选)"}),o.jsxs("div",{className:"space-y-2 max-h-32 overflow-y-auto p-2 border rounded-md",children:[(l||[]).map(A=>o.jsxs("label",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",checked:F.includes(A.id),onChange:k=>{const P=k.target.checked;Y(R=>P?[...R,A.id]:R.filter(z=>z!==A.id))}}),o.jsx("span",{children:A.name})]},A.id)),(l||[]).length===0&&o.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无应用,可在“应用管理”中创建。"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"协议类型"}),o.jsxs("select",{value:p.type,onChange:A=>y({...p,type:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",children:[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:p.type==="http"?"URL地址":"命令"}),o.jsx("input",{type:"text",value:p.command,onChange:A=>y({...p,command:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:p.type==="http"?"https://api.example.com/mcp":"npx @modelcontextprotocol/server-filesystem /path/to/allowed/files",required:!0}),p.type==="stdio"&&o.jsx(o.Fragment,{})]}),p.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:p.cwd,onChange:A=>y({...p,cwd:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"/absolute/path/to/executable"}),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 A,k;if(p.command.trim()){S(!0),j(null);try{const P=await ie.getMcpConfigResourceByCommand({type:p.type,command:p.command.trim(),args:(A=p.argsInput)!=null&&A.trim()?p.argsInput.split(",").map(R=>R.trim()).filter(Boolean):void 0,env:void 0,cwd:(k=p.cwd)!=null&&k.trim()?p.cwd.trim():void 0,alias:null});if(P&&P.success&&P.config){const R=P.config;if(I(R),f!=null&&f.id)try{const z=await ie.getMcpConfigProfiles(f.id);O(Array.isArray(z)?z:[])}catch{}}else j("无法获取服务器可配置参数")}catch(P){j((P==null?void 0:P.message)||"获取配置失败")}finally{S(!1)}}},children:b?"获取中…":"获取配置"})})]}),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:p.argsInput,onChange:A=>y({...p,argsInput:A.target.value}),className:"w-full px-3 py-2 border border-input bg-background text-foreground rounded-md focus:outline-none focus:ring-2 focus:ring-ring",placeholder:"--flag, value, --opt"}),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:p.enabled,onChange:A=>y({...p,enabled:A.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:"启用此服务器"})]}),p.type==="stdio"&&Object.keys(v).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:"服务器可配置参数(动态解析)"}),b&&o.jsx("span",{className:"text-xs text-muted-foreground",children:"解析中…"})]}),_&&o.jsx("p",{className:"text-xs text-red-600 mb-2",children:_}),o.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[Object.keys(v).map(A=>{const k=v[A],P=typeof k,R=Array.isArray(k);return o.jsxs("div",{children:[o.jsx("label",{className:"block text-xs text-muted-foreground mb-1",children:A}),P==="boolean"?o.jsxs("div",{className:"flex items-center",children:[o.jsx("input",{type:"checkbox",checked:!!k,onChange:z=>I({...v,[A]:z.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(k)})]}):R?o.jsx("input",{type:"text",value:k.join(", "),onChange:z=>I({...v,[A]:z.target.value.split(",").map(ne=>ne.trim()).filter(Boolean)}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"}):o.jsx("input",{type:P==="number"?"number":"text",value:k??"",onChange:z=>I({...v,[A]:P==="number"?Number(z.target.value):z.target.value}),className:"w-full px-2 py-1 border border-input bg-background text-foreground rounded-md"})]},A)}),(f==null?void 0:f.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:L,onChange:A=>C(A.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 A,k;if(f!=null&&f.id)try{await ie.createMcpConfigProfile(f.id,{name:L||`配置-${new Date().toLocaleString()}`,env:Object.keys(v).reduce((R,z)=>{const ne=v[z];return R[z]=typeof ne=="string"?ne:String(ne),R},{}),args:(A=p.argsInput)!=null&&A.trim()?p.argsInput.split(",").map(R=>R.trim()).filter(Boolean):void 0,cwd:(k=p.cwd)!=null&&k.trim()?p.cwd.trim():void 0,enabled:!1});const P=await ie.getMcpConfigProfiles(f.id);O(Array.isArray(P)?P:[]),C("")}catch(P){console.error("保存配置档案失败:",P),j("保存配置档案失败")}},children:"保存为配置档案"})]}),M.length>0&&o.jsxs("div",{className:"mt-3 space-y-2",children:[o.jsx("div",{className:"text-xs text-muted-foreground",children:"已有配置档案:"}),M.map(A=>{const k=Array.isArray(A.args)?A.args.join(", "):"",P=A.env?Object.keys(A.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:A.name}),A.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 ie.activateMcpConfigProfile(f.id,A.id);const R=await ie.getMcpConfigProfiles(f.id);O(Array.isArray(R)?R:[])}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:()=>{y(R=>({...R,argsInput:Array.isArray(A.args)?A.args.join(", "):R.argsInput,cwd:A.cwd??R.cwd})),I(A.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:A.cwd||"未设置",children:[o.jsx("span",{className:"text-muted-foreground",children:"cwd:"}),A.cwd||"未设置"]}),o.jsxs("div",{className:"truncate",title:k||"未设置",children:[o.jsx("span",{className:"text-muted-foreground",children:"args:"}),k||"未设置"]}),o.jsxs("div",{children:[o.jsxs("span",{className:"text-muted-foreground",children:["env(",P.length,"):"]}),P.length===0?"未设置":o.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:P.map(R=>o.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[o.jsx("span",{className:"text-muted-foreground shrink-0",children:R}),o.jsx("span",{className:"text-foreground truncate",title:String(A.env[R]),children:String(A.env[R])})]},R))})]})]})]},A.id)})]})]})]})]})]}),(f==null?void 0:f.id)&&!w&&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 A=await ie.getMcpConfigProfiles(f.id);O(Array.isArray(A)?A:[])}catch{}},children:"刷新"})]}),M.length===0?o.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无配置档案"}):o.jsx("div",{className:"space-y-2",children:M.map(A=>{const k=Array.isArray(A.args)?A.args.join(", "):"",P=A.env?Object.keys(A.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:A.name}),A.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 ie.activateMcpConfigProfile(f.id,A.id);const R=await ie.getMcpConfigProfiles(f.id);O(Array.isArray(R)?R:[])}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:"}),A.cwd||"未设置"]}),o.jsxs("div",{children:[o.jsx("span",{className:"text-muted-foreground",children:"args:"}),k||"未设置"]}),o.jsxs("div",{children:[o.jsxs("span",{className:"text-muted-foreground",children:["env(",P.length,"):"]}),P.length===0?"未设置":o.jsx("div",{className:"mt-1 grid grid-cols-1 gap-1",children:P.map(R=>o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("span",{className:"text-muted-foreground",children:R}),o.jsx("span",{className:"text-foreground",children:String(A.env[R])})]},R))})]})]})]},A.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:f?"更新":"添加"}),o.jsx("button",{type:"button",onClick:W,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:"暂无 MCP 服务器配置"}),o.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个服务器"})]}):n.map(A=>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 ${A.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:A.name,children:A.name}),o.jsx("span",{className:`px-2 py-1 text-xs rounded-full ${A.type==="http"?"bg-blue-100 text-blue-800 dark:bg-blue-900 dark:text-blue-200":"bg-purple-100 text-purple-800 dark:bg-purple-900 dark:text-purple-200"}`,children:A.type==="http"?"HTTP":"Stdio"})]}),o.jsx("p",{className:"text-xs sm:text-sm text-muted-foreground truncate break-all font-mono",title:A.command,children:A.command}),typeof window<"u"&&hp&&!1,A.type==="stdio"&&o.jsxs("div",{className:"mt-1 space-y-0.5 min-w-0",children:[A.cwd&&o.jsxs("div",{className:"text-xs text-muted-foreground truncate",title:String(A.cwd),children:["cwd: ",o.jsx("span",{className:"text-foreground",children:String(A.cwd)})]}),o.jsx("div",{className:"text-xs text-muted-foreground truncate",title:(()=>{const k=A.args;let P=null,R=!1;if(Array.isArray(k))P=k.map(ne=>String(ne));else if(typeof k=="string"&&k.trim()!=="")try{const ne=JSON.parse(k);Array.isArray(ne)&&(P=ne.map(B=>String(B)),R=!0)}catch{}const z=Array.isArray(P)&&P.length>0?P.join(", "):typeof k=="string"&&!R?k:"—";return String(z)})(),children:(()=>{const k=A.args;let P=null,R=!1;if(Array.isArray(k))P=k.map(ne=>String(ne));else if(typeof k=="string"&&k.trim()!=="")try{const ne=JSON.parse(k);Array.isArray(ne)&&(P=ne.map(B=>String(B)),R=!0)}catch{}const z=Array.isArray(P)&&P.length>0?P.join(", "):typeof k=="string"&&!R?k:"—";return o.jsxs("span",{children:["参数(args):",o.jsx("span",{className:"text-foreground",children:z})]})})()})]})]})]}),o.jsxs("div",{className:"flex items-center space-x-2 shrink-0",children:[o.jsx("button",{onClick:()=>$(A),className:`px-3 py-1 text-xs rounded-full ${A.enabled?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-secondary text-secondary-foreground"}`,children:A.enabled?"已启用":"已禁用"}),o.jsx("button",{onClick:()=>ae(A),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:()=>U(A),className:"p-2 text-muted-foreground hover:text-blue-600 transition-colors",title:"编辑",children:o.jsx(xp,{})}),o.jsx("button",{onClick:()=>N(A.id),className:"p-2 text-muted-foreground hover:text-red-600 transition-colors",title:"删除",children:o.jsx(pp,{})})]})]},A.id))})]})]}),o.jsx(fp,{open:H,config:V,onClose:()=>{D(!1),X(null)}}),o.jsx(Mn,{isOpen:u.isOpen,title:u.title,message:u.message,confirmText:u.confirmText,cancelText:u.cancelText,type:u.type,onConfirm:h,onCancel:x})]})},Ua=()=>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"})}),yp=()=>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"})}),bp=()=>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"})}),wp=()=>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"})}),vp=()=>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"})}),Co=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=_t()}catch{t=vt()}const{aiModelConfigs:n,loadAiModelConfigs:s,updateAiModelConfig:a,deleteAiModelConfig:i}=t,[l,d]=T.useState(!1),[u,g]=T.useState(null),[h,x]=T.useState({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),{dialogState:w,showConfirmDialog:m,handleConfirm:f,handleCancel:c}=En();T.useEffect(()=>{const v="__aiModelManagerInitAt__",I=window[v]||0,M=Date.now();typeof I=="number"&&M-I<1e3||(window[v]=M,s())},[s]);const p=()=>{x({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),g(null),d(!1)},y=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),p()},b=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),p()},S=v=>{g(v),x({name:v.name,base_url:v.base_url,api_key:v.api_key,model_name:v.model_name,enabled:v.enabled}),d(!0)},_=async v=>{const I=n.find(M=>M.id===v);m({title:"删除确认",message:`确定要删除AI模型配置 "${(I==null?void 0:I.name)||"Unknown"}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",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(Ua,{}),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(yp,{})})]}),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(bp,{}),o.jsx("span",{children:"添加 AI 模型"})]}),l&&o.jsxs("form",{onSubmit:u?b:y,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=>x({...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=>x({...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=>x({...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=>x({...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=>x({...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:p,className:"px-4 py-2 bg-secondary text-secondary-foreground rounded-md hover:bg-secondary/80 focus:outline-none focus:ring-2 focus:ring-ring",children:"取消"})]})]}),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(Ua,{}),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:()=>S(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(wp,{})}),o.jsx("button",{onClick:()=>_(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(vp,{})})]})]},v.id))})]})]}),o.jsx(Mn,{isOpen:w.isOpen,title:w.title,message:w.message,confirmText:w.confirmText,cancelText:w.cancelText,type:w.type,onConfirm:f,onCancel:c})]})},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 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"})}),_p=()=>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"})}),Sp=()=>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"})}),Cp=()=>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"})}),jp=()=>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"})}),Ap=()=>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"})}),Np=()=>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"})}),jo=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=_t()}catch{t=vt()}const{systemContexts:n,activeSystemContext:s,loadSystemContexts:a,createSystemContext:i,updateSystemContext:l,deleteSystemContext:d,activateSystemContext:u,applications:g,loadApplications:h}=t,[x,w]=T.useState("list"),[m,f]=T.useState(null),[c,p]=T.useState({name:"",content:""}),[y,b]=T.useState(!1),[S,_]=T.useState(!1),[j,v]=T.useState([]),{dialogState:I,showConfirmDialog:M,handleConfirm:O,handleCancel:L}=En();T.useEffect(()=>{const W="__systemContextEditorInitAt__",J=window[W]||0,ee=Date.now();if(typeof J=="number"&&ee-J<1e3)return;window[W]=ee,(async()=>{b(!0);try{await a();try{await(h==null?void 0:h())}catch{}}catch(N){console.error("Failed to load system contexts:",N)}finally{b(!1)}})()},[a]);const C=()=>{p({name:"",content:""}),f(null),w("create")},H=W=>{p({name:W.name,content:W.content}),f(W),v(Array.isArray(W.app_ids)?W.app_ids:[]),w("edit")},D=async()=>{if(!c.name.trim()||!c.content.trim()){alert("请填写名称和内容");return}_(!0);try{x==="create"?await i(c.name,c.content,j):x==="edit"&&m&&await l(m.id,c.name,c.content,j),w("list")}catch(W){console.error("Failed to save system context:",W),alert("保存失败,请重试")}finally{_(!1)}},V=async W=>{M({title:"删除确认",message:`确定要删除上下文 "${W.name}" 吗?此操作无法撤销。`,confirmText:"删除",cancelText:"取消",type:"danger",onConfirm:async()=>{try{await d(W.id)}catch(J){console.error("Failed to delete system context:",J),alert("删除失败,请重试")}}})},X=async W=>{try{await u(W.id),await a()}catch(J){console.error("Failed to activate system context:",J),alert("激活失败,请重试")}},F=W=>{W.ctrlKey&&W.key==="s"&&(W.preventDefault(),x!=="list"&&D())},Y=()=>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:y?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(Ba,{}),o.jsx("p",{className:"mt-2",children:"暂无系统上下文配置"}),o.jsx("p",{className:"text-sm",children:'点击"新建"按钮创建第一个配置'})]}):o.jsx("div",{className:"space-y-3",children:n.map(W=>o.jsx("div",{className:`p-4 border rounded-lg transition-colors ${W.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:W.name}),W.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(Np,{}),o.jsx("span",{className:"ml-1",children:"已激活"})]})]}),o.jsxs("p",{className:"mt-1 text-sm text-muted-foreground line-clamp-2",children:[W.content.substring(0,100),W.content.length>100&&"..."]}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["创建时间: ",new Date(W.createdAt).toLocaleString()]})]}),o.jsxs("div",{className:"flex items-center space-x-2 ml-4",children:[!W.isActive&&o.jsx("button",{onClick:()=>X(W),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"激活"}),o.jsx("button",{onClick:()=>H(W),className:"p-2 text-muted-foreground hover:text-blue-600 hover:bg-accent rounded transition-colors",children:o.jsx(jp,{})}),o.jsx("button",{onClick:()=>V(W),className:"p-2 text-muted-foreground hover:text-red-600 hover:bg-accent rounded transition-colors",children:o.jsx(Ap,{})})]})]})},W.id))})})]}),ae=()=>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:x==="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:c.name,onChange:W=>p({...c,name:W.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",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"关联应用(多选)"}),o.jsxs("div",{className:"space-y-2 max-h-32 overflow-y-auto p-2 border rounded-md",children:[(g||[]).map(W=>o.jsxs("label",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",checked:j.includes(W.id),onChange:J=>{const ee=J.target.checked;v(U=>ee?[...U,W.id]:U.filter(N=>N!==W.id))}}),o.jsx("span",{children:W.name})]},W.id)),(g||[]).length===0&&o.jsx("div",{className:"text-xs text-muted-foreground",children:"暂无应用,可在“应用管理”中创建。"})]})]}),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:[c.content.length," 字符"]})]}),o.jsx("textarea",{value:c.content,onChange:W=>p({...c,content:W.target.value}),onKeyDown:F,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(Ba,{}),o.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"系统上下文设置"})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[x==="list"?o.jsxs("button",{onClick:C,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(Cp,{}),o.jsx("span",{children:"新建"})]}):o.jsxs(o.Fragment,{children:[o.jsxs("button",{onClick:D,disabled:S,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(Sp,{}),o.jsx("span",{children:S?"保存中...":"保存"})]}),o.jsx("button",{onClick:()=>w("list"),className:"px-4 py-2 text-secondary-foreground border border-border rounded-md hover:bg-accent focus:outline-none focus:ring-2 focus:ring-ring transition-colors",children:"取消"})]}),o.jsx("button",{onClick:r,className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(_p,{})})]})]}),x==="list"?Y():ae()]}),o.jsx(Mn,{isOpen:I.isOpen,title:I.title,message:I.message,confirmText:I.confirmText,cancelText:I.cancelText,type:I.type,onConfirm:O,onCancel:L})]})},Wa=()=>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"})}),Ha=()=>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"})}),kp=()=>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"})}),Mp=()=>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"})}),kc=({onClose:r,store:e})=>{let t;if(e)t=e();else try{t=_t()}catch{t=vt()}const{aiModelConfigs:n,loadAiModelConfigs:s,mcpConfigs:a,loadMcpConfigs:i,systemContexts:l,loadSystemContexts:d,applications:u,loadApplications:g}=t,{userId:h}=rc(),x=h||"custom_user_123",m=nc()||ie,[f,c]=T.useState([]),[p,y]=T.useState(!1),[b,S]=T.useState(!1),[_,j]=T.useState(null),[v,I]=T.useState(null),[M,O]=T.useState({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),[L,C]=T.useState([]),H=T.useRef(!1),D=async()=>{y(!0);try{await Promise.all([s(),i(),d(),g?g():Promise.resolve(),t.loadAgents?t.loadAgents():Promise.resolve()]);const N=t.agents&&Array.isArray(t.agents)?t.agents:await m.getAgents(x),$=Array.isArray(N)?N:[];c($)}catch(N){console.error("加载智能体失败",N)}finally{y(!1)}},V=async N=>{for(let A=0;A<3;A++)try{t.loadAgents&&await t.loadAgents();const k=await m.getAgents(x),P=Array.isArray(k)?k:[];if(c(P),N&&Array.isArray(P)&&P.some(R=>R.id===N)||!N)break;await new Promise(R=>setTimeout(R,250))}catch(k){console.warn("刷新智能体列表失败,重试中…",k),await new Promise(P=>setTimeout(P,250))}};T.useEffect(()=>{const N="__agentManagerInitAt__",$=window[N]||0,A=Date.now();typeof $=="number"&&A-$<1e3||(window[N]=A,D())},[]);const X=()=>{O({name:"",description:"",ai_model_config_id:"",mcp_config_ids:[],system_context_id:void 0}),S(!1),I(null),C([])};T.useEffect(()=>{if(H.current){H.current=!1;return}O(N=>{const $={...N};return $.mcp_config_ids=[],$.system_context_id=void 0,$})},[L]);const F=async N=>{var $;if(N.preventDefault(),!(!M.name.trim()||!M.ai_model_config_id))try{const A=await m.createAgent({name:M.name.trim(),description:(($=M.description)==null?void 0:$.trim())||void 0,ai_model_config_id:M.ai_model_config_id,mcp_config_ids:M.mcp_config_ids,system_context_id:M.system_context_id,user_id:x,enabled:!0,app_ids:L});A&&A.id&&c(k=>k.some(R=>R.id===A.id)?k.map(R=>R.id===A.id?{...R,...A}:R):[A,...k]),await V(A==null?void 0:A.id),X()}catch(A){console.error("创建智能体失败",A),alert("创建失败,请重试")}},Y=async N=>{if(N.preventDefault(),!!v)try{const $=await m.updateAgent(v.id,{name:M.name,description:M.description,ai_model_config_id:M.ai_model_config_id,mcp_config_ids:M.mcp_config_ids,system_context_id:M.system_context_id,enabled:!0,app_ids:L});c(A=>A.map(k=>k.id===v.id?{...k,...$,name:M.name,description:M.description,ai_model_config_id:M.ai_model_config_id,mcp_config_ids:M.mcp_config_ids,system_context_id:M.system_context_id,enabled:!0}:k)),await V(v.id),X()}catch($){console.error("更新智能体失败",$),alert("更新失败,请重试")}},ae=async N=>{try{await m.deleteAgent(N),c($=>$.filter(A=>A.id!==N)),await V()}catch($){console.error("删除智能体失败",$),alert("删除失败,请重试")}},W=N=>{I(N),S(!0),O({name:N.name,description:N.description||"",ai_model_config_id:N.ai_model_config_id,mcp_config_ids:Array.isArray(N.mcp_config_ids)?N.mcp_config_ids:[],system_context_id:N.system_context_id}),H.current=!0,C(Array.isArray(N.app_ids)?N.app_ids:[])},J=N=>{const $=n.find(A=>A.id===N);return $?`${$.name}(${$.model_name})`:N},ee=N=>{if(!N)return"未选择";const $=l.find(A=>A.id===N);return $?$.name:N},U=N=>N.map(A=>{const k=a.find(P=>P.id===A);return k?k.name:A}).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(Wa,{}),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(Ha,{})})]}),o.jsxs("div",{className:"flex-1 overflow-y-auto p-4 space-y-4",children:[!b&&o.jsxs("button",{onClick:()=>S(!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(kp,{}),o.jsx("span",{children:"新增智能体"})]}),b&&o.jsxs("form",{onSubmit:v?Y:F,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.jsxs("div",{className:"space-y-2 max-h-32 overflow-y-auto p-2 border rounded-md",children:[(u||[]).map(N=>o.jsxs("label",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",checked:L.includes(N.id),onChange:$=>{const A=$.target.checked;C(k=>A?[...k,N.id]:k.filter(P=>P!==N.id))}}),o.jsx("span",{children:N.name})]},N.id)),(u||[]).length===0&&o.jsx("div",{className:"text-xs text-muted-foreground",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:N=>O({...M,name:N.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:M.description,onChange:N=>O({...M,description:N.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:M.ai_model_config_id,onChange:N=>O({...M,ai_model_config_id:N.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(N=>o.jsxs("option",{value:N.id,children:[N.name,"(",N.model_name,")"]},N.id))]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择 MCP 配置(多选)"}),o.jsxs("div",{className:"space-y-2 max-h-40 overflow-y-auto p-2 border rounded-md",children:[(L.length?a.filter(N=>Array.isArray(N.app_ids)&&N.app_ids.some($=>L.includes($))):a).map(N=>o.jsxs("label",{className:"flex items-center space-x-2",children:[o.jsx("input",{type:"checkbox",checked:M.mcp_config_ids.includes(N.id),onChange:$=>{const A=$.target.checked;O(k=>({...k,mcp_config_ids:A?[...k.mcp_config_ids,N.id]:k.mcp_config_ids.filter(P=>P!==N.id)}))}}),o.jsx("span",{children:N.name})]},N.id)),L.length>0&&a.filter(N=>Array.isArray(N.app_ids)&&N.app_ids.some($=>L.includes($))).length===0&&o.jsx("div",{className:"text-xs text-muted-foreground",children:"所选应用下暂无 MCP 配置"})]})]}),o.jsxs("div",{children:[o.jsx("label",{className:"block text-sm font-medium text-foreground mb-2",children:"选择系统上下文"}),o.jsxs("select",{value:M.system_context_id||"",onChange:N=>O({...M,system_context_id:N.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.length?l.filter(N=>Array.isArray(N.app_ids)&&N.app_ids.some($=>L.includes($))):l).map(N=>o.jsx("option",{value:N.id,children:N.name},N.id)),L.length>0&&l.filter(N=>Array.isArray(N.app_ids)&&N.app_ids.some($=>L.includes($))).length===0&&o.jsx("option",{value:"",disabled:!0,children:"所选应用下暂无系统上下文"})]})]}),o.jsxs("div",{className:"flex items-center justify-end space-x-2",children:[o.jsx("button",{type:"button",onClick:X,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:p?o.jsx("div",{className:"text-muted-foreground",children:"加载中..."}):f.length===0?o.jsx("div",{className:"text-muted-foreground",children:"暂无智能体配置"}):o.jsx("div",{className:"space-y-3",children:f.map(N=>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:N.name,children:N.name}),!N.enabled&&o.jsx("span",{className:"text-xs px-2 py-0.5 rounded bg-muted text-muted-foreground",children:"未启用"})]}),N.description&&o.jsx("p",{className:"mt-1 text-sm text-muted-foreground truncate",title:N.description,children:N.description}),o.jsxs("p",{className:"mt-2 text-xs text-muted-foreground truncate",title:J(N.ai_model_config_id),children:["模型:",J(N.ai_model_config_id)]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:ee(N.system_context_id),children:["系统上下文:",ee(N.system_context_id)]}),o.jsxs("p",{className:"mt-1 text-xs text-muted-foreground truncate",title:U(N.mcp_config_ids||[]),children:["MCP配置:",U(N.mcp_config_ids||[])]})]}),o.jsxs("div",{className:"flex items-center space-x-2 ml-4 shrink-0",children:[o.jsx("button",{onClick:()=>j(N),className:"px-3 py-1 text-sm bg-muted text-foreground rounded hover:bg-accent transition-colors",children:"详情"}),o.jsx("button",{onClick:()=>W(N),className:"px-3 py-1 text-sm bg-blue-600 text-white rounded hover:bg-blue-700 transition-colors",children:"编辑"}),o.jsxs("button",{onClick:()=>ae(N.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(Mp,{}),o.jsx("span",{children:"删除"})]})]})]},N.id))})})]}),_&&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:()=>j(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(Wa,{}),o.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"智能体详情"})]}),o.jsx("button",{onClick:()=>j(null),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:o.jsx(Ha,{})})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"名称:"}),_.name]}),_.description&&o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"描述:"}),_.description]}),o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"模型:"}),J(_.ai_model_config_id)]}),o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"系统上下文:"}),ee(_.system_context_id)]}),o.jsxs("p",{children:[o.jsx("span",{className:"text-muted-foreground",children:"MCP配置:"}),U(_.mcp_config_ids||[])]}),Array.isArray(_.mcp_config_ids)&&_.mcp_config_ids.length>0&&o.jsx("div",{className:"mt-2 space-y-2",children:(_.mcp_config_ids||[]).map(N=>{var P,R;const $=(a||[]).find(z=>z.id===N);if(!$)return null;let A="—";const k=$.args;if(Array.isArray(k))A=k.map(z=>String(z)).join(", ");else if(typeof k=="string"&&k.trim()!=="")try{const z=JSON.parse(k);Array.isArray(z)?A=z.map(ne=>String(ne)).join(", "):A=k}catch{A=k}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:$.name}),o.jsx("span",{className:`px-1.5 py-0.5 text-xs rounded ${$.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:((R=(P=$.type)==null?void 0:P.toUpperCase)==null?void 0:R.call(P))||$.type})]}),o.jsxs("div",{className:"mt-1 text-xs text-muted-foreground break-all",children:[$.type==="http"?"URL:":"命令:",o.jsx("span",{className:"text-foreground",children:$.command})]}),$.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($.cwd)})]}),$.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:A})]})]},N)})}),o.jsxs("p",{className:"text-xs text-muted-foreground",children:["创建时间:",_.created_at?new Date(_.created_at).toLocaleString():"-"]})]}),o.jsx("div",{className:"mt-4 flex justify-end space-x-2",children:o.jsx("button",{onClick:()=>j(null),className:"px-3 py-2 rounded bg-muted text-muted-foreground hover:bg-accent",children:"关闭"})})]})]})]})]})},Mc=({isOpen:r,onClose:e,manageOnly:t=!1,title:n,layout:s="modal",onApplicationSelect:a})=>{let i;try{i=_t()}catch{i=vt()}const{applications:l,loadApplications:d,createApplication:u,updateApplication:g,deleteApplication:h}=i,x=T.useRef(new Map),[w,m]=T.useState(!!t),[f,c]=T.useState(!1),[p,y]=T.useState(null),[b,S]=T.useState({name:"",url:"",iconUrl:""});T.useEffect(()=>{try{console.log("[ApplicationsPanel] useEffect -> loadApplications"),d==null||d()}catch(C){console.error("[ApplicationsPanel] loadApplications error:",C)}},[d]);const _=()=>{y(null),S({name:"",url:"",iconUrl:""}),c(!1)},j=async C=>{C.preventDefault(),b.name.trim()&&(p?await(g==null?void 0:g(p,{name:b.name.trim(),url:b.url.trim(),iconUrl:b.iconUrl.trim()||void 0})):await(u==null?void 0:u(b.name.trim(),b.url.trim(),b.iconUrl.trim()||void 0)),_())},v=C=>{console.log("[ApplicationsPanel] closeAppWindow:",C);const H=x.current.get(C);H&&!H.closed&&H.close(),x.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 O=t?!0:w,L=n??(O?"应用管理":"应用列表");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),_()},className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent transition-colors",children:O?"浏览模式":"管理模式"}),!O&&x.current.size>0&&o.jsx("button",{className:"px-3 py-1.5 text-sm rounded bg-muted hover:bg-accent",onClick:()=>{x.current.forEach((C,H)=>v(H))},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:O?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:b.name,onChange:C=>S({...b,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:b.url,onChange:C=>S({...b,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:b.iconUrl,onChange:C=>S({...b,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:_,children:"取消"}),o.jsx("button",{type:"submit",className:"px-3 py-2 rounded bg-blue-600 text-white hover:bg-blue-700",children:p?"保存":"创建"})]})]}),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:()=>{y(C.id),c(!0),S({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 H=x.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 ${H?"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()})}),H&&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})]}),H&&o.jsx("button",{onClick:D=>{D.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),_()},className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent transition-colors",children:O?"浏览模式":"管理模式"}),!O&&x.current.size>0&&o.jsx("button",{className:"px-2 py-1 text-xs rounded bg-muted hover:bg-accent",onClick:()=>{x.current.forEach((C,H)=>v(H))},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:O?o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4 flex items-center justify-between",children:o.jsx("button",{type:"button",onClick:()=>{y(null),S({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 X,F,Y;C.preventDefault();const H=((X=b.name)==null?void 0:X.trim())||"",D=((F=b.url)==null?void 0:F.trim())||"",V=((Y=b.iconUrl)==null?void 0:Y.trim())||void 0;H&&(p?g==null||g(p,{name:H,url:D,iconUrl:V}):u==null||u(H,D,V),c(!1),_())},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:b.name,onChange:C=>S({...b,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:b.url,onChange:C=>S({...b,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:b.iconUrl,onChange:C=>S({...b,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),_(),y(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:p?"保存":"创建"})]})]}),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),y(C.id),S({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 H=x.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 ${H?"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})]}),H&&o.jsx("button",{onClick:D=>{D.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:"切换到管理模式以添加应用"})]})]})})]})},Ao=({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=T.useMemo(()=>{if(e)return e;if(t)return`http://localhost:${t}/api`},[e,t]),h=T.useMemo(()=>{if(g)return new ar(g)},[g]);return o.jsx(Lh,{userId:n,projectId:s,customApiClient:h,children:o.jsx(Ep,{className:r,showMcpManager:a,showAiModelManager:i,showSystemContextEditor:l,showAgentManager:d,onApplicationSelect:u})})},Ep=({className:r,showMcpManager:e,showAiModelManager:t,showSystemContextEditor:n,showAgentManager:s,onApplicationSelect:a})=>{const i=tc(),{currentSession:l,messages:d,isLoading:u,isStreaming:g,hasMoreMessages:h,error:x,loadSessions:w,sendMessage:m,clearError:f,aiModelConfigs:c,selectedModelId:p,setSelectedModel:y,loadAiModelConfigs:b,agents:S,selectedAgentId:_,setSelectedAgent:j,loadAgents:v,abortCurrentConversation:I,loadMoreMessages:M}=i(),O=T.useRef(null),[L,C]=T.useState(!1),[H,D]=T.useState(!1),[V,X]=T.useState(!1),[F,Y]=T.useState(!1),[ae,W]=T.useState(!1),[J,ee]=T.useState(!1);T.useEffect(()=>{(window.__standaloneChatInterfaceDidInit__??!1)||(window.__standaloneChatInterfaceDidInit__=!0,w(),b(),v())},[w,b,v]),T.useEffect(()=>{O.current&&O.current.scrollIntoView({behavior:"smooth"})},[d,g]);const U=async(N,$)=>{try{await m(N,$)}catch(A){console.error("Failed to send message:",A)}};return o.jsxs("div",{className:Ee("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"),ee(!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:()=>D(!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:()=>X(!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:()=>Y(!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:()=>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",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(_o,{})]})]}),x&&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:x}),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(bo,{messages:d,isLoading:u,isStreaming:g,hasMore:h,onLoadMore:()=>l&&M(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:O})]})}),l&&o.jsx(wo,{onSend:U,onStop:I,disabled:u||g,isStreaming:g,selectedModelId:p,availableModels:c,onModelChange:y,showModelSelector:!0,selectedAgentId:_,availableAgents:S,onAgentChange:j}),o.jsx(vo,{isOpen:L,onClose:()=>C(!1),store:i}),o.jsx(Mc,{isOpen:J,onClose:()=>ee(!1),title:"应用列表",layout:"modal",onApplicationSelect:a}),H&&o.jsx(So,{onClose:()=>D(!1),store:i}),V&&o.jsx(Co,{onClose:()=>X(!1),store:i}),s&&ae&&o.jsx(kc,{onClose:()=>W(!1),store:i}),F&&o.jsx(jo,{onClose:()=>Y(!1),store:i})]})};class Pp{constructor(e,t,n,s,a=!0,i=!0,l=!0,d=!0,u){q(this,"userId");q(this,"projectId");q(this,"configUrl");q(this,"apiClient");q(this,"store");q(this,"className");q(this,"showMcpManager");q(this,"showAiModelManager");q(this,"showSystemContextEditor");q(this,"showAgentManager");q(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 ar(this.configUrl),this.store=rn(this.apiClient,{userId:this.userId,projectId:this.projectId,configUrl:this.configUrl})}render(){return T.createElement(Ip,{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 ar(this.configUrl),this.store=rn(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 Ip=({className:r,userId:e,projectId:t,configUrl:n,showMcpManager:s,showAiModelManager:a,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d})=>o.jsx(Ao,{className:r,apiBaseUrl:n,userId:e,projectId:t,showMcpManager:s,showAiModelManager:a,showSystemContextEditor:i,showAgentManager:l,onApplicationSelect:d}),Tp=({onClose:r})=>{const t=nc()||ie,{userId:n}=rc(),[s,a]=T.useState(!0),[i,l]=T.useState(!1),[d,u]=T.useState(null),[g,h]=T.useState({});T.useEffect(()=>{let m=!0;return(async()=>{try{const f=await t.getUserSettings(n);if(!m)return;h((f==null?void 0:f.effective)||{})}catch(f){u(String((f==null?void 0:f.message)||f))}finally{m&&a(!1)}})(),()=>{m=!1}},[t,n]);const x=m=>({value:g[m]??"",onChange:f=>{const c=f.target.type==="checkbox"?f.target.checked:f.target.value;h(p=>({...p,[m]:f.target.type==="number"?Number(c):c}))}}),w=async()=>{if(!n){u("缺少 userId,无法保存");return}l(!0),u(null);try{const m={SUMMARY_ENABLED:!!g.SUMMARY_ENABLED,DYNAMIC_SUMMARY_ENABLED:!!g.DYNAMIC_SUMMARY_ENABLED,SUMMARY_MESSAGE_LIMIT:Number(g.SUMMARY_MESSAGE_LIMIT||0),SUMMARY_MAX_CONTEXT_TOKENS:Number(g.SUMMARY_MAX_CONTEXT_TOKENS||0),SUMMARY_KEEP_LAST_N:Number(g.SUMMARY_KEEP_LAST_N||0),SUMMARY_TARGET_TOKENS:Number(g.SUMMARY_TARGET_TOKENS||0),SUMMARY_COOLDOWN_SECONDS:Number(g.SUMMARY_COOLDOWN_SECONDS||0),MAX_ITERATIONS:Number(g.MAX_ITERATIONS||0),LOG_LEVEL:String(g.LOG_LEVEL||"info"),CHAT_MAX_TOKENS:g.CHAT_MAX_TOKENS===""||g.CHAT_MAX_TOKENS===null||g.CHAT_MAX_TOKENS===void 0?null:Number(g.CHAT_MAX_TOKENS)},f=await t.updateUserSettings(n,m);h((f==null?void 0:f.effective)||m)}catch(m){u(String((m==null?void 0:m.message)||m))}finally{l(!1)}};return o.jsxs("div",{className:"fixed inset-0 z-50 flex items-center justify-center",children:[o.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-background/60 to-background/80 backdrop-blur-sm"}),o.jsxs("div",{className:"relative bg-card text-card-foreground w-full max-w-3xl rounded-xl shadow-2xl border border-border/60",children:[o.jsxs("div",{className:"flex items-center justify-between p-4 sm:p-5 border-b border-border/60",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("div",{className:"p-2 rounded-lg bg-accent/60 text-accent-foreground",children:o.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 6V4m0 16v-2m8-6h2M4 12H2m15.364 5.364l1.414 1.414M5.636 6.636L4.222 5.222m12.728 0l1.414 1.414M5.636 17.364l-1.414 1.414"})})}),o.jsxs("div",{children:[o.jsx("h3",{className:"font-semibold leading-tight",children:"用户参数设置"}),o.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"为当前用户定制会话摘要与递归参数"})]})]}),o.jsx("button",{onClick:r,className:"p-2 hover:bg-accent rounded-lg transition-colors","aria-label":"关闭",children:o.jsx("svg",{className:"w-5 h-5",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",children:o.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),o.jsx("div",{className:"p-4 sm:p-6 space-y-4 max-h-[75vh] overflow-auto",children:s?o.jsx("div",{className:"text-sm text-muted-foreground",children:"加载中..."}):o.jsxs(o.Fragment,{children:[d&&o.jsx("div",{className:"p-2 text-sm rounded-lg bg-destructive/10 text-destructive border border-destructive/20",children:d}),o.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[o.jsxs("div",{className:"p-3 rounded-lg border border-border/60 bg-muted/40",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-sm font-medium",children:"启用会话摘要"}),o.jsx("label",{className:"inline-flex items-center gap-2",children:o.jsx("input",{type:"checkbox",className:"h-4 w-4",checked:!!g.SUMMARY_ENABLED,onChange:m=>h(f=>({...f,SUMMARY_ENABLED:m.target.checked}))})})]}),o.jsx("div",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:"当对话较长时,将早期内容压缩为摘要,作为系统提示继续对话。 优点: 降低上下文长度、减少费用;风险: 可能丢失细节。建议保持开启。"})]}),o.jsxs("div",{className:"p-3 rounded-lg border border-border/60 bg-muted/40",children:[o.jsxs("div",{className:"flex items-center justify-between",children:[o.jsx("div",{className:"text-sm font-medium",children:"启用动态摘要"}),o.jsx("label",{className:"inline-flex items-center gap-2",children:o.jsx("input",{type:"checkbox",className:"h-4 w-4",checked:!!g.DYNAMIC_SUMMARY_ENABLED,onChange:m=>h(f=>({...f,DYNAMIC_SUMMARY_ENABLED:m.target.checked}))})})]}),o.jsx("div",{className:"text-xs text-muted-foreground mt-1 leading-relaxed",children:"在工具调用/多轮递归过程中按需实时压缩历史。更稳定,但会有少量额外延迟与开销。建议开启。"})]})]}),o.jsxs("div",{className:"rounded-xl border border-border/60 overflow-hidden",children:[o.jsx("div",{className:"px-4 py-2.5 border-b border-border/60 bg-accent/10 text-sm font-medium",children:"摘要参数"}),o.jsxs("div",{className:"p-4 grid grid-cols-1 sm:grid-cols-2 gap-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"消息阈值"}),o.jsx("input",{type:"number",className:"w-full mt-1 p-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/40",...x("SUMMARY_MESSAGE_LIMIT")}),o.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"达到该消息数量即触发摘要(与 Token 阈值择一触发更早者)。建议: 50–150。"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"最大上下文 Tokens"}),o.jsx("input",{type:"number",className:"w-full mt-1 p-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/40",...x("SUMMARY_MAX_CONTEXT_TOKENS")}),o.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"估算上下文超过该 Token 值时触发摘要。建议: 3000–8000;小模型或移动端可更低。"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"保留最近 N 条"}),o.jsx("input",{type:"number",className:"w-full mt-1 p-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/40",...x("SUMMARY_KEEP_LAST_N")}),o.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"摘要后保留最近 N 条原文,确保近期上下文完整。建议: 3–8。"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"目标摘要 Tokens"}),o.jsx("input",{type:"number",className:"w-full mt-1 p-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/40",...x("SUMMARY_TARGET_TOKENS")}),o.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"摘要目标长度。越大信息保留越多、费用更高。建议: 300–1000(常用 500)。"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"摘要冷却 (秒)"}),o.jsx("input",{type:"number",className:"w-full mt-1 p-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/40",...x("SUMMARY_COOLDOWN_SECONDS")}),o.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"两次摘要之间的最小间隔,避免频繁触发。建议: 30–120 秒。"})]})]})]}),o.jsxs("div",{className:"rounded-xl border border-border/60 overflow-hidden",children:[o.jsx("div",{className:"px-4 py-2.5 border-b border-border/60 bg-accent/10 text-sm font-medium",children:"递归与日志"}),o.jsxs("div",{className:"p-4 grid grid-cols-1 sm:grid-cols-2 gap-4",children:[o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"最大输出 Tokens(每次回复)"}),o.jsx("input",{type:"number",className:"w-full mt-1 p-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/40",...x("CHAT_MAX_TOKENS")}),o.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"后端只从此处读取。留空则不限制,模型按默认生成。"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"最大递归轮数"}),o.jsx("input",{type:"number",className:"w-full mt-1 p-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/40",...x("MAX_ITERATIONS")}),o.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"一次请求内的工具调用迭代上限,用于防止无限循环。建议: 4–6(调试可临时提高)。"})]}),o.jsxs("div",{children:[o.jsx("label",{className:"text-xs text-muted-foreground",children:"日志级别"}),o.jsx("input",{type:"text",className:"w-full mt-1 p-2 border rounded-lg bg-background focus:outline-none focus:ring-2 focus:ring-primary/40",...x("LOG_LEVEL"),placeholder:"info|warn|error|debug"}),o.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"仅作为本用户偏好保存,不修改服务器全局日志。debug 最详细,error 最少。"})]})]})]})]})}),o.jsxs("div",{className:"p-4 sm:p-5 border-t border-border/60 flex items-center justify-end gap-2",children:[o.jsx("button",{onClick:r,className:"px-3 py-2 rounded-lg bg-muted text-foreground hover:bg-muted/80",children:"取消"}),o.jsx("button",{onClick:w,disabled:i,className:"px-3 py-2 rounded-lg bg-primary text-primary-foreground hover:bg-primary/90 disabled:opacity-50",children:i?"保存中...":"保存"})]})]})]})},Op=({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:x,aiModelConfigs:w,selectedModelId:m,setSelectedModel:f,loadAiModelConfigs:c,agents:p,selectedAgentId:y,setSelectedAgent:b,loadAgents:S,abortCurrentConversation:_}=_t(),j=T.useRef(null),[v,I]=T.useState(!1),[M,O]=T.useState(!1),[L,C]=T.useState(!1),[H,D]=T.useState(!1),[V,X]=T.useState(!1),[F,Y]=T.useState(!1),[ae,W]=T.useState(!1);T.useEffect(()=>{(window.__chatInterfaceDidInit__??!1)||(window.__chatInterfaceDidInit__=!0,u(),c(),S())},[u,c,S]),T.useEffect(()=>{j.current&&j.current.scrollIntoView({behavior:"smooth"})},[s,i]);const J=async(ee,U)=>{try{await h(ee,U),e==null||e(ee,[])}catch(N){console.error("Failed to send message:",N)}};return o.jsxs("div",{className:Ee("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:()=>I(!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"})})}),n&&o.jsx("div",{className:"flex-1 min-w-0",children:o.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:n.title})})]}),o.jsxs("div",{className:"flex items-center space-x-2",children:[o.jsx("button",{onClick:()=>Y(!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:()=>O(!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:()=>X(!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:()=>C(!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:()=>D(!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"})})}),o.jsx(_o,{}),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:"M12 6V4m0 16v-2m8-6h2M4 12H2m15.364 5.364l1.414 1.414M5.636 6.636L4.222 5.222m12.728 0l1.414 1.414M5.636 17.364l-1.414 1.414"})})})]})]}),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:x,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 flex-1 overflow-hidden",children:o.jsxs("div",{className:"flex-1 overflow-hidden",children:[n?o.jsx(bo,{messages:s,isLoading:a,isStreaming:i,hasMore:l,onLoadMore:()=>n&&g(n.id),customRenderer:t}):o.jsx("div",{className:"flex items-center justify-center h-full",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:"点击左上角按钮选择会话,或创建新的会话开始对话"}),o.jsx("button",{onClick:()=>I(!0),className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"打开会话列表"})]})}),o.jsx("div",{ref:j})]})}),n&&o.jsx("div",{className:"border-t border-border",children:o.jsx(wo,{onSend:J,onStop:_,disabled:a,isStreaming:i,placeholder:"输入消息...",allowAttachments:!0,showModelSelector:!0,selectedModelId:m,availableModels:w,onModelChange:f,selectedAgentId:y,availableAgents:p,onAgentChange:b})}),o.jsx(vo,{isOpen:v,onClose:()=>I(!1)}),M&&o.jsx(So,{onClose:()=>O(!1)}),V&&o.jsx(kc,{onClose:()=>X(!1)}),L&&o.jsx(Co,{onClose:()=>C(!1)}),H&&o.jsx(jo,{onClose:()=>D(!1)}),ae&&o.jsx(Tp,{onClose:()=>W(!1)}),o.jsx(Mc,{isOpen:F,onClose:()=>Y(!1),title:"应用列表",layout:"modal"})]})};class Rp extends T.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("ErrorBoundary caught an error:",e,t)}render(){var e;return this.state.hasError?this.props.fallback?this.props.fallback: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 Lp="1.0.10";exports.AiChat=Pp;exports.AiModelManager=Co;exports.AiServer=Ql;exports.ApiClient=ar;exports.AppError=Qg;exports.AttachmentRenderer=yc;exports.ChatIcon=jc;exports.ChatInterface=Op;exports.ChatService=ec;exports.CheckIcon=rp;exports.ChevronDownIcon=ap;exports.CopyIcon=sp;exports.DatabaseService=Ms;exports.DotsVerticalIcon=_c;exports.ErrorBoundary=Rp;exports.InputArea=wo;exports.LoadingSpinner=wc;exports.MarkdownRenderer=gt;exports.McpManager=So;exports.MessageItem=bc;exports.MessageList=bo;exports.MessageManager=Zl;exports.PencilIcon=Sc;exports.PlayIcon=op;exports.PlusIcon=vc;exports.SessionList=vo;exports.StandaloneChatInterface=Ao;exports.SystemContextEditor=jo;exports.ThemeToggle=_o;exports.ToolCallRenderer=As;exports.TrashIcon=Cc;exports.XIcon=np;exports.apiClient=ie;exports.cleanHtmlContent=Bg;exports.cn=Ee;exports.conversationsApi=$r;exports.copyToClipboard=Xg;exports.debounce=zg;exports.deepClone=js;exports.default=Ao;exports.downloadFile=Gg;exports.formatDate=Dg;exports.formatDateTime=Fg;exports.formatFileSize=pc;exports.formatRelativeTime=$g;exports.formatTime=gc;exports.generateId=Lg;exports.generateRandomColor=Vg;exports.getFileExtension=xc;exports.getOS=Kg;exports.isImageFile=Jg;exports.isMobile=Yg;exports.isValidEmail=Wg;exports.isValidUrl=Hg;exports.retry=Zg;exports.storage=ep;exports.throttle=qg;exports.truncateText=Ug;exports.useChatStore=vt;exports.useTheme=Nc;exports.version=Lp;
100
121
  //# sourceMappingURL=index.cjs.js.map