@leeoohoo/aichat 1.0.1 → 1.0.7
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 +56 -26
- package/dist/index.cjs.js.map +1 -1
- package/dist/index.css +2 -2
- package/dist/index.d.ts +543 -62
- package/dist/index.esm.js +17171 -14413
- package/dist/index.esm.js.map +1 -1
- package/package.json +10 -75
package/dist/index.cjs.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";require('./index.css');var
|
|
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={};/**
|
|
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
|
|
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={};/**
|
|
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
|
|
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}/**
|
|
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
|
|
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={};/**
|
|
26
26
|
* @license React
|
|
27
27
|
* use-sync-external-store-shim/with-selector.development.js
|
|
28
28
|
*
|
|
@@ -30,16 +30,16 @@
|
|
|
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 ho;function sc(){return ho||(ho=1,process.env.NODE_ENV!=="production"&&function(){function r(c,u){return c===u&&(c!==0||1/c===1/u)||c!==c&&u!==u}typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStart(Error());var e=M,t=va(),n=typeof Object.is=="function"?Object.is:r,s=t.useSyncExternalStore,o=e.useRef,a=e.useEffect,i=e.useMemo,d=e.useDebugValue;hn.useSyncExternalStoreWithSelector=function(c,u,f,m,b){var g=o(null);if(g.current===null){var h={hasValue:!1,value:null};g.current=h}else h=g.current;g=i(function(){function y(A){if(!w){if(w=!0,x=A,A=m(A),b!==void 0&&h.hasValue){var k=h.value;if(b(k,A))return v=k}return v=A}if(k=v,n(x,A))return k;var $=m(A);return b!==void 0&&b(k,$)?(x=A,k):(x=A,v=$)}var w=!1,x,v,S=f===void 0?null:f;return[function(){return y(u())},S===null?void 0:function(){return y(S())}]},[u,f,m,b]);var p=s(c,g[0],g[1]);return a(function(){h.hasValue=!0,h.value=p},[p]),d(p),p},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"&&typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop=="function"&&__REACT_DEVTOOLS_GLOBAL_HOOK__.registerInternalModuleStop(Error())}()),hn}process.env.NODE_ENV==="production"?Pn.exports=nc():Pn.exports=sc();var oc=Pn.exports;const ac=ec(oc),Sa={},{useDebugValue:ic}=M,{useSyncExternalStoreWithSelector:lc}=ac;let mo=!1;const cc=r=>r;function dc(r,e=cc,t){(Sa?"production":void 0)!=="production"&&t&&!mo&&(console.warn("[DEPRECATED] Use `createWithEqualityFn` instead of `create` or use `useStoreWithEqualityFn` instead of `useStore`. They can be imported from 'zustand/traditional'. https://github.com/pmndrs/zustand/discussions/1937"),mo=!0);const n=lc(r.subscribe,r.getState,r.getServerState||r.getInitialState,e,t);return ic(n),n}const uc=r=>{(Sa?"production":void 0)!=="production"&&typeof r!="function"&&console.warn("[DEPRECATED] Passing a vanilla store will be unsupported in a future version. Instead use `import { useStore } from 'zustand'`.");const e=typeof r=="function"?Zl(r):r,t=(n,s)=>dc(e,n,s);return Object.assign(t,e),t},Ca=r=>uc,fc={},hc=r=>(e,t,n)=>{const s=n.subscribe;return n.subscribe=(a,i,d)=>{let c=a;if(i){const u=(d==null?void 0:d.equalityFn)||Object.is;let f=a(n.getState());c=m=>{const b=a(m);if(!u(f,b)){const g=f;i(f=b,g)}},d!=null&&d.fireImmediately&&i(f,f)}return s(c)},r(e,t,n)},ka=hc;function mc(r,e){let t;try{t=r()}catch{return}return{getItem:s=>{var o;const a=d=>d===null?null:JSON.parse(d,void 0),i=(o=t.getItem(s))!=null?o:null;return i instanceof Promise?i.then(a):a(i)},setItem:(s,o)=>t.setItem(s,JSON.stringify(o,void 0)),removeItem:s=>t.removeItem(s)}}const Ft=r=>e=>{try{const t=r(e);return t instanceof Promise?t:{then(n){return Ft(n)(t)},catch(n){return this}}}catch(t){return{then(n){return this},catch(n){return Ft(n)(t)}}}},gc=(r,e)=>(t,n,s)=>{let o={getStorage:()=>localStorage,serialize:JSON.stringify,deserialize:JSON.parse,partialize:p=>p,version:0,merge:(p,y)=>({...y,...p}),...e},a=!1;const i=new Set,d=new Set;let c;try{c=o.getStorage()}catch{}if(!c)return r((...p)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...p)},n,s);const u=Ft(o.serialize),f=()=>{const p=o.partialize({...n()});let y;const w=u({state:p,version:o.version}).then(x=>c.setItem(o.name,x)).catch(x=>{y=x});if(y)throw y;return w},m=s.setState;s.setState=(p,y)=>{m(p,y),f()};const b=r((...p)=>{t(...p),f()},n,s);let g;const h=()=>{var p;if(!c)return;a=!1,i.forEach(w=>w(n()));const y=((p=o.onRehydrateStorage)==null?void 0:p.call(o,n()))||void 0;return Ft(c.getItem.bind(c))(o.name).then(w=>{if(w)return o.deserialize(w)}).then(w=>{if(w)if(typeof w.version=="number"&&w.version!==o.version){if(o.migrate)return o.migrate(w.state,w.version);console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return w.state}).then(w=>{var x;return g=o.merge(w,(x=n())!=null?x:b),t(g,!0),f()}).then(()=>{y==null||y(g,void 0),a=!0,d.forEach(w=>w(g))}).catch(w=>{y==null||y(void 0,w)})};return s.persist={setOptions:p=>{o={...o,...p},p.getStorage&&(c=p.getStorage())},clearStorage:()=>{c==null||c.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>h(),hasHydrated:()=>a,onHydrate:p=>(i.add(p),()=>{i.delete(p)}),onFinishHydration:p=>(d.add(p),()=>{d.delete(p)})},h(),g||b},pc=(r,e)=>(t,n,s)=>{let o={storage:mc(()=>localStorage),partialize:h=>h,version:0,merge:(h,p)=>({...p,...h}),...e},a=!1;const i=new Set,d=new Set;let c=o.storage;if(!c)return r((...h)=>{console.warn(`[zustand persist middleware] Unable to update item '${o.name}', the given storage is currently unavailable.`),t(...h)},n,s);const u=()=>{const h=o.partialize({...n()});return c.setItem(o.name,{state:h,version:o.version})},f=s.setState;s.setState=(h,p)=>{f(h,p),u()};const m=r((...h)=>{t(...h),u()},n,s);s.getInitialState=()=>m;let b;const g=()=>{var h,p;if(!c)return;a=!1,i.forEach(w=>{var x;return w((x=n())!=null?x:m)});const y=((p=o.onRehydrateStorage)==null?void 0:p.call(o,(h=n())!=null?h:m))||void 0;return Ft(c.getItem.bind(c))(o.name).then(w=>{if(w)if(typeof w.version=="number"&&w.version!==o.version){if(o.migrate)return[!0,o.migrate(w.state,w.version)];console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,w.state];return[!1,void 0]}).then(w=>{var x;const[v,S]=w;if(b=o.merge(S,(x=n())!=null?x:m),t(b,!0),v)return u()}).then(()=>{y==null||y(b,void 0),b=n(),a=!0,d.forEach(w=>w(b))}).catch(w=>{y==null||y(void 0,w)})};return s.persist={setOptions:h=>{o={...o,...h},h.storage&&(c=h.storage)},clearStorage:()=>{c==null||c.removeItem(o.name)},getOptions:()=>o,rehydrate:()=>g(),hasHydrated:()=>a,onHydrate:h=>(i.add(h),()=>{i.delete(h)}),onFinishHydration:h=>(d.add(h),()=>{d.delete(h)})},o.skipHydration||g(),b||m},yc=(r,e)=>"getStorage"in e||"serialize"in e||"deserialize"in e?((fc?"production":void 0)!=="production"&&console.warn("[DEPRECATED] `getStorage`, `serialize` and `deserialize` options are deprecated. Use `storage` option instead."),gc(r,e)):pc(r,e),Aa=yc;var Ea=Symbol.for("immer-nothing"),go=Symbol.for("immer-draftable"),pe=Symbol.for("immer-state"),bc=process.env.NODE_ENV!=="production"?[function(r){return`The plugin for '${r}' has not been loaded into Immer. To enable the plugin, import and call \`enable${r}()\` when initializing your application.`},function(r){return`produce can only be called on things that are draftable: plain objects, arrays, Map, Set or classes that are marked with '[immerable]: true'. Got '${r}'`},"This object has been frozen and should not be mutated",function(r){return"Cannot use a proxy that has been revoked. Did you pass an object from inside an immer function to an async process? "+r},"An immer producer returned a new value *and* modified its draft. Either return a new value *or* modify the draft.","Immer forbids circular references","The first or second argument to `produce` must be a function","The third argument to `produce` must be a function or undefined","First argument to `createDraft` must be a plain object, an array, or an immerable object","First argument to `finishDraft` must be a draft returned by `createDraft`",function(r){return`'current' expects a draft, got: ${r}`},"Object.defineProperty() cannot be used on an Immer draft","Object.setPrototypeOf() cannot be used on an Immer draft","Immer only supports deleting array indices","Immer only supports setting array indices and the 'length' property",function(r){return`'original' expects a draft, got: ${r}`}]:[];function ce(r,...e){if(process.env.NODE_ENV!=="production"){const t=bc[r],n=typeof t=="function"?t.apply(null,e):t;throw new Error(`[Immer] ${n}`)}throw new Error(`[Immer] minified error nr: ${r}. Full error at: https://bit.ly/3cXEKWf`)}var mt=Object.getPrototypeOf;function gt(r){return!!r&&!!r[pe]}function Ke(r){var e;return r?Ma(r)||Array.isArray(r)||!!r[go]||!!((e=r.constructor)!=null&&e[go])||zt(r)||Ur(r):!1}var wc=Object.prototype.constructor.toString();function Ma(r){if(!r||typeof r!="object")return!1;const e=mt(r);if(e===null)return!0;const t=Object.hasOwnProperty.call(e,"constructor")&&e.constructor;return t===Object?!0:typeof t=="function"&&Function.toString.call(t)===wc}function jr(r,e){Br(r)===0?Reflect.ownKeys(r).forEach(t=>{e(t,r[t],r)}):r.forEach((t,n)=>e(n,t,r))}function Br(r){const e=r[pe];return e?e.type_:Array.isArray(r)?1:zt(r)?2:Ur(r)?3:0}function Rn(r,e){return Br(r)===2?r.has(e):Object.prototype.hasOwnProperty.call(r,e)}function ja(r,e,t){const n=Br(r);n===2?r.set(e,t):n===3?r.add(t):r[e]=t}function xc(r,e){return r===e?r!==0||1/r===1/e:r!==r&&e!==e}function zt(r){return r instanceof Map}function Ur(r){return r instanceof Set}function ze(r){return r.copy_||r.base_}function Tn(r,e){if(zt(r))return new Map(r);if(Ur(r))return new Set(r);if(Array.isArray(r))return Array.prototype.slice.call(r);const t=Ma(r);if(e===!0||e==="class_only"&&!t){const n=Object.getOwnPropertyDescriptors(r);delete n[pe];let s=Reflect.ownKeys(n);for(let o=0;o<s.length;o++){const a=s[o],i=n[a];i.writable===!1&&(i.writable=!0,i.configurable=!0),(i.get||i.set)&&(n[a]={configurable:!0,writable:!0,enumerable:i.enumerable,value:r[a]})}return Object.create(mt(r),n)}else{const n=mt(r);if(n!==null&&t)return{...r};const s=Object.create(n);return Object.assign(s,r)}}function ls(r,e=!1){return Wr(r)||gt(r)||!Ke(r)||(Br(r)>1&&Object.defineProperties(r,{set:{value:ar},add:{value:ar},clear:{value:ar},delete:{value:ar}}),Object.freeze(r),e&&Object.values(r).forEach(t=>ls(t,!0))),r}function ar(){ce(2)}function Wr(r){return Object.isFrozen(r)}var _c={};function Qe(r){const e=_c[r];return e||ce(0,r),e}var $t;function Na(){return $t}function vc(r,e){return{drafts_:[],parent_:r,immer_:e,canAutoFreeze_:!0,unfinalizedDrafts_:0}}function po(r,e){e&&(Qe("Patches"),r.patches_=[],r.inversePatches_=[],r.patchListener_=e)}function In(r){Ln(r),r.drafts_.forEach(Sc),r.drafts_=null}function Ln(r){r===$t&&($t=r.parent_)}function yo(r){return $t=vc($t,r)}function Sc(r){const e=r[pe];e.type_===0||e.type_===1?e.revoke_():e.revoked_=!0}function bo(r,e){e.unfinalizedDrafts_=e.drafts_.length;const t=e.drafts_[0];return r!==void 0&&r!==t?(t[pe].modified_&&(In(e),ce(4)),Ke(r)&&(r=Nr(e,r),e.parent_||Or(e,r)),e.patches_&&Qe("Patches").generateReplacementPatches_(t[pe].base_,r,e.patches_,e.inversePatches_)):r=Nr(e,t,[]),In(e),e.patches_&&e.patchListener_(e.patches_,e.inversePatches_),r!==Ea?r:void 0}function Nr(r,e,t){if(Wr(e))return e;const n=e[pe];if(!n)return jr(e,(s,o)=>wo(r,n,e,s,o,t)),e;if(n.scope_!==r)return e;if(!n.modified_)return Or(r,n.base_,!0),n.base_;if(!n.finalized_){n.finalized_=!0,n.scope_.unfinalizedDrafts_--;const s=n.copy_;let o=s,a=!1;n.type_===3&&(o=new Set(s),s.clear(),a=!0),jr(o,(i,d)=>wo(r,n,s,i,d,t,a)),Or(r,s,!1),t&&r.patches_&&Qe("Patches").generatePatches_(n,t,r.patches_,r.inversePatches_)}return n.copy_}function wo(r,e,t,n,s,o,a){if(process.env.NODE_ENV!=="production"&&s===t&&ce(5),gt(s)){const i=o&&e&&e.type_!==3&&!Rn(e.assigned_,n)?o.concat(n):void 0,d=Nr(r,s,i);if(ja(t,n,d),gt(d))r.canAutoFreeze_=!1;else return}else a&&t.add(s);if(Ke(s)&&!Wr(s)){if(!r.immer_.autoFreeze_&&r.unfinalizedDrafts_<1)return;Nr(r,s),(!e||!e.scope_.parent_)&&typeof n!="symbol"&&(zt(t)?t.has(n):Object.prototype.propertyIsEnumerable.call(t,n))&&Or(r,s)}}function Or(r,e,t=!1){!r.parent_&&r.immer_.autoFreeze_&&r.canAutoFreeze_&&ls(e,t)}function Cc(r,e){const t=Array.isArray(r),n={type_:t?1:0,scope_:e?e.scope_:Na(),modified_:!1,finalized_:!1,assigned_:{},parent_:e,base_:r,draft_:null,copy_:null,revoke_:null,isManual_:!1};let s=n,o=cs;t&&(s=[n],o=Bt);const{revoke:a,proxy:i}=Proxy.revocable(s,o);return n.draft_=i,n.revoke_=a,i}var cs={get(r,e){if(e===pe)return r;const t=ze(r);if(!Rn(t,e))return kc(r,t,e);const n=t[e];return r.finalized_||!Ke(n)?n:n===mn(r.base_,e)?(gn(r),r.copy_[e]=Fn(n,r)):n},has(r,e){return e in ze(r)},ownKeys(r){return Reflect.ownKeys(ze(r))},set(r,e,t){const n=Oa(ze(r),e);if(n!=null&&n.set)return n.set.call(r.draft_,t),!0;if(!r.modified_){const s=mn(ze(r),e),o=s==null?void 0:s[pe];if(o&&o.base_===t)return r.copy_[e]=t,r.assigned_[e]=!1,!0;if(xc(t,s)&&(t!==void 0||Rn(r.base_,e)))return!0;gn(r),Dn(r)}return r.copy_[e]===t&&(t!==void 0||e in r.copy_)||Number.isNaN(t)&&Number.isNaN(r.copy_[e])||(r.copy_[e]=t,r.assigned_[e]=!0),!0},deleteProperty(r,e){return mn(r.base_,e)!==void 0||e in r.base_?(r.assigned_[e]=!1,gn(r),Dn(r)):delete r.assigned_[e],r.copy_&&delete r.copy_[e],!0},getOwnPropertyDescriptor(r,e){const t=ze(r),n=Reflect.getOwnPropertyDescriptor(t,e);return n&&{writable:!0,configurable:r.type_!==1||e!=="length",enumerable:n.enumerable,value:t[e]}},defineProperty(){ce(11)},getPrototypeOf(r){return mt(r.base_)},setPrototypeOf(){ce(12)}},Bt={};jr(cs,(r,e)=>{Bt[r]=function(){return arguments[0]=arguments[0][0],e.apply(this,arguments)}});Bt.deleteProperty=function(r,e){return process.env.NODE_ENV!=="production"&&isNaN(parseInt(e))&&ce(13),Bt.set.call(this,r,e,void 0)};Bt.set=function(r,e,t){return process.env.NODE_ENV!=="production"&&e!=="length"&&isNaN(parseInt(e))&&ce(14),cs.set.call(this,r[0],e,t,r[0])};function mn(r,e){const t=r[pe];return(t?ze(t):r)[e]}function kc(r,e,t){var s;const n=Oa(e,t);return n?"value"in n?n.value:(s=n.get)==null?void 0:s.call(r.draft_):void 0}function Oa(r,e){if(!(e in r))return;let t=mt(r);for(;t;){const n=Object.getOwnPropertyDescriptor(t,e);if(n)return n;t=mt(t)}}function Dn(r){r.modified_||(r.modified_=!0,r.parent_&&Dn(r.parent_))}function gn(r){r.copy_||(r.copy_=Tn(r.base_,r.scope_.immer_.useStrictShallowCopy_))}var Ac=class{constructor(r){this.autoFreeze_=!0,this.useStrictShallowCopy_=!1,this.produce=(e,t,n)=>{if(typeof e=="function"&&typeof t!="function"){const o=t;t=e;const a=this;return function(d=o,...c){return a.produce(d,u=>t.call(this,u,...c))}}typeof t!="function"&&ce(6),n!==void 0&&typeof n!="function"&&ce(7);let s;if(Ke(e)){const o=yo(this),a=Fn(e,void 0);let i=!0;try{s=t(a),i=!1}finally{i?In(o):Ln(o)}return po(o,n),bo(s,o)}else if(!e||typeof e!="object"){if(s=t(e),s===void 0&&(s=e),s===Ea&&(s=void 0),this.autoFreeze_&&ls(s,!0),n){const o=[],a=[];Qe("Patches").generateReplacementPatches_(e,s,o,a),n(o,a)}return s}else ce(1,e)},this.produceWithPatches=(e,t)=>{if(typeof e=="function")return(a,...i)=>this.produceWithPatches(a,d=>e(d,...i));let n,s;return[this.produce(e,t,(a,i)=>{n=a,s=i}),n,s]},typeof(r==null?void 0:r.autoFreeze)=="boolean"&&this.setAutoFreeze(r.autoFreeze),typeof(r==null?void 0:r.useStrictShallowCopy)=="boolean"&&this.setUseStrictShallowCopy(r.useStrictShallowCopy)}createDraft(r){Ke(r)||ce(8),gt(r)&&(r=Ec(r));const e=yo(this),t=Fn(r,void 0);return t[pe].isManual_=!0,Ln(e),t}finishDraft(r,e){const t=r&&r[pe];(!t||!t.isManual_)&&ce(9);const{scope_:n}=t;return po(n,e),bo(void 0,n)}setAutoFreeze(r){this.autoFreeze_=r}setUseStrictShallowCopy(r){this.useStrictShallowCopy_=r}applyPatches(r,e){let t;for(t=e.length-1;t>=0;t--){const s=e[t];if(s.path.length===0&&s.op==="replace"){r=s.value;break}}t>-1&&(e=e.slice(t+1));const n=Qe("Patches").applyPatches_;return gt(r)?n(r,e):this.produce(r,s=>n(s,e))}};function Fn(r,e){const t=zt(r)?Qe("MapSet").proxyMap_(r,e):Ur(r)?Qe("MapSet").proxySet_(r,e):Cc(r,e);return(e?e.scope_:Na()).drafts_.push(t),t}function Ec(r){return gt(r)||ce(10,r),Pa(r)}function Pa(r){if(!Ke(r)||Wr(r))return r;const e=r[pe];let t;if(e){if(!e.modified_)return e.base_;e.finalized_=!0,t=Tn(r,e.scope_.immer_.useStrictShallowCopy_)}else t=Tn(r,!0);return jr(t,(n,s)=>{ja(t,n,Pa(s))}),e&&(e.finalized_=!1),t}var Mc=new Ac,jc=Mc.produce;const Nc=r=>(e,t,n)=>(n.setState=(s,o,...a)=>{const i=typeof s=="function"?jc(s):s;return e(i,o,...a)},r(n.setState,t,n)),Ra=Nc,Oc="/api";class Ta{constructor(e=Oc){D(this,"baseUrl");this.baseUrl=e}async request(e,t={}){const n=`${this.baseUrl}${e}`,s={headers:{"Content-Type":"application/json",...t.headers},...t};try{const o=await fetch(n,s);if(!o.ok)throw new Error(`HTTP error! status: ${o.status}`);return await o.json()}catch(o){throw console.error(`API request failed: ${e}`,o),o}}async getSessions(){return this.request("/sessions")}async createSession(e){return this.request("/sessions",{method:"POST",body:JSON.stringify(e)})}async getSession(e){return this.request(`/sessions/${e}`)}async deleteSession(e){return this.request(`/sessions/${e}`,{method:"DELETE"})}async getSessionMessages(e){return this.request(`/sessions/${e}/messages`)}async createMessage(e){const t={...e,createdAt:e.createdAt?e.createdAt.toISOString():void 0};return this.request("/messages",{method:"POST",body:JSON.stringify(t)})}async getMcpConfigs(){return this.request("/mcp-configs")}async createMcpConfig(e){return this.request("/mcp-configs",{method:"POST",body:JSON.stringify(e)})}async updateMcpConfig(e,t){return this.request(`/mcp-configs/${e}`,{method:"PUT",body:JSON.stringify(t)})}async deleteMcpConfig(e){return this.request(`/mcp-configs/${e}`,{method:"DELETE"})}async getSystemContext(){return this.request("/system-context")}async updateSystemContext(e){return this.request("/system-context",{method:"POST",body:JSON.stringify({content:e})})}}const ge=new Ta;class Ia{constructor(){}async createSession(e){const t={id:crypto.randomUUID(),title:e.title},n=await ge.createSession(t);return{id:n.id,title:n.title,createdAt:new Date(n.created_at),updatedAt:new Date(n.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}}async getSession(e){try{const t=await ge.getSession(e);return t?{id:t.id,title:t.title,createdAt:new Date(t.created_at),updatedAt:new Date(t.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}:null}catch{return null}}async getAllSessions(){return(await ge.getSessions()).map(t=>({id:t.id,title:t.title,createdAt:new Date(t.created_at),updatedAt:new Date(t.updated_at),messageCount:0,tokenUsage:0,pinned:!1,archived:!1,tags:null,metadata:null}))}async updateSession(e,t){return console.warn("updateSession not implemented yet"),null}async deleteSession(e){try{return await ge.deleteSession(e),!0}catch{return!1}}async createMessage(e){var o;const t={id:crypto.randomUUID(),session_id:e.sessionId,role:e.role,content:e.content,summary:e.rawContent,tool_calls:(o=e.metadata)!=null&&o.toolCalls?JSON.stringify(e.metadata.toolCalls):void 0,tool_call_id:e.toolCallId,metadata:e.metadata?JSON.stringify(e.metadata):void 0},n={id:t.id,sessionId:t.session_id,role:t.role,content:t.content,metadata:t.metadata?JSON.parse(t.metadata):void 0,toolCalls:t.tool_calls?JSON.parse(t.tool_calls):void 0},s=await ge.createMessage(n);return{id:s.id,sessionId:s.session_id,role:s.role,content:s.content,rawContent:s.summary,tokensUsed:e.tokensUsed,status:e.status||"completed",createdAt:new Date(s.created_at),updatedAt:e.updatedAt,toolCallId:s.tool_call_id,metadata:s.metadata?JSON.parse(s.metadata):e.metadata}}async getSessionMessages(e){return(await ge.getSessionMessages(e)).map(n=>({id:n.id,sessionId:n.session_id,role:n.role,content:n.content,rawContent:n.summary,tokensUsed:void 0,status:"completed",createdAt:new Date(n.created_at),updatedAt:void 0,toolCallId:n.tool_call_id,metadata:n.metadata?JSON.parse(n.metadata):void 0}))}async updateMessage(e,t){return console.warn("updateMessage not implemented yet"),null}async deleteMessage(e){return console.warn("deleteMessage not implemented yet"),!1}}const q=new Ia,Je=class Je{constructor(){D(this,"pendingSaves",new Set);D(this,"savedMessages",new Map)}static getInstance(){return Je.instance||(Je.instance=new Je),Je.instance}async saveUserMessage(e){var n;const t=`${e.sessionId}-${e.role}-${e.content}-${(n=e.createdAt)==null?void 0:n.getTime()}`;if(this.pendingSaves.has(t)){for(;this.pendingSaves.has(t);)await new Promise(o=>setTimeout(o,10));const s=this.savedMessages.get(t);if(s)return s}this.pendingSaves.add(t);try{const s=await q.createMessage(e);return this.savedMessages.set(t,s),s}finally{this.pendingSaves.delete(t)}}async saveAssistantMessage(e){var n,s;const t=`${e.sessionId}-${e.role}-${JSON.stringify(((n=e.metadata)==null?void 0:n.toolCalls)||[])}-${(s=e.createdAt)==null?void 0:s.getTime()}`;if(this.pendingSaves.has(t)){for(;this.pendingSaves.has(t);)await new Promise(a=>setTimeout(a,10));const o=this.savedMessages.get(t);if(o)return o}this.pendingSaves.add(t);try{const o=await q.createMessage(e);return this.savedMessages.set(t,o),o}finally{this.pendingSaves.delete(t)}}async saveToolMessage(e){var n;const t=`${e.sessionId}-${e.role}-${e.content}-${(n=e.createdAt)==null?void 0:n.getTime()}`;if(this.pendingSaves.has(t)){for(;this.pendingSaves.has(t);)await new Promise(o=>setTimeout(o,10));const s=this.savedMessages.get(t);if(s)return s}this.pendingSaves.add(t);try{const s=await q.createMessage(e);return this.savedMessages.set(t,s),s}finally{this.pendingSaves.delete(t)}}async saveMessage(e){switch(e.role){case"user":return this.saveUserMessage(e);case"assistant":return this.saveAssistantMessage(e);case"tool":return this.saveToolMessage(e);default:return q.createMessage(e)}}clearCache(){this.savedMessages.clear()}getCacheStats(){return{pendingCount:this.pendingSaves.size,cachedCount:this.savedMessages.size}}};D(Je,"instance");let $n=Je;const Pr=$n.getInstance(),Pe=Ca()(ka(Ra(Aa((r,e)=>({sessions:[],currentSessionId:null,currentSession:null,messages:[],isLoading:!1,isStreaming:!1,streamingMessageId:null,sidebarOpen:!0,theme:"light",chatConfig:{model:"gpt-4",temperature:.7,maxTokens:2048,systemPrompt:"",enableMcp:!0},mcpConfigs:[],aiModelConfigs:[],systemContext:null,selectedModelId:null,error:null,loadSessions:async()=>{try{r(n=>{n.isLoading=!0,n.error=null});const t=await q.getAllSessions();r(n=>{n.sessions=t,n.isLoading=!1})}catch(t){r(n=>{n.error=t instanceof Error?t.message:"Failed to load sessions",n.isLoading=!1})}},createSession:async(t="New Chat")=>{try{const n=await q.createSession({title:t,createdAt:new Date,updatedAt:new Date,messageCount:0,tokenUsage:0,pinned:!1,archived:!1});return r(s=>{s.sessions.unshift(n),s.currentSessionId=n.id,s.currentSession=n,s.messages=[]}),n.id}catch(n){throw r(s=>{s.error=n instanceof Error?n.message:"Failed to create session"}),n}},selectSession:async t=>{var n;try{console.log("🔍 selectSession 被调用,sessionId:",t),r(d=>{d.isLoading=!0,d.error=null}),console.log("✅ isLoading 已设置为 true");const{conversationsApi:s}=await Promise.resolve().then(()=>To),o=await s.getDetails(t),a=await s.getMessages(t);console.log("✅ API 调用完成,获取到会话和消息数据"),console.log("📊 原始消息数据结构:",a);const i=((n=a.data)==null?void 0:n.messages)||[];console.log("📊 解析后的消息数组:",i.length,"条消息"),i.forEach((d,c)=>{var u,f;console.log(`📝 消息 ${c+1}:`,{id:d.id,role:d.role,content:d.content?d.content.substring(0,100)+"...":"(空内容)",metadata:d.metadata,hasToolCalls:!!(d.metadata&&d.metadata.toolCalls),toolCallsCount:(u=d.metadata)!=null&&u.toolCalls?d.metadata.toolCalls.length:0,toolCallsPreview:(f=d.metadata)!=null&&f.toolCalls?d.metadata.toolCalls.map(m=>m.name||m.type):[]})}),r(d=>{d.currentSessionId=t;const c=o.data.conversation;d.currentSession={id:c.id,title:c.title,createdAt:new Date(c.created_at),updatedAt:new Date(c.updated_at),messageCount:c.messageCount||0,tokenUsage:c.tokenUsage||0,tags:c.tags||null,pinned:c.pinned||!1,archived:c.archived||!1,metadata:c.metadata||null};const u=a.data.messages.map((f,m)=>{const b={...f,createdAt:new Date(f.created_at||f.createdAt),updatedAt:f.updated_at?new Date(f.updated_at):void 0,status:f.status||"completed"};return console.log(`🔄 处理消息 ${m+1} (${f.id}):`,{原始content:f.content,原始metadata:f.metadata,处理后content:b.content,处理后metadata:b.metadata}),b});d.messages=u.sort((f,m)=>{const b=f.createdAt.getTime(),g=m.createdAt.getTime();return b-g}),console.log("✅ 最终存储的messages数量:",u.length),d.isLoading=!1}),console.log("✅ selectSession 完成,currentSessionId 已设置为:",t)}catch(s){console.error("❌ selectSession 失败:",s),r(o=>{o.error=s instanceof Error?s.message:"Failed to load session",o.isLoading=!1})}},updateSession:async(t,n)=>{try{await q.updateSession(t,n),r(s=>{const o=s.sessions.findIndex(a=>a.id===t);o!==-1&&(s.sessions[o]={...s.sessions[o],...n}),s.currentSessionId===t&&s.currentSession&&(s.currentSession={...s.currentSession,...n})})}catch(s){r(o=>{o.error=s instanceof Error?s.message:"Failed to update session"})}},deleteSession:async t=>{try{await q.deleteSession(t),r(n=>{n.sessions=n.sessions.filter(s=>s.id!==t),n.currentSessionId===t&&(n.currentSessionId=null,n.currentSession=null,n.messages=[])})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to delete session"})}},loadMessages:async t=>{try{const{conversationsApi:n}=await Promise.resolve().then(()=>To),s=await n.getMessages(t);console.log("=== loadMessages Debug ==="),console.log("Session ID:",t),console.log("Raw messages from API:",s.data.messages.length),s.data.messages.forEach((o,a)=>{var i;console.log(`Message ${a+1}:`,{id:o.id,role:o.role,content:o.content?o.content.substring(0,100)+"...":"[EMPTY]",hasToolCalls:!!(o.toolCalls||(i=o.metadata)!=null&&i.toolCalls),tool_calls:o.tool_calls?"YES":"NO"})}),r(o=>{const a=s.data.messages.map(i=>{var c;const d={...i.metadata,toolCalls:i.toolCalls||((c=i.metadata)==null?void 0:c.toolCalls)||[]};return{...i,createdAt:new Date(i.created_at||i.createdAt),status:i.status||"completed",metadata:d}});o.messages=a.sort((i,d)=>{const c=i.createdAt.getTime(),u=d.createdAt.getTime();return c-u}),console.log("Final processed messages:",o.messages.length),o.messages.forEach((i,d)=>{var c,u,f,m;console.log(`Processed ${d+1}:`,{id:i.id,role:i.role,content:i.content?i.content.substring(0,50)+"...":"[EMPTY]",hasMetadataToolCalls:!!((u=(c=i.metadata)==null?void 0:c.toolCalls)!=null&&u.length),toolCallsCount:((m=(f=i.metadata)==null?void 0:f.toolCalls)==null?void 0:m.length)||0})})})}catch(n){console.error("loadMessages error:",n),r(s=>{s.error=n instanceof Error?n.message:"Failed to load messages"})}},sendMessage:async(t,n=[])=>{const{currentSessionId:s,selectedModelId:o,aiModelConfigs:a}=e();if(!s)throw new Error("No active session");if(!o)throw new Error("请先选择一个AI模型");const i=a.find(d=>d.id===o);if(!i||!i.enabled)throw new Error("选择的模型不可用");try{const d=new Date,c=await Pr.saveUserMessage({sessionId:s,role:"user",content:t,status:"completed",createdAt:d,metadata:{...n.length>0?{attachments:n}:{},model:i.model_name,modelConfig:{id:i.id,name:i.name,base_url:i.base_url,model_name:i.model_name}}});r(h=>{h.messages.push(c),h.isLoading=!0});const u=new Date(d.getTime()+1),f={id:`temp_${Date.now()}_${Math.random().toString(36).substr(2,9)}`,sessionId:s,role:"assistant",content:"",status:"streaming",createdAt:u,metadata:{model:i.model_name,modelConfig:{id:i.id,name:i.name,base_url:i.base_url,model_name:i.model_name},toolCalls:[],contentSegments:[{content:"",type:"text"}],currentSegmentIndex:0}};r(h=>{h.messages.push(f),h.isStreaming=!0,h.streamingMessageId=f.id});const{chatService:m}=await Promise.resolve().then(()=>ng),{chatConfig:b}=e(),g=i?{model_name:i.model_name,temperature:b.temperature,max_tokens:16e3,api_key:i.api_key,base_url:i.base_url}:void 0;await m.sendMessage(s,t,n,{onChunk:h=>{r(p=>{const y=p.messages.find(w=>w.id===f.id);if(y&&y.metadata){const w=typeof h.content=="string"?h.content:typeof h=="string"?h:h.content||"",x=y.metadata.currentSegmentIndex||0,v=y.metadata.contentSegments||[];v[x]&&v[x].type==="text"?v[x].content+=w:(v.push({content:w,type:"text"}),y.metadata.currentSegmentIndex=v.length-1),y.content=v.filter(S=>S.type==="text").map(S=>S.content).join("")}})},onToolCall:h=>{console.log("Tool calls:",h),r(p=>{var w,x;const y=p.messages.find(v=>v.id===f.id);if(y&&y.metadata){y.metadata.toolCalls||(y.metadata.toolCalls=[]);const v=y.metadata.contentSegments||[];if(Array.isArray(h))h.forEach(S=>{var k,$;const A={id:S.id,messageId:y.id,name:((k=S.function)==null?void 0:k.name)||S.name,arguments:(($=S.function)==null?void 0:$.arguments)||S.arguments,result:"",createdAt:new Date};y.metadata.toolCalls.push(A),v.push({content:"",type:"tool_call",toolCallId:A.id})});else{const S={id:h.id,messageId:y.id,name:((w=h.function)==null?void 0:w.name)||h.name,arguments:((x=h.function)==null?void 0:x.arguments)||h.arguments,result:"",createdAt:new Date};y.metadata.toolCalls.push(S),v.push({content:"",type:"tool_call",toolCallId:h.id})}v.push({content:"",type:"text"}),y.metadata.currentSegmentIndex=v.length-1}})},onToolResult:h=>{console.log("Tool results:",h),r(p=>{const y=p.messages.find(w=>w.id===f.id);if(y&&y.metadata&&y.metadata.toolCalls){if(Array.isArray(h))h.forEach(w=>{const x=y.metadata.toolCalls.find(v=>v.id===w.toolCallId);x&&(x.result=w.result)});else if(h.toolCallId){const w=y.metadata.toolCalls.find(x=>x.id===h.toolCallId);w&&(w.result=h.result)}}})},onToolStreamChunk:h=>{r(p=>{const y=p.messages.find(w=>w.id===f.id);if(y&&y.metadata&&y.metadata.toolCalls){const w=y.metadata.toolCalls.find(x=>x.id===h.toolCallId);w&&(w.result=(w.result||"")+h.chunk)}})},onComplete:async()=>{var h;try{const p=e().messages.find(y=>y.id===f.id);if(p){const y={sessionId:s,role:"assistant",content:p.content,status:"completed",createdAt:p.createdAt,metadata:p.metadata};(h=p.metadata)!=null&&h.toolCalls&&p.metadata.toolCalls.length>0&&(y.toolCalls=p.metadata.toolCalls.map(x=>({id:x.id,function:{name:x.name,arguments:typeof x.arguments=="string"?x.arguments:JSON.stringify(x.arguments)}})));const w=await Pr.saveAssistantMessage(y);r(x=>{const v=x.messages.findIndex(S=>S.id===f.id);v!==-1&&(x.messages[v]=w),x.isLoading=!1,x.isStreaming=!1,x.streamingMessageId=null}),s&&await e().selectSession(s)}}catch(p){console.error("Failed to save assistant message:",p),r(y=>{y.isLoading=!1,y.isStreaming=!1,y.streamingMessageId=null})}},onError:h=>{r(p=>{p.error=h.message||"AI response failed",p.isLoading=!1,p.isStreaming=!1,p.streamingMessageId=null})}},g)}catch(d){r(c=>{c.error=d instanceof Error?d.message:"Failed to send message",c.isLoading=!1,c.isStreaming=!1,c.streamingMessageId=null})}},updateMessage:async(t,n)=>{try{const s={...n,...n.role==="tool"?{role:void 0}:{}};s.role===void 0&&delete s.role,await q.updateMessage(t,s),r(o=>{const a=o.messages.findIndex(i=>i.id===t);a!==-1&&(o.messages[a]={...o.messages[a],...n})})}catch(s){r(o=>{o.error=s instanceof Error?s.message:"Failed to update message"})}},deleteMessage:async t=>{try{await q.deleteMessage(t),r(n=>{n.messages=n.messages.filter(s=>s.id!==t)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to delete message"})}},startStreaming:t=>{r(n=>{n.isStreaming=!0,n.streamingMessageId=t})},updateStreamingMessage:t=>{const{streamingMessageId:n}=e();n&&r(s=>{const o=s.messages.findIndex(a=>a.id===n);o!==-1&&(s.messages[o].content=t)})},stopStreaming:()=>{const{streamingMessageId:t}=e();if(r(n=>{n.isStreaming=!1,n.isLoading=!1,n.streamingMessageId=null}),t){const n=e().messages.find(s=>s.id===t);n&&q.updateMessage(t,{content:n.content,updatedAt:new Date})}},toggleSidebar:()=>{r(t=>{t.sidebarOpen=!t.sidebarOpen})},setTheme:t=>{r(n=>{n.theme=t})},updateChatConfig:async t=>{try{const n={...e().chatConfig,...t};r(s=>{s.chatConfig=n})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to update config"})}},loadMcpConfigs:async()=>{try{const t=await ge.getMcpConfigs();r(n=>{n.mcpConfigs=t.map(s=>({id:s.id,name:s.name,serverUrl:s.command,enabled:s.enabled,createdAt:new Date(s.created_at),updatedAt:new Date(s.created_at)}))})}catch(t){r(n=>{n.error=t instanceof Error?t.message:"Failed to load MCP configs"})}},updateMcpConfig:async t=>{try{e().mcpConfigs.findIndex(s=>s.id===t.id)!==-1?await ge.updateMcpConfig(t.id,{name:t.name,command:t.serverUrl,enabled:t.enabled,args:"[]",env:"{}"}):await ge.createMcpConfig({id:t.id,name:t.name,command:t.serverUrl,enabled:t.enabled,args:"[]",env:"{}"}),r(s=>{const o=s.mcpConfigs.findIndex(a=>a.id===t.id);o!==-1?s.mcpConfigs[o]=t:s.mcpConfigs.push(t)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to update MCP config"})}},deleteMcpConfig:async t=>{try{await ge.deleteMcpConfig(t),r(n=>{n.mcpConfigs=n.mcpConfigs.filter(s=>s.id!==t)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to delete MCP config"})}},loadAiModelConfigs:async()=>{try{const t=await fetch("/api/ai-model-configs");if(!t.ok)throw new Error("Failed to load AI model configs");const s=(await t.json()).map(o=>({id:o.id,name:o.name,base_url:o.base_url,api_key:o.api_key,model_name:o.model,enabled:o.enabled,createdAt:new Date(o.created_at),updatedAt:new Date(o.created_at)}));r(o=>{o.aiModelConfigs=s})}catch(t){r(n=>{n.error=t instanceof Error?t.message:"Failed to load AI model configs"})}},updateAiModelConfig:async t=>{try{const n=e().aiModelConfigs.find(d=>d.id===t.id),s=n?"PUT":"POST",o=n?`/api/ai-model-configs/${t.id}`:"/api/ai-model-configs",a={id:t.id,name:t.name,provider:"openai",model:t.model_name,apiKey:t.api_key,baseUrl:t.base_url,enabled:t.enabled},i=await fetch(o,{method:s,headers:{"Content-Type":"application/json"},body:JSON.stringify(a)});if(!i.ok){const d=await i.text();throw new Error(`Failed to save AI model config: ${d}`)}r(d=>{const c=d.aiModelConfigs.findIndex(u=>u.id===t.id);c!==-1?d.aiModelConfigs[c]=t:d.aiModelConfigs.push(t)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to update AI model config"})}},deleteAiModelConfig:async t=>{try{if(!(await fetch(`/api/ai-model-configs/${t}`,{method:"DELETE"})).ok)throw new Error("Failed to delete AI model config");r(s=>{s.aiModelConfigs=s.aiModelConfigs.filter(o=>o.id!==t),s.selectedModelId===t&&(s.selectedModelId=null)})}catch(n){r(s=>{s.error=n instanceof Error?n.message:"Failed to delete AI model config"})}},setError:t=>{r(n=>{n.error=t})},clearError:()=>{r(t=>{t.error=null})},setSelectedModel:t=>{r(n=>{n.selectedModelId=t})},loadSystemContext:async()=>{try{console.log("Store: Loading system context from API");const t=await ge.getSystemContext();console.log("Store: API response:",t),r(n=>{n.systemContext=t.content||null}),console.log("Store: System context set to:",t.content||null)}catch(t){console.error("Store: Failed to load system context:",t),r(n=>{n.systemContext=null})}},updateSystemContext:async t=>{try{await ge.updateSystemContext(t),r(n=>{n.systemContext=t})}catch(n){throw console.error("Failed to update system context:",n),n}}}),{name:"chat-store",partialize:r=>({theme:r.theme,sidebarOpen:r.sidebarOpen,chatConfig:r.chatConfig,selectedModelId:r.selectedModelId})})))),Pc=()=>Pe(r=>r.currentSession),Rc=()=>Pe(r=>r.sessions);function Tc(r){const e=r||ge;return Ca()(ka(Ra(Aa((t,n)=>({sessions:[],currentSessionId:null,currentSession:null,messages:[],isLoading:!1,isStreaming:!1,streamingMessageId:null,sidebarOpen:!0,theme:"light",chatConfig:{model:"gpt-4",temperature:.7,maxTokens:2048,systemPrompt:"",enableMcp:!0},mcpConfigs:[],aiModelConfigs:[],systemContext:null,selectedModelId:null,error:null,loadSessions:async()=>{try{t(o=>{o.isLoading=!0,o.error=null});const s=await q.getAllSessions();t(o=>{o.sessions=s,o.isLoading=!1})}catch(s){console.error("Failed to load sessions:",s),t(o=>{o.error=s instanceof Error?s.message:"Failed to load sessions",o.isLoading=!1})}},createSession:async(s="New Chat")=>{try{const o=await q.createSession({title:s,messageCount:0,tokenUsage:0,pinned:!1,archived:!1,createdAt:new Date,updatedAt:new Date});return t(a=>{a.sessions.unshift(o),a.currentSessionId=o.id,a.currentSession=o,a.messages=[],a.error=null}),o.id}catch(o){throw console.error("Failed to create session:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to create session"}),o}},selectSession:async s=>{try{t(i=>{i.isLoading=!0,i.error=null});const o=await q.getSession(s),a=await q.getSessionMessages(s);t(i=>{i.currentSessionId=s,i.currentSession=o,i.messages=a,i.isLoading=!1,o||(i.error="Session not found")})}catch(o){console.error("Failed to select session:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to select session",a.isLoading=!1})}},updateSession:async(s,o)=>{try{const a=await q.updateSession(s,o);t(i=>{const d=i.sessions.findIndex(c=>c.id===s);d!==-1&&a&&(i.sessions[d]=a),i.currentSessionId===s&&(i.currentSession=a)})}catch(a){console.error("Failed to update session:",a),t(i=>{i.error=a instanceof Error?a.message:"Failed to update session"})}},deleteSession:async s=>{try{await q.deleteSession(s),t(o=>{o.sessions=o.sessions.filter(a=>a.id!==s),o.currentSessionId===s&&(o.currentSessionId=null,o.currentSession=null,o.messages=[])})}catch(o){console.error("Failed to delete session:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to delete session"})}},loadMessages:async s=>{try{t(a=>{a.isLoading=!0,a.error=null});const o=await q.getSessionMessages(s);t(a=>{a.messages=o,a.isLoading=!1})}catch(o){console.error("Failed to load messages:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to load messages",a.isLoading=!1})}},sendMessage:async(s,o=[])=>{const{currentSession:a}=n();if(!a)throw new Error("No active session");try{t(c=>{c.isLoading=!0,c.error=null});const i=await q.createMessage({sessionId:a.id,role:"user",content:s,status:"completed",createdAt:new Date,metadata:{attachments:o}});t(c=>{c.messages.push(i)});const d=await q.createMessage({sessionId:a.id,role:"assistant",content:"",status:"streaming",createdAt:new Date});t(c=>{c.messages.push(d),c.streamingMessageId=d.id,c.isStreaming=!0}),t(c=>{c.isStreaming=!1,c.streamingMessageId=null,c.isLoading=!1})}catch(i){console.error("Failed to send message:",i),t(d=>{d.error=i instanceof Error?i.message:"Failed to send message",d.isLoading=!1,d.isStreaming=!1,d.streamingMessageId=null})}},updateMessage:async(s,o)=>{try{const a=await q.updateMessage(s,o);t(i=>{const d=i.messages.findIndex(c=>c.id===s);d!==-1&&a&&(i.messages[d]=a)})}catch(a){console.error("Failed to update message:",a),t(i=>{i.error=a instanceof Error?a.message:"Failed to update message"})}},deleteMessage:async s=>{try{await q.deleteMessage(s),t(o=>{o.messages=o.messages.filter(a=>a.id!==s)})}catch(o){console.error("Failed to delete message:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to delete message"})}},startStreaming:s=>{t(o=>{o.isStreaming=!0,o.streamingMessageId=s})},updateStreamingMessage:s=>{t(o=>{if(o.streamingMessageId){const a=o.messages.findIndex(i=>i.id===o.streamingMessageId);a!==-1&&(o.messages[a].content=s)}})},stopStreaming:()=>{t(s=>{s.isStreaming=!1,s.streamingMessageId=null})},toggleSidebar:()=>{t(s=>{s.sidebarOpen=!s.sidebarOpen})},setTheme:s=>{t(o=>{o.theme=s})},updateChatConfig:async s=>{try{t(o=>{o.chatConfig={...o.chatConfig,...s}})}catch(o){console.error("Failed to update chat config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to update chat config"})}},loadMcpConfigs:async()=>{try{const s=await e.getMcpConfigs();t(o=>{o.mcpConfigs=s})}catch(s){console.error("Failed to load MCP configs:",s),t(o=>{o.error=s instanceof Error?s.message:"Failed to load MCP configs"})}},updateMcpConfig:async s=>{try{s.id?await e.updateMcpConfig(s.id,{id:s.id,name:s.name,command:s.serverUrl,enabled:s.enabled}):await e.createMcpConfig({id:crypto.randomUUID(),name:s.name,command:s.serverUrl,enabled:s.enabled});const o=await e.getMcpConfigs();t(a=>{a.mcpConfigs=o})}catch(o){console.error("Failed to update MCP config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to update MCP config"})}},deleteMcpConfig:async s=>{try{await e.deleteMcpConfig(s),t(o=>{o.mcpConfigs=o.mcpConfigs.filter(a=>a.id!==s)})}catch(o){console.error("Failed to delete MCP config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to delete MCP config"})}},loadAiModelConfigs:async()=>{try{const s=[];t(o=>{o.aiModelConfigs=s})}catch(s){console.error("Failed to load AI model configs:",s),t(o=>{o.error=s instanceof Error?s.message:"Failed to load AI model configs"})}},updateAiModelConfig:async s=>{try{t(o=>{if(s.id){const a=o.aiModelConfigs.findIndex(i=>i.id===s.id);a!==-1&&(o.aiModelConfigs[a]=s)}else{const a={...s,id:crypto.randomUUID()};o.aiModelConfigs.push(a)}})}catch(o){console.error("Failed to update AI model config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to update AI model config"})}},deleteAiModelConfig:async s=>{try{t(o=>{o.aiModelConfigs=o.aiModelConfigs.filter(a=>a.id!==s)})}catch(o){console.error("Failed to delete AI model config:",o),t(a=>{a.error=o instanceof Error?o.message:"Failed to delete AI model config"})}},setSelectedModel:s=>{t(o=>{o.selectedModelId=s})},loadSystemContext:async()=>{try{const s=await e.getSystemContext();t(o=>{o.systemContext=s.content||null})}catch(s){console.error("Failed to load system context:",s),t(o=>{o.systemContext=null})}},updateSystemContext:async s=>{try{await e.updateSystemContext(s),t(o=>{o.systemContext=s})}catch(o){throw console.error("Failed to update system context:",o),o}},setError:s=>{t(o=>{o.error=s})},clearError:()=>{t(s=>{s.error=null})}}),{name:"chat-store",partialize:t=>({theme:t.theme,sidebarOpen:t.sidebarOpen,chatConfig:t.chatConfig,selectedModelId:t.selectedModelId})}))))}function La(r){var e,t,n="";if(typeof r=="string"||typeof r=="number")n+=r;else if(typeof r=="object")if(Array.isArray(r)){var s=r.length;for(e=0;e<s;e++)r[e]&&(t=La(r[e]))&&(n&&(n+=" "),n+=t)}else for(t in r)r[t]&&(n&&(n+=" "),n+=t);return n}function Ic(){for(var r,e,t=0,n="",s=arguments.length;t<s;t++)(r=arguments[t])&&(e=La(r))&&(n&&(n+=" "),n+=e);return n}const ds="-",Lc=r=>{const e=Fc(r),{conflictingClassGroups:t,conflictingClassGroupModifiers:n}=r;return{getClassGroupId:a=>{const i=a.split(ds);return i[0]===""&&i.length!==1&&i.shift(),Da(i,e)||Dc(a)},getConflictingClassGroupIds:(a,i)=>{const d=t[a]||[];return i&&n[a]?[...d,...n[a]]:d}}},Da=(r,e)=>{var a;if(r.length===0)return e.classGroupId;const t=r[0],n=e.nextPart.get(t),s=n?Da(r.slice(1),n):void 0;if(s)return s;if(e.validators.length===0)return;const o=r.join(ds);return(a=e.validators.find(({validator:i})=>i(o)))==null?void 0:a.classGroupId},xo=/^\[(.+)\]$/,Dc=r=>{if(xo.test(r)){const e=xo.exec(r)[1],t=e==null?void 0:e.substring(0,e.indexOf(":"));if(t)return"arbitrary.."+t}},Fc=r=>{const{theme:e,prefix:t}=r,n={nextPart:new Map,validators:[]};return Bc(Object.entries(r.classGroups),t).forEach(([o,a])=>{Bn(a,n,o,e)}),n},Bn=(r,e,t,n)=>{r.forEach(s=>{if(typeof s=="string"){const o=s===""?e:_o(e,s);o.classGroupId=t;return}if(typeof s=="function"){if($c(s)){Bn(s(n),e,t,n);return}e.validators.push({validator:s,classGroupId:t});return}Object.entries(s).forEach(([o,a])=>{Bn(a,_o(e,o),t,n)})})},_o=(r,e)=>{let t=r;return e.split(ds).forEach(n=>{t.nextPart.has(n)||t.nextPart.set(n,{nextPart:new Map,validators:[]}),t=t.nextPart.get(n)}),t},$c=r=>r.isThemeGetter,Bc=(r,e)=>e?r.map(([t,n])=>{const s=n.map(o=>typeof o=="string"?e+o:typeof o=="object"?Object.fromEntries(Object.entries(o).map(([a,i])=>[e+a,i])):o);return[t,s]}):r,Uc=r=>{if(r<1)return{get:()=>{},set:()=>{}};let e=0,t=new Map,n=new Map;const s=(o,a)=>{t.set(o,a),e++,e>r&&(e=0,n=t,t=new Map)};return{get(o){let a=t.get(o);if(a!==void 0)return a;if((a=n.get(o))!==void 0)return s(o,a),a},set(o,a){t.has(o)?t.set(o,a):s(o,a)}}},Fa="!",Wc=r=>{const{separator:e,experimentalParseClassName:t}=r,n=e.length===1,s=e[0],o=e.length,a=i=>{const d=[];let c=0,u=0,f;for(let p=0;p<i.length;p++){let y=i[p];if(c===0){if(y===s&&(n||i.slice(p,p+o)===e)){d.push(i.slice(u,p)),u=p+o;continue}if(y==="/"){f=p;continue}}y==="["?c++:y==="]"&&c--}const m=d.length===0?i:i.substring(u),b=m.startsWith(Fa),g=b?m.substring(1):m,h=f&&f>u?f-u:void 0;return{modifiers:d,hasImportantModifier:b,baseClassName:g,maybePostfixModifierPosition:h}};return t?i=>t({className:i,parseClassName:a}):a},Hc=r=>{if(r.length<=1)return r;const e=[];let t=[];return r.forEach(n=>{n[0]==="["?(e.push(...t.sort(),n),t=[]):t.push(n)}),e.push(...t.sort()),e},zc=r=>({cache:Uc(r.cacheSize),parseClassName:Wc(r),...Lc(r)}),qc=/\s+/,Vc=(r,e)=>{const{parseClassName:t,getClassGroupId:n,getConflictingClassGroupIds:s}=e,o=[],a=r.trim().split(qc);let i="";for(let d=a.length-1;d>=0;d-=1){const c=a[d],{modifiers:u,hasImportantModifier:f,baseClassName:m,maybePostfixModifierPosition:b}=t(c);let g=!!b,h=n(g?m.substring(0,b):m);if(!h){if(!g){i=c+(i.length>0?" "+i:i);continue}if(h=n(m),!h){i=c+(i.length>0?" "+i:i);continue}g=!1}const p=Hc(u).join(":"),y=f?p+Fa:p,w=y+h;if(o.includes(w))continue;o.push(w);const x=s(h,g);for(let v=0;v<x.length;++v){const S=x[v];o.push(y+S)}i=c+(i.length>0?" "+i:i)}return i};function Jc(){let r=0,e,t,n="";for(;r<arguments.length;)(e=arguments[r++])&&(t=$a(e))&&(n&&(n+=" "),n+=t);return n}const $a=r=>{if(typeof r=="string")return r;let e,t="";for(let n=0;n<r.length;n++)r[n]&&(e=$a(r[n]))&&(t&&(t+=" "),t+=e);return t};function Gc(r,...e){let t,n,s,o=a;function a(d){const c=e.reduce((u,f)=>f(u),r());return t=zc(c),n=t.cache.get,s=t.cache.set,o=i,i(d)}function i(d){const c=n(d);if(c)return c;const u=Vc(d,t);return s(d,u),u}return function(){return o(Jc.apply(null,arguments))}}const H=r=>{const e=t=>t[r]||[];return e.isThemeGetter=!0,e},Ba=/^\[(?:([a-z-]+):)?(.+)\]$/i,Xc=/^\d+\/\d+$/,Yc=new Set(["px","full","screen"]),Kc=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Qc=/\d+(%|px|r?em|[sdl]?v([hwib]|min|max)|pt|pc|in|cm|mm|cap|ch|ex|r?lh|cq(w|h|i|b|min|max))|\b(calc|min|max|clamp)\(.+\)|^0$/,Zc=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,ed=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,td=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Me=r=>ut(r)||Yc.has(r)||Xc.test(r),Te=r=>yt(r,"length",cd),ut=r=>!!r&&!Number.isNaN(Number(r)),pn=r=>yt(r,"number",ut),Ct=r=>!!r&&Number.isInteger(Number(r)),rd=r=>r.endsWith("%")&&ut(r.slice(0,-1)),L=r=>Ba.test(r),Ie=r=>Kc.test(r),nd=new Set(["length","size","percentage"]),sd=r=>yt(r,nd,Ua),od=r=>yt(r,"position",Ua),ad=new Set(["image","url"]),id=r=>yt(r,ad,ud),ld=r=>yt(r,"",dd),kt=()=>!0,yt=(r,e,t)=>{const n=Ba.exec(r);return n?n[1]?typeof e=="string"?n[1]===e:e.has(n[1]):t(n[2]):!1},cd=r=>Qc.test(r)&&!Zc.test(r),Ua=()=>!1,dd=r=>ed.test(r),ud=r=>td.test(r),fd=()=>{const r=H("colors"),e=H("spacing"),t=H("blur"),n=H("brightness"),s=H("borderColor"),o=H("borderRadius"),a=H("borderSpacing"),i=H("borderWidth"),d=H("contrast"),c=H("grayscale"),u=H("hueRotate"),f=H("invert"),m=H("gap"),b=H("gradientColorStops"),g=H("gradientColorStopPositions"),h=H("inset"),p=H("margin"),y=H("opacity"),w=H("padding"),x=H("saturate"),v=H("scale"),S=H("sepia"),A=H("skew"),k=H("space"),$=H("translate"),j=()=>["auto","contain","none"],T=()=>["auto","hidden","clip","visible","scroll"],P=()=>["auto",L,e],C=()=>[L,e],F=()=>["",Me,Te],U=()=>["auto",ut,L],G=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],te=()=>["solid","dashed","dotted","double","none"],St=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],ye=()=>["start","end","center","between","around","evenly","stretch"],Re=()=>["","0",L],nr=()=>["auto","avoid","all","avoid-page","page","left","right","column"],Q=()=>[ut,L];return{cacheSize:500,separator:":",theme:{colors:[kt],spacing:[Me,Te],blur:["none","",Ie,L],brightness:Q(),borderColor:[r],borderRadius:["none","","full",Ie,L],borderSpacing:C(),borderWidth:F(),contrast:Q(),grayscale:Re(),hueRotate:Q(),invert:Re(),gap:C(),gradientColorStops:[r],gradientColorStopPositions:[rd,Te],inset:P(),margin:P(),opacity:Q(),padding:C(),saturate:Q(),scale:Q(),sepia:Re(),skew:Q(),space:C(),translate:C()},classGroups:{aspect:[{aspect:["auto","square","video",L]}],container:["container"],columns:[{columns:[Ie]}],"break-after":[{"break-after":nr()}],"break-before":[{"break-before":nr()}],"break-inside":[{"break-inside":["auto","avoid","avoid-page","avoid-column"]}],"box-decoration":[{"box-decoration":["slice","clone"]}],box:[{box:["border","content"]}],display:["block","inline-block","inline","flex","inline-flex","table","inline-table","table-caption","table-cell","table-column","table-column-group","table-footer-group","table-header-group","table-row-group","table-row","flow-root","grid","inline-grid","contents","list-item","hidden"],float:[{float:["right","left","none","start","end"]}],clear:[{clear:["left","right","both","none","start","end"]}],isolation:["isolate","isolation-auto"],"object-fit":[{object:["contain","cover","fill","none","scale-down"]}],"object-position":[{object:[...G(),L]}],overflow:[{overflow:T()}],"overflow-x":[{"overflow-x":T()}],"overflow-y":[{"overflow-y":T()}],overscroll:[{overscroll:j()}],"overscroll-x":[{"overscroll-x":j()}],"overscroll-y":[{"overscroll-y":j()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[h]}],"inset-x":[{"inset-x":[h]}],"inset-y":[{"inset-y":[h]}],start:[{start:[h]}],end:[{end:[h]}],top:[{top:[h]}],right:[{right:[h]}],bottom:[{bottom:[h]}],left:[{left:[h]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",Ct,L]}],basis:[{basis:P()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",L]}],grow:[{grow:Re()}],shrink:[{shrink:Re()}],order:[{order:["first","last","none",Ct,L]}],"grid-cols":[{"grid-cols":[kt]}],"col-start-end":[{col:["auto",{span:["full",Ct,L]},L]}],"col-start":[{"col-start":U()}],"col-end":[{"col-end":U()}],"grid-rows":[{"grid-rows":[kt]}],"row-start-end":[{row:["auto",{span:[Ct,L]},L]}],"row-start":[{"row-start":U()}],"row-end":[{"row-end":U()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",L]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",L]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...ye()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...ye(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...ye(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[w]}],px:[{px:[w]}],py:[{py:[w]}],ps:[{ps:[w]}],pe:[{pe:[w]}],pt:[{pt:[w]}],pr:[{pr:[w]}],pb:[{pb:[w]}],pl:[{pl:[w]}],m:[{m:[p]}],mx:[{mx:[p]}],my:[{my:[p]}],ms:[{ms:[p]}],me:[{me:[p]}],mt:[{mt:[p]}],mr:[{mr:[p]}],mb:[{mb:[p]}],ml:[{ml:[p]}],"space-x":[{"space-x":[k]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[k]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",L,e]}],"min-w":[{"min-w":[L,e,"min","max","fit"]}],"max-w":[{"max-w":[L,e,"none","full","min","max","fit","prose",{screen:[Ie]},Ie]}],h:[{h:[L,e,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[L,e,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[L,e,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[L,e,"auto","min","max","fit"]}],"font-size":[{text:["base",Ie,Te]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",pn]}],"font-family":[{font:[kt]}],"fvn-normal":["normal-nums"],"fvn-ordinal":["ordinal"],"fvn-slashed-zero":["slashed-zero"],"fvn-figure":["lining-nums","oldstyle-nums"],"fvn-spacing":["proportional-nums","tabular-nums"],"fvn-fraction":["diagonal-fractions","stacked-fractions"],tracking:[{tracking:["tighter","tight","normal","wide","wider","widest",L]}],"line-clamp":[{"line-clamp":["none",ut,pn]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Me,L]}],"list-image":[{"list-image":["none",L]}],"list-style-type":[{list:["none","disc","decimal",L]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[r]}],"placeholder-opacity":[{"placeholder-opacity":[y]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[r]}],"text-opacity":[{"text-opacity":[y]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...te(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Me,Te]}],"underline-offset":[{"underline-offset":["auto",Me,L]}],"text-decoration-color":[{decoration:[r]}],"text-transform":["uppercase","lowercase","capitalize","normal-case"],"text-overflow":["truncate","text-ellipsis","text-clip"],"text-wrap":[{text:["wrap","nowrap","balance","pretty"]}],indent:[{indent:C()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",L]}],whitespace:[{whitespace:["normal","nowrap","pre","pre-line","pre-wrap","break-spaces"]}],break:[{break:["normal","words","all","keep"]}],hyphens:[{hyphens:["none","manual","auto"]}],content:[{content:["none",L]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[y]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...G(),od]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",sd]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},id]}],"bg-color":[{bg:[r]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[b]}],"gradient-via":[{via:[b]}],"gradient-to":[{to:[b]}],rounded:[{rounded:[o]}],"rounded-s":[{"rounded-s":[o]}],"rounded-e":[{"rounded-e":[o]}],"rounded-t":[{"rounded-t":[o]}],"rounded-r":[{"rounded-r":[o]}],"rounded-b":[{"rounded-b":[o]}],"rounded-l":[{"rounded-l":[o]}],"rounded-ss":[{"rounded-ss":[o]}],"rounded-se":[{"rounded-se":[o]}],"rounded-ee":[{"rounded-ee":[o]}],"rounded-es":[{"rounded-es":[o]}],"rounded-tl":[{"rounded-tl":[o]}],"rounded-tr":[{"rounded-tr":[o]}],"rounded-br":[{"rounded-br":[o]}],"rounded-bl":[{"rounded-bl":[o]}],"border-w":[{border:[i]}],"border-w-x":[{"border-x":[i]}],"border-w-y":[{"border-y":[i]}],"border-w-s":[{"border-s":[i]}],"border-w-e":[{"border-e":[i]}],"border-w-t":[{"border-t":[i]}],"border-w-r":[{"border-r":[i]}],"border-w-b":[{"border-b":[i]}],"border-w-l":[{"border-l":[i]}],"border-opacity":[{"border-opacity":[y]}],"border-style":[{border:[...te(),"hidden"]}],"divide-x":[{"divide-x":[i]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[i]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[y]}],"divide-style":[{divide:te()}],"border-color":[{border:[s]}],"border-color-x":[{"border-x":[s]}],"border-color-y":[{"border-y":[s]}],"border-color-s":[{"border-s":[s]}],"border-color-e":[{"border-e":[s]}],"border-color-t":[{"border-t":[s]}],"border-color-r":[{"border-r":[s]}],"border-color-b":[{"border-b":[s]}],"border-color-l":[{"border-l":[s]}],"divide-color":[{divide:[s]}],"outline-style":[{outline:["",...te()]}],"outline-offset":[{"outline-offset":[Me,L]}],"outline-w":[{outline:[Me,Te]}],"outline-color":[{outline:[r]}],"ring-w":[{ring:F()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[r]}],"ring-opacity":[{"ring-opacity":[y]}],"ring-offset-w":[{"ring-offset":[Me,Te]}],"ring-offset-color":[{"ring-offset":[r]}],shadow:[{shadow:["","inner","none",Ie,ld]}],"shadow-color":[{shadow:[kt]}],opacity:[{opacity:[y]}],"mix-blend":[{"mix-blend":[...St(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":St()}],filter:[{filter:["","none"]}],blur:[{blur:[t]}],brightness:[{brightness:[n]}],contrast:[{contrast:[d]}],"drop-shadow":[{"drop-shadow":["","none",Ie,L]}],grayscale:[{grayscale:[c]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[f]}],saturate:[{saturate:[x]}],sepia:[{sepia:[S]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[t]}],"backdrop-brightness":[{"backdrop-brightness":[n]}],"backdrop-contrast":[{"backdrop-contrast":[d]}],"backdrop-grayscale":[{"backdrop-grayscale":[c]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[f]}],"backdrop-opacity":[{"backdrop-opacity":[y]}],"backdrop-saturate":[{"backdrop-saturate":[x]}],"backdrop-sepia":[{"backdrop-sepia":[S]}],"border-collapse":[{border:["collapse","separate"]}],"border-spacing":[{"border-spacing":[a]}],"border-spacing-x":[{"border-spacing-x":[a]}],"border-spacing-y":[{"border-spacing-y":[a]}],"table-layout":[{table:["auto","fixed"]}],caption:[{caption:["top","bottom"]}],transition:[{transition:["none","all","","colors","opacity","shadow","transform",L]}],duration:[{duration:Q()}],ease:[{ease:["linear","in","out","in-out",L]}],delay:[{delay:Q()}],animate:[{animate:["none","spin","ping","pulse","bounce",L]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[v]}],"scale-x":[{"scale-x":[v]}],"scale-y":[{"scale-y":[v]}],rotate:[{rotate:[Ct,L]}],"translate-x":[{"translate-x":[$]}],"translate-y":[{"translate-y":[$]}],"skew-x":[{"skew-x":[A]}],"skew-y":[{"skew-y":[A]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",L]}],accent:[{accent:["auto",r]}],appearance:[{appearance:["none","auto"]}],cursor:[{cursor:["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out",L]}],"caret-color":[{caret:[r]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":C()}],"scroll-mx":[{"scroll-mx":C()}],"scroll-my":[{"scroll-my":C()}],"scroll-ms":[{"scroll-ms":C()}],"scroll-me":[{"scroll-me":C()}],"scroll-mt":[{"scroll-mt":C()}],"scroll-mr":[{"scroll-mr":C()}],"scroll-mb":[{"scroll-mb":C()}],"scroll-ml":[{"scroll-ml":C()}],"scroll-p":[{"scroll-p":C()}],"scroll-px":[{"scroll-px":C()}],"scroll-py":[{"scroll-py":C()}],"scroll-ps":[{"scroll-ps":C()}],"scroll-pe":[{"scroll-pe":C()}],"scroll-pt":[{"scroll-pt":C()}],"scroll-pr":[{"scroll-pr":C()}],"scroll-pb":[{"scroll-pb":C()}],"scroll-pl":[{"scroll-pl":C()}],"snap-align":[{snap:["start","end","center","align-none"]}],"snap-stop":[{snap:["normal","always"]}],"snap-type":[{snap:["none","x","y","both"]}],"snap-strictness":[{snap:["mandatory","proximity"]}],touch:[{touch:["auto","none","manipulation"]}],"touch-x":[{"touch-pan":["x","left","right"]}],"touch-y":[{"touch-pan":["y","up","down"]}],"touch-pz":["touch-pinch-zoom"],select:[{select:["none","text","all","auto"]}],"will-change":[{"will-change":["auto","scroll","contents","transform",L]}],fill:[{fill:[r,"none"]}],"stroke-w":[{stroke:[Me,Te,pn]}],stroke:[{stroke:[r,"none"]}],sr:["sr-only","not-sr-only"],"forced-color-adjust":[{"forced-color-adjust":["auto","none"]}]},conflictingClassGroups:{overflow:["overflow-x","overflow-y"],overscroll:["overscroll-x","overscroll-y"],inset:["inset-x","inset-y","start","end","top","right","bottom","left"],"inset-x":["right","left"],"inset-y":["top","bottom"],flex:["basis","grow","shrink"],gap:["gap-x","gap-y"],p:["px","py","ps","pe","pt","pr","pb","pl"],px:["pr","pl"],py:["pt","pb"],m:["mx","my","ms","me","mt","mr","mb","ml"],mx:["mr","ml"],my:["mt","mb"],size:["w","h"],"font-size":["leading"],"fvn-normal":["fvn-ordinal","fvn-slashed-zero","fvn-figure","fvn-spacing","fvn-fraction"],"fvn-ordinal":["fvn-normal"],"fvn-slashed-zero":["fvn-normal"],"fvn-figure":["fvn-normal"],"fvn-spacing":["fvn-normal"],"fvn-fraction":["fvn-normal"],"line-clamp":["display","overflow"],rounded:["rounded-s","rounded-e","rounded-t","rounded-r","rounded-b","rounded-l","rounded-ss","rounded-se","rounded-ee","rounded-es","rounded-tl","rounded-tr","rounded-br","rounded-bl"],"rounded-s":["rounded-ss","rounded-es"],"rounded-e":["rounded-se","rounded-ee"],"rounded-t":["rounded-tl","rounded-tr"],"rounded-r":["rounded-tr","rounded-br"],"rounded-b":["rounded-br","rounded-bl"],"rounded-l":["rounded-tl","rounded-bl"],"border-spacing":["border-spacing-x","border-spacing-y"],"border-w":["border-w-s","border-w-e","border-w-t","border-w-r","border-w-b","border-w-l"],"border-w-x":["border-w-r","border-w-l"],"border-w-y":["border-w-t","border-w-b"],"border-color":["border-color-s","border-color-e","border-color-t","border-color-r","border-color-b","border-color-l"],"border-color-x":["border-color-r","border-color-l"],"border-color-y":["border-color-t","border-color-b"],"scroll-m":["scroll-mx","scroll-my","scroll-ms","scroll-me","scroll-mt","scroll-mr","scroll-mb","scroll-ml"],"scroll-mx":["scroll-mr","scroll-ml"],"scroll-my":["scroll-mt","scroll-mb"],"scroll-p":["scroll-px","scroll-py","scroll-ps","scroll-pe","scroll-pt","scroll-pr","scroll-pb","scroll-pl"],"scroll-px":["scroll-pr","scroll-pl"],"scroll-py":["scroll-pt","scroll-pb"],touch:["touch-x","touch-y","touch-pz"],"touch-x":["touch"],"touch-y":["touch"],"touch-pz":["touch"]},conflictingClassGroupModifiers:{"font-size":["leading"]}}},hd=Gc(fd);let ir;const md=new Uint8Array(16);function gd(){if(!ir&&(ir=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!ir))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return ir(md)}const re=[];for(let r=0;r<256;++r)re.push((r+256).toString(16).slice(1));function pd(r,e=0){return re[r[e+0]]+re[r[e+1]]+re[r[e+2]]+re[r[e+3]]+"-"+re[r[e+4]]+re[r[e+5]]+"-"+re[r[e+6]]+re[r[e+7]]+"-"+re[r[e+8]]+re[r[e+9]]+"-"+re[r[e+10]]+re[r[e+11]]+re[r[e+12]]+re[r[e+13]]+re[r[e+14]]+re[r[e+15]]}const yd=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),vo={randomUUID:yd};function bd(r,e,t){if(vo.randomUUID&&!r)return vo.randomUUID();r=r||{};const n=r.random||(r.rng||gd)();return n[6]=n[6]&15|64,n[8]=n[8]&63|128,pd(n)}const Wa=6048e5,wd=864e5,lr=43200,So=1440,Co=Symbol.for("constructDateFrom");function Oe(r,e){return typeof r=="function"?r(e):r&&typeof r=="object"&&Co in r?r[Co](e):r instanceof Date?new r.constructor(e):new Date(e)}function ee(r,e){return Oe(e||r,r)}let xd={};function qt(){return xd}function Ut(r,e){var i,d,c,u;const t=qt(),n=(e==null?void 0:e.weekStartsOn)??((d=(i=e==null?void 0:e.locale)==null?void 0:i.options)==null?void 0:d.weekStartsOn)??t.weekStartsOn??((u=(c=t.locale)==null?void 0:c.options)==null?void 0:u.weekStartsOn)??0,s=ee(r,e==null?void 0:e.in),o=s.getDay(),a=(o<n?7:0)+o-n;return s.setDate(s.getDate()-a),s.setHours(0,0,0,0),s}function Rr(r,e){return Ut(r,{...e,weekStartsOn:1})}function Ha(r,e){const t=ee(r,e==null?void 0:e.in),n=t.getFullYear(),s=Oe(t,0);s.setFullYear(n+1,0,4),s.setHours(0,0,0,0);const o=Rr(s),a=Oe(t,0);a.setFullYear(n,0,4),a.setHours(0,0,0,0);const i=Rr(a);return t.getTime()>=o.getTime()?n+1:t.getTime()>=i.getTime()?n:n-1}function Tr(r){const e=ee(r),t=new Date(Date.UTC(e.getFullYear(),e.getMonth(),e.getDate(),e.getHours(),e.getMinutes(),e.getSeconds(),e.getMilliseconds()));return t.setUTCFullYear(e.getFullYear()),+r-+t}function Hr(r,...e){const t=Oe.bind(null,r||e.find(n=>typeof n=="object"));return e.map(t)}function ko(r,e){const t=ee(r,e==null?void 0:e.in);return t.setHours(0,0,0,0),t}function _d(r,e,t){const[n,s]=Hr(t==null?void 0:t.in,r,e),o=ko(n),a=ko(s),i=+o-Tr(o),d=+a-Tr(a);return Math.round((i-d)/wd)}function vd(r,e){const t=Ha(r,e),n=Oe(r,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),Rr(n)}function wr(r,e){const t=+ee(r)-+ee(e);return t<0?-1:t>0?1:t}function Sd(r){return Oe(r,Date.now())}function Cd(r){return r instanceof Date||typeof r=="object"&&Object.prototype.toString.call(r)==="[object Date]"}function kd(r){return!(!Cd(r)&&typeof r!="number"||isNaN(+ee(r)))}function Ad(r,e,t){const[n,s]=Hr(t==null?void 0:t.in,r,e),o=n.getFullYear()-s.getFullYear(),a=n.getMonth()-s.getMonth();return o*12+a}function Ed(r){return e=>{const n=(r?Math[r]:Math.trunc)(e);return n===0?0:n}}function Md(r,e){return+ee(r)-+ee(e)}function jd(r,e){const t=ee(r,e==null?void 0:e.in);return t.setHours(23,59,59,999),t}function Nd(r,e){const t=ee(r,e==null?void 0:e.in),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function Od(r,e){const t=ee(r,e==null?void 0:e.in);return+jd(t,e)==+Nd(t,e)}function Pd(r,e,t){const[n,s,o]=Hr(t==null?void 0:t.in,r,r,e),a=wr(s,o),i=Math.abs(Ad(s,o));if(i<1)return 0;s.getMonth()===1&&s.getDate()>27&&s.setDate(30),s.setMonth(s.getMonth()-a*i);let d=wr(s,o)===-a;Od(n)&&i===1&&wr(n,o)===1&&(d=!1);const c=a*(i-+d);return c===0?0:c}function Rd(r,e,t){const n=Md(r,e)/1e3;return Ed(t==null?void 0:t.roundingMethod)(n)}function Td(r,e){const t=ee(r,e==null?void 0:e.in);return t.setFullYear(t.getFullYear(),0,1),t.setHours(0,0,0,0),t}const Id={lessThanXSeconds:{one:"less than a second",other:"less than {{count}} seconds"},xSeconds:{one:"1 second",other:"{{count}} seconds"},halfAMinute:"half a minute",lessThanXMinutes:{one:"less than a minute",other:"less than {{count}} minutes"},xMinutes:{one:"1 minute",other:"{{count}} minutes"},aboutXHours:{one:"about 1 hour",other:"about {{count}} hours"},xHours:{one:"1 hour",other:"{{count}} hours"},xDays:{one:"1 day",other:"{{count}} days"},aboutXWeeks:{one:"about 1 week",other:"about {{count}} weeks"},xWeeks:{one:"1 week",other:"{{count}} weeks"},aboutXMonths:{one:"about 1 month",other:"about {{count}} months"},xMonths:{one:"1 month",other:"{{count}} months"},aboutXYears:{one:"about 1 year",other:"about {{count}} years"},xYears:{one:"1 year",other:"{{count}} years"},overXYears:{one:"over 1 year",other:"over {{count}} years"},almostXYears:{one:"almost 1 year",other:"almost {{count}} years"}},Ld=(r,e,t)=>{let n;const s=Id[r];return typeof s=="string"?n=s:e===1?n=s.one:n=s.other.replace("{{count}}",e.toString()),t!=null&&t.addSuffix?t.comparison&&t.comparison>0?"in "+n:n+" ago":n};function yn(r){return(e={})=>{const t=e.width?String(e.width):r.defaultWidth;return r.formats[t]||r.formats[r.defaultWidth]}}const Dd={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},Fd={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},$d={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},Bd={date:yn({formats:Dd,defaultWidth:"full"}),time:yn({formats:Fd,defaultWidth:"full"}),dateTime:yn({formats:$d,defaultWidth:"full"})},Ud={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},Wd=(r,e,t,n)=>Ud[r];function At(r){return(e,t)=>{const n=t!=null&&t.context?String(t.context):"standalone";let s;if(n==="formatting"&&r.formattingValues){const a=r.defaultFormattingWidth||r.defaultWidth,i=t!=null&&t.width?String(t.width):a;s=r.formattingValues[i]||r.formattingValues[a]}else{const a=r.defaultWidth,i=t!=null&&t.width?String(t.width):r.defaultWidth;s=r.values[i]||r.values[a]}const o=r.argumentCallback?r.argumentCallback(e):e;return s[o]}}const Hd={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},zd={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},qd={narrow:["J","F","M","A","M","J","J","A","S","O","N","D"],abbreviated:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],wide:["January","February","March","April","May","June","July","August","September","October","November","December"]},Vd={narrow:["S","M","T","W","T","F","S"],short:["Su","Mo","Tu","We","Th","Fr","Sa"],abbreviated:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],wide:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"]},Jd={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"}},Gd={narrow:{am:"a",pm:"p",midnight:"mi",noon:"n",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},abbreviated:{am:"AM",pm:"PM",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"},wide:{am:"a.m.",pm:"p.m.",midnight:"midnight",noon:"noon",morning:"in the morning",afternoon:"in the afternoon",evening:"in the evening",night:"at night"}},Xd=(r,e)=>{const t=Number(r),n=t%100;if(n>20||n<10)switch(n%10){case 1:return t+"st";case 2:return t+"nd";case 3:return t+"rd"}return t+"th"},Yd={ordinalNumber:Xd,era:At({values:Hd,defaultWidth:"wide"}),quarter:At({values:zd,defaultWidth:"wide",argumentCallback:r=>r-1}),month:At({values:qd,defaultWidth:"wide"}),day:At({values:Vd,defaultWidth:"wide"}),dayPeriod:At({values:Jd,defaultWidth:"wide",formattingValues:Gd,defaultFormattingWidth:"wide"})};function Et(r){return(e,t={})=>{const n=t.width,s=n&&r.matchPatterns[n]||r.matchPatterns[r.defaultMatchWidth],o=e.match(s);if(!o)return null;const a=o[0],i=n&&r.parsePatterns[n]||r.parsePatterns[r.defaultParseWidth],d=Array.isArray(i)?Qd(i,f=>f.test(a)):Kd(i,f=>f.test(a));let c;c=r.valueCallback?r.valueCallback(d):d,c=t.valueCallback?t.valueCallback(c):c;const u=e.slice(a.length);return{value:c,rest:u}}}function Kd(r,e){for(const t in r)if(Object.prototype.hasOwnProperty.call(r,t)&&e(r[t]))return t}function Qd(r,e){for(let t=0;t<r.length;t++)if(e(r[t]))return t}function Zd(r){return(e,t={})=>{const n=e.match(r.matchPattern);if(!n)return null;const s=n[0],o=e.match(r.parsePattern);if(!o)return null;let a=r.valueCallback?r.valueCallback(o[0]):o[0];a=t.valueCallback?t.valueCallback(a):a;const i=e.slice(s.length);return{value:a,rest:i}}}const eu=/^(\d+)(th|st|nd|rd)?/i,tu=/\d+/i,ru={narrow:/^(b|a)/i,abbreviated:/^(b\.?\s?c\.?|b\.?\s?c\.?\s?e\.?|a\.?\s?d\.?|c\.?\s?e\.?)/i,wide:/^(before christ|before common era|anno domini|common era)/i},nu={any:[/^b/i,/^(a|c)/i]},su={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},ou={any:[/1/i,/2/i,/3/i,/4/i]},au={narrow:/^[jfmasond]/i,abbreviated:/^(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)/i,wide:/^(january|february|march|april|may|june|july|august|september|october|november|december)/i},iu={narrow:[/^j/i,/^f/i,/^m/i,/^a/i,/^m/i,/^j/i,/^j/i,/^a/i,/^s/i,/^o/i,/^n/i,/^d/i],any:[/^ja/i,/^f/i,/^mar/i,/^ap/i,/^may/i,/^jun/i,/^jul/i,/^au/i,/^s/i,/^o/i,/^n/i,/^d/i]},lu={narrow:/^[smtwf]/i,short:/^(su|mo|tu|we|th|fr|sa)/i,abbreviated:/^(sun|mon|tue|wed|thu|fri|sat)/i,wide:/^(sunday|monday|tuesday|wednesday|thursday|friday|saturday)/i},cu={narrow:[/^s/i,/^m/i,/^t/i,/^w/i,/^t/i,/^f/i,/^s/i],any:[/^su/i,/^m/i,/^tu/i,/^w/i,/^th/i,/^f/i,/^sa/i]},du={narrow:/^(a|p|mi|n|(in the|at) (morning|afternoon|evening|night))/i,any:/^([ap]\.?\s?m\.?|midnight|noon|(in the|at) (morning|afternoon|evening|night))/i},uu={any:{am:/^a/i,pm:/^p/i,midnight:/^mi/i,noon:/^no/i,morning:/morning/i,afternoon:/afternoon/i,evening:/evening/i,night:/night/i}},fu={ordinalNumber:Zd({matchPattern:eu,parsePattern:tu,valueCallback:r=>parseInt(r,10)}),era:Et({matchPatterns:ru,defaultMatchWidth:"wide",parsePatterns:nu,defaultParseWidth:"any"}),quarter:Et({matchPatterns:su,defaultMatchWidth:"wide",parsePatterns:ou,defaultParseWidth:"any",valueCallback:r=>r+1}),month:Et({matchPatterns:au,defaultMatchWidth:"wide",parsePatterns:iu,defaultParseWidth:"any"}),day:Et({matchPatterns:lu,defaultMatchWidth:"wide",parsePatterns:cu,defaultParseWidth:"any"}),dayPeriod:Et({matchPatterns:du,defaultMatchWidth:"any",parsePatterns:uu,defaultParseWidth:"any"})},za={code:"en-US",formatDistance:Ld,formatLong:Bd,formatRelative:Wd,localize:Yd,match:fu,options:{weekStartsOn:0,firstWeekContainsDate:1}};function hu(r,e){const t=ee(r,e==null?void 0:e.in);return _d(t,Td(t))+1}function mu(r,e){const t=ee(r,e==null?void 0:e.in),n=+Rr(t)-+vd(t);return Math.round(n/Wa)+1}function qa(r,e){var u,f,m,b;const t=ee(r,e==null?void 0:e.in),n=t.getFullYear(),s=qt(),o=(e==null?void 0:e.firstWeekContainsDate)??((f=(u=e==null?void 0:e.locale)==null?void 0:u.options)==null?void 0:f.firstWeekContainsDate)??s.firstWeekContainsDate??((b=(m=s.locale)==null?void 0:m.options)==null?void 0:b.firstWeekContainsDate)??1,a=Oe((e==null?void 0:e.in)||r,0);a.setFullYear(n+1,0,o),a.setHours(0,0,0,0);const i=Ut(a,e),d=Oe((e==null?void 0:e.in)||r,0);d.setFullYear(n,0,o),d.setHours(0,0,0,0);const c=Ut(d,e);return+t>=+i?n+1:+t>=+c?n:n-1}function gu(r,e){var i,d,c,u;const t=qt(),n=(e==null?void 0:e.firstWeekContainsDate)??((d=(i=e==null?void 0:e.locale)==null?void 0:i.options)==null?void 0:d.firstWeekContainsDate)??t.firstWeekContainsDate??((u=(c=t.locale)==null?void 0:c.options)==null?void 0:u.firstWeekContainsDate)??1,s=qa(r,e),o=Oe((e==null?void 0:e.in)||r,0);return o.setFullYear(s,0,n),o.setHours(0,0,0,0),Ut(o,e)}function pu(r,e){const t=ee(r,e==null?void 0:e.in),n=+Ut(t,e)-+gu(t,e);return Math.round(n/Wa)+1}function B(r,e){const t=r<0?"-":"",n=Math.abs(r).toString().padStart(e,"0");return t+n}const Le={y(r,e){const t=r.getFullYear(),n=t>0?t:1-t;return B(e==="yy"?n%100:n,e.length)},M(r,e){const t=r.getMonth();return e==="M"?String(t+1):B(t+1,2)},d(r,e){return B(r.getDate(),e.length)},a(r,e){const t=r.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.toUpperCase();case"aaa":return t;case"aaaaa":return t[0];case"aaaa":default:return t==="am"?"a.m.":"p.m."}},h(r,e){return B(r.getHours()%12||12,e.length)},H(r,e){return B(r.getHours(),e.length)},m(r,e){return B(r.getMinutes(),e.length)},s(r,e){return B(r.getSeconds(),e.length)},S(r,e){const t=e.length,n=r.getMilliseconds(),s=Math.trunc(n*Math.pow(10,t-3));return B(s,e.length)}},rt={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Ao={G:function(r,e,t){const n=r.getFullYear()>0?1:0;switch(e){case"G":case"GG":case"GGG":return t.era(n,{width:"abbreviated"});case"GGGGG":return t.era(n,{width:"narrow"});case"GGGG":default:return t.era(n,{width:"wide"})}},y:function(r,e,t){if(e==="yo"){const n=r.getFullYear(),s=n>0?n:1-n;return t.ordinalNumber(s,{unit:"year"})}return Le.y(r,e)},Y:function(r,e,t,n){const s=qa(r,n),o=s>0?s:1-s;if(e==="YY"){const a=o%100;return B(a,2)}return e==="Yo"?t.ordinalNumber(o,{unit:"year"}):B(o,e.length)},R:function(r,e){const t=Ha(r);return B(t,e.length)},u:function(r,e){const t=r.getFullYear();return B(t,e.length)},Q:function(r,e,t){const n=Math.ceil((r.getMonth()+1)/3);switch(e){case"Q":return String(n);case"QQ":return B(n,2);case"Qo":return t.ordinalNumber(n,{unit:"quarter"});case"QQQ":return t.quarter(n,{width:"abbreviated",context:"formatting"});case"QQQQQ":return t.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return t.quarter(n,{width:"wide",context:"formatting"})}},q:function(r,e,t){const n=Math.ceil((r.getMonth()+1)/3);switch(e){case"q":return String(n);case"qq":return B(n,2);case"qo":return t.ordinalNumber(n,{unit:"quarter"});case"qqq":return t.quarter(n,{width:"abbreviated",context:"standalone"});case"qqqqq":return t.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return t.quarter(n,{width:"wide",context:"standalone"})}},M:function(r,e,t){const n=r.getMonth();switch(e){case"M":case"MM":return Le.M(r,e);case"Mo":return t.ordinalNumber(n+1,{unit:"month"});case"MMM":return t.month(n,{width:"abbreviated",context:"formatting"});case"MMMMM":return t.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return t.month(n,{width:"wide",context:"formatting"})}},L:function(r,e,t){const n=r.getMonth();switch(e){case"L":return String(n+1);case"LL":return B(n+1,2);case"Lo":return t.ordinalNumber(n+1,{unit:"month"});case"LLL":return t.month(n,{width:"abbreviated",context:"standalone"});case"LLLLL":return t.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return t.month(n,{width:"wide",context:"standalone"})}},w:function(r,e,t,n){const s=pu(r,n);return e==="wo"?t.ordinalNumber(s,{unit:"week"}):B(s,e.length)},I:function(r,e,t){const n=mu(r);return e==="Io"?t.ordinalNumber(n,{unit:"week"}):B(n,e.length)},d:function(r,e,t){return e==="do"?t.ordinalNumber(r.getDate(),{unit:"date"}):Le.d(r,e)},D:function(r,e,t){const n=hu(r);return e==="Do"?t.ordinalNumber(n,{unit:"dayOfYear"}):B(n,e.length)},E:function(r,e,t){const n=r.getDay();switch(e){case"E":case"EE":case"EEE":return t.day(n,{width:"abbreviated",context:"formatting"});case"EEEEE":return t.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return t.day(n,{width:"short",context:"formatting"});case"EEEE":default:return t.day(n,{width:"wide",context:"formatting"})}},e:function(r,e,t,n){const s=r.getDay(),o=(s-n.weekStartsOn+8)%7||7;switch(e){case"e":return String(o);case"ee":return B(o,2);case"eo":return t.ordinalNumber(o,{unit:"day"});case"eee":return t.day(s,{width:"abbreviated",context:"formatting"});case"eeeee":return t.day(s,{width:"narrow",context:"formatting"});case"eeeeee":return t.day(s,{width:"short",context:"formatting"});case"eeee":default:return t.day(s,{width:"wide",context:"formatting"})}},c:function(r,e,t,n){const s=r.getDay(),o=(s-n.weekStartsOn+8)%7||7;switch(e){case"c":return String(o);case"cc":return B(o,e.length);case"co":return t.ordinalNumber(o,{unit:"day"});case"ccc":return t.day(s,{width:"abbreviated",context:"standalone"});case"ccccc":return t.day(s,{width:"narrow",context:"standalone"});case"cccccc":return t.day(s,{width:"short",context:"standalone"});case"cccc":default:return t.day(s,{width:"wide",context:"standalone"})}},i:function(r,e,t){const n=r.getDay(),s=n===0?7:n;switch(e){case"i":return String(s);case"ii":return B(s,e.length);case"io":return t.ordinalNumber(s,{unit:"day"});case"iii":return t.day(n,{width:"abbreviated",context:"formatting"});case"iiiii":return t.day(n,{width:"narrow",context:"formatting"});case"iiiiii":return t.day(n,{width:"short",context:"formatting"});case"iiii":default:return t.day(n,{width:"wide",context:"formatting"})}},a:function(r,e,t){const s=r.getHours()/12>=1?"pm":"am";switch(e){case"a":case"aa":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"aaa":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return t.dayPeriod(s,{width:"narrow",context:"formatting"});case"aaaa":default:return t.dayPeriod(s,{width:"wide",context:"formatting"})}},b:function(r,e,t){const n=r.getHours();let s;switch(n===12?s=rt.noon:n===0?s=rt.midnight:s=n/12>=1?"pm":"am",e){case"b":case"bb":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"bbb":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return t.dayPeriod(s,{width:"narrow",context:"formatting"});case"bbbb":default:return t.dayPeriod(s,{width:"wide",context:"formatting"})}},B:function(r,e,t){const n=r.getHours();let s;switch(n>=17?s=rt.evening:n>=12?s=rt.afternoon:n>=4?s=rt.morning:s=rt.night,e){case"B":case"BB":case"BBB":return t.dayPeriod(s,{width:"abbreviated",context:"formatting"});case"BBBBB":return t.dayPeriod(s,{width:"narrow",context:"formatting"});case"BBBB":default:return t.dayPeriod(s,{width:"wide",context:"formatting"})}},h:function(r,e,t){if(e==="ho"){let n=r.getHours()%12;return n===0&&(n=12),t.ordinalNumber(n,{unit:"hour"})}return Le.h(r,e)},H:function(r,e,t){return e==="Ho"?t.ordinalNumber(r.getHours(),{unit:"hour"}):Le.H(r,e)},K:function(r,e,t){const n=r.getHours()%12;return e==="Ko"?t.ordinalNumber(n,{unit:"hour"}):B(n,e.length)},k:function(r,e,t){let n=r.getHours();return n===0&&(n=24),e==="ko"?t.ordinalNumber(n,{unit:"hour"}):B(n,e.length)},m:function(r,e,t){return e==="mo"?t.ordinalNumber(r.getMinutes(),{unit:"minute"}):Le.m(r,e)},s:function(r,e,t){return e==="so"?t.ordinalNumber(r.getSeconds(),{unit:"second"}):Le.s(r,e)},S:function(r,e){return Le.S(r,e)},X:function(r,e,t){const n=r.getTimezoneOffset();if(n===0)return"Z";switch(e){case"X":return Mo(n);case"XXXX":case"XX":return qe(n);case"XXXXX":case"XXX":default:return qe(n,":")}},x:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"x":return Mo(n);case"xxxx":case"xx":return qe(n);case"xxxxx":case"xxx":default:return qe(n,":")}},O:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"O":case"OO":case"OOO":return"GMT"+Eo(n,":");case"OOOO":default:return"GMT"+qe(n,":")}},z:function(r,e,t){const n=r.getTimezoneOffset();switch(e){case"z":case"zz":case"zzz":return"GMT"+Eo(n,":");case"zzzz":default:return"GMT"+qe(n,":")}},t:function(r,e,t){const n=Math.trunc(+r/1e3);return B(n,e.length)},T:function(r,e,t){return B(+r,e.length)}};function Eo(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=Math.trunc(n/60),o=n%60;return o===0?t+String(s):t+String(s)+e+B(o,2)}function Mo(r,e){return r%60===0?(r>0?"-":"+")+B(Math.abs(r)/60,2):qe(r,e)}function qe(r,e=""){const t=r>0?"-":"+",n=Math.abs(r),s=B(Math.trunc(n/60),2),o=B(n%60,2);return t+s+e+o}const jo=(r,e)=>{switch(r){case"P":return e.date({width:"short"});case"PP":return e.date({width:"medium"});case"PPP":return e.date({width:"long"});case"PPPP":default:return e.date({width:"full"})}},Va=(r,e)=>{switch(r){case"p":return e.time({width:"short"});case"pp":return e.time({width:"medium"});case"ppp":return e.time({width:"long"});case"pppp":default:return e.time({width:"full"})}},yu=(r,e)=>{const t=r.match(/(P+)(p+)?/)||[],n=t[1],s=t[2];if(!s)return jo(r,e);let o;switch(n){case"P":o=e.dateTime({width:"short"});break;case"PP":o=e.dateTime({width:"medium"});break;case"PPP":o=e.dateTime({width:"long"});break;case"PPPP":default:o=e.dateTime({width:"full"});break}return o.replace("{{date}}",jo(n,e)).replace("{{time}}",Va(s,e))},bu={p:Va,P:yu},wu=/^D+$/,xu=/^Y+$/,_u=["D","DD","YY","YYYY"];function vu(r){return wu.test(r)}function Su(r){return xu.test(r)}function Cu(r,e,t){const n=ku(r,e,t);if(console.warn(n),_u.includes(r))throw new RangeError(n)}function ku(r,e,t){const n=r[0]==="Y"?"years":"days of the month";return`Use \`${r.toLowerCase()}\` instead of \`${r}\` (in \`${e}\`) for formatting ${n} to the input \`${t}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const Au=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Eu=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Mu=/^'([^]*?)'?$/,ju=/''/g,Nu=/[a-zA-Z]/;function us(r,e,t){var u,f,m,b;const n=qt(),s=n.locale??za,o=n.firstWeekContainsDate??((f=(u=n.locale)==null?void 0:u.options)==null?void 0:f.firstWeekContainsDate)??1,a=n.weekStartsOn??((b=(m=n.locale)==null?void 0:m.options)==null?void 0:b.weekStartsOn)??0,i=ee(r,t==null?void 0:t.in);if(!kd(i))throw new RangeError("Invalid time value");let d=e.match(Eu).map(g=>{const h=g[0];if(h==="p"||h==="P"){const p=bu[h];return p(g,s.formatLong)}return g}).join("").match(Au).map(g=>{if(g==="''")return{isToken:!1,value:"'"};const h=g[0];if(h==="'")return{isToken:!1,value:Ou(g)};if(Ao[h])return{isToken:!0,value:g};if(h.match(Nu))throw new RangeError("Format string contains an unescaped latin alphabet character `"+h+"`");return{isToken:!1,value:g}});s.localize.preprocessor&&(d=s.localize.preprocessor(i,d));const c={firstWeekContainsDate:o,weekStartsOn:a,locale:s};return d.map(g=>{if(!g.isToken)return g.value;const h=g.value;(Su(h)||vu(h))&&Cu(h,e,String(r));const p=Ao[h[0]];return p(i,h,s.localize,c)}).join("")}function Ou(r){const e=r.match(Mu);return e?e[1].replace(ju,"'"):r}function Pu(r,e,t){const n=qt(),s=(t==null?void 0:t.locale)??n.locale??za,o=2520,a=wr(r,e);if(isNaN(a))throw new RangeError("Invalid time value");const i=Object.assign({},t,{addSuffix:t==null?void 0:t.addSuffix,comparison:a}),[d,c]=Hr(t==null?void 0:t.in,...a>0?[e,r]:[r,e]),u=Rd(c,d),f=(Tr(c)-Tr(d))/1e3,m=Math.round((u-f)/60);let b;if(m<2)return t!=null&&t.includeSeconds?u<5?s.formatDistance("lessThanXSeconds",5,i):u<10?s.formatDistance("lessThanXSeconds",10,i):u<20?s.formatDistance("lessThanXSeconds",20,i):u<40?s.formatDistance("halfAMinute",0,i):u<60?s.formatDistance("lessThanXMinutes",1,i):s.formatDistance("xMinutes",1,i):m===0?s.formatDistance("lessThanXMinutes",1,i):s.formatDistance("xMinutes",m,i);if(m<45)return s.formatDistance("xMinutes",m,i);if(m<90)return s.formatDistance("aboutXHours",1,i);if(m<So){const g=Math.round(m/60);return s.formatDistance("aboutXHours",g,i)}else{if(m<o)return s.formatDistance("xDays",1,i);if(m<lr){const g=Math.round(m/So);return s.formatDistance("xDays",g,i)}else if(m<lr*2)return b=Math.round(m/lr),s.formatDistance("aboutXMonths",b,i)}if(b=Pd(c,d),b<12){const g=Math.round(m/lr);return s.formatDistance("xMonths",g,i)}else{const g=b%12,h=Math.trunc(b/12);return g<3?s.formatDistance("aboutXYears",h,i):g<9?s.formatDistance("overXYears",h,i):s.formatDistance("almostXYears",h+1,i)}}function Ru(r,e){return Pu(r,Sd(r),e)}function se(...r){return hd(Ic(r))}function Tu(){return bd()}function Ja(r){if(!r)return"--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"--:--":us(e,"HH:mm")}function Iu(r){if(!r)return"时间未知";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"时间未知":Ru(e,{addSuffix:!0})}function Lu(r){if(!r)return"----/--/--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/--":us(e,"yyyy-MM-dd")}function Du(r){if(!r)return"----/--/-- --:--:--";const e=typeof r=="string"?new Date(r):r;return!(e instanceof Date)||isNaN(e.getTime())?"----/--/-- --:--:--":us(e,"yyyy-MM-dd HH:mm:ss")}function Fu(r,e){return r.length<=e?r:r.slice(0,e)+"..."}function $u(r){return r.replace(/<[^>]*>/g,"").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').trim()}function Bu(r){return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(r)}function Uu(r){try{return new URL(r),!0}catch{return!1}}function Un(r){if(r===null||typeof r!="object")return r;if(r instanceof Date)return isNaN(r.getTime())?new Date:new Date(r.getTime());if(r instanceof Array)return r.map(e=>Un(e));if(typeof r=="object"){const e={};for(const t in r)r.hasOwnProperty(t)&&(e[t]=Un(r[t]));return e}return r}function Wu(r,e){let t;return(...n)=>{clearTimeout(t),t=setTimeout(()=>r(...n),e)}}function Hu(r,e){let t;return(...n)=>{t||(r(...n),t=!0,setTimeout(()=>t=!1,e))}}function Ga(r){if(r===0)return"0 Bytes";const e=1024,t=["Bytes","KB","MB","GB","TB"],n=Math.floor(Math.log(r)/Math.log(e));return parseFloat((r/Math.pow(e,n)).toFixed(2))+" "+t[n]}function Xa(r){return r.slice((r.lastIndexOf(".")-1>>>0)+2)}function zu(r){const e=["jpg","jpeg","png","gif","bmp","webp","svg"],t=Xa(r).toLowerCase();return e.includes(t)}function qu(){const r=["#3b82f6","#10b981","#f59e0b","#ef4444","#8b5cf6","#06b6d4","#84cc16","#f97316","#ec4899","#6366f1"];return r[Math.floor(Math.random()*r.length)]}async function Vu(r){try{return await navigator.clipboard.writeText(r),!0}catch(e){return console.error("Failed to copy text to clipboard:",e),!1}}function Ju(r,e,t="text/plain"){const n=new Blob([r],{type:t}),s=URL.createObjectURL(n),o=document.createElement("a");o.href=s,o.download=e,document.body.appendChild(o),o.click(),document.body.removeChild(o),URL.revokeObjectURL(s)}function Gu(){return/Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)}function Xu(){const r=navigator.userAgent;return r.indexOf("Win")!==-1?"Windows":r.indexOf("Mac")!==-1?"macOS":r.indexOf("Linux")!==-1?"Linux":r.indexOf("Android")!==-1?"Android":r.indexOf("iOS")!==-1?"iOS":"Unknown"}class Yu extends Error{constructor(t,n="UNKNOWN_ERROR",s=500){super(t);D(this,"code");D(this,"statusCode");this.name="AppError",this.code=n,this.statusCode=s}}async function Ku(r,e=3,t=1e3){let n;for(let s=1;s<=e;s++)try{return await r()}catch(o){if(n=o,s===e)break;await new Promise(a=>setTimeout(a,t*s))}throw n}const Qu={get:(r,e)=>{try{const t=localStorage.getItem(r);return t?JSON.parse(t):e||null}catch{return e||null}},set:(r,e)=>{try{localStorage.setItem(r,JSON.stringify(e))}catch(t){console.error("Failed to save to localStorage:",t)}},remove:r=>{try{localStorage.removeItem(r)}catch(e){console.error("Failed to remove from localStorage:",e)}},clear:()=>{try{localStorage.clear()}catch(r){console.error("Failed to clear localStorage:",r)}}},Wn=({content:r,isStreaming:e=!1,className:t})=>{const n=M.useMemo(()=>o=>{let a=o;const i=/\$\$([\s\S]*?)\$\$/g;a=a.replace(i,(f,m)=>`<div class="math-block bg-muted/50 p-3 rounded-md my-2 text-center font-mono text-sm border">${m.trim()}</div>`);const d=/\$([^$]+)\$/g;a=a.replace(d,(f,m)=>`<span class="math-inline bg-muted/30 px-1 py-0.5 rounded font-mono text-sm">${m}</span>`);const c=/```(\w+)?\n?([\s\S]*?)```/g;a=a.replace(c,(f,m,b)=>{const g=m||"text",h=s(b.trim(),g);return`<div class="code-block my-3"><div class="code-header bg-muted/50 px-3 py-1 text-xs text-muted-foreground border-b">${g}</div><pre class="bg-muted p-3 overflow-x-auto"><code class="text-sm">${h}</code></pre></div>`});const u=/`([^`]+)`/g;return a=a.replace(u,(f,m)=>`<code class="bg-muted px-1.5 py-0.5 rounded text-sm font-mono">${m}</code>`),a=a.replace(/^### (.*$)/gm,'<h3 class="text-lg font-semibold mt-4 mb-2">$1</h3>'),a=a.replace(/^## (.*$)/gm,'<h2 class="text-xl font-semibold mt-4 mb-2">$1</h2>'),a=a.replace(/^# (.*$)/gm,'<h1 class="text-2xl font-bold mt-4 mb-2">$1</h1>'),a=a.replace(/^\* (.*$)/gm,'<li class="ml-4">• $1</li>'),a=a.replace(/^\d+\. (.*$)/gm,'<li class="ml-4 list-decimal">$1</li>'),a=a.replace(/\*\*(.*?)\*\*/g,'<strong class="font-semibold">$1</strong>'),a=a.replace(/\*(.*?)\*/g,'<em class="italic">$1</em>'),a=a.replace(/\[([^\]]+)\]\(([^)]+)\)/g,'<a href="$2" class="text-primary hover:underline" target="_blank" rel="noopener noreferrer">$1</a>'),a=a.replace(/^> (.*$)/gm,'<blockquote class="border-l-4 border-primary/30 pl-4 italic text-muted-foreground">$1</blockquote>'),a=a.replace(/\n\n/g,'</p><p class="mb-2">'),a=a.replace(/\n/g,"<br>"),a&&!a.startsWith("<")&&(a=`<p class="mb-2">${a}</p>`),a},[]),s=(o,a)=>{let i=o;return a==="javascript"||a==="js"||a==="typescript"||a==="ts"?(i=i.replace(/\b(const|let|var|function|return|if|else|for|while|class|import|export|from|async|await)\b/g,'<span class="text-blue-600 dark:text-blue-400 font-semibold">$1</span>'),i=i.replace(/(['"`])([^'"\`]*?)\1/g,'<span class="text-green-600 dark:text-green-400">$1$2$1</span>'),i=i.replace(/(\/\/.*$)/gm,'<span class="text-gray-500 italic">$1</span>')):(a==="python"||a==="py")&&(i=i.replace(/\b(def|class|import|from|return|if|else|elif|for|while|try|except|with|as|pass|break|continue)\b/g,'<span class="text-blue-600 dark:text-blue-400 font-semibold">$1</span>'),i=i.replace(/(['"`])([^'"\`]*?)\1/g,'<span class="text-green-600 dark:text-green-400">$1$2$1</span>'),i=i.replace(/(#.*$)/gm,'<span class="text-gray-500 italic">$1</span>')),i};return l.jsxs("div",{className:se("prose prose-sm max-w-none","prose-headings:text-foreground prose-p:text-foreground","prose-strong:text-foreground prose-em:text-foreground","prose-code:text-foreground prose-pre:bg-muted","prose-a:text-primary prose-a:no-underline hover:prose-a:underline",t),children:[l.jsx("div",{dangerouslySetInnerHTML:{__html:n(r)}}),e&&l.jsx("span",{className:"inline-block w-2 h-4 bg-primary animate-pulse ml-1"})]})},Ya=({attachment:r,customRenderer:e,className:t})=>{if(e)return l.jsx("div",{children:e(r)});const n=r.type==="image",s=r.type==="audio",o=()=>n?l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"})}):s?l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 19V6l12-3v13M9 19c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zm12-3c0 1.105-1.343 2-3 2s-3-.895-3-2 1.343-2 3-2 3 .895 3 2zM9 10l12-3"})}):l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})});return l.jsxs("div",{className:se("inline-flex items-center gap-2 p-2 bg-muted rounded-lg border max-w-sm",t),children:[l.jsx("div",{className:"flex-shrink-0 text-muted-foreground",children:o()}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-sm font-medium truncate",children:r.name}),l.jsx("span",{className:"text-xs text-muted-foreground flex-shrink-0",children:Ga(r.size)})]}),r.mimeType&&l.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:r.mimeType})]}),l.jsx("div",{className:"flex-shrink-0",children:n?l.jsx("button",{onClick:()=>window.open(r.url,"_blank"),className:"p-1 hover:bg-background rounded transition-colors",title:"View image",children:l.jsxs("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"})]})}):l.jsx("a",{href:r.url,download:r.name,className:"p-1 hover:bg-background rounded transition-colors inline-block",title:"Download file",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 10v6m0 0l-3-3m3 3l3-3m2 8H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})})}),n&&l.jsx("div",{className:"w-full mt-2",children:l.jsx("img",{src:r.url,alt:r.name,className:"max-w-full h-auto rounded border",style:{maxHeight:"200px"},loading:"lazy"})}),s&&l.jsx("div",{className:"w-full mt-2",children:l.jsxs("audio",{controls:!0,className:"w-full",preload:"metadata",children:[l.jsx("source",{src:r.url,type:r.mimeType}),"Your browser does not support the audio element."]})})]})},Hn=({toolCall:r,allMessages:e=[],className:t})=>{var p;const[n,s]=M.useState(!1),[o,a]=M.useState(!1),[i,d]=M.useState(!1),c=e.find(y=>y.role==="tool"&&(y.toolCallId===r.id||y.tool_call_id===r.id)),u=(c==null?void 0:c.content)||r.result,f=(c==null?void 0:c.summary)||((p=c==null?void 0:c.metadata)==null?void 0:p.summary),m=!!r.error,b=!!u,g=r.arguments&&Object.keys(r.arguments).length>0,h=y=>{try{return JSON.stringify(y,null,2)}catch{return String(y)}};return l.jsxs("div",{className:se("border rounded-lg p-3 bg-muted/50",m&&"border-destructive bg-destructive/5",t),children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsxs("svg",{className:"w-4 h-4 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:[l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z"}),l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15 12a3 3 0 11-6 0 3 3 0 016 0z"})]}),l.jsxs("span",{className:"text-sm font-medium",children:["Tool: ",r.name]})]}),m&&l.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-destructive bg-destructive/10 px-2 py-0.5 rounded",children:[l.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"})}),"Error"]}),b&&!m&&l.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-green-600 bg-green-50 px-2 py-0.5 rounded",children:[l.jsx("svg",{className:"w-3 h-3",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),"Success"]})]}),l.jsx("button",{onClick:()=>s(!n),className:"p-1 hover:bg-muted rounded transition-colors",title:n?"Collapse":"Expand",children:l.jsx("svg",{className:se("w-4 h-4 transition-transform",n&&"rotate-180"),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 9l-7 7-7-7"})})})]}),n&&l.jsxs("div",{className:"mt-3 space-y-3",children:[g&&l.jsxs("div",{children:[l.jsxs("button",{onClick:()=>a(!o),className:"flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors",children:[l.jsx("svg",{className:se("w-3 h-3 transition-transform",o&&"rotate-90"),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),"Arguments"]}),o&&l.jsx("pre",{className:"mt-2 p-2 bg-background border rounded text-xs overflow-x-auto",children:l.jsx("code",{children:h(r.arguments)})})]}),b&&l.jsx("div",{children:f?l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-sm font-medium text-muted-foreground",children:"AI Summary"}),l.jsx("div",{className:"p-3 bg-blue-50 border border-blue-200 rounded-lg text-sm text-blue-800",children:f}),l.jsxs("button",{onClick:()=>d(!i),className:"flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors",children:[l.jsx("svg",{className:se("w-3 h-3 transition-transform",i&&"rotate-90"),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),i?"Hide Full Result":"Show Full Result"]}),i&&l.jsx("pre",{className:"mt-2 p-2 bg-background border rounded text-xs overflow-x-auto",children:l.jsx("code",{children:u})})]}):l.jsxs("div",{children:[l.jsxs("button",{onClick:()=>d(!i),className:"flex items-center gap-1 text-sm font-medium text-muted-foreground hover:text-foreground transition-colors",children:[l.jsx("svg",{className:se("w-3 h-3 transition-transform",i&&"rotate-90"),fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 5l7 7-7 7"})}),"Result"]}),i&&l.jsx("pre",{className:"mt-2 p-2 bg-background border rounded text-xs overflow-x-auto",children:l.jsx("code",{children:u})})]})}),m&&l.jsxs("div",{children:[l.jsx("div",{className:"text-sm font-medium text-destructive mb-2",children:"Error"}),l.jsx("div",{className:"p-2 bg-destructive/5 border border-destructive/20 rounded text-sm text-destructive",children:r.error})]}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:["Executed at: ",(()=>{const y=new Date(r.createdAt);return isNaN(y.getTime())?"时间未知":y.toLocaleString()})()]})]})]})},Ka=({message:r,isLast:e=!1,isStreaming:t=!1,onEdit:n,onDelete:s,allMessages:o=[],customRenderer:a})=>{var A,k,$;const[i,d]=M.useState(!1),[c,u]=M.useState(r.content),[f,m]=M.useState(!1),b=r.role==="user",g=r.role==="assistant",h=r.role==="system",p=r.role==="tool";if(p)return null;if(a!=null&&a.renderMessage)return l.jsx("div",{children:a.renderMessage(r)});const y=()=>{n&&c.trim()!==r.content&&n(r.id,c.trim()),d(!1)},w=()=>{u(r.content),d(!1)},x=async()=>{try{await navigator.clipboard.writeText(r.content)}catch(j){console.error("Failed to copy message:",j)}},v=((A=r.metadata)==null?void 0:A.attachments)||[];let S=((k=r.metadata)==null?void 0:k.toolCalls)||[];if(S.length===0&&(r.toolCalls||r.tool_calls)){const j=r.toolCalls||r.tool_calls;Array.isArray(j)&&(S=j.map(T=>{var P,C;return{id:T.id,messageId:r.id,name:((P=T.function)==null?void 0:P.name)||T.name,arguments:((C=T.function)==null?void 0:C.arguments)||T.arguments,result:"",createdAt:r.createdAt}}))}return l.jsxs("div",{className:se("group relative flex gap-3 px-4 py-4 rounded-lg transition-colors",b&&"bg-user-message ml-12",g&&"bg-assistant-message mr-12",h&&"bg-muted mx-12 border-l-4 border-primary",p&&"bg-blue-50 dark:bg-blue-950/20 mx-12 border-l-4 border-blue-500","hover:bg-opacity-80"),onMouseEnter:()=>m(!0),onMouseLeave:()=>m(!1),children:[l.jsx("div",{className:"flex-shrink-0",children:l.jsx("div",{className:se("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium",b&&"bg-primary text-primary-foreground",g&&"bg-secondary text-secondary-foreground",h&&"bg-muted text-muted-foreground",p&&"bg-blue-500 text-white"),children:b?"U":g?"AI":p?"T":"S"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[l.jsx("span",{className:"text-sm font-medium",children:b?"You":g?"Assistant":p?"Tool Result":"System"}),l.jsx("span",{className:"text-xs text-muted-foreground",children:Ja(r.createdAt)}),(($=r.metadata)==null?void 0:$.model)&&l.jsx("span",{className:"text-xs text-muted-foreground bg-muted px-1.5 py-0.5 rounded",children:r.metadata.model})]}),v.length>0&&l.jsx("div",{className:"mb-3 space-y-2",children:v.map(j=>l.jsx(Ya,{attachment:j,customRenderer:a==null?void 0:a.renderAttachment},j.id))}),i?l.jsxs("div",{className:"space-y-2",children:[l.jsx("textarea",{value:c,onChange:j=>u(j.target.value),className:"w-full p-2 border rounded-md resize-none focus:outline-none focus:ring-2 focus:ring-primary",rows:3,autoFocus:!0}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx("button",{onClick:y,className:"px-3 py-1 text-sm bg-primary text-primary-foreground rounded hover:bg-primary/90",children:"Save"}),l.jsx("button",{onClick:w,className:"px-3 py-1 text-sm bg-muted text-muted-foreground rounded hover:bg-muted/80",children:"Cancel"})]})]}):l.jsx("div",{className:"space-y-3",children:(()=>{var C;const j=((C=r.metadata)==null?void 0:C.contentSegments)||[],T=r.content&&r.content.trim().length>0,P=t&&e;return j.length>0?l.jsx("div",{className:"space-y-3",children:j.map((F,U)=>{if(F.type==="text")return l.jsx("div",{className:"prose prose-sm max-w-none",children:l.jsx(Wn,{content:F.content,isStreaming:P&&U===j.length-1})},`segment-${U}`);if(F.type==="tool_call"){const G=S.find(te=>te.id===F.toolCallId);if(G)return l.jsx("div",{children:l.jsx(Hn,{toolCall:G,allMessages:o})},`tool-${G.id}`)}return null})}):l.jsxs("div",{className:"space-y-3",children:[T&&l.jsx("div",{className:"prose prose-sm max-w-none",children:l.jsx(Wn,{content:r.content,isStreaming:P})}),S.length>0&&l.jsx("div",{className:"space-y-2",children:S.map(F=>l.jsx("div",{children:l.jsx(Hn,{toolCall:F,allMessages:o})},`tool-${F.id}`))})]})})()}),r.tokensUsed&&l.jsxs("div",{className:"mt-2 text-xs text-muted-foreground",children:["Tokens used: ",r.tokensUsed]})]}),f&&!i&&l.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 bg-background border rounded-md shadow-sm opacity-0 group-hover:opacity-100 transition-opacity",children:[l.jsx("button",{onClick:x,className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Copy message",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"})})}),b&&n&&l.jsx("button",{onClick:()=>d(!0),className:"p-1.5 hover:bg-muted rounded text-muted-foreground hover:text-foreground transition-colors",title:"Edit message",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})})}),s&&l.jsx("button",{onClick:()=>s(r.id),className:"p-1.5 hover:bg-destructive/10 rounded text-muted-foreground hover:text-destructive transition-colors",title:"Delete message",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})})})]})]})},Qa=({size:r="md",className:e})=>{const t={sm:"w-4 h-4",md:"w-6 h-6",lg:"w-8 h-8"};return l.jsx("div",{className:se("animate-spin rounded-full border-2 border-current border-t-transparent",t[r],e),role:"status","aria-label":"Loading",children:l.jsx("span",{className:"sr-only",children:"Loading..."})})},fs=({messages:r,isLoading:e=!1,isStreaming:t=!1,onMessageEdit:n,onMessageDelete:s,customRenderer:o})=>r.length===0&&!e?l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsxs("div",{className:"text-center space-y-4",children:[l.jsx("div",{className:"w-16 h-16 mx-auto bg-muted rounded-full flex items-center justify-center",children:l.jsx("svg",{className:"w-8 h-8 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Start a conversation"}),l.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Send a message to begin your chat with AI"})]})]})}):l.jsx("div",{className:"flex flex-col h-full",children:l.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-6 space-y-6",children:[r.map((a,i)=>l.jsx(Ka,{message:a,isLast:i===r.length-1,isStreaming:t&&i===r.length-1,onEdit:n,onDelete:s,allMessages:r,customRenderer:o},a.id)),e&&l.jsx("div",{className:"flex justify-start",children:l.jsxs("div",{className:"flex items-center space-x-2 bg-muted px-4 py-3 rounded-lg max-w-xs",children:[l.jsx(Qa,{size:"sm"}),l.jsx("span",{className:"text-sm text-muted-foreground",children:"AI is thinking..."})]})})]})}),hs=({onSend:r,disabled:e=!1,placeholder:t="Type your message...",maxLength:n=4e3,allowAttachments:s=!1,supportedFileTypes:o=["image/*","text/*","application/pdf"],showModelSelector:a=!1,selectedModelId:i=null,availableModels:d=[],onModelChange:c})=>{const[u,f]=M.useState(""),[m,b]=M.useState([]),[g,h]=M.useState(!1),p=M.useRef(null),y=M.useRef(null),w=M.useCallback(()=>{const C=p.current;if(C){C.style.height="auto";const F=C.scrollHeight,U=200;C.style.height=`${Math.min(F,U)}px`}},[]),x=C=>{const F=C.target.value;F.length<=n&&(f(F),w())},v=C=>{C.key==="Enter"&&!C.shiftKey&&(C.preventDefault(),S())},S=()=>{const C=u.trim();if(!(!C&&m.length===0)&&!e){if(a&&!i){alert("请先选择一个AI模型");return}r(C,m),f(""),b([]),p.current&&(p.current.style.height="auto")}},A=C=>{const F=Array.from(C.target.files||[]);b(U=>[...U,...F]),y.current&&(y.current.value="")},k=C=>{b(F=>F.filter((U,G)=>G!==C))},$=C=>{C.preventDefault(),s&&!e&&h(!0)},j=C=>{C.preventDefault(),h(!1)},T=C=>{if(C.preventDefault(),h(!1),!s||e)return;const F=Array.from(C.dataTransfer.files);b(U=>[...U,...F])},P=C=>{if(C===0)return"0 Bytes";const F=1024,U=["Bytes","KB","MB","GB"],G=Math.floor(Math.log(C)/Math.log(F));return parseFloat((C/Math.pow(F,G)).toFixed(2))+" "+U[G]};return l.jsxs("div",{className:"border-t bg-background p-4",children:[a&&l.jsx("div",{className:"mb-3",children:d.length>0?l.jsxs("select",{value:i||"",onChange:C=>c==null?void 0:c(C.target.value||null),disabled:e,className:se("w-80 max-w-full px-3 py-2 border border-input bg-background rounded-md","text-sm text-foreground placeholder:text-muted-foreground","focus:outline-none focus:ring-2 focus:ring-ring focus:border-transparent","disabled:opacity-50 disabled:cursor-not-allowed"),children:[l.jsx("option",{value:"",children:"请选择模型..."}),d.filter(C=>C.enabled).map(C=>l.jsxs("option",{value:C.id,children:[C.name," (",C.model_name,")"]},C.id))]}):l.jsx("div",{className:"w-80 max-w-full px-3 py-2 border border-input bg-muted rounded-md text-sm text-muted-foreground",children:"暂无可用模型,请先在右上角配置AI模型"})}),m.length>0&&l.jsx("div",{className:"mb-3 flex flex-wrap gap-2",children:m.map((C,F)=>l.jsxs("div",{className:"flex items-center gap-2 bg-muted px-3 py-2 rounded-lg text-sm",children:[l.jsx("svg",{className:"w-4 h-4 text-muted-foreground",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})}),l.jsx("span",{className:"truncate max-w-32",children:C.name}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",P(C.size),")"]}),l.jsx("button",{onClick:()=>k(F),className:"text-muted-foreground hover:text-destructive transition-colors",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]},F))}),l.jsxs("div",{className:se("relative flex items-end gap-2 p-3 border rounded-lg transition-colors","focus-within:border-primary",g&&"border-primary bg-primary/5",e&&"opacity-50 cursor-not-allowed"),onDragOver:$,onDragLeave:j,onDrop:T,children:[s&&l.jsx("button",{onClick:()=>{var C;return(C=y.current)==null?void 0:C.click()},disabled:e,className:"flex-shrink-0 p-2 text-muted-foreground hover:text-foreground transition-colors disabled:opacity-50 disabled:cursor-not-allowed",title:"Attach files",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13"})})}),l.jsx("textarea",{ref:p,value:u,onChange:x,onKeyDown:v,placeholder:t,disabled:e,className:se("flex-1 resize-none bg-transparent border-none outline-none","placeholder:text-muted-foreground","disabled:cursor-not-allowed"),rows:1,style:{minHeight:"24px",maxHeight:"200px"}}),l.jsxs("div",{className:"flex-shrink-0 text-xs text-muted-foreground",children:[u.length,"/",n]}),l.jsx("button",{onClick:S,disabled:e||!u.trim()&&m.length===0,className:se("flex-shrink-0 p-2 rounded-md transition-colors","disabled:opacity-50 disabled:cursor-not-allowed",(u.trim()||m.length>0)&&!e?"bg-primary text-primary-foreground hover:bg-primary/90":"text-muted-foreground"),title:a&&!i?"请先选择AI模型":"Send message",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 19l9 2-9-18-9 18 9-2zm0 0v-8"})})}),s&&l.jsx("input",{ref:y,type:"file",multiple:!0,accept:o.join(","),onChange:A,className:"hidden"})]}),g&&s&&l.jsx("div",{className:"absolute inset-0 bg-primary/10 border-2 border-dashed border-primary rounded-lg flex items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("svg",{className:"w-8 h-8 mx-auto text-primary mb-2",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M7 16a4 4 0 01-.88-7.903A5 5 0 1115.9 6L16 6a5 5 0 011 9.9M15 13l-3-3m0 0l-3 3m3-3v12"})}),l.jsx("p",{className:"text-sm font-medium text-primary",children:"Drop files here to attach"})]})})]})},Za=({className:r="w-5 h-5"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),ei=({className:r="w-5 h-5"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 5v.01M12 12v.01M12 19v.01M12 6a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2zm0 7a1 1 0 110-2 1 1 0 010 2z"})}),ti=({className:r="w-4 h-4"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z"})}),ri=({className:r="w-4 h-4"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),Zu=({className:r="w-4 h-4"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 13l4 4L19 7"})}),ef=({className:r="w-4 h-4"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),ni=({className:r="w-5 h-5"})=>l.jsx("svg",{className:r,fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})}),tf=r=>{const e=new Date;let t;if(!r)return"时间未知";if(typeof r=="string"){const s=r.replace(" ","T")+"Z";t=new Date(s),isNaN(t.getTime())&&(t=new Date(r))}else t=r;if(!t||isNaN(t.getTime()))return"时间未知";const n=Math.floor((e.getTime()-t.getTime())/1e3);return n<60?"刚刚":n<3600?`${Math.floor(n/60)}分钟前`:n<86400?`${Math.floor(n/3600)}小时前`:n<2592e3?`${Math.floor(n/86400)}天前`:t.toLocaleDateString("zh-CN")},ms=({onClose:r})=>{const e=Rc(),t=Pc(),n=Pe(),{createSession:s,selectSession:o,deleteSession:a,updateSession:i}=n,[d,c]=M.useState(null),[u,f]=M.useState(""),m=async()=>{try{await s(),r==null||r()}catch(x){console.error("Failed to create session:",x)}},b=async x=>{try{await o(x),r==null||r()}catch(v){console.error("Failed to select session:",v)}},g=async x=>{if(window.confirm("确定要删除这个会话吗?此操作无法撤销。"))try{await a(x)}catch(v){console.error("Failed to delete session:",v)}},h=(x,v)=>{c(x),f(v)},p=async()=>{if(d&&u.trim())try{await i(d,{title:u.trim()}),c(null),f("")}catch(x){console.error("Failed to update session:",x)}},y=()=>{c(null),f("")},w=x=>{x.key==="Enter"?p():x.key==="Escape"&&y()};return l.jsxs("div",{className:"flex flex-col h-full bg-white dark:bg-gray-900 border-r border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700",children:[l.jsx("h2",{className:"text-lg font-semibold text-gray-900 dark:text-white",children:"会话列表"}),l.jsx("button",{onClick:m,className:"p-2 text-gray-500 hover:text-gray-700 dark:text-gray-400 dark:hover:text-gray-200 hover:bg-gray-100 dark:hover:bg-gray-800 rounded-lg transition-colors",title:"新建会话",children:l.jsx(Za,{className:"w-5 h-5"})})]}),l.jsx("div",{className:"flex-1 overflow-y-auto",children:e.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-gray-500 dark:text-gray-400",children:[l.jsx(ni,{className:"w-12 h-12 mb-4 opacity-50"}),l.jsx("p",{className:"text-sm",children:"还没有会话"}),l.jsx("button",{onClick:m,className:"mt-2 px-4 py-2 text-sm bg-blue-500 text-white rounded-lg hover:bg-blue-600 transition-colors",children:"创建第一个会话"})]}):l.jsx("div",{className:"p-2 space-y-1",children:e.map(x=>l.jsxs("div",{className:`group relative flex items-center p-3 rounded-lg cursor-pointer transition-colors ${(t==null?void 0:t.id)===x.id?"bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800":"hover:bg-gray-50 dark:hover:bg-gray-800"}`,onClick:()=>b(x.id),children:[l.jsx("div",{className:"flex-1 min-w-0",children:d===x.id?l.jsx("input",{type:"text",value:u,onChange:v=>f(v.target.value),onBlur:p,onKeyDown:w,className:"w-full px-2 py-1 text-sm bg-white dark:bg-gray-800 border border-gray-300 dark:border-gray-600 rounded focus:outline-none focus:ring-2 focus:ring-blue-500",autoFocus:!0,onClick:v=>v.stopPropagation()}):l.jsxs(l.Fragment,{children:[l.jsx("h3",{className:"text-sm font-medium text-gray-900 dark:text-white truncate",children:x.title}),l.jsx("p",{className:"text-xs text-gray-500 dark:text-gray-400 mt-1",children:tf(x.updatedAt)})]})}),d!==x.id&&l.jsxs("div",{className:"relative",children:[l.jsx("button",{className:"p-1 text-gray-400 hover:text-gray-600 dark:hover:text-gray-300 opacity-0 group-hover:opacity-100 transition-opacity",onClick:v=>{v.stopPropagation();const S=v.currentTarget.nextElementSibling;S&&S.classList.toggle("hidden")},children:l.jsx(ei,{className:"w-4 h-4"})}),l.jsx("div",{className:"hidden absolute right-0 z-10 mt-1 w-32 bg-white dark:bg-gray-800 rounded-md shadow-lg ring-1 ring-black ring-opacity-5",children:l.jsxs("div",{className:"py-1",children:[l.jsxs("button",{onClick:v=>{v.stopPropagation(),h(x.id,x.title);const S=v.currentTarget.closest(".absolute");S&&S.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-gray-700 dark:text-gray-300 hover:bg-gray-100 dark:hover:bg-gray-700",children:[l.jsx(ti,{className:"w-4 h-4 mr-2"}),"重命名"]}),l.jsxs("button",{onClick:v=>{v.stopPropagation(),g(x.id);const S=v.currentTarget.closest(".absolute");S&&S.classList.add("hidden")},className:"flex items-center w-full px-3 py-2 text-sm text-red-600 dark:text-red-400 hover:bg-red-50 dark:hover:bg-red-900/20",children:[l.jsx(ri,{className:"w-4 h-4 mr-2"}),"删除"]})]})})]})]},x.id))})})]})},si=()=>typeof window>"u"?"light":window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light",No=r=>r==="system"?si():r,bn=r=>{if(typeof window>"u")return;const e=window.document.documentElement;e.classList.remove("light","dark"),e.classList.add(r);const t=document.querySelector('meta[name="theme-color"]');t&&t.setAttribute("content",r==="dark"?"#0f172a":"#ffffff")},Oo=()=>typeof window>"u"?"system":localStorage.getItem("theme")||"system",rf=r=>{typeof window>"u"||localStorage.setItem("theme",r)},oi=()=>{const[r,e]=M.useState(()=>Oo()),[t,n]=M.useState(()=>No(Oo())),s=a=>{e(a),rf(a);const i=No(a);n(i),bn(i)},o=()=>{let a;switch(r){case"light":a="dark";break;case"dark":a="system";break;case"system":a="light";break;default:a="system"}s(a)};return M.useEffect(()=>{if(r!=="system")return;const a=window.matchMedia("(prefers-color-scheme: dark)"),i=()=>{const d=si();n(d),bn(d)};return a.addEventListener("change",i),()=>a.removeEventListener("change",i)},[r]),M.useEffect(()=>{bn(t)},[t]),{theme:r,actualTheme:t,setTheme:s,toggleTheme:o}},gs=({className:r=""})=>{const{theme:e,toggleTheme:t}=oi(),n=()=>{switch(e){case"light":return l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 3v1m0 16v1m9-9h-1M4 12H3m15.364 6.364l-.707-.707M6.343 6.343l-.707-.707m12.728 0l-.707.707M6.343 17.657l-.707.707M16 12a4 4 0 11-8 0 4 4 0 018 0z"})});case"dark":return l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M20.354 15.354A9 9 0 018.646 3.646 9.003 9.003 0 0012 21a9.003 9.003 0 008.354-5.646z"})});case"system":return l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"})});default:return null}},s=()=>{switch(e){case"light":return"Light mode";case"dark":return"Dark mode";case"system":return"System theme";default:return"Toggle theme"}};return l.jsx("button",{onClick:t,className:`p-2 hover:bg-muted rounded-lg transition-colors ${r}`,title:s(),"aria-label":s(),children:n()})},Po=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"})}),nf=()=>l.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),sf=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),of=()=>l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),af=()=>l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})}),ps=({onClose:r})=>{const{mcpConfigs:e,updateMcpConfig:t,deleteMcpConfig:n,loadMcpConfigs:s}=Pe(),[o,a]=M.useState(!1),[i,d]=M.useState(null),[c,u]=M.useState({name:"",serverUrl:"",enabled:!0});M.useEffect(()=>{s()},[s]);const f=()=>{u({name:"",serverUrl:"",enabled:!0}),d(null),a(!1)},m=async y=>{if(y.preventDefault(),!c.name.trim()||!c.serverUrl.trim())return;const w={id:Date.now().toString(),name:c.name.trim(),serverUrl:c.serverUrl.trim(),enabled:c.enabled,createdAt:new Date,updatedAt:new Date};await t(w),f()},b=async y=>{if(y.preventDefault(),!i||!c.name.trim()||!c.serverUrl.trim())return;const w={...i,name:c.name.trim(),serverUrl:c.serverUrl.trim(),enabled:c.enabled,updatedAt:new Date};await t(w),f()},g=y=>{d(y),u({name:y.name,serverUrl:y.serverUrl,enabled:y.enabled}),a(!0)},h=async y=>{confirm("确定要删除这个MCP服务器配置吗?")&&await n(y)},p=async y=>{const w={...y,enabled:!y.enabled,updatedAt:new Date};await t(w)};return l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx(Po,{}),l.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"MCP 服务器管理"})]}),l.jsx("button",{onClick:r,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:l.jsx(nf,{})})]}),l.jsxs("div",{className:"p-6 overflow-y-auto max-h-[calc(80vh-120px)]",children:[!o&&l.jsxs("button",{onClick:()=>a(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg hover:border-blue-500 dark:hover:border-blue-400 transition-colors flex items-center justify-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400",children:[l.jsx(sf,{}),l.jsx("span",{children:"添加 MCP 服务器"})]}),o&&l.jsxs("form",{onSubmit:i?b:m,className:"mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-white mb-4",children:i?"编辑服务器":"添加新服务器"}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"服务器名称"}),l.jsx("input",{type:"text",value:c.name,onChange:y=>u({...c,name:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: File System",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"服务器URL"}),l.jsx("input",{type:"url",value:c.serverUrl,onChange:y=>u({...c,serverUrl:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: http://localhost:3001",required:!0})]}),l.jsxs("div",{className:"flex items-center",children:[l.jsx("input",{type:"checkbox",id:"enabled",checked:c.enabled,onChange:y=>u({...c,enabled:y.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),l.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-gray-700 dark:text-gray-300",children:"启用此服务器"})]})]}),l.jsxs("div",{className:"flex space-x-3 mt-6",children:[l.jsx("button",{type:"submit",className:"px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500",children:i?"更新":"添加"}),l.jsx("button",{type:"button",onClick:f,className:"px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-400 dark:hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-500",children:"取消"})]})]}),l.jsx("div",{className:"space-y-3",children:e.length===0?l.jsxs("div",{className:"text-center py-8 text-gray-500 dark:text-gray-400",children:[l.jsx(Po,{}),l.jsx("p",{className:"mt-2",children:"暂无 MCP 服务器配置"}),l.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个服务器"})]}):e.map(y=>l.jsxs("div",{className:"flex items-center justify-between p-4 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx("div",{className:`w-3 h-3 rounded-full ${y.enabled?"bg-green-500":"bg-gray-400"}`}),l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium text-gray-900 dark:text-white",children:y.name}),l.jsx("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:y.serverUrl})]})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx("button",{onClick:()=>p(y),className:`px-3 py-1 text-xs rounded-full ${y.enabled?"bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200":"bg-gray-100 text-gray-800 dark:bg-gray-600 dark:text-gray-200"}`,children:y.enabled?"已启用":"已禁用"}),l.jsx("button",{onClick:()=>g(y),className:"p-2 text-gray-500 hover:text-blue-600 dark:text-gray-400 dark:hover:text-blue-400 transition-colors",title:"编辑",children:l.jsx(af,{})}),l.jsx("button",{onClick:()=>h(y.id),className:"p-2 text-gray-500 hover:text-red-600 dark:text-gray-400 dark:hover:text-red-400 transition-colors",title:"删除",children:l.jsx(of,{})})]})]},y.id))})]})]})})},Ro=()=>l.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})}),lf=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),cf=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 4v16m8-8H4"})}),df=()=>l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"})}),uf=()=>l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"})}),ys=({onClose:r})=>{const{aiModelConfigs:e,loadAiModelConfigs:t,updateAiModelConfig:n,deleteAiModelConfig:s}=Pe(),[o,a]=M.useState(!1),[i,d]=M.useState(null),[c,u]=M.useState({name:"",base_url:"",api_key:"",model_name:"",enabled:!0});M.useEffect(()=>{t()},[t]);const f=()=>{u({name:"",base_url:"",api_key:"",model_name:"",enabled:!0}),d(null),a(!1)},m=async y=>{if(y.preventDefault(),!c.name.trim()||!c.base_url.trim()||!c.api_key.trim()||!c.model_name.trim())return;const w={id:Math.random().toString(36).substr(2,9),name:c.name.trim(),base_url:c.base_url.trim(),api_key:c.api_key.trim(),model_name:c.model_name.trim(),enabled:c.enabled,createdAt:new Date,updatedAt:new Date};await n(w),f()},b=async y=>{if(y.preventDefault(),!i||!c.name.trim()||!c.base_url.trim()||!c.api_key.trim()||!c.model_name.trim())return;const w={...i,name:c.name.trim(),base_url:c.base_url.trim(),api_key:c.api_key.trim(),model_name:c.model_name.trim(),enabled:c.enabled,updatedAt:new Date};await n(w),f()},g=y=>{d(y),u({name:y.name,base_url:y.base_url,api_key:y.api_key,model_name:y.model_name,enabled:y.enabled}),a(!0)},h=async y=>{confirm("确定要删除这个AI模型配置吗?")&&await s(y)},p=async y=>{const w={...y,enabled:!y.enabled,updatedAt:new Date};await n(w)};return l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-2xl max-h-[80vh] overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx(Ro,{}),l.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"AI 模型管理"})]}),l.jsx("button",{onClick:r,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:l.jsx(lf,{})})]}),l.jsxs("div",{className:"p-6 overflow-y-auto max-h-[calc(80vh-120px)]",children:[!o&&l.jsxs("button",{onClick:()=>a(!0),className:"w-full mb-6 p-4 border-2 border-dashed border-gray-300 dark:border-gray-600 rounded-lg hover:border-blue-500 dark:hover:border-blue-400 transition-colors flex items-center justify-center space-x-2 text-gray-600 dark:text-gray-400 hover:text-blue-600 dark:hover:text-blue-400",children:[l.jsx(cf,{}),l.jsx("span",{children:"添加 AI 模型"})]}),o&&l.jsxs("form",{onSubmit:i?b:m,className:"mb-6 p-4 bg-gray-50 dark:bg-gray-700 rounded-lg",children:[l.jsx("h3",{className:"text-lg font-medium text-gray-900 dark:text-white mb-4",children:i?"编辑 AI 模型":"添加 AI 模型"}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"配置名称"}),l.jsx("input",{type:"text",value:c.name,onChange:y=>u({...c,name:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: OpenAI GPT-4",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"Base URL"}),l.jsx("input",{type:"url",value:c.base_url,onChange:y=>u({...c,base_url:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: https://api.openai.com/v1",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"API Key"}),l.jsx("input",{type:"password",value:c.api_key,onChange:y=>u({...c,api_key:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"输入API密钥",required:!0})]}),l.jsxs("div",{children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300 mb-2",children:"模型名称"}),l.jsx("input",{type:"text",value:c.model_name,onChange:y=>u({...c,model_name:y.target.value}),className:"w-full px-3 py-2 border border-gray-300 dark:border-gray-600 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-800 dark:text-white",placeholder:"例如: gpt-4",required:!0})]}),l.jsxs("div",{className:"flex items-center",children:[l.jsx("input",{type:"checkbox",id:"enabled",checked:c.enabled,onChange:y=>u({...c,enabled:y.target.checked}),className:"h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"}),l.jsx("label",{htmlFor:"enabled",className:"ml-2 block text-sm text-gray-700 dark:text-gray-300",children:"启用此模型"})]})]}),l.jsxs("div",{className:"flex space-x-3 mt-6",children:[l.jsx("button",{type:"submit",className:"px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500",children:i?"更新":"添加"}),l.jsx("button",{type:"button",onClick:f,className:"px-4 py-2 bg-gray-300 dark:bg-gray-600 text-gray-700 dark:text-gray-300 rounded-md hover:bg-gray-400 dark:hover:bg-gray-500 focus:outline-none focus:ring-2 focus:ring-gray-500",children:"取消"})]})]}),l.jsx("div",{className:"space-y-3",children:e.length===0?l.jsxs("div",{className:"text-center py-8 text-gray-500 dark:text-gray-400",children:[l.jsx(Ro,{}),l.jsx("p",{className:"mt-2",children:"暂无 AI 模型配置"}),l.jsx("p",{className:"text-sm",children:"点击上方按钮添加第一个模型"})]}):e.map(y=>l.jsxs("div",{className:"flex items-center justify-between p-4 bg-white dark:bg-gray-700 border border-gray-200 dark:border-gray-600 rounded-lg hover:shadow-md transition-shadow",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx("div",{className:`w-3 h-3 rounded-full ${y.enabled?"bg-green-500":"bg-gray-400"}`}),l.jsxs("div",{children:[l.jsx("h4",{className:"font-medium text-gray-900 dark:text-white",children:y.name}),l.jsxs("p",{className:"text-sm text-gray-500 dark:text-gray-400",children:[y.base_url," - ",y.model_name]})]})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx("button",{onClick:()=>p(y),className:`px-3 py-1 text-xs rounded-full transition-colors ${y.enabled?"bg-green-100 text-green-800 hover:bg-green-200 dark:bg-green-900 dark:text-green-200":"bg-gray-100 text-gray-800 hover:bg-gray-200 dark:bg-gray-800 dark:text-gray-200"}`,children:y.enabled?"已启用":"已禁用"}),l.jsx("button",{onClick:()=>g(y),className:"p-2 text-gray-500 hover:text-blue-600 hover:bg-blue-50 dark:hover:bg-blue-900 rounded transition-colors",title:"编辑",children:l.jsx(df,{})}),l.jsx("button",{onClick:()=>h(y.id),className:"p-2 text-gray-500 hover:text-red-600 hover:bg-red-50 dark:hover:bg-red-900 rounded transition-colors",title:"删除",children:l.jsx(uf,{})})]})]},y.id))})]})]})})},ff=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})}),hf=()=>l.jsx("svg",{className:"w-6 h-6",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})}),mf=()=>l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4"})}),bs=({onClose:r})=>{const{systemContext:e,updateSystemContext:t,loadSystemContext:n}=Pe(),[s,o]=M.useState(""),[a,i]=M.useState(!1),[d,c]=M.useState(!1);M.useEffect(()=>{(async()=>{console.log("SystemContextEditor: Starting to load system context"),i(!0);try{await n(),console.log("SystemContextEditor: System context loaded successfully")}catch(b){console.error("SystemContextEditor: Failed to load system context:",b)}finally{i(!1)}})()},[]),M.useEffect(()=>{o(e||"")},[e]);const u=async()=>{c(!0);try{await t(s),r==null||r()}catch(m){console.error("Failed to save system context:",m),alert("保存失败,请重试")}finally{c(!1)}},f=m=>{m.ctrlKey&&m.key==="s"&&(m.preventDefault(),u())};return l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-white dark:bg-gray-800 rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-6 border-b border-gray-200 dark:border-gray-700",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx(ff,{}),l.jsx("h2",{className:"text-xl font-semibold text-gray-900 dark:text-white",children:"系统上下文设置"})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsxs("button",{onClick:u,disabled:d,className:"flex items-center space-x-2 px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors",children:[l.jsx(mf,{}),l.jsx("span",{children:d?"保存中...":"保存"})]}),l.jsx("button",{onClick:r,className:"p-2 hover:bg-gray-100 dark:hover:bg-gray-700 rounded-lg transition-colors",children:l.jsx(hf,{})})]})]}),l.jsxs("div",{className:"p-6 overflow-hidden flex flex-col",style:{height:"calc(90vh - 120px)"},children:[l.jsxs("div",{className:"mb-4 p-4 bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800 rounded-lg",children:[l.jsxs("p",{className:"text-sm text-blue-800 dark:text-blue-200",children:[l.jsx("strong",{children:"系统上下文"}),"将作为每次对话的系统提示词,支持 Markdown 格式。 您可以在这里设置 AI 的角色、行为规范、回答风格等。"]}),l.jsx("p",{className:"text-xs text-blue-600 dark:text-blue-300 mt-2",children:"提示:使用 Ctrl+S 快速保存"})]}),l.jsxs("div",{className:"flex-1 flex flex-col",children:[l.jsxs("div",{className:"mb-2 flex items-center justify-between",children:[l.jsx("label",{className:"block text-sm font-medium text-gray-700 dark:text-gray-300",children:"Markdown 内容"}),l.jsxs("div",{className:"text-xs text-gray-500 dark:text-gray-400",children:[s.length," 字符"]})]}),a?l.jsx("div",{className:"flex-1 flex items-center justify-center bg-gray-50 dark:bg-gray-700 rounded-lg border border-gray-300 dark:border-gray-600",children:l.jsx("div",{className:"text-gray-500 dark:text-gray-400",children:"加载中..."})}):l.jsx("textarea",{value:s,onChange:m=>o(m.target.value),onKeyDown:f,className:"flex-1 w-full px-4 py-3 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 dark:bg-gray-700 dark:text-white resize-none font-mono text-sm",placeholder:"请输入系统上下文内容,支持 Markdown 格式...\\n\\n例如:\\n# AI 助手角色设定\\n\\n你是一个专业的编程助手,具有以下特点:\\n- 提供准确、简洁的代码解决方案\\n- 遵循最佳实践和代码规范\\n- 耐心解答技术问题\\n\\n## 回答风格\\n- 使用中文回答\\n- 代码示例要完整可运行\\n- 提供必要的解释说明",spellCheck:!1})]}),l.jsxs("div",{className:"mt-4 text-xs text-gray-500 dark:text-gray-400",children:[l.jsx("p",{children:"• 支持标准 Markdown 语法:标题、列表、代码块、链接等"}),l.jsx("p",{children:"• 内容将在每次对话开始时自动发送给 AI"}),l.jsx("p",{children:"• 留空则使用默认系统提示词"})]})]})]})})},ai=({className:r,apiBaseUrl:e,port:t})=>{const n=M.useMemo(()=>{if(e)return e;if(t)return`http://localhost:${t}/api`},[e,t]),s=M.useMemo(()=>{if(n)return new Ta(n)},[n]),a=M.useMemo(()=>s?Tc(s):null,[s])||Pe,{currentSession:i,messages:d,isLoading:c,isStreaming:u,error:f,loadSessions:m,sendMessage:b,clearError:g,aiModelConfigs:h,selectedModelId:p,setSelectedModel:y,loadAiModelConfigs:w}=a(),x=M.useRef(null),[v,S]=M.useState(!1),[A,k]=M.useState(!1),[$,j]=M.useState(!1),[T,P]=M.useState(!1);M.useEffect(()=>{m(),w()},[m,w]),M.useEffect(()=>{x.current&&x.current.scrollIntoView({behavior:"smooth"})},[d,u]);const C=async(F,U)=>{try{await b(F,U)}catch(G){console.error("Failed to send message:",G)}};return l.jsxs("div",{className:se("flex flex-col h-screen bg-background text-foreground",r),children:[l.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx("button",{onClick:()=>S(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),i&&l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:i.title})})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx("button",{onClick:()=>k(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP 服务器管理",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"})})}),l.jsx("button",{onClick:()=>j(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI 模型管理",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})})}),l.jsx("button",{onClick:()=>P(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"系统上下文设置",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})}),l.jsx(gs,{})]})]}),f&&l.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("p",{className:"text-sm text-destructive",children:f}),l.jsx("button",{onClick:g,className:"text-destructive hover:text-destructive/80 transition-colors",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),l.jsxs("div",{className:"flex-1 overflow-hidden",children:[i?l.jsx(fs,{messages:d,isLoading:c,isStreaming:u}):l.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:l.jsxs("div",{className:"text-center",children:[l.jsx("svg",{className:"w-16 h-16 mx-auto mb-4 opacity-50",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1,d:"M8 12h.01M12 12h.01M16 12h.01M21 12c0 4.418-4.03 8-9 8a9.863 9.863 0 01-4.255-.949L3 20l1.395-3.72C3.512 15.042 3 13.574 3 12c0-4.418 4.03-8 9-8s9 3.582 9 8z"})}),l.jsx("p",{className:"text-lg mb-2",children:"欢迎使用AI聊天助手"}),l.jsx("p",{className:"text-sm",children:"点击左上角按钮创建新会话开始对话"})]})}),l.jsx("div",{ref:x})]}),i&&l.jsx(hs,{onSend:C,disabled:c||u,selectedModelId:p,availableModels:h,onModelChange:y,showModelSelector:!0}),v&&l.jsx("div",{className:"fixed inset-0 bg-black/50 flex items-center justify-center z-50",children:l.jsxs("div",{className:"bg-card border border-border rounded-lg w-full max-w-md mx-4 max-h-[80vh] overflow-hidden",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[l.jsx("h2",{className:"text-lg font-semibold",children:"会话列表"}),l.jsx("button",{onClick:()=>S(!1),className:"p-1 text-muted-foreground hover:text-foreground hover:bg-accent rounded transition-colors",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]}),l.jsx("div",{className:"overflow-y-auto max-h-[60vh]",children:l.jsx(ms,{onClose:()=>S(!1)})})]})}),A&&l.jsx(ps,{onClose:()=>k(!1)}),$&&l.jsx(ys,{onClose:()=>j(!1)}),T&&l.jsx(bs,{onClose:()=>P(!1)})]})},gf=({className:r,onMessageSend:e,customRenderer:t})=>{const{currentSession:n,messages:s,isLoading:o,isStreaming:a,error:i,loadSessions:d,sendMessage:c,clearError:u,aiModelConfigs:f,selectedModelId:m,setSelectedModel:b,loadAiModelConfigs:g}=Pe(),h=M.useRef(null),[p,y]=M.useState(!1),[w,x]=M.useState(!1),[v,S]=M.useState(!1),[A,k]=M.useState(!1);M.useEffect(()=>{d(),g()},[d,g]),M.useEffect(()=>{h.current&&h.current.scrollIntoView({behavior:"smooth"})},[s,a]);const $=async(j,T)=>{try{await c(j,T),e==null||e(j,[])}catch(P){console.error("Failed to send message:",P)}};return l.jsxs("div",{className:se("flex flex-col h-screen bg-background text-foreground",r),children:[l.jsxs("div",{className:"flex items-center justify-between p-4 bg-card border-b border-border",children:[l.jsxs("div",{className:"flex items-center space-x-3",children:[l.jsx("button",{onClick:()=>y(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"打开会话列表",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5"})})}),n&&l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("h1",{className:"text-lg font-semibold text-foreground truncate",children:n.title})})]}),l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx("button",{onClick:()=>x(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"MCP 服务器管理",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M5 12h14M5 12a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v4a2 2 0 01-2 2M5 12a2 2 0 00-2 2v4a2 2 0 002 2h14a2 2 0 002-2v-4a2 2 0 00-2-2m-2-4h.01M17 16h.01"})})}),l.jsx("button",{onClick:()=>S(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"AI 模型管理",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"})})}),l.jsx("button",{onClick:()=>k(!0),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",title:"系统上下文设置",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z"})})}),l.jsx(gs,{})]})]}),i&&l.jsx("div",{className:"mx-4 mt-4 p-3 bg-destructive/10 border border-destructive/20 rounded-lg",children:l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("p",{className:"text-sm text-destructive",children:i}),l.jsx("button",{onClick:u,className:"text-destructive hover:text-destructive/80 transition-colors",children:l.jsx("svg",{className:"w-4 h-4",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M6 18L18 6M6 6l12 12"})})})]})}),l.jsxs("div",{className:"flex-1 overflow-hidden",children:[n?l.jsx(fs,{messages:s,isLoading:o,isStreaming:a,customRenderer:t}):l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsxs("div",{className:"text-center",children:[l.jsx("h2",{className:"text-xl font-semibold text-muted-foreground mb-2",children:"欢迎使用 AI 聊天"}),l.jsx("p",{className:"text-muted-foreground mb-4",children:"点击左上角按钮选择会话,或创建新的会话开始对话"}),l.jsx("button",{onClick:()=>y(!0),className:"px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"打开会话列表"})]})}),l.jsx("div",{ref:h})]}),n&&l.jsx("div",{className:"border-t border-border",children:l.jsx(hs,{onSend:$,disabled:o||a,placeholder:"输入消息...",showModelSelector:!0,selectedModelId:m,availableModels:f,onModelChange:b})}),p&&l.jsxs("div",{className:"fixed inset-0 z-50 overflow-y-auto",children:[l.jsx("div",{className:"fixed inset-0 bg-black bg-opacity-25 transition-opacity",onClick:()=>y(!1)}),l.jsx("div",{className:"flex min-h-full items-center justify-center p-4",children:l.jsxs("div",{className:"w-full max-w-md transform overflow-hidden rounded-2xl bg-card shadow-xl transition-all",children:[l.jsxs("div",{className:"flex items-center justify-between p-4 border-b border-border",children:[l.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"会话管理"}),l.jsx("button",{onClick:()=>y(!1),className:"p-2 text-muted-foreground hover:text-foreground hover:bg-accent rounded-lg transition-colors",children:l.jsx("svg",{className:"w-5 h-5",fill:"none",viewBox:"0 0 24 24",strokeWidth:1.5,stroke:"currentColor",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M6 18L18 6M6 6l12 12"})})})]}),l.jsx("div",{className:"h-96",children:l.jsx(ms,{onClose:()=>y(!1)})})]})})]}),w&&l.jsx(ps,{onClose:()=>x(!1)}),v&&l.jsx(ys,{onClose:()=>S(!1)}),A&&l.jsx(bs,{onClose:()=>k(!1)})]})};class pf extends M.Component{constructor(e){super(e),this.state={hasError:!1}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error("ErrorBoundary caught an error:",e,t)}render(){var e;return this.state.hasError?this.props.fallback?this.props.fallback:l.jsx("div",{className:"flex items-center justify-center h-full p-8",children:l.jsxs("div",{className:"text-center space-y-4",children:[l.jsx("div",{className:"w-16 h-16 mx-auto bg-destructive/10 rounded-full flex items-center justify-center",children:l.jsx("svg",{className:"w-8 h-8 text-destructive",fill:"none",stroke:"currentColor",viewBox:"0 0 24 24",children:l.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-2.5L13.732 4c-.77-.833-1.964-.833-2.732 0L3.732 16.5c-.77.833.192 2.5 1.732 2.5z"})})}),l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Something went wrong"}),l.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:((e=this.state.error)==null?void 0:e.message)||"An unexpected error occurred"}),l.jsx("button",{onClick:()=>this.setState({hasError:!1,error:void 0}),className:"mt-4 px-4 py-2 bg-primary text-primary-foreground rounded-lg hover:bg-primary/90 transition-colors",children:"Try again"})]})]})}):this.props.children}}const yf="http://localhost:3001/api",Mt=async(r,e={})=>{try{const t=await fetch(`${yf}${r}`,{headers:{"Content-Type":"application/json",...e.headers},...e});if(!t.ok){let n=`HTTP error! status: ${t.status}`;try{const s=await t.json();n=s.error||s.message||n}catch{}throw new Error(n)}return t.json()}catch(t){throw t instanceof TypeError&&t.message.includes("fetch")?new Error("网络连接失败,请检查网络连接或服务器状态"):t}},ct={async getDetails(r){try{const e=await Mt(`/sessions/${r}`);return{data:{conversation:{id:e.id,title:e.title,created_at:e.created_at,updated_at:e.updated_at}}}}catch(e){return console.error("Failed to get conversation details:",e),{data:{conversation:{id:r,title:"Default Conversation",created_at:new Date().toISOString(),updated_at:new Date().toISOString()}}}}},async getAssistant(r){try{const e=await Mt("/ai-model-configs"),t=e.find(n=>n.enabled)||e[0];if(!t)throw new Error("No AI model configuration found");return{data:{assistant:{id:t.id,name:t.name,model_config:{model_name:t.model_name,temperature:.7,max_tokens:4e3,api_key:t.api_key,base_url:t.base_url}}}}}catch(e){return console.error("Failed to get assistant:",e),{data:{assistant:{id:"default-assistant",name:"AI Assistant",model_config:{model_name:"gpt-3.5-turbo",temperature:.7,max_tokens:4e3,api_key:"",base_url:"https://api.openai.com/v1"}}}}}},async getMcpServers(r){try{return{data:{mcp_servers:(await Mt("/mcp-configs")).filter(n=>n.enabled).map(n=>({name:n.name,url:n.command}))}}}catch(e){return console.error("Failed to get MCP servers:",e),{data:{mcp_servers:[]}}}},async saveMessage(r,e){try{const t=e.id||`msg_${Date.now()}_${Math.random().toString(36).substr(2,9)}`;return{data:{message:await Mt("/messages",{method:"POST",body:JSON.stringify({id:t,sessionId:r,role:e.role,content:e.content,toolCalls:e.tool_calls||null,toolCallId:e.tool_call_id||null,reasoning:e.reasoning||null,metadata:e.metadata||null})})}}}catch(t){return console.error("Failed to save message:",t),{data:{message:{...e,id:Date.now().toString(),created_at:new Date().toISOString()}}}}},async getMessages(r,e={}){try{return{data:{messages:await Mt(`/sessions/${r}/messages`)}}}catch(t){return console.error("Failed to get messages:",t),{data:{messages:[]}}}},async addMessage(r,e){return this.saveMessage(r,e)}},To=Object.freeze(Object.defineProperty({__proto__:null,conversationsApi:ct},Symbol.toStringTag,{value:"Module"})),zn="RFC3986",qn={RFC1738:r=>String(r).replace(/%20/g,"+"),RFC3986:r=>String(r)},bf="RFC1738",wf=Array.isArray,Se=(()=>{const r=[];for(let e=0;e<256;++e)r.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return r})(),wn=1024,xf=(r,e,t,n,s)=>{if(r.length===0)return r;let o=r;if(typeof r=="symbol"?o=Symbol.prototype.toString.call(r):typeof r!="string"&&(o=String(r)),t==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(i){return"%26%23"+parseInt(i.slice(2),16)+"%3B"});let a="";for(let i=0;i<o.length;i+=wn){const d=o.length>=wn?o.slice(i,i+wn):o,c=[];for(let u=0;u<d.length;++u){let f=d.charCodeAt(u);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||s===bf&&(f===40||f===41)){c[c.length]=d.charAt(u);continue}if(f<128){c[c.length]=Se[f];continue}if(f<2048){c[c.length]=Se[192|f>>6]+Se[128|f&63];continue}if(f<55296||f>=57344){c[c.length]=Se[224|f>>12]+Se[128|f>>6&63]+Se[128|f&63];continue}u+=1,f=65536+((f&1023)<<10|d.charCodeAt(u)&1023),c[c.length]=Se[240|f>>18]+Se[128|f>>12&63]+Se[128|f>>6&63]+Se[128|f&63]}a+=c.join("")}return a};function _f(r){return!r||typeof r!="object"?!1:!!(r.constructor&&r.constructor.isBuffer&&r.constructor.isBuffer(r))}function Io(r,e){if(wf(r)){const t=[];for(let n=0;n<r.length;n+=1)t.push(e(r[n]));return t}return e(r)}const vf=Object.prototype.hasOwnProperty,ii={brackets(r){return String(r)+"[]"},comma:"comma",indices(r,e){return String(r)+"["+e+"]"},repeat(r){return String(r)}},ke=Array.isArray,Sf=Array.prototype.push,li=function(r,e){Sf.apply(r,ke(e)?e:[e])},Cf=Date.prototype.toISOString,Y={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:xf,encodeValuesOnly:!1,format:zn,formatter:qn[zn],indices:!1,serializeDate(r){return Cf.call(r)},skipNulls:!1,strictNullHandling:!1};function kf(r){return typeof r=="string"||typeof r=="number"||typeof r=="boolean"||typeof r=="symbol"||typeof r=="bigint"}const xn={};function ci(r,e,t,n,s,o,a,i,d,c,u,f,m,b,g,h,p,y){let w=r,x=y,v=0,S=!1;for(;(x=x.get(xn))!==void 0&&!S;){const T=x.get(r);if(v+=1,typeof T<"u"){if(T===v)throw new RangeError("Cyclic object value");S=!0}typeof x.get(xn)>"u"&&(v=0)}if(typeof c=="function"?w=c(e,w):w instanceof Date?w=m==null?void 0:m(w):t==="comma"&&ke(w)&&(w=Io(w,function(T){return T instanceof Date?m==null?void 0:m(T):T})),w===null){if(o)return d&&!h?d(e,Y.encoder,p,"key",b):e;w=""}if(kf(w)||_f(w)){if(d){const T=h?e:d(e,Y.encoder,p,"key",b);return[(g==null?void 0:g(T))+"="+(g==null?void 0:g(d(w,Y.encoder,p,"value",b)))]}return[(g==null?void 0:g(e))+"="+(g==null?void 0:g(String(w)))]}const A=[];if(typeof w>"u")return A;let k;if(t==="comma"&&ke(w))h&&d&&(w=Io(w,d)),k=[{value:w.length>0?w.join(",")||null:void 0}];else if(ke(c))k=c;else{const T=Object.keys(w);k=u?T.sort(u):T}const $=i?String(e).replace(/\./g,"%2E"):String(e),j=n&&ke(w)&&w.length===1?$+"[]":$;if(s&&ke(w)&&w.length===0)return j+"[]";for(let T=0;T<k.length;++T){const P=k[T],C=typeof P=="object"&&typeof P.value<"u"?P.value:w[P];if(a&&C===null)continue;const F=f&&i?P.replace(/\./g,"%2E"):P,U=ke(w)?typeof t=="function"?t(j,F):j:j+(f?"."+F:"["+F+"]");y.set(r,v);const G=new WeakMap;G.set(xn,y),li(A,ci(C,U,t,n,s,o,a,i,t==="comma"&&h&&ke(w)?null:d,c,u,f,m,b,g,h,p,G))}return A}function Af(r=Y){if(typeof r.allowEmptyArrays<"u"&&typeof r.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof r.encodeDotInKeys<"u"&&typeof r.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(r.encoder!==null&&typeof r.encoder<"u"&&typeof r.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=r.charset||Y.charset;if(typeof r.charset<"u"&&r.charset!=="utf-8"&&r.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=zn;if(typeof r.format<"u"){if(!vf.call(qn,r.format))throw new TypeError("Unknown format option provided.");t=r.format}const n=qn[t];let s=Y.filter;(typeof r.filter=="function"||ke(r.filter))&&(s=r.filter);let o;if(r.arrayFormat&&r.arrayFormat in ii?o=r.arrayFormat:"indices"in r?o=r.indices?"indices":"repeat":o=Y.arrayFormat,"commaRoundTrip"in r&&typeof r.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof r.allowDots>"u"?r.encodeDotInKeys?!0:Y.allowDots:!!r.allowDots;return{addQueryPrefix:typeof r.addQueryPrefix=="boolean"?r.addQueryPrefix:Y.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof r.allowEmptyArrays=="boolean"?!!r.allowEmptyArrays:Y.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof r.charsetSentinel=="boolean"?r.charsetSentinel:Y.charsetSentinel,commaRoundTrip:!!r.commaRoundTrip,delimiter:typeof r.delimiter>"u"?Y.delimiter:r.delimiter,encode:typeof r.encode=="boolean"?r.encode:Y.encode,encodeDotInKeys:typeof r.encodeDotInKeys=="boolean"?r.encodeDotInKeys:Y.encodeDotInKeys,encoder:typeof r.encoder=="function"?r.encoder:Y.encoder,encodeValuesOnly:typeof r.encodeValuesOnly=="boolean"?r.encodeValuesOnly:Y.encodeValuesOnly,filter:s,format:t,formatter:n,serializeDate:typeof r.serializeDate=="function"?r.serializeDate:Y.serializeDate,skipNulls:typeof r.skipNulls=="boolean"?r.skipNulls:Y.skipNulls,sort:typeof r.sort=="function"?r.sort:null,strictNullHandling:typeof r.strictNullHandling=="boolean"?r.strictNullHandling:Y.strictNullHandling}}function Ef(r,e={}){let t=r;const n=Af(e);let s,o;typeof n.filter=="function"?(o=n.filter,t=o("",t)):ke(n.filter)&&(o=n.filter,s=o);const a=[];if(typeof t!="object"||t===null)return"";const i=ii[n.arrayFormat],d=i==="comma"&&n.commaRoundTrip;s||(s=Object.keys(t)),n.sort&&s.sort(n.sort);const c=new WeakMap;for(let m=0;m<s.length;++m){const b=s[m];n.skipNulls&&t[b]===null||li(a,ci(t[b],b,i,d,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,c))}const u=a.join(n.delimiter);let f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),u.length>0?f+u:""}const it="4.104.0";let Lo=!1,Lt,di,ui,Vn,fi,hi,mi,gi,pi;function Mf(r,e={auto:!1}){if(Lo)throw new Error(`you must \`import 'openai/shims/${r.kind}'\` before importing anything else from openai`);if(Lt)throw new Error(`can't \`import 'openai/shims/${r.kind}'\` after \`import 'openai/shims/${Lt}'\``);Lo=e.auto,Lt=r.kind,di=r.fetch,ui=r.FormData,Vn=r.File,fi=r.ReadableStream,hi=r.getMultipartRequestOptions,mi=r.getDefaultAgent,gi=r.fileFromPath,pi=r.isFsReadStream}class jf{constructor(e){this.body=e}get[Symbol.toStringTag](){return"MultipartBody"}}function Nf({manuallyImported:r}={}){const e=r?"You may need to use polyfills":"Add one of these imports before your first `import … from 'openai'`:\n- `import 'openai/shims/node'` (if you're running on Node)\n- `import 'openai/shims/web'` (otherwise)\n";let t,n,s,o;try{t=fetch,n=Request,s=Response,o=Headers}catch(a){throw new Error(`this environment is missing the following Web Fetch API type: ${a.message}. ${e}`)}return{kind:"web",fetch:t,Request:n,Response:s,Headers:o,FormData:typeof FormData<"u"?FormData:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'FormData' is undefined. ${e}`)}},Blob:typeof Blob<"u"?Blob:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'Blob' is undefined. ${e}`)}},File:typeof File<"u"?File:class{constructor(){throw new Error(`file uploads aren't supported in this environment yet as 'File' is undefined. ${e}`)}},ReadableStream:typeof ReadableStream<"u"?ReadableStream:class{constructor(){throw new Error(`streaming isn't supported in this environment yet as 'ReadableStream' is undefined. ${e}`)}},getMultipartRequestOptions:async(a,i)=>({...i,body:new jf(a)}),getDefaultAgent:a=>{},fileFromPath:()=>{throw new Error("The `fileFromPath` function is only supported in Node. See the README for more details: https://www.github.com/openai/openai-node#file-uploads")},isFsReadStream:a=>!1}}const yi=()=>{Lt||Mf(Nf(),{auto:!0})};yi();class N extends Error{}class oe extends N{constructor(e,t,n,s){super(`${oe.makeMessage(e,t,n)}`),this.status=e,this.headers=s,this.request_id=s==null?void 0:s["x-request-id"],this.error=t;const o=t;this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(e,t,n){const s=t!=null&&t.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,n,s){if(!e||!s)return new zr({message:n,cause:Gn(t)});const o=t==null?void 0:t.error;return e===400?new bi(e,o,n,s):e===401?new wi(e,o,n,s):e===403?new xi(e,o,n,s):e===404?new _i(e,o,n,s):e===409?new vi(e,o,n,s):e===422?new Si(e,o,n,s):e===429?new Ci(e,o,n,s):e>=500?new ki(e,o,n,s):new oe(e,o,n,s)}}class be extends oe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class zr extends oe{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ws extends zr{constructor({message:e}={}){super({message:e??"Request timed out."})}}class bi extends oe{}class wi extends oe{}class xi extends oe{}class _i extends oe{}class vi extends oe{}class Si extends oe{}class Ci extends oe{}class ki extends oe{}class Ai extends N{constructor(){super("Could not parse response content as the length limit was reached")}}class Ei extends N{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}var cr=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},He=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},he;class qr{constructor(){he.set(this,void 0),this.buffer=new Uint8Array,cr(this,he,null,"f")}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e;let n=new Uint8Array(this.buffer.length+t.length);n.set(this.buffer),n.set(t,this.buffer.length),this.buffer=n;const s=[];let o;for(;(o=Of(this.buffer,He(this,he,"f")))!=null;){if(o.carriage&&He(this,he,"f")==null){cr(this,he,o.index,"f");continue}if(He(this,he,"f")!=null&&(o.index!==He(this,he,"f")+1||o.carriage)){s.push(this.decodeText(this.buffer.slice(0,He(this,he,"f")-1))),this.buffer=this.buffer.slice(He(this,he,"f")),cr(this,he,null,"f");continue}const a=He(this,he,"f")!==null?o.preceding-1:o.preceding,i=this.decodeText(this.buffer.slice(0,a));s.push(i),this.buffer=this.buffer.slice(o.index),cr(this,he,null,"f")}return s}decodeText(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof Buffer<"u"){if(e instanceof Buffer)return e.toString();if(e instanceof Uint8Array)return Buffer.from(e).toString();throw new N(`Unexpected: received non-Uint8Array (${e.constructor.name}) stream chunk in an environment with a global "Buffer" defined, which this library assumes to be Node. Please report this error.`)}if(typeof TextDecoder<"u"){if(e instanceof Uint8Array||e instanceof ArrayBuffer)return this.textDecoder??(this.textDecoder=new TextDecoder("utf8")),this.textDecoder.decode(e);throw new N(`Unexpected: received non-Uint8Array/ArrayBuffer (${e.constructor.name}) in a web platform. Please report this error.`)}throw new N("Unexpected: neither Buffer nor TextDecoder are available as globals. Please report this error.")}flush(){return this.buffer.length?this.decode(`
|
|
34
|
-
`):[]}}
|
|
35
|
-
`,"\r"]);
|
|
36
|
-
`);s.enqueue(
|
|
37
|
-
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,n,s]=Lf(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function Lf(r,e){const t=r.indexOf(e);return t!==-1?[r.substring(0,t),e,r.substring(t+e.length)]:[r,"",""]}const ji=r=>r!=null&&typeof r=="object"&&typeof r.url=="string"&&typeof r.blob=="function",Ni=r=>r!=null&&typeof r=="object"&&typeof r.name=="string"&&typeof r.lastModified=="number"&&Vr(r),Vr=r=>r!=null&&typeof r=="object"&&typeof r.size=="number"&&typeof r.type=="string"&&typeof r.text=="function"&&typeof r.slice=="function"&&typeof r.arrayBuffer=="function",Df=r=>Ni(r)||ji(r)||pi(r);async function Oi(r,e,t){var s;if(r=await r,Ni(r))return r;if(ji(r)){const o=await r.blob();e||(e=new URL(r.url).pathname.split(/[\\/]/).pop()??"unknown_file");const a=Vr(o)?[await o.arrayBuffer()]:[o];return new Vn(a,e,t)}const n=await Ff(r);if(e||(e=Bf(r)??"unknown_file"),!(t!=null&&t.type)){const o=(s=n[0])==null?void 0:s.type;typeof o=="string"&&(t={...t,type:o})}return new Vn(n,e,t)}async function Ff(r){var t;let e=[];if(typeof r=="string"||ArrayBuffer.isView(r)||r instanceof ArrayBuffer)e.push(r);else if(Vr(r))e.push(await r.arrayBuffer());else if(Uf(r))for await(const n of r)e.push(n);else throw new Error(`Unexpected data type: ${typeof r}; constructor: ${(t=r==null?void 0:r.constructor)==null?void 0:t.name}; props: ${$f(r)}`);return e}function $f(r){return`[${Object.getOwnPropertyNames(r).map(t=>`"${t}"`).join(", ")}]`}function Bf(r){var e;return _n(r.name)||_n(r.filename)||((e=_n(r.path))==null?void 0:e.split(/[\\/]/).pop())}const _n=r=>{if(typeof r=="string")return r;if(typeof Buffer<"u"&&r instanceof Buffer)return String(r)},Uf=r=>r!=null&&typeof r=="object"&&typeof r[Symbol.asyncIterator]=="function",Do=r=>r&&typeof r=="object"&&r.body&&r[Symbol.toStringTag]==="MultipartBody",Ze=async r=>{const e=await Wf(r.body);return hi(e,r)},Wf=async r=>{const e=new ui;return await Promise.all(Object.entries(r||{}).map(([t,n])=>Jn(e,t,n))),e},Jn=async(r,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")r.append(e,String(t));else if(Df(t)){const n=await Oi(t);r.append(e,n)}else if(Array.isArray(t))await Promise.all(t.map(n=>Jn(r,e+"[]",n)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([n,s])=>Jn(r,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}};var Hf=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},zf=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},dr;yi();async function Pi(r){var a;const{response:e}=r;if(r.options.stream)return Be("response",e.status,e.url,e.headers,e.body),r.options.__streamClass?r.options.__streamClass.fromSSEResponse(e,r.controller):Ee.fromSSEResponse(e,r.controller);if(e.status===204)return null;if(r.options.__binaryResponse)return e;const t=e.headers.get("content-type"),n=(a=t==null?void 0:t.split(";")[0])==null?void 0:a.trim();if((n==null?void 0:n.includes("application/json"))||(n==null?void 0:n.endsWith("+json"))){const i=await e.json();return Be("response",e.status,e.url,e.headers,i),Ri(i,e)}const o=await e.text();return Be("response",e.status,e.url,e.headers,o),o}function Ri(r,e){return!r||typeof r!="object"||Array.isArray(r)?r:Object.defineProperty(r,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}class Jr extends Promise{constructor(e,t=Pi){super(n=>{n(null)}),this.responsePromise=e,this.parseResponse=t}_thenUnwrap(e){return new Jr(this.responsePromise,async t=>Ri(e(await this.parseResponse(t),t),t.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}class qf{constructor({baseURL:e,maxRetries:t=2,timeout:n=6e5,httpAgent:s,fetch:o}){this.baseURL=e,this.maxRetries=vn("maxRetries",t),this.timeout=vn("timeout",n),this.httpAgent=s,this.fetch=o??di}authHeaders(e){return{}}defaultHeaders(e){return{Accept:"application/json","Content-Type":"application/json","User-Agent":this.getUserAgent(),...Yf(),...this.authHeaders(e)}}validateHeaders(e,t){}defaultIdempotencyKey(){return`stainless-node-retry-${eh()}`}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(async s=>{const o=s&&Vr(s==null?void 0:s.body)?new DataView(await s.body.arrayBuffer()):(s==null?void 0:s.body)instanceof DataView?s.body:(s==null?void 0:s.body)instanceof ArrayBuffer?new DataView(s.body):s&&ArrayBuffer.isView(s==null?void 0:s.body)?new DataView(s.body.buffer):s==null?void 0:s.body;return{method:e,path:t,...s,body:o}}))}getAPIList(e,t,n){return this.requestAPIList(t,{method:"get",path:e,...n})}calculateContentLength(e){if(typeof e=="string"){if(typeof Buffer<"u")return Buffer.byteLength(e,"utf8").toString();if(typeof TextEncoder<"u")return new TextEncoder().encode(e).length.toString()}else if(ArrayBuffer.isView(e))return e.byteLength.toString();return null}buildRequest(e,{retryCount:t=0}={}){var h;const n={...e},{method:s,path:o,query:a,headers:i={}}=n,d=ArrayBuffer.isView(n.body)||n.__binaryRequest&&typeof n.body=="string"?n.body:Do(n.body)?n.body.body:n.body?JSON.stringify(n.body,null,2):null,c=this.calculateContentLength(d),u=this.buildURL(o,a);"timeout"in n&&vn("timeout",n.timeout),n.timeout=n.timeout??this.timeout;const f=n.httpAgent??this.httpAgent??mi(u),m=n.timeout+1e3;typeof((h=f==null?void 0:f.options)==null?void 0:h.timeout)=="number"&&m>(f.options.timeout??0)&&(f.options.timeout=m),this.idempotencyHeader&&s!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const b=this.buildHeaders({options:n,headers:i,contentLength:c,retryCount:t});return{req:{method:s,...d&&{body:d},headers:b,...f&&{agent:f},signal:n.signal??null},url:u,timeout:n.timeout}}buildHeaders({options:e,headers:t,contentLength:n,retryCount:s}){const o={};n&&(o["content-length"]=n);const a=this.defaultHeaders(e);return Uo(o,a),Uo(o,t),Do(e.body)&&Lt!=="node"&&delete o["content-type"],fr(a,"x-stainless-retry-count")===void 0&&fr(t,"x-stainless-retry-count")===void 0&&(o["x-stainless-retry-count"]=String(s)),fr(a,"x-stainless-timeout")===void 0&&fr(t,"x-stainless-timeout")===void 0&&e.timeout&&(o["x-stainless-timeout"]=String(Math.trunc(e.timeout/1e3))),this.validateHeaders(o,t),o}async prepareOptions(e){}async prepareRequest(e,{url:t,options:n}){}parseHeaders(e){return e?Symbol.iterator in e?Object.fromEntries(Array.from(e).map(t=>[...t])):{...e}:{}}makeStatusError(e,t,n,s){return oe.generate(e,t,n,s)}request(e,t=null){return new Jr(this.makeRequest(e,t))}async makeRequest(e,t){var f,m;const n=await e,s=n.maxRetries??this.maxRetries;t==null&&(t=s),await this.prepareOptions(n);const{req:o,url:a,timeout:i}=this.buildRequest(n,{retryCount:s-t});if(await this.prepareRequest(o,{url:a,options:n}),Be("request",a,n,o.headers),(f=n.signal)!=null&&f.aborted)throw new be;const d=new AbortController,c=await this.fetchWithTimeout(a,o,i,d).catch(Gn);if(c instanceof Error){if((m=n.signal)!=null&&m.aborted)throw new be;if(t)return this.retryRequest(n,t);throw c.name==="AbortError"?new ws:new zr({cause:c})}const u=Ii(c.headers);if(!c.ok){if(t&&this.shouldRetry(c)){const w=`retrying, ${t} attempts remaining`;return Be(`response (error; ${w})`,c.status,a,u),this.retryRequest(n,t,u)}const b=await c.text().catch(w=>Gn(w).message),g=Kf(b),h=g?void 0:b;throw Be(`response (error; ${t?"(error; no more retries left)":"(error; not retryable)"})`,c.status,a,u,h),this.makeStatusError(c.status,g,h,u)}return{response:c,options:n,controller:d}}requestAPIList(e,t){const n=this.makeRequest(t,null);return new Vf(this,n,e)}buildURL(e,t){const n=Zf(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return Li(s)||(t={...s,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(n.search=this.stringifyQuery(t)),n.toString()}stringifyQuery(e){return Object.entries(e).filter(([t,n])=>typeof n<"u").map(([t,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(t)}=`;throw new N(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}async fetchWithTimeout(e,t,n,s){const{signal:o,...a}=t||{};o&&o.addEventListener("abort",()=>s.abort());const i=setTimeout(()=>s.abort(),n),d={signal:s.signal,...a};return d.method&&(d.method=d.method.toUpperCase()),this.fetch.call(void 0,e,d).finally(()=>{clearTimeout(i)})}shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n){let s;const o=n==null?void 0:n["retry-after-ms"];if(o){const i=parseFloat(o);Number.isNaN(i)||(s=i)}const a=n==null?void 0:n["retry-after"];if(a&&!s){const i=parseFloat(a);Number.isNaN(i)?s=Date.parse(a)-Date.now():s=i*1e3}if(!(s&&0<=s&&s<60*1e3)){const i=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(t,i)}return await Vt(s),this.makeRequest(e,t-1)}calculateDefaultRetryTimeoutMillis(e,t){const o=t-e,a=Math.min(.5*Math.pow(2,o),8),i=1-Math.random()*.25;return a*i*1e3}getUserAgent(){return`${this.constructor.name}/JS ${it}`}}class Ti{constructor(e,t,n,s){dr.set(this,void 0),Hf(this,dr,e,"f"),this.options=s,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageInfo()!=null:!1}async getNextPage(){const e=this.nextPageInfo();if(!e)throw new N("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");const t={...this.options};if("params"in e&&typeof t.query=="object")t.query={...t.query,...e.params};else if("url"in e){const n=[...Object.entries(t.query||{}),...e.url.searchParams.entries()];for(const[s,o]of n)e.url.searchParams.set(s,o);t.query=void 0,t.path=e.url.toString()}return await zf(this,dr,"f").requestAPIList(this.constructor,t)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(dr=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class Vf extends Jr{constructor(e,t,n){super(t,async s=>new n(e,s.response,await Pi(s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}const Ii=r=>new Proxy(Object.fromEntries(r.entries()),{get(e,t){const n=t.toString();return e[n.toLowerCase()]||e[n]}}),Jf={method:!0,path:!0,query:!0,body:!0,headers:!0,maxRetries:!0,stream:!0,timeout:!0,httpAgent:!0,signal:!0,idempotencyKey:!0,__metadata:!0,__binaryRequest:!0,__binaryResponse:!0,__streamClass:!0},V=r=>typeof r=="object"&&r!==null&&!Li(r)&&Object.keys(r).every(e=>Di(Jf,e)),Gf=()=>{var e;if(typeof Deno<"u"&&Deno.build!=null)return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":$o(Deno.build.os),"X-Stainless-Arch":Fo(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((e=Deno.version)==null?void 0:e.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":process.version};if(Object.prototype.toString.call(typeof process<"u"?process:0)==="[object process]")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":$o(process.platform),"X-Stainless-Arch":Fo(process.arch),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":process.version};const r=Xf();return r?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${r.browser}`,"X-Stainless-Runtime-Version":r.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":it,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Xf(){if(typeof navigator>"u"||!navigator)return null;const r=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of r){const n=t.exec(navigator.userAgent);if(n){const s=n[1]||0,o=n[2]||0,a=n[3]||0;return{browser:e,version:`${s}.${o}.${a}`}}}return null}const Fo=r=>r==="x32"?"x32":r==="x86_64"||r==="x64"?"x64":r==="arm"?"arm":r==="aarch64"||r==="arm64"?"arm64":r?`other:${r}`:"unknown",$o=r=>(r=r.toLowerCase(),r.includes("ios")?"iOS":r==="android"?"Android":r==="darwin"?"MacOS":r==="win32"?"Windows":r==="freebsd"?"FreeBSD":r==="openbsd"?"OpenBSD":r==="linux"?"Linux":r?`Other:${r}`:"Unknown");let Bo;const Yf=()=>Bo??(Bo=Gf()),Kf=r=>{try{return JSON.parse(r)}catch{return}},Qf=/^[a-z][a-z0-9+.-]*:/i,Zf=r=>Qf.test(r),Vt=r=>new Promise(e=>setTimeout(e,r)),vn=(r,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new N(`${r} must be an integer`);if(e<0)throw new N(`${r} must be a positive integer`);return e},Gn=r=>{if(r instanceof Error)return r;if(typeof r=="object"&&r!==null)try{return new Error(JSON.stringify(r))}catch{}return new Error(r)},ur=r=>{var e,t,n,s,o;if(typeof process<"u")return((t=(e=process.env)==null?void 0:e[r])==null?void 0:t.trim())??void 0;if(typeof Deno<"u")return(o=(s=(n=Deno.env)==null?void 0:n.get)==null?void 0:s.call(n,r))==null?void 0:o.trim()};function Li(r){if(!r)return!0;for(const e in r)return!1;return!0}function Di(r,e){return Object.prototype.hasOwnProperty.call(r,e)}function Uo(r,e){for(const t in e){if(!Di(e,t))continue;const n=t.toLowerCase();if(!n)continue;const s=e[t];s===null?delete r[n]:s!==void 0&&(r[n]=s)}}const Wo=new Set(["authorization","api-key"]);function Be(r,...e){var t;if(typeof process<"u"&&((t=process==null?void 0:process.env)==null?void 0:t.DEBUG)==="true"){const n=e.map(s=>{if(!s)return s;if(s.headers){const a={...s,headers:{...s.headers}};for(const i in s.headers)Wo.has(i.toLowerCase())&&(a.headers[i]="REDACTED");return a}let o=null;for(const a in s)Wo.has(a.toLowerCase())&&(o??(o={...s}),o[a]="REDACTED");return o??s});console.log(`OpenAI:DEBUG:${r}`,...n)}}const eh=()=>"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const e=Math.random()*16|0;return(r==="x"?e:e&3|8).toString(16)}),th=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u",rh=r=>typeof(r==null?void 0:r.get)=="function",fr=(r,e)=>{var n;const t=e.toLowerCase();if(rh(r)){const s=((n=e[0])==null?void 0:n.toUpperCase())+e.substring(1).replace(/([^\w])(\w)/g,(o,a,i)=>a+i.toUpperCase());for(const o of[e,t,e.toUpperCase(),s]){const a=r.get(o);if(a)return a}}for(const[s,o]of Object.entries(r))if(s.toLowerCase()===t)return Array.isArray(o)?(o.length<=1||console.warn(`Received ${o.length} entries for the ${e} header, using the first entry.`),o[0]):o},nh=r=>{if(typeof Buffer<"u"){const e=Buffer.from(r,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(r),t=e.length,n=new Uint8Array(t);for(let s=0;s<t;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};function Sn(r){return r!=null&&typeof r=="object"&&!Array.isArray(r)}class Gr extends Ti{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageParams(){return null}nextPageInfo(){return null}}class K extends Ti{constructor(e,t,n,s){super(e,t,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageParams(){const e=this.nextPageInfo();if(!e)return null;if("params"in e)return e.params;const t=Object.fromEntries(e.url.searchParams);return Object.keys(t).length?t:null}nextPageInfo(){var n;const e=this.getPaginatedItems();if(!e.length)return null;const t=(n=e[e.length-1])==null?void 0:n.id;return t?{params:{after:t}}:null}}class O{constructor(e){this._client=e}}let Fi=class extends O{list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/chat/completions/${e}/messages`,sh,{query:t,...n})}},Xr=class extends O{constructor(){super(...arguments),this.messages=new Fi(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(`/chat/completions/${e}`,t)}update(e,t,n){return this._client.post(`/chat/completions/${e}`,{body:t,...n})}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/chat/completions",Yr,{query:e,...t})}del(e,t){return this._client.delete(`/chat/completions/${e}`,t)}};class Yr extends K{}class sh extends K{}Xr.ChatCompletionsPage=Yr;Xr.Messages=Fi;let Kr=class extends O{constructor(){super(...arguments),this.completions=new Xr(this._client)}};Kr.Completions=Xr;Kr.ChatCompletionsPage=Yr;class $i extends O{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:{Accept:"application/octet-stream",...t==null?void 0:t.headers},__binaryResponse:!0})}}class Bi extends O{create(e,t){return this._client.post("/audio/transcriptions",Ze({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}}))}}class Ui extends O{create(e,t){return this._client.post("/audio/translations",Ze({body:e,...t,__metadata:{model:e.model}}))}}class Jt extends O{constructor(){super(...arguments),this.transcriptions=new Bi(this._client),this.translations=new Ui(this._client),this.speech=new $i(this._client)}}Jt.Transcriptions=Bi;Jt.Translations=Ui;Jt.Speech=$i;class xs extends O{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(`/batches/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/batches",_s,{query:e,...t})}cancel(e,t){return this._client.post(`/batches/${e}/cancel`,t)}}class _s extends K{}xs.BatchesPage=_s;var we=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},z=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},Xn,xr,_r,Nt,Ot,vr,Pt,Ne,Rt,Ir,Lr,lt,Wi;class vs{constructor(){Xn.add(this),this.controller=new AbortController,xr.set(this,void 0),_r.set(this,()=>{}),Nt.set(this,()=>{}),Ot.set(this,void 0),vr.set(this,()=>{}),Pt.set(this,()=>{}),Ne.set(this,{}),Rt.set(this,!1),Ir.set(this,!1),Lr.set(this,!1),lt.set(this,!1),we(this,xr,new Promise((e,t)=>{we(this,_r,e,"f"),we(this,Nt,t,"f")}),"f"),we(this,Ot,new Promise((e,t)=>{we(this,vr,e,"f"),we(this,Pt,t,"f")}),"f"),z(this,xr,"f").catch(()=>{}),z(this,Ot,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},z(this,Xn,"m",Wi).bind(this))},0)}_connected(){this.ended||(z(this,_r,"f").call(this),this._emit("connect"))}get ended(){return z(this,Rt,"f")}get errored(){return z(this,Ir,"f")}get aborted(){return z(this,Lr,"f")}abort(){this.controller.abort()}on(e,t){return(z(this,Ne,"f")[e]||(z(this,Ne,"f")[e]=[])).push({listener:t}),this}off(e,t){const n=z(this,Ne,"f")[e];if(!n)return this;const s=n.findIndex(o=>o.listener===t);return s>=0&&n.splice(s,1),this}once(e,t){return(z(this,Ne,"f")[e]||(z(this,Ne,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{we(this,lt,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,t)})}async done(){we(this,lt,!0,"f"),await z(this,Ot,"f")}_emit(e,...t){if(z(this,Rt,"f"))return;e==="end"&&(we(this,Rt,!0,"f"),z(this,vr,"f").call(this));const n=z(this,Ne,"f")[e];if(n&&(z(this,Ne,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!z(this,lt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),z(this,Nt,"f").call(this,s),z(this,Pt,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!z(this,lt,"f")&&!(n!=null&&n.length)&&Promise.reject(s),z(this,Nt,"f").call(this,s),z(this,Pt,"f").call(this,s),this._emit("end")}}_emitFinal(){}}xr=new WeakMap,_r=new WeakMap,Nt=new WeakMap,Ot=new WeakMap,vr=new WeakMap,Pt=new WeakMap,Ne=new WeakMap,Rt=new WeakMap,Ir=new WeakMap,Lr=new WeakMap,lt=new WeakMap,Xn=new WeakSet,Wi=function(e){if(we(this,Ir,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new be),e instanceof be)return we(this,Lr,!0,"f"),this._emit("abort",e);if(e instanceof N)return this._emit("error",e);if(e instanceof Error){const t=new N(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new N(String(e)))};var E=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},fe=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},ne,Yn,Ae,Sr,xe,Ge,dt,Ve,Dr,me,Cr,kr,Dt,Tt,It,Ho,zo,qo,Vo,Jo,Go,Xo;class _e extends vs{constructor(){super(...arguments),ne.add(this),Yn.set(this,[]),Ae.set(this,{}),Sr.set(this,{}),xe.set(this,void 0),Ge.set(this,void 0),dt.set(this,void 0),Ve.set(this,void 0),Dr.set(this,void 0),me.set(this,void 0),Cr.set(this,void 0),kr.set(this,void 0),Dt.set(this,void 0)}[(Yn=new WeakMap,Ae=new WeakMap,Sr=new WeakMap,xe=new WeakMap,Ge=new WeakMap,dt=new WeakMap,Ve=new WeakMap,Dr=new WeakMap,me=new WeakMap,Cr=new WeakMap,kr=new WeakMap,Dt=new WeakMap,ne=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new _e;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){var o;const n=t==null?void 0:t.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=Ee.fromReadableStream(e,this.controller);for await(const a of s)E(this,ne,"m",Tt).call(this,a);if((o=s.controller.signal)!=null&&o.aborted)throw new be;return this._addRun(E(this,ne,"m",It).call(this))}toReadableStream(){return new Ee(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,s,o){const a=new _e;return a._run(()=>a._runToolAssistantStream(e,t,n,s,{...o,headers:{...o==null?void 0:o.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,n,s,o){var c;const a=o==null?void 0:o.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...s,stream:!0},d=await e.submitToolOutputs(t,n,i,{...o,signal:this.controller.signal});this._connected();for await(const u of d)E(this,ne,"m",Tt).call(this,u);if((c=d.controller.signal)!=null&&c.aborted)throw new be;return this._addRun(E(this,ne,"m",It).call(this))}static createThreadAssistantStream(e,t,n){const s=new _e;return s._run(()=>s._threadAssistantStream(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,n,s){const o=new _e;return o._run(()=>o._runAssistantStream(e,t,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return E(this,Cr,"f")}currentRun(){return E(this,kr,"f")}currentMessageSnapshot(){return E(this,xe,"f")}currentRunStepSnapshot(){return E(this,Dt,"f")}async finalRunSteps(){return await this.done(),Object.values(E(this,Ae,"f"))}async finalMessages(){return await this.done(),Object.values(E(this,Sr,"f"))}async finalRun(){if(await this.done(),!E(this,Ge,"f"))throw Error("Final run was not received.");return E(this,Ge,"f")}async _createThreadAssistantStream(e,t,n){var i;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const o={...t,stream:!0},a=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(const d of a)E(this,ne,"m",Tt).call(this,d);if((i=a.controller.signal)!=null&&i.aborted)throw new be;return this._addRun(E(this,ne,"m",It).call(this))}async _createAssistantStream(e,t,n,s){var d;const o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));const a={...n,stream:!0},i=await e.create(t,a,{...s,signal:this.controller.signal});this._connected();for await(const c of i)E(this,ne,"m",Tt).call(this,c);if((d=i.controller.signal)!=null&&d.aborted)throw new be;return this._addRun(E(this,ne,"m",It).call(this))}static accumulateDelta(e,t){for(const[n,s]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let o=e[n];if(o==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(Sn(o)&&Sn(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(a=>typeof a=="string"||typeof a=="number")){o.push(...s);continue}for(const a of s){if(!Sn(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const i=a.index;if(i==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof i!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${i}`);const d=o[i];d==null?o.push(a):o[i]=this.accumulateDelta(d,a)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,s){return await this._createAssistantStream(t,e,n,s)}async _runToolAssistantStream(e,t,n,s,o){return await this._createToolAssistantStream(n,e,t,s,o)}}Tt=function(e){if(!this.ended)switch(fe(this,Cr,e,"f"),E(this,ne,"m",qo).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":E(this,ne,"m",Xo).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":E(this,ne,"m",zo).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":E(this,ne,"m",Ho).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},It=function(){if(this.ended)throw new N("stream has ended, this shouldn't happen");if(!E(this,Ge,"f"))throw Error("Final run has not been received");return E(this,Ge,"f")},Ho=function(e){const[t,n]=E(this,ne,"m",Jo).call(this,e,E(this,xe,"f"));fe(this,xe,t,"f"),E(this,Sr,"f")[t.id]=t;for(const s of n){const o=t.content[s.index];(o==null?void 0:o.type)=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,a=t.content[s.index];if(a&&a.type=="text")this._emit("textDelta",o,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=E(this,dt,"f")){if(E(this,Ve,"f"))switch(E(this,Ve,"f").type){case"text":this._emit("textDone",E(this,Ve,"f").text,E(this,xe,"f"));break;case"image_file":this._emit("imageFileDone",E(this,Ve,"f").image_file,E(this,xe,"f"));break}fe(this,dt,s.index,"f")}fe(this,Ve,t.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(E(this,dt,"f")!==void 0){const s=e.data.content[E(this,dt,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,E(this,xe,"f"));break;case"text":this._emit("textDone",s.text,E(this,xe,"f"));break}}E(this,xe,"f")&&this._emit("messageDone",e.data),fe(this,xe,void 0,"f")}},zo=function(e){const t=E(this,ne,"m",Vo).call(this,e);switch(fe(this,Dt,t,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const o of n.step_details.tool_calls)o.index==E(this,Dr,"f")?this._emit("toolCallDelta",o,t.step_details.tool_calls[o.index]):(E(this,me,"f")&&this._emit("toolCallDone",E(this,me,"f")),fe(this,Dr,o.index,"f"),fe(this,me,t.step_details.tool_calls[o.index],"f"),E(this,me,"f")&&this._emit("toolCallCreated",E(this,me,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":fe(this,Dt,void 0,"f"),e.data.step_details.type=="tool_calls"&&E(this,me,"f")&&(this._emit("toolCallDone",E(this,me,"f")),fe(this,me,void 0,"f")),this._emit("runStepDone",e.data,t);break}},qo=function(e){E(this,Yn,"f").push(e),this._emit("event",e)},Vo=function(e){switch(e.event){case"thread.run.step.created":return E(this,Ae,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=E(this,Ae,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){const s=_e.accumulateDelta(t,n.delta);E(this,Ae,"f")[e.data.id]=s}return E(this,Ae,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":E(this,Ae,"f")[e.data.id]=e.data;break}if(E(this,Ae,"f")[e.data.id])return E(this,Ae,"f")[e.data.id];throw new Error("No snapshot available")},Jo=function(e,t){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const o of s.delta.content)if(o.index in t.content){let a=t.content[o.index];t.content[o.index]=E(this,ne,"m",Go).call(this,o,a)}else t.content[o.index]=o,n.push(o);return[t,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Go=function(e,t){return _e.accumulateDelta(t,e)},Xo=function(e){switch(fe(this,kr,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":fe(this,Ge,e.data,"f"),E(this,me,"f")&&(this._emit("toolCallDone",E(this,me,"f")),fe(this,me,void 0,"f"));break}};class Ss extends O{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/assistants/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/assistants",Cs,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/assistants/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Cs extends K{}Ss.AssistantsPage=Cs;function Yo(r){return typeof r.parse=="function"}const ft=r=>(r==null?void 0:r.role)==="assistant",Hi=r=>(r==null?void 0:r.role)==="function",zi=r=>(r==null?void 0:r.role)==="tool";function ks(r){return(r==null?void 0:r.$brand)==="auto-parseable-response-format"}function Gt(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function oh(r,e){return!e||!qi(e)?{...r,choices:r.choices.map(t=>({...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:As(r,e)}function As(r,e){const t=r.choices.map(n=>{var s;if(n.finish_reason==="length")throw new Ai;if(n.finish_reason==="content_filter")throw new Ei;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:((s=n.message.tool_calls)==null?void 0:s.map(o=>ih(e,o)))??void 0}:void 0,parsed:n.message.content&&!n.message.refusal?ah(e,n.message.content):null}}});return{...r,choices:t}}function ah(r,e){var t,n;return((t=r.response_format)==null?void 0:t.type)!=="json_schema"?null:((n=r.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in r.response_format?r.response_format.$parseRaw(e):JSON.parse(e):null}function ih(r,e){var n;const t=(n=r.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:Gt(t)?t.$parseRaw(e.function.arguments):t!=null&&t.function.strict?JSON.parse(e.function.arguments):null}}}function lh(r,e){var n;if(!r)return!1;const t=(n=r.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return Gt(t)||(t==null?void 0:t.function.strict)||!1}function qi(r){var e;return ks(r.response_format)?!0:((e=r.tools)==null?void 0:e.some(t=>Gt(t)||t.type==="function"&&t.function.strict===!0))??!1}function ch(r){for(const e of r??[]){if(e.type!=="function")throw new N(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new N(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var le=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},ae,Kn,Fr,Qn,Zn,es,Vi,ts;const Ko=10;class Ji extends vs{constructor(){super(...arguments),ae.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=(n=e.choices[0])==null?void 0:n.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),(Hi(e)||zi(e))&&e.content)this._emit("functionCallResult",e.content);else if(ft(e)&&e.function_call)this._emit("functionCall",e.function_call);else if(ft(e)&&e.tool_calls)for(const n of e.tool_calls)n.type==="function"&&this._emit("functionCall",n.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new N("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),le(this,ae,"m",Kn).call(this)}async finalMessage(){return await this.done(),le(this,ae,"m",Fr).call(this)}async finalFunctionCall(){return await this.done(),le(this,ae,"m",Qn).call(this)}async finalFunctionCallResult(){return await this.done(),le(this,ae,"m",Zn).call(this)}async totalUsage(){return await this.done(),le(this,ae,"m",es).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=le(this,ae,"m",Fr).call(this);t&&this._emit("finalMessage",t);const n=le(this,ae,"m",Kn).call(this);n&&this._emit("finalContent",n);const s=le(this,ae,"m",Qn).call(this);s&&this._emit("finalFunctionCall",s);const o=le(this,ae,"m",Zn).call(this);o!=null&&this._emit("finalFunctionCallResult",o),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",le(this,ae,"m",es).call(this))}async _createChatCompletion(e,t,n){const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),le(this,ae,"m",Vi).call(this,t);const o=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(As(o,t))}async _runChatCompletion(e,t,n){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,n)}async _runFunctions(e,t,n){var m;const s="function",{function_call:o="auto",stream:a,...i}=t,d=typeof o!="string"&&(o==null?void 0:o.name),{maxChatCompletions:c=Ko}=n||{},u={};for(const b of t.functions)u[b.name||b.function.name]=b;const f=t.functions.map(b=>({name:b.name||b.function.name,parameters:b.parameters,description:b.description}));for(const b of t.messages)this._addMessage(b,!1);for(let b=0;b<c;++b){const h=(m=(await this._createChatCompletion(e,{...i,function_call:o,functions:f,messages:[...this.messages]},n)).choices[0])==null?void 0:m.message;if(!h)throw new N("missing message in ChatCompletion response");if(!h.function_call)return;const{name:p,arguments:y}=h.function_call,w=u[p];if(w){if(d&&d!==p){const A=`Invalid function_call: ${JSON.stringify(p)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,name:p,content:A});continue}}else{const A=`Invalid function_call: ${JSON.stringify(p)}. Available options are: ${f.map(k=>JSON.stringify(k.name)).join(", ")}. Please try again`;this._addMessage({role:s,name:p,content:A});continue}let x;try{x=Yo(w)?await w.parse(y):y}catch(A){this._addMessage({role:s,name:p,content:A instanceof Error?A.message:String(A)});continue}const v=await w.function(x,this),S=le(this,ae,"m",ts).call(this,v);if(this._addMessage({role:s,name:p,content:S}),d)return}}async _runTools(e,t,n){var b,g,h;const s="tool",{tool_choice:o="auto",stream:a,...i}=t,d=typeof o!="string"&&((b=o==null?void 0:o.function)==null?void 0:b.name),{maxChatCompletions:c=Ko}=n||{},u=t.tools.map(p=>{if(Gt(p)){if(!p.$callback)throw new N("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:p.$callback,name:p.function.name,description:p.function.description||"",parameters:p.function.parameters,parse:p.$parseRaw,strict:!0}}}return p}),f={};for(const p of u)p.type==="function"&&(f[p.function.name||p.function.function.name]=p.function);const m="tools"in t?u.map(p=>p.type==="function"?{type:"function",function:{name:p.function.name||p.function.function.name,parameters:p.function.parameters,description:p.function.description,strict:p.function.strict}}:p):void 0;for(const p of t.messages)this._addMessage(p,!1);for(let p=0;p<c;++p){const w=(g=(await this._createChatCompletion(e,{...i,tool_choice:o,tools:m,messages:[...this.messages]},n)).choices[0])==null?void 0:g.message;if(!w)throw new N("missing message in ChatCompletion response");if(!((h=w.tool_calls)!=null&&h.length))return;for(const x of w.tool_calls){if(x.type!=="function")continue;const v=x.id,{name:S,arguments:A}=x.function,k=f[S];if(k){if(d&&d!==S){const P=`Invalid tool_call: ${JSON.stringify(S)}. ${JSON.stringify(d)} requested. Please try again`;this._addMessage({role:s,tool_call_id:v,content:P});continue}}else{const P=`Invalid tool_call: ${JSON.stringify(S)}. Available options are: ${Object.keys(f).map(C=>JSON.stringify(C)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:v,content:P});continue}let $;try{$=Yo(k)?await k.parse(A):A}catch(P){const C=P instanceof Error?P.message:String(P);this._addMessage({role:s,tool_call_id:v,content:C});continue}const j=await k.function($,this),T=le(this,ae,"m",ts).call(this,j);if(this._addMessage({role:s,tool_call_id:v,content:T}),d)return}}}}ae=new WeakSet,Kn=function(){return le(this,ae,"m",Fr).call(this).content??null},Fr=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(ft(t)){const{function_call:n,...s}=t,o={...s,content:t.content??null,refusal:t.refusal??null};return n&&(o.function_call=n),o}}throw new N("stream ended without producing a ChatCompletionMessage with role=assistant")},Qn=function(){var e,t;for(let n=this.messages.length-1;n>=0;n--){const s=this.messages[n];if(ft(s)&&(s!=null&&s.function_call))return s.function_call;if(ft(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(t=s.tool_calls.at(-1))==null?void 0:t.function}},Zn=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Hi(t)&&t.content!=null||zi(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(n=>{var s;return n.role==="assistant"&&((s=n.tool_calls)==null?void 0:s.some(o=>o.type==="function"&&o.id===t.tool_call_id))}))return t.content}},es=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},Vi=function(e){if(e.n!=null&&e.n>1)throw new N("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},ts=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Wt extends Ji{static runFunctions(e,t,n){const s=new Wt,o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,o)),s}static runTools(e,t,n){const s=new Wt,o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}_addMessage(e,t=!0){super._addMessage(e,t),ft(e)&&e.content&&this._emit("content",e.content)}}const Gi=1,Xi=2,Yi=4,Ki=8,Qi=16,Zi=32,el=64,tl=128,rl=256,nl=tl|rl,sl=Qi|Zi|nl|el,ol=Gi|Xi|sl,al=Yi|Ki,dh=ol|al,Z={STR:Gi,NUM:Xi,ARR:Yi,OBJ:Ki,NULL:Qi,BOOL:Zi,NAN:el,INFINITY:tl,MINUS_INFINITY:rl,INF:nl,SPECIAL:sl,ATOM:ol,COLLECTION:al,ALL:dh};class uh extends Error{}class fh extends Error{}function hh(r,e=Z.ALL){if(typeof r!="string")throw new TypeError(`expecting str, got ${typeof r}`);if(!r.trim())throw new Error(`${r} is empty`);return mh(r.trim(),e)}const mh=(r,e)=>{const t=r.length;let n=0;const s=m=>{throw new uh(`${m} at position ${n}`)},o=m=>{throw new fh(`${m} at position ${n}`)},a=()=>(f(),n>=t&&s("Unexpected end of input"),r[n]==='"'?i():r[n]==="{"?d():r[n]==="["?c():r.substring(n,n+4)==="null"||Z.NULL&e&&t-n<4&&"null".startsWith(r.substring(n))?(n+=4,null):r.substring(n,n+4)==="true"||Z.BOOL&e&&t-n<4&&"true".startsWith(r.substring(n))?(n+=4,!0):r.substring(n,n+5)==="false"||Z.BOOL&e&&t-n<5&&"false".startsWith(r.substring(n))?(n+=5,!1):r.substring(n,n+8)==="Infinity"||Z.INFINITY&e&&t-n<8&&"Infinity".startsWith(r.substring(n))?(n+=8,1/0):r.substring(n,n+9)==="-Infinity"||Z.MINUS_INFINITY&e&&1<t-n&&t-n<9&&"-Infinity".startsWith(r.substring(n))?(n+=9,-1/0):r.substring(n,n+3)==="NaN"||Z.NAN&e&&t-n<3&&"NaN".startsWith(r.substring(n))?(n+=3,NaN):u()),i=()=>{const m=n;let b=!1;for(n++;n<t&&(r[n]!=='"'||b&&r[n-1]==="\\");)b=r[n]==="\\"?!b:!1,n++;if(r.charAt(n)=='"')try{return JSON.parse(r.substring(m,++n-Number(b)))}catch(g){o(String(g))}else if(Z.STR&e)try{return JSON.parse(r.substring(m,n-Number(b))+'"')}catch{return JSON.parse(r.substring(m,r.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},d=()=>{n++,f();const m={};try{for(;r[n]!=="}";){if(f(),n>=t&&Z.OBJ&e)return m;const b=i();f(),n++;try{const g=a();Object.defineProperty(m,b,{value:g,writable:!0,enumerable:!0,configurable:!0})}catch(g){if(Z.OBJ&e)return m;throw g}f(),r[n]===","&&n++}}catch{if(Z.OBJ&e)return m;s("Expected '}' at end of object")}return n++,m},c=()=>{n++;const m=[];try{for(;r[n]!=="]";)m.push(a()),f(),r[n]===","&&n++}catch{if(Z.ARR&e)return m;s("Expected ']' at end of array")}return n++,m},u=()=>{if(n===0){r==="-"&&Z.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r)}catch(b){if(Z.NUM&e)try{return r[r.length-1]==="."?JSON.parse(r.substring(0,r.lastIndexOf("."))):JSON.parse(r.substring(0,r.lastIndexOf("e")))}catch{}o(String(b))}}const m=n;for(r[n]==="-"&&n++;r[n]&&!",]}".includes(r[n]);)n++;n==t&&!(Z.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(r.substring(m,n))}catch{r.substring(m,n)==="-"&&Z.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(r.substring(m,r.lastIndexOf("e")))}catch(g){o(String(g))}}},f=()=>{for(;n<t&&`
|
|
38
|
-
\r `.includes(r[n]);)n++};return
|
|
39
|
-
${
|
|
40
|
-
${
|
|
41
|
-
${
|
|
42
|
-
${gr(r)}`);return{...$,id:k,type:A,function:{...P,name:T,arguments:j}}})}}:{...b,message:{...y,content:g,role:w,refusal:c.refusal??null},finish_reason:u,index:f,logprobs:m}}),created:s,model:o,object:"chat.completion",...a?{system_fingerprint:a}:{}};return oh(d,e)}function gr(r){return JSON.stringify(r)}class ht extends Ht{static fromReadableStream(e){const t=new ht(null);return t._run(()=>t._fromReadableStream(e)),t}static runFunctions(e,t,n){const s=new ht(null),o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runFunctions"}};return s._run(()=>s._runFunctions(e,t,o)),s}static runTools(e,t,n){const s=new ht(t),o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,o)),s}}let il=class extends O{parse(e,t){return ch(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t==null?void 0:t.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(n=>As(n,e))}runFunctions(e,t){return e.stream?ht.runFunctions(this._client,e,t):Wt.runFunctions(this._client,e,t)}runTools(e,t){return e.stream?ht.runTools(this._client,e,t):Wt.runTools(this._client,e,t)}stream(e,t){return Ht.createChatCompletion(this._client,e,t)}};class rs extends O{constructor(){super(...arguments),this.completions=new il(this._client)}}(function(r){r.Completions=il})(rs||(rs={}));class ll extends O{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class cl extends O{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}}class Qr extends O{constructor(){super(...arguments),this.sessions=new ll(this._client),this.transcriptionSessions=new cl(this._client)}}Qr.Sessions=ll;Qr.TranscriptionSessions=cl;class Es extends O{create(e,t,n){return this._client.post(`/threads/${e}/messages`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/messages/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/messages`,Ms,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t,n){return this._client.delete(`/threads/${e}/messages/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class Ms extends K{}Es.MessagesPage=Ms;class js extends O{retrieve(e,t,n,s={},o){return V(s)?this.retrieve(e,t,n,{},s):this._client.get(`/threads/${e}/runs/${t}/steps/${n}`,{query:s,...o,headers:{"OpenAI-Beta":"assistants=v2",...o==null?void 0:o.headers}})}list(e,t,n={},s){return V(n)?this.list(e,t,{},n):this._client.getAPIList(`/threads/${e}/runs/${t}/steps`,Ns,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}}class Ns extends K{}js.RunStepsPage=Ns;let Xt=class extends O{constructor(){super(...arguments),this.steps=new js(this._client)}create(e,t,n){const{include:s,...o}=t;return this._client.post(`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers},stream:t.stream??!1})}retrieve(e,t,n){return this._client.get(`/threads/${e}/runs/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/threads/${e}/runs`,Os,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}cancel(e,t,n){return this._client.post(`/threads/${e}/runs/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}createAndStream(e,t,n){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:o,response:a}=await this.retrieve(e,t,{...n,headers:{...n==null?void 0:n.headers,...s}}).withResponse();switch(o.status){case"queued":case"in_progress":case"cancelling":let i=5e3;if(n!=null&&n.pollIntervalMs)i=n.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const c=parseInt(d);isNaN(c)||(i=c)}}await Vt(i);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return o}}}stream(e,t,n){return _e.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n,s){return this._client.post(`/threads/${e}/runs/${t}/submit_tool_outputs`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers},stream:n.stream??!1})}async submitToolOutputsAndPoll(e,t,n,s){const o=await this.submitToolOutputs(e,t,n,s);return await this.poll(e,o.id,s)}submitToolOutputsStream(e,t,n,s){return _e.createToolAssistantStream(e,t,this._client.beta.threads.runs,n,s)}};class Os extends K{}Xt.RunsPage=Os;Xt.Steps=js;Xt.RunStepsPage=Ns;class bt extends O{constructor(){super(...arguments),this.runs=new Xt(this._client),this.messages=new Es(this._client)}create(e={},t){return V(e)?this.create({},e):this._client.post("/threads",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/threads/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t){return this._client.delete(`/threads/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers},stream:e.stream??!1})}async createAndRunPoll(e,t){const n=await this.createAndRun(e,t);return await this.runs.poll(n.thread_id,n.id,t)}createAndRunStream(e,t){return _e.createThreadAssistantStream(e,this._client.beta.threads,t)}}bt.Runs=Xt;bt.RunsPage=Os;bt.Messages=Es;bt.MessagesPage=Ms;class wt extends O{constructor(){super(...arguments),this.realtime=new Qr(this._client),this.chat=new rs(this._client),this.assistants=new Ss(this._client),this.threads=new bt(this._client)}}wt.Realtime=Qr;wt.Assistants=Ss;wt.AssistantsPage=Cs;wt.Threads=bt;class dl extends O{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class ul extends O{retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}/content`,{...n,headers:{Accept:"application/binary",...n==null?void 0:n.headers},__binaryResponse:!0})}}let Zr=class extends O{constructor(){super(...arguments),this.content=new ul(this._client)}create(e,t,n){return this._client.post(`/containers/${e}/files`,Ze({body:t,...n}))}retrieve(e,t,n){return this._client.get(`/containers/${e}/files/${t}`,n)}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/containers/${e}/files`,Ps,{query:t,...n})}del(e,t,n){return this._client.delete(`/containers/${e}/files/${t}`,{...n,headers:{Accept:"*/*",...n==null?void 0:n.headers}})}};class Ps extends K{}Zr.FileListResponsesPage=Ps;Zr.Content=ul;class Yt extends O{constructor(){super(...arguments),this.files=new Zr(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(`/containers/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/containers",Rs,{query:e,...t})}del(e,t){return this._client.delete(`/containers/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}}class Rs extends K{}Yt.ContainerListResponsesPage=Rs;Yt.Files=Zr;Yt.FileListResponsesPage=Ps;class fl extends O{create(e,t){const n=!!e.encoding_format;let s=n?e.encoding_format:"base64";n&&Be("Request","User defined encoding_format:",e.encoding_format);const o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return n?o:(Be("response","Decoding base64 embeddings to float32 array"),o._thenUnwrap(a=>(a&&a.data&&a.data.forEach(i=>{const d=i.embedding;i.embedding=nh(d)}),a)))}}class Ts extends O{retrieve(e,t,n,s){return this._client.get(`/evals/${e}/runs/${t}/output_items/${n}`,s)}list(e,t,n={},s){return V(n)?this.list(e,t,{},n):this._client.getAPIList(`/evals/${e}/runs/${t}/output_items`,Is,{query:n,...s})}}class Is extends K{}Ts.OutputItemListResponsesPage=Is;class Kt extends O{constructor(){super(...arguments),this.outputItems=new Ts(this._client)}create(e,t,n){return this._client.post(`/evals/${e}/runs`,{body:t,...n})}retrieve(e,t,n){return this._client.get(`/evals/${e}/runs/${t}`,n)}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/evals/${e}/runs`,Ls,{query:t,...n})}del(e,t,n){return this._client.delete(`/evals/${e}/runs/${t}`,n)}cancel(e,t,n){return this._client.post(`/evals/${e}/runs/${t}`,n)}}class Ls extends K{}Kt.RunListResponsesPage=Ls;Kt.OutputItems=Ts;Kt.OutputItemListResponsesPage=Is;class Qt extends O{constructor(){super(...arguments),this.runs=new Kt(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(`/evals/${e}`,t)}update(e,t,n){return this._client.post(`/evals/${e}`,{body:t,...n})}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/evals",Ds,{query:e,...t})}del(e,t){return this._client.delete(`/evals/${e}`,t)}}class Ds extends K{}Qt.EvalListResponsesPage=Ds;Qt.Runs=Kt;Qt.RunListResponsesPage=Ls;let Fs=class extends O{create(e,t){return this._client.post("/files",Ze({body:e,...t}))}retrieve(e,t){return this._client.get(`/files/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/files",$s,{query:e,...t})}del(e,t){return this._client.delete(`/files/${e}`,t)}content(e,t){return this._client.get(`/files/${e}/content`,{...t,headers:{Accept:"application/binary",...t==null?void 0:t.headers},__binaryResponse:!0})}retrieveContent(e,t){return this._client.get(`/files/${e}/content`,t)}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=30*60*1e3}={}){const s=new Set(["processed","error","deleted"]),o=Date.now();let a=await this.retrieve(e);for(;!a.status||!s.has(a.status);)if(await Vt(t),a=await this.retrieve(e),Date.now()-o>n)throw new ws({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}};class $s extends K{}Fs.FileObjectsPage=$s;class hl extends O{}let ml=class extends O{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class Bs extends O{constructor(){super(...arguments),this.graders=new ml(this._client)}}Bs.Graders=ml;class Us extends O{create(e,t,n){return this._client.getAPIList(`/fine_tuning/checkpoints/${e}/permissions`,Ws,{body:t,method:"post",...n})}retrieve(e,t={},n){return V(t)?this.retrieve(e,{},t):this._client.get(`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n})}del(e,t,n){return this._client.delete(`/fine_tuning/checkpoints/${e}/permissions/${t}`,n)}}class Ws extends Gr{}Us.PermissionCreateResponsesPage=Ws;let en=class extends O{constructor(){super(...arguments),this.permissions=new Us(this._client)}};en.Permissions=Us;en.PermissionCreateResponsesPage=Ws;class Hs extends O{list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/checkpoints`,zs,{query:t,...n})}}class zs extends K{}Hs.FineTuningJobCheckpointsPage=zs;class xt extends O{constructor(){super(...arguments),this.checkpoints=new Hs(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(`/fine_tuning/jobs/${e}`,t)}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/fine_tuning/jobs",qs,{query:e,...t})}cancel(e,t){return this._client.post(`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},n){return V(t)?this.listEvents(e,{},t):this._client.getAPIList(`/fine_tuning/jobs/${e}/events`,Vs,{query:t,...n})}pause(e,t){return this._client.post(`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(`/fine_tuning/jobs/${e}/resume`,t)}}class qs extends K{}class Vs extends K{}xt.FineTuningJobsPage=qs;xt.FineTuningJobEventsPage=Vs;xt.Checkpoints=Hs;xt.FineTuningJobCheckpointsPage=zs;class Ue extends O{constructor(){super(...arguments),this.methods=new hl(this._client),this.jobs=new xt(this._client),this.checkpoints=new en(this._client),this.alpha=new Bs(this._client)}}Ue.Methods=hl;Ue.Jobs=xt;Ue.FineTuningJobsPage=qs;Ue.FineTuningJobEventsPage=Vs;Ue.Checkpoints=en;Ue.Alpha=Bs;class gl extends O{}class Js extends O{constructor(){super(...arguments),this.graderModels=new gl(this._client)}}Js.GraderModels=gl;class pl extends O{createVariation(e,t){return this._client.post("/images/variations",Ze({body:e,...t}))}edit(e,t){return this._client.post("/images/edits",Ze({body:e,...t}))}generate(e,t){return this._client.post("/images/generations",{body:e,...t})}}class Gs extends O{retrieve(e,t){return this._client.get(`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Xs,e)}del(e,t){return this._client.delete(`/models/${e}`,t)}}class Xs extends Gr{}Gs.ModelsPage=Xs;class yl extends O{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function ph(r,e){return!e||!bh(e)?{...r,output_parsed:null,output:r.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(n=>({...n,parsed:null}))}:t)}:bl(r,e)}function bl(r,e){const t=r.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:_h(e,s)};if(s.type==="message"){const o=s.content.map(a=>a.type==="output_text"?{...a,parsed:yh(e,a.text)}:a);return{...s,content:o}}return s}),n=Object.assign({},r,{output:t});return Object.getOwnPropertyDescriptor(r,"output_text")||wl(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(const s of n.output)if(s.type==="message"){for(const o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function yh(r,e){var t,n,s,o;return((n=(t=r.text)==null?void 0:t.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((s=r.text)==null?void 0:s.format)?((o=r.text)==null?void 0:o.format).$parseRaw(e):JSON.parse(e)}function bh(r){var e;return!!ks((e=r.text)==null?void 0:e.format)}function wh(r){return(r==null?void 0:r.$brand)==="auto-parseable-tool"}function xh(r,e){return r.find(t=>t.type==="function"&&t.name===e)}function _h(r,e){const t=xh(r.tools??[],e.name);return{...e,...e,parsed_arguments:wh(t)?t.$parseRaw(e.arguments):t!=null&&t.strict?JSON.parse(e.arguments):null}}function wl(r){const e=[];for(const t of r.output)if(t.type==="message")for(const n of t.content)n.type==="output_text"&&e.push(n.text);r.output_text=e.join("")}class xl extends O{list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/responses/${e}/input_items`,Sh,{query:t,...n})}}var ot=function(r,e,t,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!s:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(r,t):s?s.value=t:e.set(r,t),t},Fe=function(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)},at,pr,$e,yr,ea,ta,ra,na;class Ys extends vs{constructor(e){super(),at.add(this),pr.set(this,void 0),$e.set(this,void 0),yr.set(this,void 0),ot(this,pr,e,"f")}static createResponse(e,t,n){const s=new Ys(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,n){var i;const s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),Fe(this,at,"m",ea).call(this);let o,a=null;"response_id"in t?(o=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):o=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(const d of o)Fe(this,at,"m",ta).call(this,d,a);if((i=o.controller.signal)!=null&&i.aborted)throw new be;return Fe(this,at,"m",ra).call(this)}[(pr=new WeakMap,$e=new WeakMap,yr=new WeakMap,at=new WeakSet,ea=function(){this.ended||ot(this,$e,void 0,"f")},ta=function(t,n){if(this.ended)return;const s=(a,i)=>{(n==null||i.sequence_number>n)&&this._emit(a,i)},o=Fe(this,at,"m",na).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const a=o.output[t.output_index];if(!a)throw new N(`missing output at index ${t.output_index}`);if(a.type==="message"){const i=a.content[t.content_index];if(!i)throw new N(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new N(`expected content to be 'output_text', got ${i.type}`);s("response.output_text.delta",{...t,snapshot:i.text})}break}case"response.function_call_arguments.delta":{const a=o.output[t.output_index];if(!a)throw new N(`missing output at index ${t.output_index}`);a.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:s(t.type,t);break}},ra=function(){if(this.ended)throw new N("stream has ended, this shouldn't happen");const t=Fe(this,$e,"f");if(!t)throw new N("request ended without sending any events");ot(this,$e,void 0,"f");const n=vh(t,Fe(this,pr,"f"));return ot(this,yr,n,"f"),n},na=function(t){let n=Fe(this,$e,"f");if(!n){if(t.type!=="response.created")throw new N(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return n=ot(this,$e,t.response,"f"),n}switch(t.type){case"response.output_item.added":{n.output.push(t.item);break}case"response.content_part.added":{const s=n.output[t.output_index];if(!s)throw new N(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{const s=n.output[t.output_index];if(!s)throw new N(`missing output at index ${t.output_index}`);if(s.type==="message"){const o=s.content[t.content_index];if(!o)throw new N(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new N(`expected content to be 'output_text', got ${o.type}`);o.text+=t.delta}break}case"response.function_call_arguments.delta":{const s=n.output[t.output_index];if(!s)throw new N(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{ot(this,$e,t.response,"f");break}}return n},Symbol.asyncIterator)](){const e=[],t=[];let n=!1;return this.on("event",s=>{const o=t.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),this.on("error",s=>{n=!0;for(const o of t)o.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,a)=>t.push({resolve:o,reject:a})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=Fe(this,yr,"f");if(!e)throw new N("stream ended without producing a ChatCompletion");return e}}function vh(r,e){return ph(r,e)}class Ks extends O{constructor(){super(...arguments),this.inputItems=new xl(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(n=>("object"in n&&n.object==="response"&&wl(n),n))}retrieve(e,t={},n){return this._client.get(`/responses/${e}`,{query:t,...n,stream:(t==null?void 0:t.stream)??!1})}del(e,t){return this._client.delete(`/responses/${e}`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(n=>bl(n,e))}stream(e,t){return Ys.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(`/responses/${e}/cancel`,{...t,headers:{Accept:"*/*",...t==null?void 0:t.headers}})}}class Sh extends K{}Ks.InputItems=xl;class _l extends O{create(e,t,n){return this._client.post(`/uploads/${e}/parts`,Ze({body:t,...n}))}}class Qs extends O{constructor(){super(...arguments),this.parts=new _l(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(`/uploads/${e}/cancel`,t)}complete(e,t,n){return this._client.post(`/uploads/${e}/complete`,{body:t,...n})}}Qs.Parts=_l;const Ch=async r=>{const e=await Promise.allSettled(r),t=e.filter(s=>s.status==="rejected");if(t.length){for(const s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const n=[];for(const s of e)s.status==="fulfilled"&&n.push(s.value);return n};class tn extends O{create(e,t,n){return this._client.post(`/vector_stores/${e}/files`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}update(e,t,n,s){return this._client.post(`/vector_stores/${e}/files/${t}`,{body:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}list(e,t={},n){return V(t)?this.list(e,{},t):this._client.getAPIList(`/vector_stores/${e}/files`,rn,{query:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}del(e,t,n){return this._client.delete(`/vector_stores/${e}/files/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t,n);return await this.poll(e,s.id,n)}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const o=await this.retrieve(e,t,{...n,headers:s}).withResponse(),a=o.data;switch(a.status){case"in_progress":let i=5e3;if(n!=null&&n.pollIntervalMs)i=n.pollIntervalMs;else{const d=o.response.headers.get("openai-poll-after-ms");if(d){const c=parseInt(d);isNaN(c)||(i=c)}}await Vt(i);break;case"failed":case"completed":return a}}}async upload(e,t,n){const s=await this._client.files.create({file:t,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,t,n){const s=await this.upload(e,t,n);return await this.poll(e,s.id,n)}content(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/files/${t}/content`,Zs,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class rn extends K{}class Zs extends Gr{}tn.VectorStoreFilesPage=rn;tn.FileContentResponsesPage=Zs;class vl extends O{create(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}retrieve(e,t,n){return this._client.get(`/vector_stores/${e}/file_batches/${t}`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}cancel(e,t,n){return this._client.post(`/vector_stores/${e}/file_batches/${t}/cancel`,{...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}async createAndPoll(e,t,n){const s=await this.create(e,t);return await this.poll(e,s.id,n)}listFiles(e,t,n={},s){return V(n)?this.listFiles(e,t,{},n):this._client.getAPIList(`/vector_stores/${e}/file_batches/${t}/files`,rn,{query:n,...s,headers:{"OpenAI-Beta":"assistants=v2",...s==null?void 0:s.headers}})}async poll(e,t,n){const s={...n==null?void 0:n.headers,"X-Stainless-Poll-Helper":"true"};for(n!=null&&n.pollIntervalMs&&(s["X-Stainless-Custom-Poll-Interval"]=n.pollIntervalMs.toString());;){const{data:o,response:a}=await this.retrieve(e,t,{...n,headers:s}).withResponse();switch(o.status){case"in_progress":let i=5e3;if(n!=null&&n.pollIntervalMs)i=n.pollIntervalMs;else{const d=a.headers.get("openai-poll-after-ms");if(d){const c=parseInt(d);isNaN(c)||(i=c)}}await Vt(i);break;case"failed":case"cancelled":case"completed":return o}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const o=(s==null?void 0:s.maxConcurrency)??5,a=Math.min(o,t.length),i=this._client,d=t.values(),c=[...n];async function u(m){for(let b of m){const g=await i.files.create({file:b,purpose:"assistants"},s);c.push(g.id)}}const f=Array(a).fill(d).map(u);return await Ch(f),await this.createAndPoll(e,{file_ids:c})}}class We extends O{constructor(){super(...arguments),this.files=new tn(this._client),this.fileBatches=new vl(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}retrieve(e,t){return this._client.get(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}update(e,t,n){return this._client.post(`/vector_stores/${e}`,{body:t,...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}list(e={},t){return V(e)?this.list({},e):this._client.getAPIList("/vector_stores",eo,{query:e,...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}del(e,t){return this._client.delete(`/vector_stores/${e}`,{...t,headers:{"OpenAI-Beta":"assistants=v2",...t==null?void 0:t.headers}})}search(e,t,n){return this._client.getAPIList(`/vector_stores/${e}/search`,to,{body:t,method:"post",...n,headers:{"OpenAI-Beta":"assistants=v2",...n==null?void 0:n.headers}})}}class eo extends K{}class to extends Gr{}We.VectorStoresPage=eo;We.VectorStoreSearchResponsesPage=to;We.Files=tn;We.VectorStoreFilesPage=rn;We.FileContentResponsesPage=Zs;We.FileBatches=vl;var Sl;class R extends qf{constructor({baseURL:e=ur("OPENAI_BASE_URL"),apiKey:t=ur("OPENAI_API_KEY"),organization:n=ur("OPENAI_ORG_ID")??null,project:s=ur("OPENAI_PROJECT_ID")??null,...o}={}){if(t===void 0)throw new N("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const a={apiKey:t,organization:n,project:s,...o,baseURL:e||"https://api.openai.com/v1"};if(!a.dangerouslyAllowBrowser&&th())throw new N(`It looks like you're running in a browser-like environment.
|
|
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.
|
|
43
43
|
|
|
44
44
|
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
45
45
|
If you understand the risks and have appropriate mitigations in place,
|
|
@@ -48,23 +48,53 @@ you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
|
48
48
|
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
49
49
|
|
|
50
50
|
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
51
|
-
`);super({baseURL:
|
|
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(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/ /g," "),t=t.replace(/[ \t]+/g," ").replace(/\n[ \t]*/g,`
|
|
52
52
|
`).replace(/\n{3,}/g,`
|
|
53
53
|
|
|
54
|
-
`).trim(),t}convertToOpenAIFormat(e){return e.map(t=>{let n=t.content||t.message||"";t.role==="assistant"&&(n=this.cleanHtmlContent(n));const s={role:t.role,content:n};if(t.role==="assistant"&&(t.tool_calls||t.function_calls)){const o=t.tool_calls||t.function_calls||[];o.length>0&&(console.log("Converting tool calls for assistant message:",o),s.tool_calls=o.map(
|
|
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:`请帮我对以下内容进行总结:
|
|
55
55
|
|
|
56
56
|
${e}`,rawContent:`请帮我对以下内容进行总结:
|
|
57
57
|
|
|
58
|
-
${e}`,status:"completed",createdAt:new Date}];let s="";return await new
|
|
59
|
-
`+s.content:s.content;if(s.data)return typeof s.data=="string"&&s.data.startsWith("data: ")?this.processChunk(s.data,!0):s.data;if(s.ai_stream_chunk)return typeof s.ai_stream_chunk=="string"&&s.ai_stream_chunk.startsWith("data: ")?this.processChunk(s.ai_stream_chunk,!1):s.ai_stream_chunk}}catch{return e}return""}}function kl(r,e){return function(){return r.apply(e,arguments)}}const{toString:Ah}=Object.prototype,{getPrototypeOf:ro}=Object,{iterator:nn,toStringTag:Al}=Symbol,sn=(r=>e=>{const t=Ah.call(e);return r[t]||(r[t]=t.slice(8,-1).toLowerCase())})(Object.create(null)),ve=r=>(r=r.toLowerCase(),e=>sn(e)===r),on=r=>e=>typeof e===r,{isArray:_t}=Array,pt=on("undefined");function Zt(r){return r!==null&&!pt(r)&&r.constructor!==null&&!pt(r.constructor)&&de(r.constructor.isBuffer)&&r.constructor.isBuffer(r)}const El=ve("ArrayBuffer");function Eh(r){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(r):e=r&&r.buffer&&El(r.buffer),e}const Mh=on("string"),de=on("function"),Ml=on("number"),er=r=>r!==null&&typeof r=="object",jh=r=>r===!0||r===!1,Ar=r=>{if(sn(r)!=="object")return!1;const e=ro(r);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Al in r)&&!(nn in r)},Nh=r=>{if(!er(r)||Zt(r))return!1;try{return Object.keys(r).length===0&&Object.getPrototypeOf(r)===Object.prototype}catch{return!1}},Oh=ve("Date"),Ph=ve("File"),Rh=ve("Blob"),Th=ve("FileList"),Ih=r=>er(r)&&de(r.pipe),Lh=r=>{let e;return r&&(typeof FormData=="function"&&r instanceof FormData||de(r.append)&&((e=sn(r))==="formdata"||e==="object"&&de(r.toString)&&r.toString()==="[object FormData]"))},Dh=ve("URLSearchParams"),[Fh,$h,Bh,Uh]=["ReadableStream","Request","Response","Headers"].map(ve),Wh=r=>r.trim?r.trim():r.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function tr(r,e,{allOwnKeys:t=!1}={}){if(r===null||typeof r>"u")return;let n,s;if(typeof r!="object"&&(r=[r]),_t(r))for(n=0,s=r.length;n<s;n++)e.call(null,r[n],n,r);else{if(Zt(r))return;const o=t?Object.getOwnPropertyNames(r):Object.keys(r),a=o.length;let i;for(n=0;n<a;n++)i=o[n],e.call(null,r[i],i,r)}}function jl(r,e){if(Zt(r))return null;e=e.toLowerCase();const t=Object.keys(r);let n=t.length,s;for(;n-- >0;)if(s=t[n],e===s.toLowerCase())return s;return null}const Xe=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Nl=r=>!pt(r)&&r!==Xe;function ns(){const{caseless:r,skipUndefined:e}=Nl(this)&&this||{},t={},n=(s,o)=>{const a=r&&jl(t,o)||o;Ar(t[a])&&Ar(s)?t[a]=ns(t[a],s):Ar(s)?t[a]=ns({},s):_t(s)?t[a]=s.slice():(!e||!pt(s))&&(t[a]=s)};for(let s=0,o=arguments.length;s<o;s++)arguments[s]&&tr(arguments[s],n);return t}const Hh=(r,e,t,{allOwnKeys:n}={})=>(tr(e,(s,o)=>{t&&de(s)?r[o]=kl(s,t):r[o]=s},{allOwnKeys:n}),r),zh=r=>(r.charCodeAt(0)===65279&&(r=r.slice(1)),r),qh=(r,e,t,n)=>{r.prototype=Object.create(e.prototype,n),r.prototype.constructor=r,Object.defineProperty(r,"super",{value:e.prototype}),t&&Object.assign(r.prototype,t)},Vh=(r,e,t,n)=>{let s,o,a;const i={};if(e=e||{},r==null)return e;do{for(s=Object.getOwnPropertyNames(r),o=s.length;o-- >0;)a=s[o],(!n||n(a,r,e))&&!i[a]&&(e[a]=r[a],i[a]=!0);r=t!==!1&&ro(r)}while(r&&(!t||t(r,e))&&r!==Object.prototype);return e},Jh=(r,e,t)=>{r=String(r),(t===void 0||t>r.length)&&(t=r.length),t-=e.length;const n=r.indexOf(e,t);return n!==-1&&n===t},Gh=r=>{if(!r)return null;if(_t(r))return r;let e=r.length;if(!Ml(e))return null;const t=new Array(e);for(;e-- >0;)t[e]=r[e];return t},Xh=(r=>e=>r&&e instanceof r)(typeof Uint8Array<"u"&&ro(Uint8Array)),Yh=(r,e)=>{const n=(r&&r[nn]).call(r);let s;for(;(s=n.next())&&!s.done;){const o=s.value;e.call(r,o[0],o[1])}},Kh=(r,e)=>{let t;const n=[];for(;(t=r.exec(e))!==null;)n.push(t);return n},Qh=ve("HTMLFormElement"),Zh=r=>r.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(t,n,s){return n.toUpperCase()+s}),oa=(({hasOwnProperty:r})=>(e,t)=>r.call(e,t))(Object.prototype),em=ve("RegExp"),Ol=(r,e)=>{const t=Object.getOwnPropertyDescriptors(r),n={};tr(t,(s,o)=>{let a;(a=e(s,o,r))!==!1&&(n[o]=a||s)}),Object.defineProperties(r,n)},tm=r=>{Ol(r,(e,t)=>{if(de(r)&&["arguments","caller","callee"].indexOf(t)!==-1)return!1;const n=r[t];if(de(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+t+"'")})}})},rm=(r,e)=>{const t={},n=s=>{s.forEach(o=>{t[o]=!0})};return _t(r)?n(r):n(String(r).split(e)),t},nm=()=>{},sm=(r,e)=>r!=null&&Number.isFinite(r=+r)?r:e;function om(r){return!!(r&&de(r.append)&&r[Al]==="FormData"&&r[nn])}const am=r=>{const e=new Array(10),t=(n,s)=>{if(er(n)){if(e.indexOf(n)>=0)return;if(Zt(n))return n;if(!("toJSON"in n)){e[s]=n;const o=_t(n)?[]:{};return tr(n,(a,i)=>{const d=t(a,s+1);!pt(d)&&(o[i]=d)}),e[s]=void 0,o}}return n};return t(r,0)},im=ve("AsyncFunction"),lm=r=>r&&(er(r)||de(r))&&de(r.then)&&de(r.catch),Pl=((r,e)=>r?setImmediate:e?((t,n)=>(Xe.addEventListener("message",({source:s,data:o})=>{s===Xe&&o===t&&n.length&&n.shift()()},!1),s=>{n.push(s),Xe.postMessage(t,"*")}))(`axios@${Math.random()}`,[]):t=>setTimeout(t))(typeof setImmediate=="function",de(Xe.postMessage)),cm=typeof queueMicrotask<"u"?queueMicrotask.bind(Xe):typeof process<"u"&&process.nextTick||Pl,dm=r=>r!=null&&de(r[nn]),_={isArray:_t,isArrayBuffer:El,isBuffer:Zt,isFormData:Lh,isArrayBufferView:Eh,isString:Mh,isNumber:Ml,isBoolean:jh,isObject:er,isPlainObject:Ar,isEmptyObject:Nh,isReadableStream:Fh,isRequest:$h,isResponse:Bh,isHeaders:Uh,isUndefined:pt,isDate:Oh,isFile:Ph,isBlob:Rh,isRegExp:em,isFunction:de,isStream:Ih,isURLSearchParams:Dh,isTypedArray:Xh,isFileList:Th,forEach:tr,merge:ns,extend:Hh,trim:Wh,stripBOM:zh,inherits:qh,toFlatObject:Vh,kindOf:sn,kindOfTest:ve,endsWith:Jh,toArray:Gh,forEachEntry:Yh,matchAll:Kh,isHTMLForm:Qh,hasOwnProperty:oa,hasOwnProp:oa,reduceDescriptors:Ol,freezeMethods:tm,toObjectSet:rm,toCamelCase:Zh,noop:nm,toFiniteNumber:sm,findKey:jl,global:Xe,isContextDefined:Nl,isSpecCompliantForm:om,toJSONObject:am,isAsyncFn:im,isThenable:lm,setImmediate:Pl,asap:cm,isIterable:dm};function I(r,e,t,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=r,this.name="AxiosError",e&&(this.code=e),t&&(this.config=t),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}_.inherits(I,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:_.toJSONObject(this.config),code:this.code,status:this.status}}});const Rl=I.prototype,Tl={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(r=>{Tl[r]={value:r}});Object.defineProperties(I,Tl);Object.defineProperty(Rl,"isAxiosError",{value:!0});I.from=(r,e,t,n,s,o)=>{const a=Object.create(Rl);_.toFlatObject(r,a,function(u){return u!==Error.prototype},c=>c!=="isAxiosError");const i=r&&r.message?r.message:"Error",d=e==null&&r?r.code:e;return I.call(a,i,d,t,n,s),r&&a.cause==null&&Object.defineProperty(a,"cause",{value:r,configurable:!0}),a.name=r&&r.name||"Error",o&&Object.assign(a,o),a};const um=null;function ss(r){return _.isPlainObject(r)||_.isArray(r)}function Il(r){return _.endsWith(r,"[]")?r.slice(0,-2):r}function aa(r,e,t){return r?r.concat(e).map(function(s,o){return s=Il(s),!t&&o?"["+s+"]":s}).join(t?".":""):e}function fm(r){return _.isArray(r)&&!r.some(ss)}const hm=_.toFlatObject(_,{},null,function(e){return/^is[A-Z]/.test(e)});function an(r,e,t){if(!_.isObject(r))throw new TypeError("target must be an object");e=e||new FormData,t=_.toFlatObject(t,{metaTokens:!0,dots:!1,indexes:!1},!1,function(h,p){return!_.isUndefined(p[h])});const n=t.metaTokens,s=t.visitor||u,o=t.dots,a=t.indexes,d=(t.Blob||typeof Blob<"u"&&Blob)&&_.isSpecCompliantForm(e);if(!_.isFunction(s))throw new TypeError("visitor must be a function");function c(g){if(g===null)return"";if(_.isDate(g))return g.toISOString();if(_.isBoolean(g))return g.toString();if(!d&&_.isBlob(g))throw new I("Blob is not supported. Use a Buffer instead.");return _.isArrayBuffer(g)||_.isTypedArray(g)?d&&typeof Blob=="function"?new Blob([g]):Buffer.from(g):g}function u(g,h,p){let y=g;if(g&&!p&&typeof g=="object"){if(_.endsWith(h,"{}"))h=n?h:h.slice(0,-2),g=JSON.stringify(g);else if(_.isArray(g)&&fm(g)||(_.isFileList(g)||_.endsWith(h,"[]"))&&(y=_.toArray(g)))return h=Il(h),y.forEach(function(x,v){!(_.isUndefined(x)||x===null)&&e.append(a===!0?aa([h],v,o):a===null?h:h+"[]",c(x))}),!1}return ss(g)?!0:(e.append(aa(p,h,o),c(g)),!1)}const f=[],m=Object.assign(hm,{defaultVisitor:u,convertValue:c,isVisitable:ss});function b(g,h){if(!_.isUndefined(g)){if(f.indexOf(g)!==-1)throw Error("Circular reference detected in "+h.join("."));f.push(g),_.forEach(g,function(y,w){(!(_.isUndefined(y)||y===null)&&s.call(e,y,_.isString(w)?w.trim():w,h,m))===!0&&b(y,h?h.concat(w):[w])}),f.pop()}}if(!_.isObject(r))throw new TypeError("data must be an object");return b(r),e}function ia(r){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(r).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function no(r,e){this._pairs=[],r&&an(r,this,e)}const Ll=no.prototype;Ll.append=function(e,t){this._pairs.push([e,t])};Ll.toString=function(e){const t=e?function(n){return e.call(this,n,ia)}:ia;return this._pairs.map(function(s){return t(s[0])+"="+t(s[1])},"").join("&")};function mm(r){return encodeURIComponent(r).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Dl(r,e,t){if(!e)return r;const n=t&&t.encode||mm;_.isFunction(t)&&(t={serialize:t});const s=t&&t.serialize;let o;if(s?o=s(e,t):o=_.isURLSearchParams(e)?e.toString():new no(e,t).toString(n),o){const a=r.indexOf("#");a!==-1&&(r=r.slice(0,a)),r+=(r.indexOf("?")===-1?"?":"&")+o}return r}class la{constructor(){this.handlers=[]}use(e,t,n){return this.handlers.push({fulfilled:e,rejected:t,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){_.forEach(this.handlers,function(n){n!==null&&e(n)})}}const Fl={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},gm=typeof URLSearchParams<"u"?URLSearchParams:no,pm=typeof FormData<"u"?FormData:null,ym=typeof Blob<"u"?Blob:null,bm={isBrowser:!0,classes:{URLSearchParams:gm,FormData:pm,Blob:ym},protocols:["http","https","file","blob","url","data"]},so=typeof window<"u"&&typeof document<"u",os=typeof navigator=="object"&&navigator||void 0,wm=so&&(!os||["ReactNative","NativeScript","NS"].indexOf(os.product)<0),xm=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",_m=so&&window.location.href||"http://localhost",vm=Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:so,hasStandardBrowserEnv:wm,hasStandardBrowserWebWorkerEnv:xm,navigator:os,origin:_m},Symbol.toStringTag,{value:"Module"})),ie={...vm,...bm};function Sm(r,e){return an(r,new ie.classes.URLSearchParams,{visitor:function(t,n,s,o){return ie.isNode&&_.isBuffer(t)?(this.append(n,t.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)},...e})}function Cm(r){return _.matchAll(/\w+|\[(\w*)]/g,r).map(e=>e[0]==="[]"?"":e[1]||e[0])}function km(r){const e={},t=Object.keys(r);let n;const s=t.length;let o;for(n=0;n<s;n++)o=t[n],e[o]=r[o];return e}function $l(r){function e(t,n,s,o){let a=t[o++];if(a==="__proto__")return!0;const i=Number.isFinite(+a),d=o>=t.length;return a=!a&&_.isArray(s)?s.length:a,d?(_.hasOwnProp(s,a)?s[a]=[s[a],n]:s[a]=n,!i):((!s[a]||!_.isObject(s[a]))&&(s[a]=[]),e(t,n,s[a],o)&&_.isArray(s[a])&&(s[a]=km(s[a])),!i)}if(_.isFormData(r)&&_.isFunction(r.entries)){const t={};return _.forEachEntry(r,(n,s)=>{e(Cm(n),s,t,0)}),t}return null}function Am(r,e,t){if(_.isString(r))try{return(e||JSON.parse)(r),_.trim(r)}catch(n){if(n.name!=="SyntaxError")throw n}return(t||JSON.stringify)(r)}const rr={transitional:Fl,adapter:["xhr","http","fetch"],transformRequest:[function(e,t){const n=t.getContentType()||"",s=n.indexOf("application/json")>-1,o=_.isObject(e);if(o&&_.isHTMLForm(e)&&(e=new FormData(e)),_.isFormData(e))return s?JSON.stringify($l(e)):e;if(_.isArrayBuffer(e)||_.isBuffer(e)||_.isStream(e)||_.isFile(e)||_.isBlob(e)||_.isReadableStream(e))return e;if(_.isArrayBufferView(e))return e.buffer;if(_.isURLSearchParams(e))return t.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let i;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return Sm(e,this.formSerializer).toString();if((i=_.isFileList(e))||n.indexOf("multipart/form-data")>-1){const d=this.env&&this.env.FormData;return an(i?{"files[]":e}:e,d&&new d,this.formSerializer)}}return o||s?(t.setContentType("application/json",!1),Am(e)):e}],transformResponse:[function(e){const t=this.transitional||rr.transitional,n=t&&t.forcedJSONParsing,s=this.responseType==="json";if(_.isResponse(e)||_.isReadableStream(e))return e;if(e&&_.isString(e)&&(n&&!this.responseType||s)){const a=!(t&&t.silentJSONParsing)&&s;try{return JSON.parse(e,this.parseReviver)}catch(i){if(a)throw i.name==="SyntaxError"?I.from(i,I.ERR_BAD_RESPONSE,this,null,this.response):i}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:ie.classes.FormData,Blob:ie.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};_.forEach(["delete","get","head","post","put","patch"],r=>{rr.headers[r]={}});const Em=_.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Mm=r=>{const e={};let t,n,s;return r&&r.split(`
|
|
60
|
-
`).forEach(function(
|
|
61
|
-
`)}getSetCookie(){return this.get("set-cookie")||[]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...t){const n=new this(e);return t.forEach(s=>n.set(s)),n}static accessor(e){const n=(this[ca]=this[ca]={accessors:{}}).accessors,s=this.prototype;function o(a){const i=jt(a);n[i]||(Pm(s,a),n[i]=!0)}return _.isArray(e)?e.forEach(o):o(e),this}};ue.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);_.reduceDescriptors(ue.prototype,({value:r},e)=>{let t=e[0].toUpperCase()+e.slice(1);return{get:()=>r,set(n){this[t]=n}}});_.freezeMethods(ue);function Nn(r,e){const t=this||rr,n=e||t,s=ue.from(n.headers);let o=n.data;return _.forEach(r,function(i){o=i.call(t,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function Bl(r){return!!(r&&r.__CANCEL__)}function vt(r,e,t){I.call(this,r??"canceled",I.ERR_CANCELED,e,t),this.name="CanceledError"}_.inherits(vt,I,{__CANCEL__:!0});function Ul(r,e,t){const n=t.config.validateStatus;!t.status||!n||n(t.status)?r(t):e(new I("Request failed with status code "+t.status,[I.ERR_BAD_REQUEST,I.ERR_BAD_RESPONSE][Math.floor(t.status/100)-4],t.config,t.request,t))}function Rm(r){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(r);return e&&e[1]||""}function Tm(r,e){r=r||10;const t=new Array(r),n=new Array(r);let s=0,o=0,a;return e=e!==void 0?e:1e3,function(d){const c=Date.now(),u=n[o];a||(a=c),t[s]=d,n[s]=c;let f=o,m=0;for(;f!==s;)m+=t[f++],f=f%r;if(s=(s+1)%r,s===o&&(o=(o+1)%r),c-a<e)return;const b=u&&c-u;return b?Math.round(m*1e3/b):void 0}}function Im(r,e){let t=0,n=1e3/e,s,o;const a=(c,u=Date.now())=>{t=u,s=null,o&&(clearTimeout(o),o=null),r(...c)};return[(...c)=>{const u=Date.now(),f=u-t;f>=n?a(c,u):(s=c,o||(o=setTimeout(()=>{o=null,a(s)},n-f)))},()=>s&&a(s)]}const $r=(r,e,t=3)=>{let n=0;const s=Tm(50,250);return Im(o=>{const a=o.loaded,i=o.lengthComputable?o.total:void 0,d=a-n,c=s(d),u=a<=i;n=a;const f={loaded:a,total:i,progress:i?a/i:void 0,bytes:d,rate:c||void 0,estimated:c&&i&&u?(i-a)/c:void 0,event:o,lengthComputable:i!=null,[e?"download":"upload"]:!0};r(f)},t)},da=(r,e)=>{const t=r!=null;return[n=>e[0]({lengthComputable:t,total:r,loaded:n}),e[1]]},ua=r=>(...e)=>_.asap(()=>r(...e)),Lm=ie.hasStandardBrowserEnv?((r,e)=>t=>(t=new URL(t,ie.origin),r.protocol===t.protocol&&r.host===t.host&&(e||r.port===t.port)))(new URL(ie.origin),ie.navigator&&/(msie|trident)/i.test(ie.navigator.userAgent)):()=>!0,Dm=ie.hasStandardBrowserEnv?{write(r,e,t,n,s,o){const a=[r+"="+encodeURIComponent(e)];_.isNumber(t)&&a.push("expires="+new Date(t).toGMTString()),_.isString(n)&&a.push("path="+n),_.isString(s)&&a.push("domain="+s),o===!0&&a.push("secure"),document.cookie=a.join("; ")},read(r){const e=document.cookie.match(new RegExp("(^|;\\s*)("+r+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(r){this.write(r,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function Fm(r){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(r)}function $m(r,e){return e?r.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):r}function Wl(r,e,t){let n=!Fm(e);return r&&(n||t==!1)?$m(r,e):e}const fa=r=>r instanceof ue?{...r}:r;function et(r,e){e=e||{};const t={};function n(c,u,f,m){return _.isPlainObject(c)&&_.isPlainObject(u)?_.merge.call({caseless:m},c,u):_.isPlainObject(u)?_.merge({},u):_.isArray(u)?u.slice():u}function s(c,u,f,m){if(_.isUndefined(u)){if(!_.isUndefined(c))return n(void 0,c,f,m)}else return n(c,u,f,m)}function o(c,u){if(!_.isUndefined(u))return n(void 0,u)}function a(c,u){if(_.isUndefined(u)){if(!_.isUndefined(c))return n(void 0,c)}else return n(void 0,u)}function i(c,u,f){if(f in e)return n(c,u);if(f in r)return n(void 0,c)}const d={url:o,method:o,data:o,baseURL:a,transformRequest:a,transformResponse:a,paramsSerializer:a,timeout:a,timeoutMessage:a,withCredentials:a,withXSRFToken:a,adapter:a,responseType:a,xsrfCookieName:a,xsrfHeaderName:a,onUploadProgress:a,onDownloadProgress:a,decompress:a,maxContentLength:a,maxBodyLength:a,beforeRedirect:a,transport:a,httpAgent:a,httpsAgent:a,cancelToken:a,socketPath:a,responseEncoding:a,validateStatus:i,headers:(c,u,f)=>s(fa(c),fa(u),f,!0)};return _.forEach(Object.keys({...r,...e}),function(u){const f=d[u]||s,m=f(r[u],e[u],u);_.isUndefined(m)&&f!==i||(t[u]=m)}),t}const Hl=r=>{const e=et({},r);let{data:t,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:a,auth:i}=e;if(e.headers=a=ue.from(a),e.url=Dl(Wl(e.baseURL,e.url,e.allowAbsoluteUrls),r.params,r.paramsSerializer),i&&a.set("Authorization","Basic "+btoa((i.username||"")+":"+(i.password?unescape(encodeURIComponent(i.password)):""))),_.isFormData(t)){if(ie.hasStandardBrowserEnv||ie.hasStandardBrowserWebWorkerEnv)a.setContentType(void 0);else if(_.isFunction(t.getHeaders)){const d=t.getHeaders(),c=["content-type","content-length"];Object.entries(d).forEach(([u,f])=>{c.includes(u.toLowerCase())&&a.set(u,f)})}}if(ie.hasStandardBrowserEnv&&(n&&_.isFunction(n)&&(n=n(e)),n||n!==!1&&Lm(e.url))){const d=s&&o&&Dm.read(o);d&&a.set(s,d)}return e},Bm=typeof XMLHttpRequest<"u",Um=Bm&&function(r){return new Promise(function(t,n){const s=Hl(r);let o=s.data;const a=ue.from(s.headers).normalize();let{responseType:i,onUploadProgress:d,onDownloadProgress:c}=s,u,f,m,b,g;function h(){b&&b(),g&&g(),s.cancelToken&&s.cancelToken.unsubscribe(u),s.signal&&s.signal.removeEventListener("abort",u)}let p=new XMLHttpRequest;p.open(s.method.toUpperCase(),s.url,!0),p.timeout=s.timeout;function y(){if(!p)return;const x=ue.from("getAllResponseHeaders"in p&&p.getAllResponseHeaders()),S={data:!i||i==="text"||i==="json"?p.responseText:p.response,status:p.status,statusText:p.statusText,headers:x,config:r,request:p};Ul(function(k){t(k),h()},function(k){n(k),h()},S),p=null}"onloadend"in p?p.onloadend=y:p.onreadystatechange=function(){!p||p.readyState!==4||p.status===0&&!(p.responseURL&&p.responseURL.indexOf("file:")===0)||setTimeout(y)},p.onabort=function(){p&&(n(new I("Request aborted",I.ECONNABORTED,r,p)),p=null)},p.onerror=function(v){const S=v&&v.message?v.message:"Network Error",A=new I(S,I.ERR_NETWORK,r,p);A.event=v||null,n(A),p=null},p.ontimeout=function(){let v=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded";const S=s.transitional||Fl;s.timeoutErrorMessage&&(v=s.timeoutErrorMessage),n(new I(v,S.clarifyTimeoutError?I.ETIMEDOUT:I.ECONNABORTED,r,p)),p=null},o===void 0&&a.setContentType(null),"setRequestHeader"in p&&_.forEach(a.toJSON(),function(v,S){p.setRequestHeader(S,v)}),_.isUndefined(s.withCredentials)||(p.withCredentials=!!s.withCredentials),i&&i!=="json"&&(p.responseType=s.responseType),c&&([m,g]=$r(c,!0),p.addEventListener("progress",m)),d&&p.upload&&([f,b]=$r(d),p.upload.addEventListener("progress",f),p.upload.addEventListener("loadend",b)),(s.cancelToken||s.signal)&&(u=x=>{p&&(n(!x||x.type?new vt(null,r,p):x),p.abort(),p=null)},s.cancelToken&&s.cancelToken.subscribe(u),s.signal&&(s.signal.aborted?u():s.signal.addEventListener("abort",u)));const w=Rm(s.url);if(w&&ie.protocols.indexOf(w)===-1){n(new I("Unsupported protocol "+w+":",I.ERR_BAD_REQUEST,r));return}p.send(o||null)})},Wm=(r,e)=>{const{length:t}=r=r?r.filter(Boolean):[];if(e||t){let n=new AbortController,s;const o=function(c){if(!s){s=!0,i();const u=c instanceof Error?c:this.reason;n.abort(u instanceof I?u:new vt(u instanceof Error?u.message:u))}};let a=e&&setTimeout(()=>{a=null,o(new I(`timeout ${e} of ms exceeded`,I.ETIMEDOUT))},e);const i=()=>{r&&(a&&clearTimeout(a),a=null,r.forEach(c=>{c.unsubscribe?c.unsubscribe(o):c.removeEventListener("abort",o)}),r=null)};r.forEach(c=>c.addEventListener("abort",o));const{signal:d}=n;return d.unsubscribe=()=>_.asap(i),d}},Hm=function*(r,e){let t=r.byteLength;if(t<e){yield r;return}let n=0,s;for(;n<t;)s=n+e,yield r.slice(n,s),n=s},zm=async function*(r,e){for await(const t of qm(r))yield*Hm(t,e)},qm=async function*(r){if(r[Symbol.asyncIterator]){yield*r;return}const e=r.getReader();try{for(;;){const{done:t,value:n}=await e.read();if(t)break;yield n}}finally{await e.cancel()}},ha=(r,e,t,n)=>{const s=zm(r,e);let o=0,a,i=d=>{a||(a=!0,n&&n(d))};return new ReadableStream({async pull(d){try{const{done:c,value:u}=await s.next();if(c){i(),d.close();return}let f=u.byteLength;if(t){let m=o+=f;t(m)}d.enqueue(new Uint8Array(u))}catch(c){throw i(c),c}},cancel(d){return i(d),s.return()}},{highWaterMark:2})},ma=64*1024,{isFunction:br}=_,Vm=(({Request:r,Response:e})=>({Request:r,Response:e}))(_.global),{ReadableStream:ga,TextEncoder:pa}=_.global,ya=(r,...e)=>{try{return!!r(...e)}catch{return!1}},Jm=r=>{r=_.merge.call({skipUndefined:!0},Vm,r);const{fetch:e,Request:t,Response:n}=r,s=e?br(e):typeof fetch=="function",o=br(t),a=br(n);if(!s)return!1;const i=s&&br(ga),d=s&&(typeof pa=="function"?(g=>h=>g.encode(h))(new pa):async g=>new Uint8Array(await new t(g).arrayBuffer())),c=o&&i&&ya(()=>{let g=!1;const h=new t(ie.origin,{body:new ga,method:"POST",get duplex(){return g=!0,"half"}}).headers.has("Content-Type");return g&&!h}),u=a&&i&&ya(()=>_.isReadableStream(new n("").body)),f={stream:u&&(g=>g.body)};s&&["text","arrayBuffer","blob","formData","stream"].forEach(g=>{!f[g]&&(f[g]=(h,p)=>{let y=h&&h[g];if(y)return y.call(h);throw new I(`Response type '${g}' is not supported`,I.ERR_NOT_SUPPORT,p)})});const m=async g=>{if(g==null)return 0;if(_.isBlob(g))return g.size;if(_.isSpecCompliantForm(g))return(await new t(ie.origin,{method:"POST",body:g}).arrayBuffer()).byteLength;if(_.isArrayBufferView(g)||_.isArrayBuffer(g))return g.byteLength;if(_.isURLSearchParams(g)&&(g=g+""),_.isString(g))return(await d(g)).byteLength},b=async(g,h)=>{const p=_.toFiniteNumber(g.getContentLength());return p??m(h)};return async g=>{let{url:h,method:p,data:y,signal:w,cancelToken:x,timeout:v,onDownloadProgress:S,onUploadProgress:A,responseType:k,headers:$,withCredentials:j="same-origin",fetchOptions:T}=Hl(g),P=e||fetch;k=k?(k+"").toLowerCase():"text";let C=Wm([w,x&&x.toAbortSignal()],v),F=null;const U=C&&C.unsubscribe&&(()=>{C.unsubscribe()});let G;try{if(A&&c&&p!=="get"&&p!=="head"&&(G=await b($,y))!==0){let Q=new t(h,{method:"POST",body:y,duplex:"half"}),tt;if(_.isFormData(y)&&(tt=Q.headers.get("content-type"))&&$.setContentType(tt),Q.body){const[cn,sr]=da(G,$r(ua(A)));y=ha(Q.body,ma,cn,sr)}}_.isString(j)||(j=j?"include":"omit");const te=o&&"credentials"in t.prototype,St={...T,signal:C,method:p.toUpperCase(),headers:$.normalize().toJSON(),body:y,duplex:"half",credentials:te?j:void 0};F=o&&new t(h,St);let ye=await(o?P(F,T):P(h,St));const Re=u&&(k==="stream"||k==="response");if(u&&(S||Re&&U)){const Q={};["status","statusText","headers"].forEach(ao=>{Q[ao]=ye[ao]});const tt=_.toFiniteNumber(ye.headers.get("content-length")),[cn,sr]=S&&da(tt,$r(ua(S),!0))||[];ye=new n(ha(ye.body,ma,cn,()=>{sr&&sr(),U&&U()}),Q)}k=k||"text";let nr=await f[_.findKey(f,k)||"text"](ye,g);return!Re&&U&&U(),await new Promise((Q,tt)=>{Ul(Q,tt,{data:nr,headers:ue.from(ye.headers),status:ye.status,statusText:ye.statusText,config:g,request:F})})}catch(te){throw U&&U(),te&&te.name==="TypeError"&&/Load failed|fetch/i.test(te.message)?Object.assign(new I("Network Error",I.ERR_NETWORK,g,F),{cause:te.cause||te}):I.from(te,te&&te.code,g,F)}}},Gm=new Map,zl=r=>{let e=r?r.env:{};const{fetch:t,Request:n,Response:s}=e,o=[n,s,t];let a=o.length,i=a,d,c,u=Gm;for(;i--;)d=o[i],c=u.get(d),c===void 0&&u.set(d,c=i?new Map:Jm(e)),u=c;return c};zl();const as={http:um,xhr:Um,fetch:{get:zl}};_.forEach(as,(r,e)=>{if(r){try{Object.defineProperty(r,"name",{value:e})}catch{}Object.defineProperty(r,"adapterName",{value:e})}});const ba=r=>`- ${r}`,Xm=r=>_.isFunction(r)||r===null||r===!1,ql={getAdapter:(r,e)=>{r=_.isArray(r)?r:[r];const{length:t}=r;let n,s;const o={};for(let a=0;a<t;a++){n=r[a];let i;if(s=n,!Xm(n)&&(s=as[(i=String(n)).toLowerCase()],s===void 0))throw new I(`Unknown adapter '${i}'`);if(s&&(_.isFunction(s)||(s=s.get(e))))break;o[i||"#"+a]=s}if(!s){const a=Object.entries(o).map(([d,c])=>`adapter ${d} `+(c===!1?"is not supported by the environment":"is not available in the build"));let i=t?a.length>1?`since :
|
|
62
|
-
`+
|
|
63
|
-
`):" "+
|
|
64
|
-
`+o):n.stack=o}catch{}}throw n}}_request(e,t){typeof e=="string"?(t=t||{},t.url=e):t=e||{},t=
|
|
65
|
-
`);let s={},o=0;for(;o<n.length;){const
|
|
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(`
|
|
66
66
|
|
|
67
|
-
`),i
|
|
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+`
|
|
68
68
|
|
|
69
|
-
`+a:a=this.conversation.global_prompt,console.log("Added global prompt to system prompt:",this.conversation.global_prompt.substring(0,100)+"...")),a&&(this.messages.push({role:"system",content:a}),console.log("Final system prompt added to messages:",a.substring(0,100)+"..."));const i=o.slice(-2);this.messages.push(...i),console.log("Messages prepared for AI:",this.messages.map(c=>({role:c.role,content:(c.content||c.message||"").substring(0,50)+"...",created_at:c.created_at})));const d=new sa(this.messages,this.conversationId,this.tools,this.modelConfig,(c,u)=>this.callback(c,u),this.mcpToolsExecute);this.currentAiClient=d;try{await d.start()}catch(c){if(this.isAborted){console.log("AiServer: Request was aborted");return}throw c}finally{this.currentAiClient=null}}catch(n){throw console.error("sendMessage failed:",n),console.error("Error details:",(t=n.response)==null?void 0:t.data),this.callback("error",n),n}}async sendMessageDirect(e){try{console.log("AiServer sendMessageDirect called with:",e),this.messages=[{role:"user",content:e}],console.log("Messages prepared for AI:",this.messages);const t=new sa(this.messages,this.conversationId,[],this.modelConfig,(n,s)=>this.callback(n,s),null);this.currentAiClient=t;try{await t.start()}catch(n){if(this.isAborted){console.log("AiServer: Request was aborted");return}throw n}finally{this.currentAiClient=null}}catch(t){throw console.error("sendMessageDirect failed:",t),this.callback("error",t),t}}async getMessages(e={}){try{const t=await ct.getMessages(this.conversationId,e);return this.messages=t.data.messages||[],t.data}catch(t){throw console.error("getMessages failed:",t),t}}async addMessage(e,t="user"){try{return{message:await Pr.saveMessage({content:e,role:t,sessionId:this.conversationId,createdAt:new Date})}}catch(n){throw console.error("addMessage failed:",n),n}}abort(){console.log("AiServer: Aborting request"),this.isAborted=!0,this.currentAiClient&&this.currentAiClient.abort()}isRequestAborted(){return this.isAborted}resetAbortState(){this.isAborted=!1,this.currentAiClient=null}}class rg extends Ia{async getAllMcpConfigs(){return[]}async createMcpConfig(e){return{...e,id:Math.random().toString(36).substr(2,9),createdAt:new Date,updatedAt:new Date}}async getUserConfig(e){return null}}class oo{constructor(){D(this,"currentAiClient",null);D(this,"dbService");this.dbService=new rg}async sendMessage(e,t,n=[],s={},o){var a;try{if(!await this.dbService.getSession(e))throw new Error("Session not found");let d;if(o)d=o;else{const f=await this.getChatConfig();d={model_name:f.model,temperature:f.temperature,max_tokens:16e3,api_key:f.apiKey,base_url:f.baseUrl}}const c=new tg(e,d);let u=3;for(;u>0;)try{await c.init();break}catch(f){if(u--,u===0)throw new Error(`AI服务初始化失败: ${f instanceof Error?f.message:"未知错误"}`);await new Promise(m=>setTimeout(m,1e3))}c.callback=(f,m)=>{var b,g,h,p,y,w,x,v;try{switch(f){case"chunk":const S=typeof m=="string"?m:m.content||m.accumulated||"";(b=s.onChunk)==null||b.call(s,{type:"text",content:S,accumulated:S});break;case"summary_chunk":const A=typeof m=="string"?m:m.content||m.accumulated||"";(g=s.onChunk)==null||g.call(s,{type:"text",content:A,accumulated:A});break;case"tool_call":(h=s.onToolCall)==null||h.call(s,m);break;case"tool_result":(p=s.onToolResult)==null||p.call(s,m);break;case"tool_stream_chunk":(y=s.onToolStreamChunk)==null||y.call(s,m);break;case"complete":debugger;break;case"conversation_complete":(w=s.onComplete)==null||w.call(s,m);break;case"error":const k=m instanceof Error?m.message:typeof m=="string"?m:"AI响应出错";(x=s.onError)==null||x.call(s,new Error(k));break;default:console.warn("Unknown AI response type:",f)}}catch(S){console.error("Callback error:",S),(v=s.onError)==null||v.call(s,new Error(`处理AI响应时出错: ${S instanceof Error?S.message:"未知错误"}`))}},await c.sendMessage(t),this.currentAiClient=c}catch(i){throw console.error("Failed to send message:",i),(a=s.onError)==null||a.call(s,i instanceof Error?i:new Error(String(i))),i}}abortCurrentConversation(){this.currentAiClient&&(this.currentAiClient.abort(),this.currentAiClient=null)}async getChatConfig(){return await this.dbService.getUserConfig("chatConfig")||{model:"gpt-3.5-turbo",temperature:.7,maxTokens:4e3,apiKey:"",baseUrl:"https://api.openai.com/v1"}}}const Xl=new oo,ng=Object.freeze(Object.defineProperty({__proto__:null,ChatService:oo,chatService:Xl},Symbol.toStringTag,{value:"Module"})),sg="1.0.0";exports.AiModelManager=ys;exports.AppError=Yu;exports.AttachmentRenderer=Ya;exports.ChatIcon=ni;exports.ChatInterface=gf;exports.ChatService=oo;exports.CheckIcon=Zu;exports.DotsVerticalIcon=ei;exports.ErrorBoundary=pf;exports.InputArea=hs;exports.LoadingSpinner=Qa;exports.MarkdownRenderer=Wn;exports.McpManager=ps;exports.MessageItem=Ka;exports.MessageList=fs;exports.PencilIcon=ti;exports.PlusIcon=Za;exports.SessionList=ms;exports.StandaloneChatInterface=ai;exports.SystemContextEditor=bs;exports.ThemeToggle=gs;exports.ToolCallRenderer=Hn;exports.TrashIcon=ri;exports.XIcon=ef;exports.chatService=Xl;exports.cleanHtmlContent=$u;exports.cn=se;exports.conversationsApi=ct;exports.copyToClipboard=Vu;exports.databaseService=q;exports.debounce=Wu;exports.deepClone=Un;exports.default=ai;exports.downloadFile=Ju;exports.formatDate=Lu;exports.formatDateTime=Du;exports.formatFileSize=Ga;exports.formatRelativeTime=Iu;exports.formatTime=Ja;exports.generateId=Tu;exports.generateRandomColor=qu;exports.getFileExtension=Xa;exports.getOS=Xu;exports.isImageFile=zu;exports.isMobile=Gu;exports.isValidEmail=Bu;exports.isValidUrl=Uu;exports.retry=Ku;exports.storage=Qu;exports.throttle=Hu;exports.truncateText=Fu;exports.useChatStore=Pe;exports.useTheme=oi;exports.version=sg;
|
|
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">
|
|
72
|
+
<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}">
|
|
76
|
+
<div class="code-header">
|
|
77
|
+
<span class="code-language">${_}</span>
|
|
78
|
+
<div class="code-actions">
|
|
79
|
+
<button class="code-action-btn copy-btn" data-code="${encodeURIComponent(R)}" title="复制代码">
|
|
80
|
+
<span class="icon">复制</span>
|
|
81
|
+
</button>
|
|
82
|
+
<button class="code-action-btn apply-btn" data-code="${encodeURIComponent(R)}" data-language="${_}" title="应用代码">
|
|
83
|
+
<span class="icon">应用</span>
|
|
84
|
+
</button>
|
|
85
|
+
<button class="code-action-btn expand-btn" data-block-id="${N}" title="${P?"收起":"展开"}">
|
|
86
|
+
<span class="icon">${P?"收起":"展开"}</span>
|
|
87
|
+
</button>
|
|
88
|
+
</div>
|
|
89
|
+
</div>
|
|
90
|
+
<div class="code-content">
|
|
91
|
+
<pre><code>${T}</code></pre>
|
|
92
|
+
</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,"<").replace(/>/g,">"),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(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/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 _=`| 参数 | 值 |
|
|
97
|
+
|------|------|
|
|
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;
|
|
70
100
|
//# sourceMappingURL=index.cjs.js.map
|