zen-code 4.10.0 → 4.10.1

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.
Files changed (83) hide show
  1. package/dist/app.js +2615 -157
  2. package/dist/cli.js +3116 -1
  3. package/dist/nonInteractive.js +1950 -180
  4. package/dist/zen-keyboard.js +358 -3
  5. package/package.json +1 -1
  6. package/dist/chunk-075hks9v.js +0 -1
  7. package/dist/chunk-0fj768k4.js +0 -112
  8. package/dist/chunk-19mf2aa7.js +0 -1
  9. package/dist/chunk-1mq2jmfy.js +0 -2
  10. package/dist/chunk-1v863afn.js +0 -278
  11. package/dist/chunk-1vn8d8b8.js +0 -1
  12. package/dist/chunk-1w19w1bm.js +0 -2
  13. package/dist/chunk-3dnayvgx.js +0 -224
  14. package/dist/chunk-4hg13vwj.js +0 -1
  15. package/dist/chunk-4scrkcqv.js +0 -1
  16. package/dist/chunk-54cdhhqm.js +0 -1
  17. package/dist/chunk-5m4yb9av.js +0 -91
  18. package/dist/chunk-5yd4ntp6.js +0 -8
  19. package/dist/chunk-6scjjkn3.js +0 -23
  20. package/dist/chunk-7jatn15w.js +0 -2
  21. package/dist/chunk-7w9y11hj.js +0 -88
  22. package/dist/chunk-7yzv6385.js +0 -1
  23. package/dist/chunk-875hayaj.js +0 -3
  24. package/dist/chunk-8bs8r50r.js +0 -1
  25. package/dist/chunk-8waww0j9.js +0 -6
  26. package/dist/chunk-8ysg0rga.js +0 -1
  27. package/dist/chunk-9czhw5k6.js +0 -4
  28. package/dist/chunk-9tgp14v7.js +0 -16
  29. package/dist/chunk-a239dn0b.js +0 -1
  30. package/dist/chunk-arv4h3h1.js +0 -2
  31. package/dist/chunk-b2551zfb.js +0 -2
  32. package/dist/chunk-b9emn03n.js +0 -1
  33. package/dist/chunk-bm7578sn.js +0 -1
  34. package/dist/chunk-bytq4kd1.js +0 -176
  35. package/dist/chunk-c2wfgbj6.js +0 -1
  36. package/dist/chunk-cef4vbtb.js +0 -26
  37. package/dist/chunk-cnzhxgn5.js +0 -4
  38. package/dist/chunk-d2770b2z.js +0 -1
  39. package/dist/chunk-d72063sm.js +0 -2
  40. package/dist/chunk-d988tv30.js +0 -1
  41. package/dist/chunk-dx9k6sdd.js +0 -7
  42. package/dist/chunk-e6ggkg36.js +0 -2
  43. package/dist/chunk-fjqtrakn.js +0 -1
  44. package/dist/chunk-gbfpab0j.js +0 -1
  45. package/dist/chunk-gkvx829z.js +0 -1
  46. package/dist/chunk-gwf8b14k.js +0 -3
  47. package/dist/chunk-gz7fz9fg.js +0 -1
  48. package/dist/chunk-h0q3dvnv.js +0 -5
  49. package/dist/chunk-h0qb9jk1.js +0 -1
  50. package/dist/chunk-h9y136h8.js +0 -1
  51. package/dist/chunk-hrcxdj3c.js +0 -54
  52. package/dist/chunk-hz9yw7cs.js +0 -166
  53. package/dist/chunk-j4y5rjne.js +0 -79
  54. package/dist/chunk-k12y05c3.js +0 -3
  55. package/dist/chunk-k6fxqssr.js +0 -18
  56. package/dist/chunk-kmxdq21k.js +0 -2
  57. package/dist/chunk-mcb8rewr.js +0 -213
  58. package/dist/chunk-mm9w91rj.js +0 -4
  59. package/dist/chunk-mv0xzmq8.js +0 -2
  60. package/dist/chunk-n849zsd3.js +0 -1
  61. package/dist/chunk-nm253hhf.js +0 -81
  62. package/dist/chunk-prg6489q.js +0 -1
  63. package/dist/chunk-pxdgy0vr.js +0 -2
  64. package/dist/chunk-qhzm2qw9.js +0 -2
  65. package/dist/chunk-qmxtys9q.js +0 -2
  66. package/dist/chunk-r0cfe5c1.js +0 -294
  67. package/dist/chunk-rtjytfhh.js +0 -1
  68. package/dist/chunk-s7ttf0pm.js +0 -2
  69. package/dist/chunk-t01t72t2.js +0 -140
  70. package/dist/chunk-t0f66x64.js +0 -1
  71. package/dist/chunk-tn356gwf.js +0 -93
  72. package/dist/chunk-vd8kwzra.js +0 -41
  73. package/dist/chunk-vhn13anh.js +0 -233
  74. package/dist/chunk-vnewbtjy.js +0 -1
  75. package/dist/chunk-wbm7rn9w.js +0 -2
  76. package/dist/chunk-wd3gkd45.js +0 -3
  77. package/dist/chunk-whdf0vbb.js +0 -1
  78. package/dist/chunk-ws232ksq.js +0 -2
  79. package/dist/chunk-yerf10k7.js +0 -6
  80. package/dist/chunk-yzv3n8mw.js +0 -2
  81. package/dist/chunk-z3e4c424.js +0 -2
  82. package/dist/chunk-znw7fpep.js +0 -6
  83. package/dist/chunk-zq2g4rfd.js +0 -1
@@ -1,7 +0,0 @@
1
- import{ye as c}from"./chunk-1v863afn.js";import{Fl as h,Hl as wY}from"./chunk-z3e4c424.js";var IX=wY((DY)=>{var p=h(c());(function(){function X($){if($==null)return null;if(typeof $==="function")return $.$$typeof===i?null:$.displayName||$.name||null;if(typeof $==="string")return $;switch($){case L:return"Fragment";case k:return"Profiler";case P:return"StrictMode";case b:return"Suspense";case YX:return"SuspenseList";case d:return"Activity"}if(typeof $==="object")switch(typeof $.tag==="number"&&console.error("Received an unexpected object in getComponentNameFromType(). This is likely a bug in React. Please file an issue."),$.$$typeof){case w:return"Portal";case R:return $.displayName||"Context";case S:return($._context.displayName||"Context")+".Consumer";case g:var V=$.render;return $=$.displayName,$||($=V.displayName||V.name||"",$=$!==""?"ForwardRef("+$+")":"ForwardRef"),$;case O:return V=$.displayName||null,V!==null?V:X($.type)||"Memo";case Q:V=$._payload,$=$._init;try{return X($(V))}catch(D){}}return null}function Y($){return""+$}function G($){try{Y($);var V=!1}catch(_X){V=!0}if(V){V=console;var D=V.error,T=typeof Symbol==="function"&&Symbol.toStringTag&&$[Symbol.toStringTag]||$.constructor.name||"Object";return D.call(V,"The provided key is an unsupported type %s. This value must be coerced to a string before using it here.",T),Y($)}}function J($){if($===L)return"<>";if(typeof $==="object"&&$!==null&&$.$$typeof===Q)return"<...>";try{var V=X($);return V?"<"+V+">":"<...>"}catch(D){return"<...>"}}function Z(){var $=s.A;return $===null?null:$.getOwner()}function H(){return Error("react-stack-top-frame")}function _($){if(y.call($,"key")){var V=Object.getOwnPropertyDescriptor($,"key").get;if(V&&V.isReactWarning)return!1}return $.key!==void 0}function W($,V){function D(){vX||(vX=!0,console.error("%s: `key` is not a prop. Trying to access it will result in `undefined` being returned. If you need to access the same value within the child component, you should pass it as a different prop. (https://react.dev/link/special-props)",V))}D.isReactWarning=!0,Object.defineProperty($,"key",{get:D,configurable:!0})}function A(){var $=X(this.type);return gX[$]||(gX[$]=!0,console.error("Accessing element.ref was removed in React 19. ref is now a regular prop. It will be removed from the JSX Element type in a future release.")),$=this.props.ref,$!==void 0?$:null}function U($,V,D,T,_X,KX){var I=D.ref;return $={$$typeof:K,type:$,key:V,props:D,_owner:T},(I!==void 0?I:null)!==null?Object.defineProperty($,"ref",{enumerable:!1,get:A}):Object.defineProperty($,"ref",{enumerable:!1,value:null}),$._store={},Object.defineProperty($._store,"validated",{configurable:!1,enumerable:!1,writable:!0,value:0}),Object.defineProperty($,"_debugInfo",{configurable:!1,enumerable:!1,writable:!0,value:null}),Object.defineProperty($,"_debugStack",{configurable:!1,enumerable:!1,writable:!0,value:_X}),Object.defineProperty($,"_debugTask",{configurable:!1,enumerable:!1,writable:!0,value:KX}),Object.freeze&&(Object.freeze($.props),Object.freeze($)),$}function z($,V,D,T,_X,KX){var I=V.children;if(I!==void 0)if(T)if(n(I)){for(T=0;T<I.length;T++)E(I[T]);Object.freeze&&Object.freeze(I)}else console.error("React.jsx: Static children should always be an array. You are likely explicitly calling React.jsxs or React.jsxDEV. Use the Babel transform instead.");else E(I);if(y.call(V,"key")){I=X($);var a=Object.keys(V).filter(function(BY){return BY!=="key"});T=0<a.length?"{key: someKey, "+a.join(": ..., ")+": ...}":"{key: someKey}",mX[I+T]||(a=0<a.length?"{"+a.join(": ..., ")+": ...}":"{}",console.error(`A props object containing a "key" prop is being spread into JSX:
2
- let props = %s;
3
- <%s {...props} />
4
- React keys must be passed directly to JSX without using spread:
5
- let props = %s;
6
- <%s key={someKey} {...props} />`,T,I,a,I),mX[I+T]=!0)}if(I=null,D!==void 0&&(G(D),I=""+D),_(V)&&(G(V.key),I=""+V.key),"key"in V){D={};for(var TX in V)TX!=="key"&&(D[TX]=V[TX])}else D=V;return I&&W(D,typeof $==="function"?$.displayName||$.name||"Unknown":$),U($,I,D,Z(),_X,KX)}function E($){N($)?$._store&&($._store.validated=1):typeof $==="object"&&$!==null&&$.$$typeof===Q&&($._payload.status==="fulfilled"?N($._payload.value)&&$._payload.value._store&&($._payload.value._store.validated=1):$._store&&($._store.validated=1))}function N($){return typeof $==="object"&&$!==null&&$.$$typeof===K}var K=Symbol.for("react.transitional.element"),w=Symbol.for("react.portal"),L=Symbol.for("react.fragment"),P=Symbol.for("react.strict_mode"),k=Symbol.for("react.profiler"),S=Symbol.for("react.consumer"),R=Symbol.for("react.context"),g=Symbol.for("react.forward_ref"),b=Symbol.for("react.suspense"),YX=Symbol.for("react.suspense_list"),O=Symbol.for("react.memo"),Q=Symbol.for("react.lazy"),d=Symbol.for("react.activity"),i=Symbol.for("react.client.reference"),s=p.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,y=Object.prototype.hasOwnProperty,n=Array.isArray,EX=console.createTask?console.createTask:function(){return null};p={react_stack_bottom_frame:function($){return $()}};var vX,gX={},bX=p.react_stack_bottom_frame.bind(p,H)(),hX=EX(J(H)),mX={};DY.Fragment=L,DY.jsx=function($,V,D){var T=1e4>s.recentlyCreatedOwnerStacks++;return z($,V,D,!1,T?Error("react-stack-top-frame"):bX,T?EX(J($)):hX)},DY.jsxs=function($,V,D){var T=1e4>s.recentlyCreatedOwnerStacks++;return z($,V,D,!0,T?Error("react-stack-top-frame"):bX,T?EX(J($)):hX)}})()});var o=h(c(),1),fX=h(IX(),1),PX=o.createContext(void 0),GX=(X)=>{let Y=o.useContext(PX);if(X)return X;if(!Y)throw Error("No QueryClient set, use QueryClientProvider to set one");return Y},FY=({client:X,children:Y})=>{return o.useEffect(()=>{return X.mount(),()=>{X.unmount()}},[X]),fX.jsx(PX.Provider,{value:X,children:Y})};var M=class{constructor(){this.listeners=new Set,this.subscribe=this.subscribe.bind(this)}subscribe(X){return this.listeners.add(X),this.onSubscribe(),()=>{this.listeners.delete(X),this.onUnsubscribe()}}hasListeners(){return this.listeners.size>0}onSubscribe(){}onUnsubscribe(){}};var EY={setTimeout:(X,Y)=>setTimeout(X,Y),clearTimeout:(X)=>clearTimeout(X),setInterval:(X,Y)=>setInterval(X,Y),clearInterval:(X)=>clearInterval(X)},KY=class{#X=EY;#Y=!1;setTimeoutProvider(X){if(this.#Y&&X!==this.#X)console.error("[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.",{previous:this.#X,provider:X});this.#X=X,this.#Y=!1}setTimeout(X,Y){return this.#Y=!0,this.#X.setTimeout(X,Y)}clearTimeout(X){this.#X.clearTimeout(X)}setInterval(X,Y){return this.#Y=!0,this.#X.setInterval(X,Y)}clearInterval(X){this.#X.clearInterval(X)}},q=new KY;function dX(X){setTimeout(X,0)}var x=typeof window>"u"||"Deno"in globalThis;function F(){}function cX(X,Y){return typeof X==="function"?X(Y):X}function JX(X){return typeof X==="number"&&X>=0&&X!==1/0}function VX(X,Y){return Math.max(X+(Y||0)-Date.now(),0)}function C(X,Y){return typeof X==="function"?X(Y):X}function j(X,Y){return typeof X==="function"?X(Y):X}function AX(X,Y){let{type:G="all",exact:J,fetchStatus:Z,predicate:H,queryKey:_,stale:W}=X;if(_){if(J){if(Y.queryHash!==ZX(_,Y.options))return!1}else if(!u(Y.queryKey,_))return!1}if(G!=="all"){let A=Y.isActive();if(G==="active"&&!A)return!1;if(G==="inactive"&&A)return!1}if(typeof W==="boolean"&&Y.isStale()!==W)return!1;if(Z&&Z!==Y.state.fetchStatus)return!1;if(H&&!H(Y))return!1;return!0}function NX(X,Y){let{exact:G,status:J,predicate:Z,mutationKey:H}=X;if(H){if(!Y.options.mutationKey)return!1;if(G){if(v(Y.options.mutationKey)!==v(H))return!1}else if(!u(Y.options.mutationKey,H))return!1}if(J&&Y.state.status!==J)return!1;if(Z&&!Z(Y))return!1;return!0}function ZX(X,Y){return(Y?.queryKeyHashFn||v)(X)}function v(X){return JSON.stringify(X,(Y,G)=>kX(G)?Object.keys(G).sort().reduce((J,Z)=>{return J[Z]=G[Z],J},{}):G)}function u(X,Y){if(X===Y)return!0;if(typeof X!==typeof Y)return!1;if(X&&Y&&typeof X==="object"&&typeof Y==="object")return Object.keys(Y).every((G)=>u(X[G],Y[G]));return!1}var TY=Object.prototype.hasOwnProperty;function zX(X,Y,G=0){if(X===Y)return X;if(G>500)return Y;let J=yX(X)&&yX(Y);if(!J&&!(kX(X)&&kX(Y)))return Y;let H=(J?X:Object.keys(X)).length,_=J?Y:Object.keys(Y),W=_.length,A=J?Array(W):{},U=0;for(let z=0;z<W;z++){let E=J?z:_[z],N=X[E],K=Y[E];if(N===K){if(A[E]=N,J?z<H:TY.call(X,E))U++;continue}if(N===null||K===null||typeof N!=="object"||typeof K!=="object"){A[E]=K;continue}let w=zX(N,K,G+1);if(A[E]=w,w===N)U++}return H===W&&U===H?X:A}function r(X,Y){if(!Y||Object.keys(X).length!==Object.keys(Y).length)return!1;for(let G in X)if(X[G]!==Y[G])return!1;return!0}function yX(X){return Array.isArray(X)&&X.length===Object.keys(X).length}function kX(X){if(!pX(X))return!1;let Y=X.constructor;if(Y===void 0)return!0;let G=Y.prototype;if(!pX(G))return!1;if(!G.hasOwnProperty("isPrototypeOf"))return!1;if(Object.getPrototypeOf(X)!==Object.prototype)return!1;return!0}function pX(X){return Object.prototype.toString.call(X)==="[object Object]"}function lX(X){return new Promise((Y)=>{q.setTimeout(Y,X)})}function $X(X,Y,G){if(typeof G.structuralSharing==="function")return G.structuralSharing(X,Y);else if(G.structuralSharing!==!1){try{return zX(X,Y)}catch(J){throw console.error(`Structural sharing requires data to be JSON serializable. To fix this, turn off structuralSharing or return JSON-serializable data from your queryFn. [${G.queryHash}]: ${J}`),J}return zX(X,Y)}return Y}function uX(X,Y,G=0){let J=[...X,Y];return G&&J.length>G?J.slice(1):J}function iX(X,Y,G=0){let J=[Y,...X];return G&&J.length>G?J.slice(0,-1):J}var l=Symbol();function LX(X,Y){if(X.queryFn===l)console.error(`Attempted to invoke queryFn when set to skipToken. This is likely a configuration error. Query hash: '${X.queryHash}'`);if(!X.queryFn&&Y?.initialPromise)return()=>Y.initialPromise;if(!X.queryFn||X.queryFn===l)return()=>Promise.reject(Error(`Missing queryFn: '${X.queryHash}'`));return X.queryFn}function t(X,Y){if(typeof X==="function")return X(...Y);return!!X}function sX(X,Y,G){let J=!1,Z;return Object.defineProperty(X,"signal",{enumerable:!0,get:()=>{if(Z??=Y(),J)return Z;if(J=!0,Z.aborted)G();else Z.addEventListener("abort",G,{once:!0});return Z}}),X}var IY=class extends M{#X;#Y;#G;constructor(){super();this.#G=(X)=>{if(!x&&window.addEventListener){let Y=()=>X();return window.addEventListener("visibilitychange",Y,!1),()=>{window.removeEventListener("visibilitychange",Y)}}return}}onSubscribe(){if(!this.#Y)this.setEventListener(this.#G)}onUnsubscribe(){if(!this.hasListeners())this.#Y?.(),this.#Y=void 0}setEventListener(X){this.#G=X,this.#Y?.(),this.#Y=X((Y)=>{if(typeof Y==="boolean")this.setFocused(Y);else this.onFocus()})}setFocused(X){if(this.#X!==X)this.#X=X,this.onFocus()}onFocus(){let X=this.isFocused();this.listeners.forEach((Y)=>{Y(X)})}isFocused(){if(typeof this.#X==="boolean")return this.#X;return globalThis.document?.visibilityState!=="hidden"}},e=new IY;function WX(){let X,Y,G=new Promise((Z,H)=>{X=Z,Y=H});G.status="pending",G.catch(()=>{});function J(Z){Object.assign(G,Z),delete G.resolve,delete G.reject}return G.resolve=(Z)=>{J({status:"fulfilled",value:Z}),X(Z)},G.reject=(Z)=>{J({status:"rejected",reason:Z}),Y(Z)},G}var nX=dX;function PY(){let X=[],Y=0,G=(W)=>{W()},J=(W)=>{W()},Z=nX,H=(W)=>{if(Y)X.push(W);else Z(()=>{G(W)})},_=()=>{let W=X;if(X=[],W.length)Z(()=>{J(()=>{W.forEach((A)=>{G(A)})})})};return{batch:(W)=>{let A;Y++;try{A=W()}finally{if(Y--,!Y)_()}return A},batchCalls:(W)=>{return(...A)=>{H(()=>{W(...A)})}},schedule:H,setNotifyFunction:(W)=>{G=W},setBatchNotifyFunction:(W)=>{J=W},setScheduler:(W)=>{Z=W}}}var B=PY();var kY=class extends M{#X=!0;#Y;#G;constructor(){super();this.#G=(X)=>{if(!x&&window.addEventListener){let Y=()=>X(!0),G=()=>X(!1);return window.addEventListener("online",Y,!1),window.addEventListener("offline",G,!1),()=>{window.removeEventListener("online",Y),window.removeEventListener("offline",G)}}return}}onSubscribe(){if(!this.#Y)this.setEventListener(this.#G)}onUnsubscribe(){if(!this.hasListeners())this.#Y?.(),this.#Y=void 0}setEventListener(X){this.#G=X,this.#Y?.(),this.#Y=X(this.setOnline.bind(this))}setOnline(X){if(this.#X!==X)this.#X=X,this.listeners.forEach((G)=>{G(X)})}isOnline(){return this.#X}},XX=new kY;function QY(X){return Math.min(1000*2**X,30000)}function QX(X){return(X??"online")==="online"?XX.isOnline():!0}var UX=class extends Error{constructor(X){super("CancelledError");this.revert=X?.revert,this.silent=X?.silent}};function BX(X){let Y=!1,G=0,J,Z=WX(),H=()=>Z.status!=="pending",_=(L)=>{if(!H()){let P=new UX(L);N(P),X.onCancel?.(P)}},W=()=>{Y=!0},A=()=>{Y=!1},U=()=>e.isFocused()&&(X.networkMode==="always"||XX.isOnline())&&X.canRun(),z=()=>QX(X.networkMode)&&X.canRun(),E=(L)=>{if(!H())J?.(),Z.resolve(L)},N=(L)=>{if(!H())J?.(),Z.reject(L)},K=()=>{return new Promise((L)=>{J=(P)=>{if(H()||U())L(P)},X.onPause?.()}).then(()=>{if(J=void 0,!H())X.onContinue?.()})},w=()=>{if(H())return;let L,P=G===0?X.initialPromise:void 0;try{L=P??X.fn()}catch(k){L=Promise.reject(k)}Promise.resolve(L).then(E).catch((k)=>{if(H())return;let S=X.retry??(x?0:3),R=X.retryDelay??QY,g=typeof R==="function"?R(G,k):R,b=S===!0||typeof S==="number"&&G<S||typeof S==="function"&&S(G,k);if(Y||!b){N(k);return}G++,X.onFail?.(G,k),lX(g).then(()=>{return U()?void 0:K()}).then(()=>{if(Y)N(k);else w()})})};return{promise:Z,status:()=>Z.status,cancel:_,continue:()=>{return J?.(),Z},cancelRetry:W,continueRetry:A,canStart:z,start:()=>{if(z())w();else K().then(w);return Z}}}var wX=class{#X;destroy(){this.clearGcTimeout()}scheduleGc(){if(this.clearGcTimeout(),JX(this.gcTime))this.#X=q.setTimeout(()=>{this.optionalRemove()},this.gcTime)}updateGcTime(X){this.gcTime=Math.max(this.gcTime||0,X??(x?1/0:300000))}clearGcTimeout(){if(this.#X)q.clearTimeout(this.#X),this.#X=void 0}};var rX=class extends wX{#X;#Y;#G;#Z;#J;#W;#H;constructor(X){super();this.#H=!1,this.#W=X.defaultOptions,this.setOptions(X.options),this.observers=[],this.#Z=X.client,this.#G=this.#Z.getQueryCache(),this.queryKey=X.queryKey,this.queryHash=X.queryHash,this.#X=oX(this.options),this.state=X.state??this.#X,this.scheduleGc()}get meta(){return this.options.meta}get promise(){return this.#J?.promise}setOptions(X){if(this.options={...this.#W,...X},this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){let Y=oX(this.options);if(Y.data!==void 0)this.setState(aX(Y.data,Y.dataUpdatedAt)),this.#X=Y}}optionalRemove(){if(!this.observers.length&&this.state.fetchStatus==="idle")this.#G.remove(this)}setData(X,Y){let G=$X(this.state.data,X,this.options);return this.#$({data:G,type:"success",dataUpdatedAt:Y?.updatedAt,manual:Y?.manual}),G}setState(X,Y){this.#$({type:"setState",state:X,setStateOptions:Y})}cancel(X){let Y=this.#J?.promise;return this.#J?.cancel(X),Y?Y.then(F).catch(F):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(this.#X)}isActive(){return this.observers.some((X)=>j(X.options.enabled,this)!==!1)}isDisabled(){if(this.getObserversCount()>0)return!this.isActive();return this.options.queryFn===l||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){if(this.getObserversCount()>0)return this.observers.some((X)=>C(X.options.staleTime,this)==="static");return!1}isStale(){if(this.getObserversCount()>0)return this.observers.some((X)=>X.getCurrentResult().isStale);return this.state.data===void 0||this.state.isInvalidated}isStaleByTime(X=0){if(this.state.data===void 0)return!0;if(X==="static")return!1;if(this.state.isInvalidated)return!0;return!VX(this.state.dataUpdatedAt,X)}onFocus(){this.observers.find((Y)=>Y.shouldFetchOnWindowFocus())?.refetch({cancelRefetch:!1}),this.#J?.continue()}onOnline(){this.observers.find((Y)=>Y.shouldFetchOnReconnect())?.refetch({cancelRefetch:!1}),this.#J?.continue()}addObserver(X){if(!this.observers.includes(X))this.observers.push(X),this.clearGcTimeout(),this.#G.notify({type:"observerAdded",query:this,observer:X})}removeObserver(X){if(this.observers.includes(X)){if(this.observers=this.observers.filter((Y)=>Y!==X),!this.observers.length){if(this.#J)if(this.#H)this.#J.cancel({revert:!0});else this.#J.cancelRetry();this.scheduleGc()}this.#G.notify({type:"observerRemoved",query:this,observer:X})}}getObserversCount(){return this.observers.length}invalidate(){if(!this.state.isInvalidated)this.#$({type:"invalidate"})}async fetch(X,Y){if(this.state.fetchStatus!=="idle"&&this.#J?.status()!=="rejected"){if(this.state.data!==void 0&&Y?.cancelRefetch)this.cancel({silent:!0});else if(this.#J)return this.#J.continueRetry(),this.#J.promise}if(X)this.setOptions(X);if(!this.options.queryFn){let W=this.observers.find((A)=>A.options.queryFn);if(W)this.setOptions(W.options)}if(!Array.isArray(this.options.queryKey))console.error("As of v4, queryKey needs to be an Array. If you are using a string like 'repoData', please change it to an Array, e.g. ['repoData']");let G=new AbortController,J=(W)=>{Object.defineProperty(W,"signal",{enumerable:!0,get:()=>{return this.#H=!0,G.signal}})},Z=()=>{let W=LX(this.options,Y),U=(()=>{let z={client:this.#Z,queryKey:this.queryKey,meta:this.meta};return J(z),z})();if(this.#H=!1,this.options.persister)return this.options.persister(W,U,this);return W(U)},_=(()=>{let W={fetchOptions:Y,options:this.options,queryKey:this.queryKey,client:this.#Z,state:this.state,fetchFn:Z};return J(W),W})();if(this.options.behavior?.onFetch(_,this),this.#Y=this.state,this.state.fetchStatus==="idle"||this.state.fetchMeta!==_.fetchOptions?.meta)this.#$({type:"fetch",meta:_.fetchOptions?.meta});this.#J=BX({initialPromise:Y?.initialPromise,fn:_.fetchFn,onCancel:(W)=>{if(W instanceof UX&&W.revert)this.setState({...this.#Y,fetchStatus:"idle"});G.abort()},onFail:(W,A)=>{this.#$({type:"failed",failureCount:W,error:A})},onPause:()=>{this.#$({type:"pause"})},onContinue:()=>{this.#$({type:"continue"})},retry:_.options.retry,retryDelay:_.options.retryDelay,networkMode:_.options.networkMode,canRun:()=>!0});try{let W=await this.#J.start();if(W===void 0)throw console.error(`Query data cannot be undefined. Please make sure to return a value other than undefined from your query function. Affected query key: ${this.queryHash}`),Error(`${this.queryHash} data is undefined`);return this.setData(W),this.#G.config.onSuccess?.(W,this),this.#G.config.onSettled?.(W,this.state.error,this),W}catch(W){if(W instanceof UX){if(W.silent)return this.#J.promise;else if(W.revert){if(this.state.data===void 0)throw W;return this.state.data}}throw this.#$({type:"error",error:W}),this.#G.config.onError?.(W,this),this.#G.config.onSettled?.(this.state.data,W,this),W}finally{this.scheduleGc()}}#$(X){let Y=(G)=>{switch(X.type){case"failed":return{...G,fetchFailureCount:X.failureCount,fetchFailureReason:X.error};case"pause":return{...G,fetchStatus:"paused"};case"continue":return{...G,fetchStatus:"fetching"};case"fetch":return{...G,...xX(G.data,this.options),fetchMeta:X.meta??null};case"success":let J={...G,...aX(X.data,X.dataUpdatedAt),dataUpdateCount:G.dataUpdateCount+1,...!X.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return this.#Y=X.manual?J:void 0,J;case"error":let Z=X.error;return{...G,error:Z,errorUpdateCount:G.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:G.fetchFailureCount+1,fetchFailureReason:Z,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...G,isInvalidated:!0};case"setState":return{...G,...X.state}}};this.state=Y(this.state),B.batch(()=>{this.observers.forEach((G)=>{G.onQueryUpdate()}),this.#G.notify({query:this,type:"updated",action:X})})}};function xX(X,Y){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:QX(Y.networkMode)?"fetching":"paused",...X===void 0&&{error:null,status:"pending"}}}function aX(X,Y){return{data:X,dataUpdatedAt:Y??Date.now(),error:null,isInvalidated:!1,status:"success"}}function oX(X){let Y=typeof X.initialData==="function"?X.initialData():X.initialData,G=Y!==void 0,J=G?typeof X.initialDataUpdatedAt==="function"?X.initialDataUpdatedAt():X.initialDataUpdatedAt:0;return{data:Y,dataUpdateCount:0,dataUpdatedAt:G?J??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:G?"success":"pending",fetchStatus:"idle"}}var SX=class extends M{constructor(X,Y){super();this.options=Y,this.#X=X,this.#$=null,this.#H=WX(),this.bindMethods(),this.setOptions(Y)}#X;#Y=void 0;#G=void 0;#Z=void 0;#J;#W;#H;#$;#B;#N;#L;#z;#V;#_;#U=new Set;bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){if(this.listeners.size===1){if(this.#Y.addObserver(this),tX(this.#Y,this.options))this.#A();else this.updateResult();this.#E()}}onUnsubscribe(){if(!this.hasListeners())this.destroy()}shouldFetchOnReconnect(){return jX(this.#Y,this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return jX(this.#Y,this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,this.#K(),this.#T(),this.#Y.removeObserver(this)}setOptions(X){let Y=this.options,G=this.#Y;if(this.options=this.#X.defaultQueryOptions(X),this.options.enabled!==void 0&&typeof this.options.enabled!=="boolean"&&typeof this.options.enabled!=="function"&&typeof j(this.options.enabled,this.#Y)!=="boolean")throw Error("Expected enabled to be a boolean or a callback that returns a boolean");if(this.#I(),this.#Y.setOptions(this.options),Y._defaulted&&!r(this.options,Y))this.#X.getQueryCache().notify({type:"observerOptionsUpdated",query:this.#Y,observer:this});let J=this.hasListeners();if(J&&eX(this.#Y,G,this.options,Y))this.#A();if(this.updateResult(),J&&(this.#Y!==G||j(this.options.enabled,this.#Y)!==j(Y.enabled,this.#Y)||C(this.options.staleTime,this.#Y)!==C(Y.staleTime,this.#Y)))this.#w();let Z=this.#D();if(J&&(this.#Y!==G||j(this.options.enabled,this.#Y)!==j(Y.enabled,this.#Y)||Z!==this.#_))this.#F(Z)}getOptimisticResult(X){let Y=this.#X.getQueryCache().build(this.#X,X),G=this.createResult(Y,X);if(jY(this,G))this.#Z=G,this.#W=this.options,this.#J=this.#Y.state;return G}getCurrentResult(){return this.#Z}trackResult(X,Y){return new Proxy(X,{get:(G,J)=>{if(this.trackProp(J),Y?.(J),J==="promise"){if(this.trackProp("data"),!this.options.experimental_prefetchInRender&&this.#H.status==="pending")this.#H.reject(Error("experimental_prefetchInRender feature flag is not enabled"))}return Reflect.get(G,J)}})}trackProp(X){this.#U.add(X)}getCurrentQuery(){return this.#Y}refetch({...X}={}){return this.fetch({...X})}fetchOptimistic(X){let Y=this.#X.defaultQueryOptions(X),G=this.#X.getQueryCache().build(this.#X,Y);return G.fetch().then(()=>this.createResult(G,Y))}fetch(X){return this.#A({...X,cancelRefetch:X.cancelRefetch??!0}).then(()=>{return this.updateResult(),this.#Z})}#A(X){this.#I();let Y=this.#Y.fetch(this.options,X);if(!X?.throwOnError)Y=Y.catch(F);return Y}#w(){this.#K();let X=C(this.options.staleTime,this.#Y);if(x||this.#Z.isStale||!JX(X))return;let G=VX(this.#Z.dataUpdatedAt,X)+1;this.#z=q.setTimeout(()=>{if(!this.#Z.isStale)this.updateResult()},G)}#D(){return(typeof this.options.refetchInterval==="function"?this.options.refetchInterval(this.#Y):this.options.refetchInterval)??!1}#F(X){if(this.#T(),this.#_=X,x||j(this.options.enabled,this.#Y)===!1||!JX(this.#_)||this.#_===0)return;this.#V=q.setInterval(()=>{if(this.options.refetchIntervalInBackground||e.isFocused())this.#A()},this.#_)}#E(){this.#w(),this.#F(this.#D())}#K(){if(this.#z)q.clearTimeout(this.#z),this.#z=void 0}#T(){if(this.#V)q.clearInterval(this.#V),this.#V=void 0}createResult(X,Y){let G=this.#Y,J=this.options,Z=this.#Z,H=this.#J,_=this.#W,A=X!==G?X.state:this.#G,{state:U}=X,z={...U},E=!1,N;if(Y._optimisticResults){let Q=this.hasListeners(),d=!Q&&tX(X,Y),i=Q&&eX(X,G,Y,J);if(d||i)z={...z,...xX(U.data,X.options)};if(Y._optimisticResults==="isRestoring")z.fetchStatus="idle"}let{error:K,errorUpdatedAt:w,status:L}=z;N=z.data;let P=!1;if(Y.placeholderData!==void 0&&N===void 0&&L==="pending"){let Q;if(Z?.isPlaceholderData&&Y.placeholderData===_?.placeholderData)Q=Z.data,P=!0;else Q=typeof Y.placeholderData==="function"?Y.placeholderData(this.#L?.state.data,this.#L):Y.placeholderData;if(Q!==void 0)L="success",N=$X(Z?.data,Q,Y),E=!0}if(Y.select&&N!==void 0&&!P)if(Z&&N===H?.data&&Y.select===this.#B)N=this.#N;else try{this.#B=Y.select,N=Y.select(N),N=$X(Z?.data,N,Y),this.#N=N,this.#$=null}catch(Q){this.#$=Q}if(this.#$)K=this.#$,N=this.#N,w=Date.now(),L="error";let k=z.fetchStatus==="fetching",S=L==="pending",R=L==="error",g=S&&k,b=N!==void 0,O={status:L,fetchStatus:z.fetchStatus,isPending:S,isSuccess:L==="success",isError:R,isInitialLoading:g,isLoading:g,data:N,dataUpdatedAt:z.dataUpdatedAt,error:K,errorUpdatedAt:w,failureCount:z.fetchFailureCount,failureReason:z.fetchFailureReason,errorUpdateCount:z.errorUpdateCount,isFetched:z.dataUpdateCount>0||z.errorUpdateCount>0,isFetchedAfterMount:z.dataUpdateCount>A.dataUpdateCount||z.errorUpdateCount>A.errorUpdateCount,isFetching:k,isRefetching:k&&!S,isLoadingError:R&&!b,isPaused:z.fetchStatus==="paused",isPlaceholderData:E,isRefetchError:R&&b,isStale:MX(X,Y),refetch:this.refetch,promise:this.#H,isEnabled:j(Y.enabled,X)!==!1};if(this.options.experimental_prefetchInRender){let Q=O.data!==void 0,d=O.status==="error"&&!Q,i=(n)=>{if(d)n.reject(O.error);else if(Q)n.resolve(O.data)},s=()=>{let n=this.#H=O.promise=WX();i(n)},y=this.#H;switch(y.status){case"pending":if(X.queryHash===G.queryHash)i(y);break;case"fulfilled":if(d||O.data!==y.value)s();break;case"rejected":if(!d||O.error!==y.reason)s();break}}return O}updateResult(){let X=this.#Z,Y=this.createResult(this.#Y,this.options);if(this.#J=this.#Y.state,this.#W=this.options,this.#J.data!==void 0)this.#L=this.#Y;if(r(Y,X))return;this.#Z=Y;let G=()=>{if(!X)return!0;let{notifyOnChangeProps:J}=this.options,Z=typeof J==="function"?J():J;if(Z==="all"||!Z&&!this.#U.size)return!0;let H=new Set(Z??this.#U);if(this.options.throwOnError)H.add("error");return Object.keys(this.#Z).some((_)=>{let W=_;return this.#Z[W]!==X[W]&&H.has(W)})};this.#P({listeners:G()})}#I(){let X=this.#X.getQueryCache().build(this.#X,this.options);if(X===this.#Y)return;let Y=this.#Y;if(this.#Y=X,this.#G=X.state,this.hasListeners())Y?.removeObserver(this),X.addObserver(this)}onQueryUpdate(){if(this.updateResult(),this.hasListeners())this.#E()}#P(X){B.batch(()=>{if(X.listeners)this.listeners.forEach((Y)=>{Y(this.#Z)});this.#X.getQueryCache().notify({query:this.#Y,type:"observerResultsUpdated"})})}};function xY(X,Y){return j(Y.enabled,X)!==!1&&X.state.data===void 0&&!(X.state.status==="error"&&Y.retryOnMount===!1)}function tX(X,Y){return xY(X,Y)||X.state.data!==void 0&&jX(X,Y,Y.refetchOnMount)}function jX(X,Y,G){if(j(Y.enabled,X)!==!1&&C(Y.staleTime,X)!=="static"){let J=typeof G==="function"?G(X):G;return J==="always"||J!==!1&&MX(X,Y)}return!1}function eX(X,Y,G,J){return(X!==Y||j(J.enabled,X)===!1)&&(!G.suspense||X.state.status!=="error")&&MX(X,G)}function MX(X,Y){return j(Y.enabled,X)!==!1&&X.isStaleByTime(C(Y.staleTime,X))}function jY(X,Y){if(!r(X.getCurrentResult(),Y))return!0;return!1}function RX(X){return{onFetch:(Y,G)=>{let J=Y.options,Z=Y.fetchOptions?.meta?.fetchMore?.direction,H=Y.state.data?.pages||[],_=Y.state.data?.pageParams||[],W={pages:[],pageParams:[]},A=0,U=async()=>{let z=!1,E=(w)=>{sX(w,()=>Y.signal,()=>z=!0)},N=LX(Y.options,Y.fetchOptions),K=async(w,L,P)=>{if(z)return Promise.reject();if(L==null&&w.pages.length)return Promise.resolve(w);let S=(()=>{let YX={client:Y.client,queryKey:Y.queryKey,pageParam:L,direction:P?"backward":"forward",meta:Y.options.meta};return E(YX),YX})(),R=await N(S),{maxPages:g}=Y.options,b=P?iX:uX;return{pages:b(w.pages,R,g),pageParams:b(w.pageParams,L,g)}};if(Z&&H.length){let w=Z==="backward",L=w?SY:XY,P={pages:H,pageParams:_},k=L(J,P);W=await K(P,k,w)}else{let w=X??H.length;do{let L=A===0?_[0]??J.initialPageParam:XY(J,W);if(A>0&&L==null)break;W=await K(W,L),A++}while(A<w)}return W};if(Y.options.persister)Y.fetchFn=()=>{return Y.options.persister?.(U,{client:Y.client,queryKey:Y.queryKey,meta:Y.options.meta,signal:Y.signal},G)};else Y.fetchFn=U}}}function XY(X,{pages:Y,pageParams:G}){let J=Y.length-1;return Y.length>0?X.getNextPageParam(Y[J],Y,G[J],G):void 0}function SY(X,{pages:Y,pageParams:G}){return Y.length>0?X.getPreviousPageParam?.(Y[0],Y,G[0],G):void 0}var YY=class extends wX{#X;#Y;#G;#Z;constructor(X){super();this.#X=X.client,this.mutationId=X.mutationId,this.#G=X.mutationCache,this.#Y=[],this.state=X.state||CX(),this.setOptions(X.options),this.scheduleGc()}setOptions(X){this.options=X,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(X){if(!this.#Y.includes(X))this.#Y.push(X),this.clearGcTimeout(),this.#G.notify({type:"observerAdded",mutation:this,observer:X})}removeObserver(X){this.#Y=this.#Y.filter((Y)=>Y!==X),this.scheduleGc(),this.#G.notify({type:"observerRemoved",mutation:this,observer:X})}optionalRemove(){if(!this.#Y.length)if(this.state.status==="pending")this.scheduleGc();else this.#G.remove(this)}continue(){return this.#Z?.continue()??this.execute(this.state.variables)}async execute(X){let Y=()=>{this.#J({type:"continue"})},G={client:this.#X,meta:this.options.meta,mutationKey:this.options.mutationKey};this.#Z=BX({fn:()=>{if(!this.options.mutationFn)return Promise.reject(Error("No mutationFn found"));return this.options.mutationFn(X,G)},onFail:(H,_)=>{this.#J({type:"failed",failureCount:H,error:_})},onPause:()=>{this.#J({type:"pause"})},onContinue:Y,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>this.#G.canRun(this)});let J=this.state.status==="pending",Z=!this.#Z.canStart();try{if(J)Y();else{if(this.#J({type:"pending",variables:X,isPaused:Z}),this.#G.config.onMutate)await this.#G.config.onMutate(X,this,G);let _=await this.options.onMutate?.(X,G);if(_!==this.state.context)this.#J({type:"pending",context:_,variables:X,isPaused:Z})}let H=await this.#Z.start();return await this.#G.config.onSuccess?.(H,X,this.state.context,this,G),await this.options.onSuccess?.(H,X,this.state.context,G),await this.#G.config.onSettled?.(H,null,this.state.variables,this.state.context,this,G),await this.options.onSettled?.(H,null,X,this.state.context,G),this.#J({type:"success",data:H}),H}catch(H){try{await this.#G.config.onError?.(H,X,this.state.context,this,G)}catch(_){Promise.reject(_)}try{await this.options.onError?.(H,X,this.state.context,G)}catch(_){Promise.reject(_)}try{await this.#G.config.onSettled?.(void 0,H,this.state.variables,this.state.context,this,G)}catch(_){Promise.reject(_)}try{await this.options.onSettled?.(void 0,H,X,this.state.context,G)}catch(_){Promise.reject(_)}throw this.#J({type:"error",error:H}),H}finally{this.#G.runNext(this)}}#J(X){let Y=(G)=>{switch(X.type){case"failed":return{...G,failureCount:X.failureCount,failureReason:X.error};case"pause":return{...G,isPaused:!0};case"continue":return{...G,isPaused:!1};case"pending":return{...G,context:X.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:X.isPaused,status:"pending",variables:X.variables,submittedAt:Date.now()};case"success":return{...G,data:X.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...G,data:void 0,error:X.error,failureCount:G.failureCount+1,failureReason:X.error,isPaused:!1,status:"error"}}};this.state=Y(this.state),B.batch(()=>{this.#Y.forEach((G)=>{G.onMutationUpdate(X)}),this.#G.notify({mutation:this,type:"updated",action:X})})}};function CX(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var GY=class extends M{constructor(X={}){super();this.config=X,this.#X=new Set,this.#Y=new Map,this.#G=0}#X;#Y;#G;build(X,Y,G){let J=new YY({client:X,mutationCache:this,mutationId:++this.#G,options:X.defaultMutationOptions(Y),state:G});return this.add(J),J}add(X){this.#X.add(X);let Y=DX(X);if(typeof Y==="string"){let G=this.#Y.get(Y);if(G)G.push(X);else this.#Y.set(Y,[X])}this.notify({type:"added",mutation:X})}remove(X){if(this.#X.delete(X)){let Y=DX(X);if(typeof Y==="string"){let G=this.#Y.get(Y);if(G){if(G.length>1){let J=G.indexOf(X);if(J!==-1)G.splice(J,1)}else if(G[0]===X)this.#Y.delete(Y)}}}this.notify({type:"removed",mutation:X})}canRun(X){let Y=DX(X);if(typeof Y==="string"){let J=this.#Y.get(Y)?.find((Z)=>Z.state.status==="pending");return!J||J===X}else return!0}runNext(X){let Y=DX(X);if(typeof Y==="string")return this.#Y.get(Y)?.find((J)=>J!==X&&J.state.isPaused)?.continue()??Promise.resolve();else return Promise.resolve()}clear(){B.batch(()=>{this.#X.forEach((X)=>{this.notify({type:"removed",mutation:X})}),this.#X.clear(),this.#Y.clear()})}getAll(){return Array.from(this.#X)}find(X){let Y={exact:!0,...X};return this.getAll().find((G)=>NX(Y,G))}findAll(X={}){return this.getAll().filter((Y)=>NX(X,Y))}notify(X){B.batch(()=>{this.listeners.forEach((Y)=>{Y(X)})})}resumePausedMutations(){let X=this.getAll().filter((Y)=>Y.state.isPaused);return B.batch(()=>Promise.all(X.map((Y)=>Y.continue().catch(F))))}};function DX(X){return X.options.scope?.id}var OX=class extends M{#X;#Y=void 0;#G;#Z;constructor(X,Y){super();this.#X=X,this.setOptions(Y),this.bindMethods(),this.#J()}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(X){let Y=this.options;if(this.options=this.#X.defaultMutationOptions(X),!r(this.options,Y))this.#X.getMutationCache().notify({type:"observerOptionsUpdated",mutation:this.#G,observer:this});if(Y?.mutationKey&&this.options.mutationKey&&v(Y.mutationKey)!==v(this.options.mutationKey))this.reset();else if(this.#G?.state.status==="pending")this.#G.setOptions(this.options)}onUnsubscribe(){if(!this.hasListeners())this.#G?.removeObserver(this)}onMutationUpdate(X){this.#J(),this.#W(X)}getCurrentResult(){return this.#Y}reset(){this.#G?.removeObserver(this),this.#G=void 0,this.#J(),this.#W()}mutate(X,Y){return this.#Z=Y,this.#G?.removeObserver(this),this.#G=this.#X.getMutationCache().build(this.#X,this.options),this.#G.addObserver(this),this.#G.execute(X)}#J(){let X=this.#G?.state??CX();this.#Y={...X,isPending:X.status==="pending",isSuccess:X.status==="success",isError:X.status==="error",isIdle:X.status==="idle",mutate:this.mutate,reset:this.reset}}#W(X){B.batch(()=>{if(this.#Z&&this.hasListeners()){let Y=this.#Y.variables,G=this.#Y.context,J={client:this.#X,meta:this.options.meta,mutationKey:this.options.mutationKey};if(X?.type==="success"){try{this.#Z.onSuccess?.(X.data,Y,G,J)}catch(Z){Promise.reject(Z)}try{this.#Z.onSettled?.(X.data,null,Y,G,J)}catch(Z){Promise.reject(Z)}}else if(X?.type==="error"){try{this.#Z.onError?.(X.error,Y,G,J)}catch(Z){Promise.reject(Z)}try{this.#Z.onSettled?.(void 0,X.error,Y,G,J)}catch(Z){Promise.reject(Z)}}}this.listeners.forEach((Y)=>{Y(this.#Y)})})}};var JY=class extends M{constructor(X={}){super();this.config=X,this.#X=new Map}#X;build(X,Y,G){let J=Y.queryKey,Z=Y.queryHash??ZX(J,Y),H=this.get(Z);if(!H)H=new rX({client:X,queryKey:J,queryHash:Z,options:X.defaultQueryOptions(Y),state:G,defaultOptions:X.getQueryDefaults(J)}),this.add(H);return H}add(X){if(!this.#X.has(X.queryHash))this.#X.set(X.queryHash,X),this.notify({type:"added",query:X})}remove(X){let Y=this.#X.get(X.queryHash);if(Y){if(X.destroy(),Y===X)this.#X.delete(X.queryHash);this.notify({type:"removed",query:X})}}clear(){B.batch(()=>{this.getAll().forEach((X)=>{this.remove(X)})})}get(X){return this.#X.get(X)}getAll(){return[...this.#X.values()]}find(X){let Y={exact:!0,...X};return this.getAll().find((G)=>AX(Y,G))}findAll(X={}){let Y=this.getAll();return Object.keys(X).length>0?Y.filter((G)=>AX(X,G)):Y}notify(X){B.batch(()=>{this.listeners.forEach((Y)=>{Y(X)})})}onFocus(){B.batch(()=>{this.getAll().forEach((X)=>{X.onFocus()})})}onOnline(){B.batch(()=>{this.getAll().forEach((X)=>{X.onOnline()})})}};var MY=class{#X;#Y;#G;#Z;#J;#W;#H;#$;constructor(X={}){this.#X=X.queryCache||new JY,this.#Y=X.mutationCache||new GY,this.#G=X.defaultOptions||{},this.#Z=new Map,this.#J=new Map,this.#W=0}mount(){if(this.#W++,this.#W!==1)return;this.#H=e.subscribe(async(X)=>{if(X)await this.resumePausedMutations(),this.#X.onFocus()}),this.#$=XX.subscribe(async(X)=>{if(X)await this.resumePausedMutations(),this.#X.onOnline()})}unmount(){if(this.#W--,this.#W!==0)return;this.#H?.(),this.#H=void 0,this.#$?.(),this.#$=void 0}isFetching(X){return this.#X.findAll({...X,fetchStatus:"fetching"}).length}isMutating(X){return this.#Y.findAll({...X,status:"pending"}).length}getQueryData(X){let Y=this.defaultQueryOptions({queryKey:X});return this.#X.get(Y.queryHash)?.state.data}ensureQueryData(X){let Y=this.defaultQueryOptions(X),G=this.#X.build(this,Y),J=G.state.data;if(J===void 0)return this.fetchQuery(X);if(X.revalidateIfStale&&G.isStaleByTime(C(Y.staleTime,G)))this.prefetchQuery(Y);return Promise.resolve(J)}getQueriesData(X){return this.#X.findAll(X).map(({queryKey:Y,state:G})=>{let J=G.data;return[Y,J]})}setQueryData(X,Y,G){let J=this.defaultQueryOptions({queryKey:X}),H=this.#X.get(J.queryHash)?.state.data,_=cX(Y,H);if(_===void 0)return;return this.#X.build(this,J).setData(_,{...G,manual:!0})}setQueriesData(X,Y,G){return B.batch(()=>this.#X.findAll(X).map(({queryKey:J})=>[J,this.setQueryData(J,Y,G)]))}getQueryState(X){let Y=this.defaultQueryOptions({queryKey:X});return this.#X.get(Y.queryHash)?.state}removeQueries(X){let Y=this.#X;B.batch(()=>{Y.findAll(X).forEach((G)=>{Y.remove(G)})})}resetQueries(X,Y){let G=this.#X;return B.batch(()=>{return G.findAll(X).forEach((J)=>{J.reset()}),this.refetchQueries({type:"active",...X},Y)})}cancelQueries(X,Y={}){let G={revert:!0,...Y},J=B.batch(()=>this.#X.findAll(X).map((Z)=>Z.cancel(G)));return Promise.all(J).then(F).catch(F)}invalidateQueries(X,Y={}){return B.batch(()=>{if(this.#X.findAll(X).forEach((G)=>{G.invalidate()}),X?.refetchType==="none")return Promise.resolve();return this.refetchQueries({...X,type:X?.refetchType??X?.type??"active"},Y)})}refetchQueries(X,Y={}){let G={...Y,cancelRefetch:Y.cancelRefetch??!0},J=B.batch(()=>this.#X.findAll(X).filter((Z)=>!Z.isDisabled()&&!Z.isStatic()).map((Z)=>{let H=Z.fetch(void 0,G);if(!G.throwOnError)H=H.catch(F);return Z.state.fetchStatus==="paused"?Promise.resolve():H}));return Promise.all(J).then(F)}fetchQuery(X){let Y=this.defaultQueryOptions(X);if(Y.retry===void 0)Y.retry=!1;let G=this.#X.build(this,Y);return G.isStaleByTime(C(Y.staleTime,G))?G.fetch(Y):Promise.resolve(G.state.data)}prefetchQuery(X){return this.fetchQuery(X).then(F).catch(F)}fetchInfiniteQuery(X){return X.behavior=RX(X.pages),this.fetchQuery(X)}prefetchInfiniteQuery(X){return this.fetchInfiniteQuery(X).then(F).catch(F)}ensureInfiniteQueryData(X){return X.behavior=RX(X.pages),this.ensureQueryData(X)}resumePausedMutations(){if(XX.isOnline())return this.#Y.resumePausedMutations();return Promise.resolve()}getQueryCache(){return this.#X}getMutationCache(){return this.#Y}getDefaultOptions(){return this.#G}setDefaultOptions(X){this.#G=X}setQueryDefaults(X,Y){this.#Z.set(v(X),{queryKey:X,defaultOptions:Y})}getQueryDefaults(X){let Y=[...this.#Z.values()],G={};return Y.forEach((J)=>{if(u(X,J.queryKey))Object.assign(G,J.defaultOptions)}),G}setMutationDefaults(X,Y){this.#J.set(v(X),{mutationKey:X,defaultOptions:Y})}getMutationDefaults(X){let Y=[...this.#J.values()],G={};return Y.forEach((J)=>{if(u(X,J.mutationKey))Object.assign(G,J.defaultOptions)}),G}defaultQueryOptions(X){if(X._defaulted)return X;let Y={...this.#G.queries,...this.getQueryDefaults(X.queryKey),...X,_defaulted:!0};if(!Y.queryHash)Y.queryHash=ZX(Y.queryKey,Y);if(Y.refetchOnReconnect===void 0)Y.refetchOnReconnect=Y.networkMode!=="always";if(Y.throwOnError===void 0)Y.throwOnError=!!Y.suspense;if(!Y.networkMode&&Y.persister)Y.networkMode="offlineFirst";if(Y.queryFn===l)Y.enabled=!1;return Y}defaultMutationOptions(X){if(X?._defaulted)return X;return{...this.#G.mutations,...X?.mutationKey&&this.getMutationDefaults(X.mutationKey),...X,_defaulted:!0}}clear(){this.#X.clear(),this.#Y.clear()}};var f=h(c(),1);var HX=h(c(),1),RY=h(IX(),1);function CY(){let X=!1;return{clearReset:()=>{X=!1},reset:()=>{X=!0},isReset:()=>{return X}}}var OY=HX.createContext(CY()),ZY=()=>HX.useContext(OY);var $Y=h(c(),1);var WY=(X,Y,G)=>{let J=G?.state.error&&typeof X.throwOnError==="function"?t(X.throwOnError,[G.state.error,G]):X.throwOnError;if(X.suspense||X.experimental_prefetchInRender||J){if(!Y.isReset())X.retryOnMount=!1}},HY=(X)=>{$Y.useEffect(()=>{X.clearReset()},[X])},_Y=({result:X,errorResetBoundary:Y,throwOnError:G,query:J,suspense:Z})=>{return X.isError&&!Y.isReset()&&!X.isFetching&&J&&(Z&&X.data===void 0||t(G,[X.error,J]))};var FX=h(c(),1),zY=FX.createContext(!1),VY=()=>FX.useContext(zY),K2=zY.Provider;var AY=(X)=>{if(X.suspense){let G=(Z)=>Z==="static"?Z:Math.max(Z??1000,1000),J=X.staleTime;if(X.staleTime=typeof J==="function"?(...Z)=>G(J(...Z)):G(J),typeof X.gcTime==="number")X.gcTime=Math.max(X.gcTime,1000)}},NY=(X,Y)=>X.isLoading&&X.isFetching&&!Y,LY=(X,Y)=>X?.suspense&&Y.isPending,qX=(X,Y,G)=>Y.fetchOptimistic(X).catch(()=>{G.clearReset()});function UY(X,Y,G){if(typeof X!=="object"||Array.isArray(X))throw Error('Bad argument type. Starting with v5, only the "Object" form is allowed when calling query related functions. Please use the error stack to find the culprit call. More info here: https://tanstack.com/query/latest/docs/react/guides/migrating-to-v5#supports-a-single-signature-one-object');let J=VY(),Z=ZY(),H=GX(G),_=H.defaultQueryOptions(X);H.getDefaultOptions().queries?._experimental_beforeQuery?.(_);let W=H.getQueryCache().get(_.queryHash);if(!_.queryFn)console.error(`[${_.queryHash}]: No queryFn was passed as an option, and no default queryFn was found. The queryFn parameter is only optional when using a default queryFn. More info here: https://tanstack.com/query/latest/docs/framework/react/guides/default-query-function`);_._optimisticResults=J?"isRestoring":"optimistic",AY(_),WY(_,Z,W),HY(Z);let A=!H.getQueryCache().get(_.queryHash),[U]=f.useState(()=>new Y(H,_)),z=U.getOptimisticResult(_),E=!J&&X.subscribed!==!1;if(f.useSyncExternalStore(f.useCallback((N)=>{let K=E?U.subscribe(B.batchCalls(N)):F;return U.updateResult(),K},[U,E]),()=>U.getCurrentResult(),()=>U.getCurrentResult()),f.useEffect(()=>{U.setOptions(_)},[_,U]),LY(_,z))throw qX(_,U,Z);if(_Y({result:z,errorResetBoundary:Z,throwOnError:_.throwOnError,query:W,suspense:_.suspense}))throw z.error;if(H.getDefaultOptions().queries?._experimental_afterQuery?.(_,z),_.experimental_prefetchInRender&&!x&&NY(z,J))(A?qX(_,U,Z):W?.promise)?.catch(F).finally(()=>{U.updateResult()});return!_.notifyOnChangeProps?U.trackResult(z):z}function qY(X,Y){return UY(X,SX,Y)}var m=h(c(),1);function vY(X,Y){let G=GX(Y),[J]=m.useState(()=>new OX(G,X));m.useEffect(()=>{J.setOptions(X)},[J,X]);let Z=m.useSyncExternalStore(m.useCallback((_)=>J.subscribe(B.batchCalls(_)),[J]),()=>J.getCurrentResult(),()=>J.getCurrentResult()),H=m.useCallback((_,W)=>{J.mutate(_,W).catch(F)},[J]);if(Z.error&&t(J.options.throwOnError,[Z.error]))throw Z.error;return{...Z,mutate:H,mutateAsync:Z.mutate}}var T4={config:{all:["config"],detail:()=>["config","detail"]},providers:{all:["providers"],list:()=>["providers","list"],detail:(X)=>["providers","detail",X]},models:{all:["models"],list:(X)=>["models","list",X],available:()=>["models","available"]},skills:{all:["skills"],list:()=>["skills","list"],detail:(X)=>["skills","detail",X]},tasks:{all:["tasks"],list:(X)=>["tasks","list",X],detail:(X)=>["tasks","detail",X]},history:{all:["history"],list:()=>["history","list"],detail:(X)=>["history","detail",X]},knowledge:{all:["knowledge"],memories:()=>["knowledge","memories"],skills:()=>["knowledge","skills"]},agents:{all:["agents"],list:()=>["agents","list"],detail:(X)=>["agents","detail",X]},mcp:{all:["mcp"],config:()=>["mcp","config"]},errors:{all:["errors"],list:()=>["errors","list"],stats:()=>["errors","stats"]}};
7
- export{MY as S,IX as T,GX as U,FY as V,qY as W,vY as X,T4 as Y};
@@ -1,2 +0,0 @@
1
- import{C as r}from"./chunk-yzv3n8mw.js";import{ng as c,og as h}from"./chunk-9tgp14v7.js";import{Fg as u,Hg as S,Xg as l,Zg as i,_g as s,ah as n,bh as o,ch as d}from"./chunk-hz9yw7cs.js";import{ki as g,kj as p}from"./chunk-tn356gwf.js";import{Cl as N,El as WY}from"./chunk-arv4h3h1.js";import{Kl as L}from"./chunk-z3e4c424.js";WY();var PY=(Y)=>{let Z=Y.goto!=null&&!Array.isArray(Y.goto)?[Y.goto]:Y.goto;return new h({goto:Z?.map(($)=>{if(typeof $!=="string")return new c($.node,$.input);return $}),update:Y.update??void 0,resume:Y.resume})},I="[...]",QY="[Circular]",G=[],x=[];function zY(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function OY(Y,Z,$,J){if(typeof J>"u")J=zY();f(Y,"",0,[],void 0,0,J);var H;try{if(x.length===0)H=JSON.stringify(Y,Z,$);else H=JSON.stringify(Y,KY(Z),$)}catch(U){return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]")}finally{while(G.length!==0){var X=G.pop();if(X.length===4)Object.defineProperty(X[0],X[1],X[3]);else X[0][X[1]]=X[2]}}return H}function w(Y,Z,$,J){var H=Object.getOwnPropertyDescriptor(J,$);if(H.get!==void 0)if(H.configurable)Object.defineProperty(J,$,{value:Y}),G.push([J,$,Z,H]);else x.push([Z,$,Y]);else J[$]=Y,G.push([J,$,Z])}function f(Y,Z,$,J,H,X,U){X+=1;var W;if(typeof Y==="object"&&Y!==null){for(W=0;W<J.length;W++)if(J[W]===Y){w(QY,Y,Z,H);return}if(typeof U.depthLimit<"u"&&X>U.depthLimit){w(I,Y,Z,H);return}if(typeof U.edgesLimit<"u"&&$+1>U.edgesLimit){w(I,Y,Z,H);return}if(J.push(Y),Array.isArray(Y))for(W=0;W<Y.length;W++)f(Y[W],W,W,J,Y,X,U);else{var P=Object.keys(Y);for(W=0;W<P.length;W++){var z=P[W];f(Y[z],z,W,J,Y,X,U)}}J.pop()}}function KY(Y){return Y=typeof Y<"u"?Y:function(Z,$){return $},function(Z,$){if(x.length>0)for(var J=0;J<x.length;J++){var H=x[J];if(H[1]===Z&&H[0]===$){$=H[2],x.splice(J,1);break}}return Y.call(this,Z,$)}}function VY(Y){return Y!==null&&Y.lc===1&&Y.type==="constructor"&&Array.isArray(Y.id)}async function q(Y){if(Y&&typeof Y==="object")if(Array.isArray(Y))return await Promise.all(Y.map(($)=>q($)));else{let Z={};for(let[$,J]of Object.entries(Y))Z[$]=await q(J);if(Z.lc===2&&Z.type==="undefined")return;else if(Z.lc===2&&Z.type==="constructor"&&Array.isArray(Z.id))try{let $=Z.id[Z.id.length-1],J;switch($){case"Set":J=Set;break;case"Map":J=Map;break;case"RegExp":J=RegExp;break;case"Error":J=Error;break;default:return Z}if(Z.method)return J[Z.method](...Z.args||[]);else return new J(...Z.args||[])}catch($){return Z}else if(VY(Z))return l(JSON.stringify(Z));return Z}return Y}function M(Y,Z,$,J){return{lc:2,type:"constructor",id:[Y.name],method:Z??null,args:$??[],kwargs:J??{}}}function FY(Y){if(Y===void 0)return{lc:2,type:"undefined"};else if(Y instanceof Set||Y instanceof Map)return M(Y.constructor,void 0,[Array.from(Y)]);else if(Y instanceof RegExp)return M(RegExp,void 0,[Y.source,Y.flags]);else if(Y instanceof Error)return M(Y.constructor,void 0,[Y.message]);else if(Y?.lg_name==="Send")return{node:Y.node,args:Y.args};else return Y}class t{_dumps(Y){return new TextEncoder().encode(OY(Y,($,J)=>{return FY(J)}))}async dumpsTyped(Y){if(Y instanceof Uint8Array)return["bytes",Y];else return["json",this._dumps(Y)]}async _loads(Y){let Z=JSON.parse(Y);return q(Z)}async loadsTyped(Y,Z){if(Y==="bytes")return typeof Z==="string"?new TextEncoder().encode(Z):Z;else if(Y==="json")return this._loads(typeof Z==="string"?Z:new TextDecoder().decode(Z));else throw Error(`Unknown serialization type: ${Y}`)}}class a extends r.default{constructor(Y,Z=!0,$=300){super();this.id=Y,this.compressMessages=Z,this.ttl=$}serializer=new t;async encodeData(Y){let[Z,$]=await this.serializer.dumpsTyped(Y);return $}async decodeData(Y){return await this.serializer.loadsTyped("json",Y)}}class e{queues=new Map;defaultCompressMessages;queueConstructor;constructor(Y,Z={}){this.defaultCompressMessages=Z.defaultCompressMessages??!0,this.queueConstructor=Y}createQueue(Y,Z=300){return this.queues.set(Y,new this.queueConstructor(Y,this.defaultCompressMessages,Z)),this.queues.get(Y)}async getQueue(Y){let Z=this.queues.get(Y);if(!Z)if(await this.queueConstructor?.isQueueExist?.(Y))return this.createQueue(Y);else throw Error(`Queue with id '${Y}' does not exist`);return Z}async cancelQueue(Y){await this.removeQueue(Y)}async pushToQueue(Y,Z){await(await this.getQueue(Y)).push(Z)}async getQueueData(Y){let Z=this.queues.get(Y);if(!Z)throw Error(`Queue with id '${Y}' does not exist`);return await Z.getAll()}async clearQueue(Y){let Z=this.queues.get(Y);if(Z){let $=Z.clear();if($ instanceof Promise)await $}}async removeQueue(Y){let Z=this.queues.get(Y);if(!Z)return!1;try{await Z.cancel()}catch($){console.error("Error cancelling queue:",$)}try{let $=Z.clear();if($ instanceof Promise)await $}catch($){console.error("Error clearing queue:",$)}if(typeof Z.destroy==="function")try{await Z.destroy()}catch($){console.error("Error destroying queue:",$)}return this.queues.delete(Y)}getAllQueueIds(){return Array.from(this.queues.keys())}async getAllQueuesData(){let Y={};for(let[Z,$]of this.queues)Y[Z]=await $.getAll();return Y}clearAllQueues(){for(let Y of this.queues.values())Y.clear()}async copyQueue(Y,Z,$){let H=await(await this.getQueue(Y)).copyToQueue(Z,$);return this.queues.set(Z,H),H}}var E={};async function wY(Y,Z){E[Y]=Z}async function YY(Y,Z,$){if(!E[Y])throw Error(`Graph "${Y}" not found`);let J=typeof E[Y]==="function"?await E[Y](Z??{configurable:{}}):E[Y];if(typeof $?.checkpointer<"u")J.checkpointer=$?.checkpointer??D.globalCheckPointer;else J.checkpointer=D.globalCheckPointer;return J.store=$?.store??void 0,J}class b{db;adapter;constructor(Y){this.db=Y.db,this.adapter=Y}async setup(){await this.adapter.createTables(this.db),await this.adapter.createIndexes(this.db)}async create(Y){let Z=Y?.threadId||N(),$=new Date,J=Y?.metadata||{},H={};if(Y?.ifExists==="raise"){if(await this.db.selectFrom("threads").select("thread_id").where("thread_id","=",Z).executeTakeFirst())throw Error(`Thread with ID ${Z} already exists.`)}if(Y?.ifExists==="do_nothing"&&Y?.threadId){let X=await this.db.selectFrom("threads").selectAll().where("thread_id","=",Z).executeTakeFirst();if(X)return{thread_id:X.thread_id,created_at:this.adapter.dbToDate(X.created_at).toISOString(),updated_at:this.adapter.dbToDate(X.updated_at).toISOString(),state_updated_at:this.adapter.dbToDate(X.updated_at).toISOString(),metadata:this.adapter.dbToJson(X.metadata),status:X.status,values:X.values?this.adapter.dbToJson(X.values):null,interrupts:this.adapter.dbToJson(X.interrupts),title:X.title}}return await this.db.insertInto("threads").values({thread_id:Z,created_at:this.adapter.dateToDb($),updated_at:this.adapter.dateToDb($),metadata:this.adapter.jsonToDb(J),status:"idle",values:null,interrupts:this.adapter.jsonToDb(H)}).execute(),{thread_id:Z,created_at:$.toISOString(),updated_at:$.toISOString(),state_updated_at:$.toISOString(),metadata:J,status:"idle",values:null,interrupts:H,title:null}}async search(Y){let Z=this.db.selectFrom("threads"),$;if(Y?.select)$=new Set(Y.select);else if(Y?.withoutDetails)$=new Set(["thread_id","created_at","updated_at","metadata","status","title"]);else $=new Set(["thread_id","created_at","updated_at","metadata","status","values","interrupts","title"]);let J=[];if($.has("thread_id"))J.push("thread_id");if($.has("created_at"))J.push("created_at");if($.has("updated_at"))J.push("updated_at");if($.has("metadata"))J.push("metadata");if($.has("status"))J.push("status");if($.has("values"))J.push("values");if($.has("interrupts"))J.push("interrupts");if($.has("title"))J.push("title");if(J.length>0)Z=Z.select(J);else Z=Z.selectAll();if(Y?.ids&&Y.ids.length>0)Z=Z.where("thread_id","in",Y.ids);if(Y?.status)Z=Z.where("status","=",Y.status);if(Y?.metadata)for(let[X,U]of Object.entries(Y.metadata))Z=Z.where(this.adapter.buildJsonQuery(this.db,"metadata",X,U));if(Y?.values)Z=Z.where((X)=>{return X("values","=",this.adapter.jsonToDb(Y.values))});if(Y?.sortBy){let X=Y.sortOrder==="desc"?"desc":"asc";Z=Z.orderBy(Y.sortBy,X)}if(Y?.limit!==void 0){if(Z=Z.limit(Y.limit),Y?.offset!==void 0)Z=Z.offset(Y.offset)}return(await Z.execute()).map((X)=>{let U={thread_id:X.thread_id};if($.has("created_at"))U.created_at=this.adapter.dbToDate(X.created_at).toISOString();if($.has("updated_at"))U.updated_at=this.adapter.dbToDate(X.updated_at).toISOString();if($.has("metadata"))U.metadata=this.adapter.dbToJson(X.metadata);if($.has("status"))U.status=X.status;if($.has("values"))U.values=X.values?this.adapter.dbToJson(X.values):null;if($.has("interrupts"))U.interrupts=this.adapter.dbToJson(X.interrupts);if($.has("title"))U.title=X.title;return U})}async get(Y){let Z=await this.db.selectFrom("threads").selectAll().where("thread_id","=",Y).executeTakeFirst();if(!Z)throw Error(`Thread with ID ${Y} not found.`);return{thread_id:Z.thread_id,created_at:this.adapter.dbToDate(Z.created_at).toISOString(),updated_at:this.adapter.dbToDate(Z.updated_at).toISOString(),state_updated_at:this.adapter.dbToDate(Z.updated_at).toISOString(),metadata:this.adapter.dbToJson(Z.metadata),status:Z.status,values:Z.values?this.adapter.dbToJson(Z.values):null,interrupts:this.adapter.dbToJson(Z.interrupts),title:Z.title}}async set(Y,Z){if(!await this.db.selectFrom("threads").select("thread_id").where("thread_id","=",Y).executeTakeFirst())throw Error(`Thread with ID ${Y} not found.`);let J={updated_at:this.adapter.dateToDb(new Date)};if(Z.metadata!==void 0)J.metadata=this.adapter.jsonToDb(Z.metadata);if(Z.status!==void 0)J.status=Z.status;if(Z.values!==void 0)J.values=Z.values?this.adapter.jsonToDb(Z.values):null;if(Z.interrupts!==void 0)J.interrupts=this.adapter.jsonToDb(Z.interrupts);if(Z.title!==void 0)J.title=Z.title;await this.db.updateTable("threads").set(J).where("thread_id","=",Y).execute()}async delete(Y){if((await this.db.deleteFrom("threads").where("thread_id","=",Y).executeTakeFirst()).numDeletedRows===0n)throw Error(`Thread with ID ${Y} not found.`)}async updateState(Y,Z){let $=await this.get(Y);if($.status==="busy")throw Error(`Thread with ID ${Y} is busy, can't update state.`);let J=$.metadata?.graph_id;if(!J)return await this.set(Y,{values:Z.values??null}),{configurable:{thread_id:Y}};let H={configurable:{thread_id:Y,graph_id:J}},X=await YY(J,H),U=await X.updateState(H,Z.values),W=await X.getState(H);return await this.set(Y,{values:JSON.parse(C(W.values))}),U}async createRun(Y,Z,$){let J=N(),H=new Date,X=$?.metadata??{};return await this.db.insertInto("runs").values({run_id:J,thread_id:Y,assistant_id:Z,created_at:this.adapter.dateToDb(H),updated_at:this.adapter.dateToDb(H),status:"pending",metadata:this.adapter.jsonToDb(X),multitask_strategy:"reject"}).execute(),{run_id:J,thread_id:Y,assistant_id:Z,created_at:H.toISOString(),updated_at:H.toISOString(),status:"pending",metadata:X,multitask_strategy:"reject"}}async listRuns(Y,Z){let $=this.db.selectFrom("runs").selectAll().where("thread_id","=",Y).orderBy("created_at","desc");if(Z?.status)$=$.where("status","=",Z.status);if(Z?.limit!==void 0){if($=$.limit(Z.limit),Z?.offset!==void 0)$=$.offset(Z.offset)}return(await $.execute()).map((H)=>({run_id:H.run_id,thread_id:H.thread_id,assistant_id:H.assistant_id,created_at:this.adapter.dbToDate(H.created_at).toISOString(),updated_at:this.adapter.dbToDate(H.updated_at).toISOString(),status:H.status,metadata:this.adapter.dbToJson(H.metadata),multitask_strategy:H.multitask_strategy}))}async updateRun(Y,Z){if(!await this.db.selectFrom("runs").select("run_id").where("run_id","=",Y).executeTakeFirst())throw Error(`Run with ID ${Y} not found.`);let J={updated_at:this.adapter.dateToDb(new Date)};if(Z.status!==void 0)J.status=Z.status;if(Z.metadata!==void 0)J.metadata=this.adapter.jsonToDb(Z.metadata);if(Z.multitask_strategy!==void 0)J.multitask_strategy=Z.multitask_strategy;await this.db.updateTable("runs").set(J).where("run_id","=",Y).execute()}async count(Y){return(await this.search(Y)).length}async patch(Y,Z){let $=await this.db.selectFrom("threads").selectAll().where("thread_id","=",Y).executeTakeFirst();if(!$)throw Error(`Thread with ID ${Y} not found.`);let J={updated_at:this.adapter.dateToDb(new Date)};if(Z.metadata!==void 0){let H=this.adapter.dbToJson($.metadata)||{};J.metadata=this.adapter.jsonToDb({...H,...Z.metadata})}if(Z.status!==void 0)J.status=Z.status;if(Z.values!==void 0)J.values=Z.values?this.adapter.jsonToDb(Z.values):null;if(Z.interrupts!==void 0)J.interrupts=this.adapter.jsonToDb(Z.interrupts);if(Z.title!==void 0)J.title=Z.title;return await this.db.updateTable("threads").set(J).where("thread_id","=",Y).execute(),await this.get(Y)}async getState(Y,Z){let $=await this.get(Y);if(Z?.checkpointId){let H=await this.db.selectFrom("checkpoints").selectAll().where("checkpoint_id","=",Z.checkpointId).where("thread_id","=",Y).executeTakeFirst();if(!H)throw Error(`Checkpoint with ID ${Z.checkpointId} not found for thread ${Y}`);return{values:this.adapter.dbToJson(H.values),next:this.adapter.dbToJson(H.next),metadata:this.adapter.dbToJson(H.metadata),checkpoint:{id:H.checkpoint_id,thread_id:Y,parent_checkpoint_id:null,checkpoint_ns:"",metadata:this.adapter.dbToJson(H.metadata),created_at:this.adapter.dbToDate(H.created_at).toISOString()},created_at:this.adapter.dbToDate(H.created_at).toISOString(),parent_checkpoint:null,tasks:[]}}return{values:$.values||{},next:[],metadata:$.metadata,checkpoint:null,created_at:$.created_at,parent_checkpoint:null,tasks:[]}}async getStateHistory(Y,Z){let J=await this.db.selectFrom("checkpoints").selectAll().where("thread_id","=",Y).orderBy("created_at","asc").execute(),H=J.map((X)=>({values:this.adapter.dbToJson(X.values),next:this.adapter.dbToJson(X.next),metadata:this.adapter.dbToJson(X.metadata),checkpoint:{thread_id:Y,checkpoint_ns:"",checkpoint_id:X.checkpoint_id,checkpoint_map:null},created_at:this.adapter.dbToDate(X.created_at).toISOString(),parent_checkpoint:null,tasks:[]}));if(Z?.before){let X=J.findIndex((U)=>U.checkpoint_id===Z.before);if(X!==-1)H=H.slice(X+1)}if(Z?.limit)H=H.slice(0,Z.limit);return H}async copy(Y){let Z=await this.get(Y),$=N(),J=new Date;await this.db.insertInto("threads").values({thread_id:$,created_at:this.adapter.dateToDb(J),updated_at:this.adapter.dateToDb(J),metadata:this.adapter.jsonToDb(Z.metadata),status:Z.status,values:Z.values?this.adapter.jsonToDb(Z.values):null,interrupts:this.adapter.jsonToDb(Z.interrupts),title:Z.title}).execute();let H=await this.db.selectFrom("checkpoints").selectAll().where("thread_id","=",Y).orderBy("created_at","asc").execute();for(let X of H)await this.db.insertInto("checkpoints").values({checkpoint_id:N(),thread_id:$,values:X.values,next:X.next,config:X.config,created_at:X.created_at,metadata:X.metadata}).execute();return{...Z,thread_id:$,created_at:J.toISOString(),updated_at:J.toISOString()}}async saveCheckpoint(Y,Z,$,J,H){await this.db.insertInto("checkpoints").values({checkpoint_id:N(),thread_id:Y,values:this.adapter.jsonToDb(Z),next:this.adapter.jsonToDb($),config:this.adapter.jsonToDb(J),created_at:this.adapter.dateToDb(new Date),metadata:this.adapter.jsonToDb(H||{})}).execute()}async setTitleIfNull(Y,Z){return(await this.db.updateTable("threads").set({title:Z,updated_at:this.adapter.dateToDb(new Date)}).where("thread_id","=",Y).where("title","is",null).executeTakeFirst()).numUpdatedRows>0n}}function DY(Y){let[Z,$]=Y.split("::");return{threadId:Z,checkpointNs:$??""}}function T(Y,Z,$){return`${Y}::${Z}::${$}`}function m(Y){if(Y===null||typeof Y!=="object")return JSON.stringify(Y);if(Array.isArray(Y))return JSON.stringify(Y.map((J)=>m(J)));let Z={},$=Object.keys(Y).sort();for(let J of $)Z[J]=Y[J];return JSON.stringify(Z,(J,H)=>{if(H!==null&&typeof H==="object"&&!Array.isArray(H)){let X={},U=Object.keys(H).sort();for(let W of U)X[W]=H[W];return X}return H})}class ZY extends s{storage={};writes={};constructor(Y){super(Y)}async get(Y){return(await this.getTuple(Y))?.checkpoint}async _migratePendingSends(Y,Z,$,J){let H=Y,X=T(Z,$,J),U=await Promise.all(Object.values(this.writes[X]??{}).filter(([W,P])=>P===S).map(async([W,P,z])=>await this.serde.loadsTyped("json",z)));H.channel_values??={},H.channel_values[S]=U,H.channel_versions??={},H.channel_versions[S]=Object.keys(H.channel_versions).length>0?n(...Object.values(H.channel_versions)):this.getNextVersion(void 0)}async _loadPendingWrites(Y,Z,$){let J=T(Y,Z,$),H=this.writes[J]??{};if(Object.keys(H).length===0)return[];return await Promise.all(Object.values(H).map(async([X,U,W])=>{return[X,U,await this.serde.loadsTyped("json",W)]}))}_cleanupOldWrites(Y,Z,$){let J=T(Y,Z,$);delete this.writes[J]}_checkMetadataFilterMatch(Y,Z){for(let[$,J]of Object.entries(Z)){let H=Y?.[$];if(J===null){if(!($ in(Y||{}))||H!==null)return!1}else if(typeof J==="object"&&!Array.isArray(J)){if(typeof H!=="object"||H===null)return!1;if(m(J)!==m(H))return!1}else if(H!==J)return!1}return!0}async getTuple(Y){let Z=Y.configurable?.thread_id,$=Y.configurable?.checkpoint_ns??"",J=d(Y);if(Z===void 0)return;let H=this.storage[Z]?.[$];if(H===void 0)return;let{checkpoint:X,metadata:U,checkpoint_id:W,parent_checkpoint_id:P}=H;if(J&&W!==J)return;let z=await this.serde.loadsTyped("json",X);if(z.v<4&&P!==void 0)await this._migratePendingSends(z,Z,$,P);let Q=await this._loadPendingWrites(Z,$,W),K=await this.serde.loadsTyped("json",U),F={config:{configurable:{thread_id:Z,checkpoint_ns:$,checkpoint_id:W}},checkpoint:z,metadata:K,pendingWrites:Q};if(P!==void 0)F.parentConfig={configurable:{thread_id:Z,checkpoint_ns:$,checkpoint_id:P}};return F}async*list(Y,Z){let{before:$,limit:J,filter:H}=Z??{},X=Y.configurable?.thread_id?[Y.configurable.thread_id]:Object.keys(this.storage),U=Y.configurable?.checkpoint_ns,W=Y.configurable?.checkpoint_id,P=[];for(let Q of X){let K=this.storage[Q];if(K===void 0)continue;for(let F of Object.keys(K)){if(U!==void 0&&F!==U)continue;let A=K[F];if(A===void 0)continue;let{checkpoint_id:V}=A;if(W&&V!==W)continue;if($?.configurable?.checkpoint_id&&V>=$.configurable.checkpoint_id)continue;let B=await this.serde.loadsTyped("json",A.metadata);if(H&&!this._checkMetadataFilterMatch(B,H))continue;P.push({threadId:Q,checkpointNs:F,namespaceData:A})}}P.sort((Q,K)=>K.namespaceData.checkpoint_ts-Q.namespaceData.checkpoint_ts);let z=0;for(let{threadId:Q,checkpointNs:K,namespaceData:F}of P){if(J!==void 0&&z>=J)return;let{checkpoint:A,metadata:V,checkpoint_id:B,parent_checkpoint_id:_}=F,O=await this.serde.loadsTyped("json",A);if(O.v<4&&_!==void 0)await this._migratePendingSends(O,Q,K,_);let j=await this._loadPendingWrites(Q,K,B),UY=await this.serde.loadsTyped("json",V),y={config:{configurable:{thread_id:Q,checkpoint_ns:K,checkpoint_id:B}},checkpoint:O,metadata:UY,pendingWrites:j};if(_!==void 0)y.parentConfig={configurable:{thread_id:Q,checkpoint_ns:K,checkpoint_id:_}};z++,yield y}}async put(Y,Z,$,J){let H=i(Z),X=Y.configurable?.thread_id,U=Y.configurable?.checkpoint_ns??"",W=Y.configurable?.checkpoint_id;if(X===void 0)throw Error("thread_id is required");let P=Z.id||u(0);if(!this.storage[X])this.storage[X]={};let z=this.storage[X][U];if(z!==void 0&&z.checkpoint_id!==P)this._cleanupOldWrites(X,U,z.checkpoint_id);let[[,Q],[,K]]=await Promise.all([this.serde.dumpsTyped(H),this.serde.dumpsTyped($)]);return this.storage[X][U]={checkpoint:Q,metadata:K,checkpoint_id:P,parent_checkpoint_id:W,checkpoint_ts:Date.now()},{configurable:{thread_id:X,checkpoint_ns:U,checkpoint_id:P}}}async putWrites(Y,Z,$){let J=Y.configurable?.thread_id,H=Y.configurable?.checkpoint_ns??"",X=Y.configurable?.checkpoint_id;if(!J||!X)throw Error("thread_id and checkpoint_id are required");let U=T(J,H,X),W=this.writes[U];if(this.writes[U]===void 0)this.writes[U]={};await Promise.all(Z.map(async([P,z],Q)=>{let[,K]=await this.serde.dumpsTyped(z),F=[$,o[P]||Q],A=`${F[0]},${F[1]}`;if(F[1]>=0&&W&&A in W)return;this.writes[U][A]=[$,P,K]}))}async deleteThread(Y){delete this.storage[Y];for(let Z of Object.keys(this.writes)){let{threadId:$}=DY(Z.split("::").slice(0,2).join("::"));if($===Y)delete this.writes[Z]}}}class R{event;data;id;constructor(Y,Z){this.event=Y,this.data=Z}}class $Y extends R{constructor(){super("__system_cancel__","user cancel this run")}}class JY extends R{constructor(){super("__stream_end__","stream end")}}class v extends R{constructor(Y){super("__stream_error__",{error:Y.name,message:Y.message})}}class k extends a{data=[];activeGenerators=new Set;isDestroyed=!1;async push(Y){if(this.isDestroyed)return;let Z=this.compressMessages?await this.encodeData(Y):Y;process.env.LG_TEMP_MESSAGE!=="true"&&this.data.push(Z),this.emit("dataChange",Z)}onDataChange(Y){if(this.isDestroyed)return()=>{};return this.on("dataChange",async(Z)=>{if(this.isDestroyed)return;Y(this.compressMessages?await this.decodeData(Z):Z)}),()=>this.off("dataChange",Y)}async*onDataReceive(){if(this.isDestroyed)return;let Y=new AbortController;this.activeGenerators.add(Y);let Z=[],$=null,J=!1,H=!1,X=null,U=async(z)=>{if(H||Y.signal.aborted)return;try{let Q=this.compressMessages?await this.decodeData(z):z;if(Z.push(Q),Q.event==="__stream_end__"||Q.event==="__stream_error__"||Q.event==="__stream_cancel__"){if(X)clearTimeout(X),X=null;if(X=setTimeout(()=>{if(J=!0,$)$(),$=null},300),Q.event==="__stream_cancel__")Y.abort("stream cancelled")}if($)$(),$=null}catch(Q){if(console.error("Error in handleData:",Q),$)$(),$=null}};this.on("dataChange",U);let W=()=>{if(J=!0,$)$(),$=null};Y.signal.addEventListener("abort",W);let P=()=>{if(H)return;if(H=!0,X)clearTimeout(X),X=null;try{this.off("dataChange",U)}catch(z){}try{Y.signal.removeEventListener("abort",W)}catch(z){}if($)$(),$=null;Z.length=0,this.activeGenerators.delete(Y)};try{if(Y.signal.aborted||this.isDestroyed)return;while(!J&&!Y.signal.aborted&&!this.isDestroyed)if(Z.length>0){for(let z of Z)yield z;Z.length=0}else await new Promise((z)=>{$=z})}finally{P()}}async getAll(){if(this.isDestroyed)return[];return this.compressMessages?await Promise.all(this.data.map((Y)=>this.decodeData(Y))):[...this.data]}clear(){this.data.length=0}cancelSignal=new AbortController;async cancel(){for(let Y of this.activeGenerators)try{Y.abort("user cancel this run")}catch(Z){}if(this.activeGenerators.clear(),!this.cancelSignal.signal.aborted)this.cancelSignal.abort("user cancel this run");if(!this.isDestroyed)await this.push(new $Y)}async copyToQueue(Y,Z){let $=this.data.slice(),J=new k(Y,this.compressMessages,Z??this.ttl);return J.data=$,J}async destroy(){if(this.isDestroyed)return;this.isDestroyed=!0,await this.cancel(),this.clear(),this.removeAllListeners(),this.activeGenerators.clear()}}class XY{threads=[];checkpoints=new Map;async setup(){return}async create(Y){let Z=Y?.threadId||N();if(Y?.ifExists==="raise"&&this.threads.some((J)=>J.thread_id===Z))throw Error(`Thread with ID ${Z} already exists.`);let $={thread_id:Z,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),state_updated_at:new Date().toISOString(),metadata:Y?.metadata||{},status:"idle",values:null,interrupts:{},title:null};return this.checkpoints.set(Z,[]),this.threads.push($),$}async search(Y){let Z=[...this.threads];if(Y?.ids&&Y.ids.length>0)Z=Z.filter((X)=>Y.ids.includes(X.thread_id));if(Y?.status)Z=Z.filter((X)=>X.status===Y.status);if(Y?.metadata){for(let X in Y.metadata)if(Object.prototype.hasOwnProperty.call(Y.metadata,X))Z=Z.filter((U)=>U.metadata&&U.metadata[X]===Y.metadata?.[X])}if(Y?.values)Z=Z.filter((X)=>{if(!X.values)return!1;return this.deepEqual(X.values,Y.values)});if(Y?.sortBy)Z.sort((X,U)=>{let W,P;switch(Y.sortBy){case"thread_id":W=X.thread_id,P=U.thread_id;break;case"created_at":W=new Date(X.created_at).getTime(),P=new Date(U.created_at).getTime();break;case"updated_at":W=new Date(X.updated_at).getTime(),P=new Date(U.updated_at).getTime();break;case"status":W=X.status,P=U.status;break;default:return 0}if(Y.sortOrder==="desc")return P>W?1:P<W?-1:0;else return W>P?1:W<P?-1:0});let $=Y?.offset||0,J=Y?.limit||Z.length;return Z.slice($,$+J).map((X)=>{let U={thread_id:X.thread_id},W;if(Y?.select)W=new Set(Y.select);else if(Y?.withoutDetails)W=new Set(["thread_id","created_at","updated_at","metadata","status"]);else W=new Set(["thread_id","created_at","updated_at","metadata","status","values","interrupts","title"]);if(W.has("thread_id"))U.thread_id=X.thread_id;if(W.has("created_at"))U.created_at=X.created_at;if(W.has("updated_at"))U.updated_at=X.updated_at;if(W.has("metadata"))U.metadata=X.metadata;if(W.has("status"))U.status=X.status;if(W.has("values"))U.values=X.values;if(W.has("interrupts"))U.interrupts=X.interrupts;if(W.has("title"))U.title=X.title;return U})}deepEqual(Y,Z){if(Y===Z)return!0;if(typeof Y!==typeof Z)return!1;if(typeof Y!=="object"||Y===null||Z===null)return!1;let $=Object.keys(Y),J=Object.keys(Z);if($.length!==J.length)return!1;for(let H of $){if(!J.includes(H))return!1;if(!this.deepEqual(Y[H],Z[H]))return!1}return!0}async get(Y){let Z=this.threads.find(($)=>$.thread_id===Y);if(!Z)throw Error(`Thread with ID ${Y} not found.`);return Z}async set(Y,Z){let $=this.threads.findIndex((J)=>J.thread_id===Y);if($===-1)throw Error(`Thread with ID ${Y} not found.`);this.threads[$]={...this.threads[$],...Z}}async delete(Y){let Z=this.threads.length;if(this.threads=this.threads.filter(($)=>$.thread_id!==Y),this.checkpoints.delete(Y),this.threads.length===Z)throw Error(`Thread with ID ${Y} not found.`)}async updateState(Y,Z){let $=this.threads.findIndex((H)=>H.thread_id===Y);if($===-1)throw Error(`Thread with ID ${Y} not found.`);let J=this.threads[$];if(J.status==="busy")throw Error(`Thread with ID ${Y} is busy, can't update state.`);if(this.threads[$]={...J,values:Z.values,updated_at:new Date().toISOString()},J.metadata?.graph_id){let H=J.metadata?.graph_id,X={configurable:{thread_id:Y,graph_id:H}};try{let U=await YY(H,X),W=await U.updateState(X,Z.values),P=await U.getState(X);return await this.set(Y,{values:JSON.parse(C(P.values))}),W}catch(U){console.warn("Failed to update graph state:",U)}}return{configurable:{thread_id:Y}}}runs=[];async createRun(Y,Z,$){let H={run_id:N(),thread_id:Y,assistant_id:Z,created_at:new Date().toISOString(),updated_at:new Date().toISOString(),status:"pending",metadata:$?.metadata??{},multitask_strategy:"reject"};return this.runs.push(H),H}async listRuns(Y,Z){let $=[...this.runs];if(Z?.status)$=$.filter((J)=>J.status===Z.status);if(Z?.limit)$=$.slice(Z.offset||0,(Z.offset||0)+Z.limit);return $}async updateRun(Y,Z){let $=this.runs.findIndex((J)=>J.run_id===Y);if($===-1)throw Error(`Run with ID ${Y} not found.`);this.runs[$]={...this.runs[$],...Z}}async count(Y){return(await this.search(Y)).length}async patch(Y,Z){let $=this.threads.findIndex((H)=>H.thread_id===Y);if($===-1)throw Error(`Thread with ID ${Y} not found.`);let J={...this.threads[$],...Z,updated_at:new Date().toISOString(),metadata:Z.metadata?{...this.threads[$].metadata,...Z.metadata}:this.threads[$].metadata};return this.threads[$]=J,J}async getState(Y,Z){let $=await this.get(Y);if(Z?.checkpointId){let X=(this.checkpoints.get(Y)||[]).find((U)=>U.checkpoint_id===Z.checkpointId);if(!X)throw Error(`Checkpoint with ID ${Z.checkpointId} not found for thread ${Y}`);return{values:X.values,next:X.next,metadata:X.metadata,checkpoint:{id:X.checkpoint_id,thread_id:Y,parent_checkpoint_id:null,checkpoint_ns:"",metadata:X.metadata,created_at:X.created_at},created_at:X.created_at,parent_checkpoint:null,tasks:[]}}return{values:$.values||{},next:[],metadata:$.metadata,checkpoint:null,created_at:$.created_at,parent_checkpoint:null,tasks:[]}}async getStateHistory(Y,Z){let $=this.checkpoints.get(Y)||[],J=$.map((H)=>({values:H.values,next:H.next,metadata:H.metadata,checkpoint:{checkpoint_id:H.checkpoint_id,thread_id:Y,checkpoint_ns:"",checkpoint_map:void 0},created_at:H.created_at,parent_checkpoint:null,tasks:[]}));if(Z?.before){let H=$.findIndex((X)=>X.checkpoint_id===Z.before);if(H!==-1)J=J.slice(H+1)}if(Z?.limit)J=J.slice(0,Z.limit);return J}async copy(Y){let Z=await this.get(Y),$=N(),J={...Z,thread_id:$,created_at:new Date().toISOString(),updated_at:new Date().toISOString()};this.threads.push(J);let X=(this.checkpoints.get(Y)||[]).map((U)=>({...U,checkpoint_id:N(),thread_id:$}));return this.checkpoints.set($,X),J}async saveCheckpoint(Y,Z,$,J,H){let X=this.checkpoints.get(Y)||[],U={checkpoint_id:N(),thread_id:Y,values:Z,next:$,config:J,created_at:new Date().toISOString(),metadata:H};X.push(U),this.checkpoints.set(Y,X)}async setTitleIfNull(Y,Z){let $=this.threads.findIndex((J)=>J.thread_id===Y);if($===-1)throw Error(`Thread with ID ${Y} not found.`);if(this.threads[$].title===null)return this.threads[$]={...this.threads[$],title:Z,updated_at:new Date().toISOString()},!0;return!1}}var AY=async()=>{if(process.env.REDIS_URL&&(process.env.CHECKPOINT_TYPE==="redis"||process.env.CHECKPOINT_TYPE==="shallow/redis")){if(process.env.CHECKPOINT_TYPE==="redis"){console.debug("LG | Using redis as checkpoint");let{RedisSaver:Y}=await import("./chunk-vnewbtjy.js");return await Y.fromUrl(process.env.REDIS_URL,{defaultTTL:60,refreshOnRead:!0})}if(process.env.CHECKPOINT_TYPE==="shallow/redis"){console.debug("LG | Using shallow redis as checkpoint");let{ShallowRedisSaver:Y}=await import("./chunk-rtjytfhh.js");return await Y.fromUrl(process.env.REDIS_URL)}}if(process.env.DATABASE_URL&&HY(process.env.DATABASE_URL)==="postgres"){console.debug("LG | Using postgres as checkpoint");let{createPGCheckpoint:Y}=await import("./chunk-7w9y11hj.js");return Y()}if(process.env.SQLITE_DATABASE_URI){if(process.env.CHECKPOINT_TYPE==="sqlite"){console.debug("LG | Using sqlite (full) as checkpoint");let{SqliteSaver:$}=await import("./chunk-5m4yb9av.js");return await $.fromConnStringAsync(process.env.SQLITE_DATABASE_URI)}console.debug("LG | Using shallow sqlite as checkpoint (default)");let{SqliteShallowSaver:Y}=await import("./chunk-nm253hhf.js");return await Y.fromConnStringAsync(process.env.SQLITE_DATABASE_URI)}return console.log("LG | You are using memory as checkpoint!"),console.log("\x1B[33m%s\x1B[0m","LG | set SQLITE_DATABASE_URI=./.langgraph_api/langgraph.db to your .env file to use \x1B[1mSQLite\x1B[0m for dev!"),console.log("\x1B[33m%s\x1B[0m","LG | set DATABASE_URL=postgresql://user:pass@localhost:5432/db to your .env file to use \x1B[1mPostgreSQL\x1B[0m for prod!"),new ZY},BY=async()=>{let Y;if(process.env.REDIS_URL){console.debug("LG | Using redis as stream queue");let{RedisStreamQueue:Z}=await import("./chunk-875hayaj.js");Y=Z}else Y=k;return new e(Y)};function HY(Y){let Z=Y.toLowerCase();if(Z.startsWith("http://")||Z.startsWith("https://"))return"remote";return"postgres"}var NY=async(Y)=>{if(process.env.DATABASE_URL){if(HY(process.env.DATABASE_URL)==="remote"){console.debug("LG | Using Remote PostgreSQL ThreadsManager");let{RemoteKyselyThreadsManager:$}=await import("./chunk-d988tv30.js"),J=new $(process.env.DATABASE_URL);if(process.env.DATABASE_INIT==="true")await J.setup();return J}else if(Y.checkpointer){console.debug("LG | Using PostgreSQL ThreadsManager");let{PostgresAdapter:$}=await import("./chunk-6scjjkn3.js"),J=Y.checkpointer.pool,H=new b(new $(J));if(process.env.DATABASE_INIT==="true")await H.setup();return H}}if(process.env.SQLITE_DATABASE_URI&&Y.checkpointer){console.debug("LG | Using SQLite ThreadsManager");let{SQLiteAdapter:Z}=await import("./chunk-cef4vbtb.js"),$=Y.checkpointer.db,J=new b(new Z($));return await J.setup(),J}return new XY};function RY(Y){if(typeof Y==="string")return Y;if(Array.isArray(Y))return Y.find(($)=>$.type==="text")?.text||"";if(Y?.text)return Y.text;return""}var LY=(Y,Z)=>{let $=Y?.messages;if(!$||!Array.isArray($)||$.length===0)return null;let J=$[0];if(!J)return null;let H=RY(J.content);if(!H)return null;let X=H.trim().replace(/\n/g," ");if(!X)return null;let U=15,W=X.slice(0,U);return W.length<X.length?`${W}...`:W};class D{static globalMessageQueue=null;static globalCheckPointer=null;static globalThreadsManager=null;static isInitialized=null;static _titleGenerator=LY;static setTitleGenerator(Y){D._titleGenerator=Y}static getTitleGenerator(){return D._titleGenerator}static async initGlobal(){if(D.isInitialized)return D.isInitialized;return D.isInitialized=(async()=>{let[Y,Z]=await Promise.all([BY(),AY()]);console.debug("LG | checkpointer created");let $=await NY({checkpointer:Z});console.debug("LG | threads manager created"),console.debug("LG | global init done"),D.globalMessageQueue=Y,D.globalCheckPointer=Z,D.globalThreadsManager=$})(),D.isInitialized}}async function _Y(Y,Z,$,J,H){let U=J.config?.configurable?.graph_id;if(!U||typeof U!=="string")throw Error("Invalid or missing graph_id");let W=await H.getGraph(U,J.config,{checkpointer:J.temporary?null:void 0}),P=Array.isArray(J.streamMode)?J.streamMode:J.streamMode?[J.streamMode]:[],z=new Set(["values",...P.filter((V)=>V!=="events"&&V!=="messages-tuple")]);if(P.includes("messages-tuple"))z.add("messages");if(P.includes("messages"))z.add("values");await $.push(new R("metadata",{run_id:Z.run_id,attempt:H.attempt,graph_id:U}));let Q={...J.config?.metadata,run_attempt:H.attempt},K=null,F=null,A=null;try{K=new Set,F=new Map,A=await W.stream(J.command!=null?PY(J.command):J.input??null,{interruptAfter:J.interruptAfter,interruptBefore:J.interruptBefore,tags:J.config?.tags,configurable:J.config?.configurable,recursionLimit:J.config?.recursionLimit,subgraphs:J.streamSubgraphs,metadata:Q,runId:Z.run_id,streamMode:[...z],signal:$.cancelSignal.signal});for await(let V of A){let B=[];if(V.length===3)B=V.splice(0,1);let _=(O)=>{if(B.length===0)return O;if(B.length===1&&B[0]?.length===0)return O;return`${O}|${B.join("|")}`};if(V[0]==="values"){let O=V[1];if(_("values")==="values")if(await $.push(new R(_("values"),O)),O?.__interrupt__)await Y.set(Z.thread_id,{status:"interrupted",interrupts:O?JSON.parse(C(O)):""});else await Y.set(Z.thread_id,{values:O?JSON.parse(C(O)):""})}else if(V[0]==="messages"){let O=V[1][0],j=V[1][1];if(O.id&&!K.has(O.id))await $.push(new R("messages/metadata",{[O.id]:j})),K.add(O.id);if(g.isInstance(O)&&O.id){if(F.set(O.id,[...F.get(O.id)??[],O]),await $.push(new R("messages/partial",[F.get(O.id).reduce(p)])),O.content===""&&!O.tool_calls?.length)F.delete(O.id)}else await $.push(new R("messages/partial",[O]))}else if(V[0]==="updates"){let O=V[1];await $.push(new R(_("updates"),O))}}}catch(V){if(!(V instanceof Error&&V.message?.includes("cancel"))){console.error("streamStateWithQueue error:",V);try{await $.push(new v(V))}catch(B){}}throw V}finally{try{await $.push(new JY)}catch(V){}if(K)K.clear(),K=null;if(F)F.clear(),F=null;A=null}}var C=(Y,Z=0)=>{return JSON.stringify(Y,function($,J){let H=this[$];if(H!=null&&typeof H==="object"&&"toDict"in H&&typeof H.toDict==="function"){let{type:X,data:U}=H.toDict();return{...U,type:X}}return J},Z)};async function*MY(Y,Z,$,J){Z=await Z;let{run_id:H,thread_id:X}=Z,U=null,W=null,P=null,z=!1;try{await Y.set(X,{status:"busy"}),await Y.updateRun(Z.run_id,{status:"running"}),W=D.globalMessageQueue.createQueue(H),U=W.onDataReceive(),P=_Y(Y,Z,W,$,J).catch((Q)=>{if(z)return;if(Q.message!=="user cancel this run")console.error("Queue task error:",Q);D.globalMessageQueue.pushToQueue(H,new v(Q))});for await(let Q of U)yield Q;await Y.updateRun(Z.run_id,{status:"success"})}catch(Q){console.error("Stream error:",Q),await Y.updateRun(Z.run_id,{status:"error"}),await Y.set(X,{status:"error"})}finally{if(z=!0,U){try{await U.return(void 0)}catch(K){}U=null}if(W&&!W.cancelSignal.signal.aborted)try{W.cancelSignal.abort("Stream consumer disconnected")}catch(K){}if(P){try{await Promise.race([P,new Promise((K)=>setTimeout(K,1000))])}catch(K){}P=null}if((await Y.get(X)).status==="interrupted")await D.globalMessageQueue.copyQueue(H,X,30000);else await Y.set(X,{status:"idle",interrupts:{}});await D.globalMessageQueue.removeQueue(H),W=null}}
2
- export{a as n,E as o,wY as p,YY as q,$Y as r,D as s,C as t,MY as u};
@@ -1 +0,0 @@
1
- import{Hl as j0,Kl as $J}from"./chunk-z3e4c424.js";var h$=j0((g$,JJ)=>{var __dirname="/Users/konghayao/code/ai/code-graph/node_modules/.bun/node-sqlite3-wasm@0.8.53/node_modules/node-sqlite3-wasm/dist",Y=typeof Y<"u"?Y:{},M0=!0,BJ=-2147483648,c=2147483647,H=0,D=0,G0=100,V0=101,HJ=1,qJ=2,QJ=3,RJ=4,LJ=5,W0=1,S=-1,C0=2048,v,G={};Y.onRuntimeInitialized=()=>{v=DJ(4);let J=null,$="number",X="string",Z=[$],j=[$,...Z],W=[$,...j],M=[$,...W],V=[$,...M],F={open_v2:[$,[X,$,$,X]],exec:[$,V],errmsg:[X,Z],prepare_v2:[$,V],close_v2:[$,Z],finalize:[$,Z],reset:[$,Z],clear_bindings:[$,Z],bind_int:[$,W],bind_int64:[$,W],bind_double:[$,W],bind_text:[$,V],bind_blob:[$,V],bind_blob64:[$,V],bind_null:[$,j],bind_parameter_index:[$,[$,X]],step:[$,Z],column_int64:[$,j],column_double:[$,j],column_text:[X,j],column_blob:[$,j],column_type:[$,j],column_name:[X,j],column_count:[$,Z],column_bytes:[$,j],last_insert_rowid:[$,Z],changes:[$,Z],create_function_v2:[$,[$,X,$,$,$,$,$,$,$]],value_type:[$,Z],value_text:[X,Z],value_blob:[$,Z],value_int64:[$,Z],value_double:[$,Z],value_bytes:[$,Z],result_double:[J,j],result_null:[J,Z],result_text:[J,M],result_blob:[J,M],result_blob64:[J,M],result_int:[J,j],result_int64:[J,j],result_error:[J,W],column_table_name:[X,j],get_autocommit:[$,Z]};for(let[N,U]of Object.entries(F))G[N]=aJ(`sqlite3_${N}`,U[0],U[1])};class k extends Error{constructor(J){super(J);this.name="SQLite3Error"}}function zJ(J){let $=UJ(J.byteLength);return q.set(J,$),$}function w(J){let $=iJ(J)+1,X=UJ($);return A(J,X,$),X}function l(J){if(J>=Number.MIN_SAFE_INTEGER&&J<=Number.MAX_SAFE_INTEGER)return Number(J);return J}function D0(J,$){let X=[];for(let Z=0;Z<J;Z++){let j=_($+4*Z,"i32"),W=G.value_type(j),M;switch(W){case HJ:M=l(G.value_int64(j));break;case qJ:M=G.value_double(j);break;case QJ:M=G.value_text(j);break;case RJ:let V=G.value_blob(j);if(V!=H)M=q.slice(V,V+G.value_bytes(j));else M=new Uint8Array;break;case LJ:M=null;break}X.push(M)}return X}function U0(J,$){switch(typeof $){case"boolean":G.result_int(J,$?1:0);break;case"number":if(Number.isSafeInteger($))if($>=BJ&&$<=c)G.result_int(J,$);else G.result_int64(J,BigInt($));else G.result_double(J,$);break;case"bigint":G.result_int64(J,$);break;case"string":let X=w($);G.result_text(J,X,-1,S),L(X);break;case"object":if($===null)G.result_null(J);else if($ instanceof Uint8Array){let Z=zJ($);if($.byteLength<=c)G.result_blob(J,Z,$.byteLength,S);else G.result_blob64(J,Z,BigInt($.byteLength),S);L(Z)}else throw new k(`Unsupported type for function result: "${typeof $}"`);break;default:throw new k(`Unsupported type for function result: "${typeof $}"`)}}class AJ{constructor(J,{fileMustExist:$=!1,readOnly:X=!1}={}){let Z;if(X)Z=TJ;else if(Z=PJ,!$)Z|=bJ;let j=G.open_v2(J,v,Z,H);if(this._ptr=_(v,"i32"),j!==D){if(this._ptr!==H)G.close_v2(this._ptr);throw new k(`Could not open the database "${J}"`)}this._functions=new Map}get isOpen(){return this._ptr!==null}get inTransaction(){return this._assertOpen(),G.get_autocommit(this._ptr)===0}close(){this._assertOpen();for(let J of this._functions.values())e(J);this._functions.clear(),this._handleError(G.close_v2(this._ptr)),this._ptr=null}function(J,$,{deterministic:X=!1}={}){this._assertOpen();function Z(M,V,F){let N=D0(V,F),U;try{U=$.apply(null,N)}catch(z){let Q=w(z.toString());G.result_error(M,Q,-1),L(Q);return}U0(M,U)}if(this._functions.has(J))e(this._functions.get(J)),this._functions.delete(J);let j=tJ(Z,"viii");this._functions.set(J,j);let W=W0;if(X)W|=C0;return this._handleError(G.create_function_v2(this._ptr,J,$.length,W,H,j,H,H,H)),this}exec(J){this._assertOpen();let $=w(J);try{this._handleError(G.exec(this._ptr,$,H,H,H))}finally{L($)}}prepare(J){return this._assertOpen(),new OJ(this,J)}run(J,$){let X=this.prepare(J);try{return X.run($)}finally{X.finalize()}}all(J,$,{expand:X=!1}={}){return this._query(J,$,!1,X)}get(J,$,{expand:X=!1}={}){return this._query(J,$,!0,X)}_query(J,$,X,Z){let j=this.prepare(J);try{if(X)return j.get($,{expand:Z});else return j.all($,{expand:Z})}finally{j.finalize()}}_assertOpen(){if(!this.isOpen)throw new k("Database already closed")}_handleError(J){if(J!==D)throw new k(G.errmsg(this._ptr))}}class OJ{constructor(J,$){let X=w($);try{J._handleError(G.prepare_v2(J._ptr,X,-1,v,H))}finally{L(X)}if(this._ptr=_(v,"i32"),this._ptr===H)throw new k("Nothing to prepare");this._db=J}get database(){return this._db}get isFinalized(){return this._ptr===null}run(J){return this._assertReady(),this._bind(J),this._step(),{changes:G.changes(this._db._ptr),lastInsertRowid:l(G.last_insert_rowid(this._db._ptr))}}iterate(J,{expand:$=!1}={}){return this._queryRows(J,$)}all(J,{expand:$=!1}={}){return Array.from(this.iterate(J,{expand:$}))}get(J,{expand:$=!1}={}){let X=this._queryRows(J,$).next();return X.done?null:X.value}finalize(){if(this.isFinalized)throw new k("Statement already finalized");try{this._db._handleError(G.finalize(this._ptr))}finally{this._ptr=null}}_reset(){return G.clear_bindings(this._ptr)===D&&G.reset(this._ptr)===D}*_queryRows(J,$){this._assertReady(),this._bind(J);let X=this._getColumnNames();while(this._step())yield this._getRow(X,$)}_bind(J){if(!this._reset())throw new k("Could not reset statement prior to binding new values");if(Array.isArray(J))this._bindArray(J);else if(J!=null&&typeof J==="object")this._bindObject(J);else if(typeof J<"u")this._bindValue(J,1)}_step(){let J=G.step(this._ptr);switch(J){case G0:return!0;case V0:return!1;default:this._db._handleError(J)}}_getRow(J,$){let X={};for(let Z=0;Z<J.length;Z++){let j;switch(G.column_type(this._ptr,Z)){case HJ:j=l(G.column_int64(this._ptr,Z));break;case qJ:j=G.column_double(this._ptr,Z);break;case QJ:j=G.column_text(this._ptr,Z);break;case RJ:let V=G.column_blob(this._ptr,Z);if(V!=H)j=q.slice(V,V+G.column_bytes(this._ptr,Z));else j=new Uint8Array;break;case LJ:j=null;break}let M=J[Z];if($){let V=G.column_table_name(this._ptr,Z);if(V=V===""?"$":V,Object.hasOwn(X,V))X[V][M]=j;else X[V]={[M]:j}}else X[M]=j}return X}_getColumnNames(){let J=[],$=G.column_count(this._ptr);for(let X=0;X<$;X++)J.push(G.column_name(this._ptr,X));return J}_bindArray(J){for(let $=0;$<J.length;$++)this._bindValue(J[$],$+1)}_bindObject(J){for(let[$,X]of Object.entries(J)){let Z=G.bind_parameter_index(this._ptr,$);if(Z===0)throw new k(`Unknown binding parameter: "${$}"`);this._bindValue(X,Z)}}_bindValue(J,$){let X;switch(typeof J){case"string":let Z=w(J);X=G.bind_text(this._ptr,$,Z,-1,S),L(Z);break;case"number":if(Number.isSafeInteger(J))if(J>=BJ&&J<=c)X=G.bind_int(this._ptr,$,J);else X=G.bind_int64(this._ptr,$,BigInt(J));else X=G.bind_double(this._ptr,$,J);break;case"bigint":X=G.bind_int64(this._ptr,$,J);break;case"boolean":X=G.bind_int(this._ptr,$,J?1:0);break;case"object":if(J===null)X=G.bind_null(this._ptr,$);else if(J instanceof Uint8Array){let j=zJ(J);if(J.byteLength<=c)X=G.bind_blob(this._ptr,$,j,J.byteLength,S);else X=G.bind_blob64(this._ptr,$,j,BigInt(J.byteLength),S);L(j)}else throw new k(`Unsupported type for binding: "${typeof J}"`);break;default:throw new k(`Unsupported type for binding: "${typeof J}"`)}if(X!==D)this._db._handleError(X)}_assertReady(){if(this.isFinalized)throw new k("Statement already finalized");if(!this._db.isOpen)throw new k("Database is closed")}}Y.Database=AJ;Y.SQLite3Error=k;var SJ=$J("node:path"),F0=$J("node:crypto"),K0=14,p=266,k0=522,o=1034,FJ=778,N0=2570,B0=4106,H0=1546,q0=1802,Q0=3850,R0=2058,TJ=1,PJ=2,bJ=4,L0=16,z0=1,A0=2,IJ=0,O0=5;function I(J){return _(J+4,"i32")}function _J(J){return _(J+8,"i32")!=0}function hJ(J,$){P(J+8,$?1:0,"i32")}function XJ(J){return h(_(J+12,"i32"))}function gJ(J){if(J<Number.MIN_SAFE_INTEGER||J>Number.MAX_SAFE_INTEGER)throw 0;return Number(J)}var yJ=[],vJ="./this.program",ZJ=(J,$)=>{throw $},S0;S0="import.meta.filename";var n="";function T0(J){if(Y.locateFile)return Y.locateFile(J,n);return n+J}var P0,u;if(M0){if(C=$J("fs"),n=__dirname+"/",u=(J)=>{J=KJ(J)?new URL(J):J;var $=C.readFileSync(J);return $},P0=async(J,$=!0)=>{J=KJ(J)?new URL(J):J;var X=C.readFileSync(J,$?void 0:"utf8");return X},process.argv.length>1)vJ=process.argv[1].replace(/\\/g,"/");if(yJ=process.argv.slice(2),typeof JJ<"u")JJ.exports=Y;ZJ=(J,$)=>{throw process.exitCode=J,$}}var C,b0=console.log.bind(console),wJ=console.error.bind(console),i,x=!1,f,KJ=(J)=>J.startsWith("file://"),T,q,YJ,I0,B,m,jJ,MJ,GJ,_0,h0=!1;function EJ(){var J=d.buffer;T=new Int8Array(J),YJ=new Int16Array(J),q=new Uint8Array(J),I0=new Uint16Array(J),B=new Int32Array(J),m=new Uint32Array(J),jJ=new Float32Array(J),MJ=new Float64Array(J),GJ=new BigInt64Array(J),_0=new BigUint64Array(J)}function g0(){if(Y.preRun){if(typeof Y.preRun=="function")Y.preRun=[Y.preRun];while(Y.preRun.length)m0(Y.preRun.shift())}cJ(xJ)}function y0(){h0=!0,y.z()}function v0(){if(Y.postRun){if(typeof Y.postRun=="function")Y.postRun=[Y.postRun];while(Y.postRun.length)f0(Y.postRun.shift())}cJ(dJ)}function VJ(J){Y.onAbort?.(J),J="Aborted("+J+")",wJ(J),x=!0,J+=". Build with -sASSERTIONS for more info.";var $=new WebAssembly.RuntimeError(J);throw $}var a;function w0(){return T0("node-sqlite3-wasm.wasm")}function E0(J){if(J==a&&i)return new Uint8Array(i);if(u)return u(J);throw'sync fetching of the wasm failed: you can preload it to Module["wasmBinary"] manually, or emcc.py will do that for you when generating HTML (but not JS)'}function c0(J,$){var X,Z=E0(J);X=new WebAssembly.Module(Z);var j=new WebAssembly.Instance(X,$);return[j,X]}function d0(){var J={a:I$};return J}function x0(){function J(Z,j){return y=Z.exports,b$(y),EJ(),y}var $=d0();if(Y.instantiateWasm)return new Promise((Z,j)=>{Y.instantiateWasm($,(W,M)=>{Z(J(W,M))})});a??=w0();var X=c0(a,$);return J(X[0])}class WJ{name="ExitStatus";constructor(J){this.message=`Program terminated with exit(${J})`,this.status=J}}var cJ=(J)=>{while(J.length>0)J.shift()(Y)},dJ=[],f0=(J)=>dJ.push(J),xJ=[],m0=(J)=>xJ.push(J);function _(J,$="i8"){if($.endsWith("*"))$="*";switch($){case"i1":return T[J];case"i8":return T[J];case"i16":return YJ[J>>1];case"i32":return B[J>>2];case"i64":return GJ[J>>3];case"float":return jJ[J>>2];case"double":return MJ[J>>3];case"*":return m[J>>2];default:VJ(`invalid type for getValue: ${$}`)}}var CJ=!0;function P(J,$,X="i8"){if(X.endsWith("*"))X="*";switch(X){case"i1":T[J]=$;break;case"i8":T[J]=$;break;case"i16":YJ[J>>1]=$;break;case"i32":B[J>>2]=$;break;case"i64":GJ[J>>3]=BigInt($);break;case"float":jJ[J>>2]=$;break;case"double":MJ[J>>3]=$;break;case"*":m[J>>2]=$;break;default:VJ(`invalid type for setValue: ${X}`)}}var p0=(J)=>J0(J),l0=()=>X0(),o0=()=>VJ(""),fJ=0,n0=()=>{CJ=!1,fJ=0},u0=(J)=>J%4===0&&(J%100!==0||J%400===0),i0=[0,31,60,91,121,152,182,213,244,274,305,335],a0=[0,31,59,90,120,151,181,212,243,273,304,334],r0=(J)=>{var $=u0(J.getFullYear()),X=$?i0:a0,Z=X[J.getMonth()]+J.getDate()-1;return Z},s0=9007199254740992,t0=-9007199254740992,e0=(J)=>J<t0||J>s0?NaN:Number(J);function J8(J,$){J=e0(J);var X=new Date(J*1000);B[$>>2]=X.getSeconds(),B[$+4>>2]=X.getMinutes(),B[$+8>>2]=X.getHours(),B[$+12>>2]=X.getDate(),B[$+16>>2]=X.getMonth(),B[$+20>>2]=X.getFullYear()-1900,B[$+24>>2]=X.getDay();var Z=r0(X)|0;B[$+28>>2]=Z,B[$+36>>2]=-(X.getTimezoneOffset()*60);var j=new Date(X.getFullYear(),0,1),W=new Date(X.getFullYear(),6,1).getTimezoneOffset(),M=j.getTimezoneOffset(),V=(W!=M&&X.getTimezoneOffset()==Math.min(M,W))|0;B[$+32>>2]=V}var g={},mJ=(J)=>{if(J instanceof WJ||J=="unwind")return f;ZJ(1,J)},pJ=()=>CJ||fJ>0,lJ=(J)=>{if(f=J,!pJ())Y.onExit?.(J),x=!0;ZJ(J,new WJ(J))},$8=(J,$)=>{f=J,lJ(J)},X8=$8,Z8=()=>{if(!pJ())try{X8(f)}catch(J){mJ(J)}},Y8=(J)=>{if(x)return;try{J(),Z8()}catch($){mJ($)}},oJ=()=>performance.now(),j8=(J,$)=>{if(g[J])clearTimeout(g[J].id),delete g[J];if(!$)return 0;var X=setTimeout(()=>{delete g[J],Y8(()=>eJ(J,oJ()))},$);return g[J]={id:X,timeout_ms:$},0},M8=(J,$,X,Z)=>{if(!(Z>0))return 0;var j=X,W=X+Z-1;for(var M=0;M<J.length;++M){var V=J.codePointAt(M);if(V<=127){if(X>=W)break;$[X++]=V}else if(V<=2047){if(X+1>=W)break;$[X++]=192|V>>6,$[X++]=128|V&63}else if(V<=65535){if(X+2>=W)break;$[X++]=224|V>>12,$[X++]=128|V>>6&63,$[X++]=128|V&63}else{if(X+3>=W)break;$[X++]=240|V>>18,$[X++]=128|V>>12&63,$[X++]=128|V>>6&63,$[X++]=128|V&63,M++}}return $[X]=0,X-j},A=(J,$,X)=>M8(J,q,$,X),G8=(J,$,X,Z)=>{var j=new Date().getFullYear(),W=new Date(j,0,1),M=new Date(j,6,1),V=W.getTimezoneOffset(),F=M.getTimezoneOffset(),N=Math.max(V,F);m[J>>2]=N*60,B[$>>2]=Number(V!=F);var U=(E)=>{var K=E>=0?"-":"+",R=Math.abs(E),Z0=String(Math.floor(R/60)).padStart(2,"0"),Y0=String(R%60).padStart(2,"0");return`UTC${K}${Z0}${Y0}`},z=U(V),Q=U(F);if(F<V)A(z,X,17),A(Q,Z,17);else A(z,Z,17),A(Q,X,17)},V8=()=>Date.now(),W8=()=>2147483648,C8=(J,$)=>Math.ceil(J/$)*$,D8=(J)=>{var $=d.buffer.byteLength,X=(J-$+65535)/65536|0;try{return d.grow(X),EJ(),1}catch(Z){}},U8=(J)=>{var $=q.length;J>>>=0;var X=W8();if(J>X)return!1;for(var Z=1;Z<=4;Z*=2){var j=$*(1+0.2/Z);j=Math.min(j,J+100663296);var W=Math.min(X,C8(Math.max(J,j),65536)),M=D8(W);if(M)return!0}return!1},kJ=globalThis.TextDecoder&&new TextDecoder,F8=(J,$,X,Z)=>{var j=$+X;if(Z)return j;while(J[$]&&!($>=j))++$;return $},K8=(J,$=0,X,Z)=>{var j=F8(J,$,X,Z);if(j-$>16&&J.buffer&&kJ)return kJ.decode(J.subarray($,j));var W="";while($<j){var M=J[$++];if(!(M&128)){W+=String.fromCharCode(M);continue}var V=J[$++]&63;if((M&224)==192){W+=String.fromCharCode((M&31)<<6|V);continue}var F=J[$++]&63;if((M&240)==224)M=(M&15)<<12|V<<6|F;else M=(M&7)<<18|V<<12|F<<6|J[$++]&63;if(M<65536)W+=String.fromCharCode(M);else{var N=M-65536;W+=String.fromCharCode(55296|N>>10,56320|N&1023)}}return W},h=(J,$,X)=>J?K8(q,J,$,X):"";function k8(J,$,X,Z){let j=C.constants.F_OK;if(X==z0)j=C.constants.R_OK|C.constants.W_OK;if(X==A0)j=C.constants.R_OK;try{C.accessSync(h($),j),P(Z,1,"i32")}catch{P(Z,0,"i32")}return D}function N8(J,$){try{C.accessSync(`${XJ(J)}.lock`,C.constants.F_OK),P($,1,"i32")}catch{P($,0,"i32")}return D}function B8(J){nJ(J,IJ);try{C.closeSync(I(J))}catch{return B0}return D}function H8(J,$,X){let Z=h($);try{C.unlinkSync(Z)}catch(j){if(j.code!="ENOENT")return N0}if(X){let j=-1;try{j=C.openSync(SJ.dirname(Z),"r"),C.fsyncSync(j)}catch{return o}finally{try{C.closeSync(j)}catch{return o}}}return D}function q8(J,$){try{P($,C.fstatSync(I(J)).size,"i64")}catch{return q0}return D}function Q8(J,$,X,Z){let j=SJ.resolve(h($));return A(j,Z,X),j.length<X?D:K0}function R8(J,$){if(!_J(J)){try{C.mkdirSync(`${XJ(J)}.lock`)}catch(X){return X.code=="EEXIST"?O0:Q0}hJ(J,!0)}return D}function L8(J,$,X){let Z=q.subarray(X,X+$);return F0.randomFillSync(Z),$}function z8(J,$,X,Z){let j=q.subarray($,$+X),W;try{W=C.readSync(I(J),j,0,X,Z)}catch{return p}if(W==X)return D;else if(W>=0){if(W<X)try{j.fill(0,W)}catch{return p}return k0}return p}function A8(J,$){try{C.fsyncSync(I(J))}catch{return o}return D}function O8(J,$){try{C.ftruncateSync(I(J),gJ($))}catch{return H0}return D}function nJ(J,$){if($==IJ&&_J(J)){try{C.rmdirSync(`${XJ(J)}.lock`)}catch(X){if(X.code!="ENOENT")return R0}hJ(J,!1)}return D}function S8(J,$,X,Z){try{return C.writeSync(I(J),q.subarray($,$+X),0,X,gJ(Z))!=X?FJ:D}catch{return FJ}}function T8(){return process.platform=="win32"?260:4096}function P8(J,$,X){let Z=0;if($&L0)Z|=C.constants.O_EXCL;if($&bJ)Z|=C.constants.O_CREAT;if($&TJ)Z|=C.constants.O_RDONLY;if($&PJ)Z|=C.constants.O_RDWR;try{return C.openSync(h(J),Z,X)}catch{return-1}}var uJ=(J)=>{var $=Y["_"+J];return $},b8=(J,$)=>{T.set(J,$)},iJ=(J)=>{var $=0;for(var X=0;X<J.length;++X){var Z=J.charCodeAt(X);if(Z<=127)$++;else if(Z<=2047)$+=2;else if(Z>=55296&&Z<=57343)$+=4,++X;else $+=3}return $},DJ=(J)=>$0(J),I8=(J)=>{var $=iJ(J)+1,X=DJ($);return A(J,X,$),X},_8=(J,$,X,Z,j)=>{var W={string:(K)=>{var R=0;if(K!==null&&K!==void 0&&K!==0)R=I8(K);return R},array:(K)=>{var R=DJ(K.length);return b8(K,R),R}};function M(K){if($==="string")return h(K);if($==="boolean")return Boolean(K);return K}var V=uJ(J),F=[],N=0;if(Z)for(var U=0;U<Z.length;U++){var z=W[X[U]];if(z){if(N===0)N=l0();F[U]=z(Z[U])}else F[U]=Z[U]}var Q=V(...F);function E(K){if(N!==0)p0(N);return M(K)}return Q=E(Q),Q},aJ=(J,$,X,Z)=>{var j=!X||X.every((M)=>M==="number"||M==="boolean"),W=$!=="string";if(W&&j&&!Z)return uJ(J);return(...M)=>_8(J,$,X,M,Z)},r=[],rJ=(J)=>{var $=r[J];if(!$)r[J]=$=b.get(J);return $},h8=(J,$)=>{if(O)for(var X=J;X<J+$;X++){var Z=rJ(X);if(Z)O.set(Z,X)}},O,g8=(J)=>{if(!O)O=new WeakMap,h8(0,b.length);return O.get(J)||0},s=[],y8=()=>{if(s.length)return s.pop();return b.grow(1)},t=(J,$)=>{b.set(J,$),r[J]=b.get(J)},sJ=(J)=>{let $=J.length;return[$%128|128,$>>7,...J]},v8={i:127,p:127,j:126,f:125,d:124,e:111},NJ=(J)=>sJ(Array.from(J,($)=>{var X=v8[$];return X})),w8=(J,$)=>{var X=Uint8Array.of(0,97,115,109,1,0,0,0,1,...sJ([1,96,...NJ($.slice(1)),...NJ($[0]==="v"?"":$[0])]),2,7,1,1,101,1,102,0,0,7,5,1,1,102,0,0),Z=new WebAssembly.Module(X),j=new WebAssembly.Instance(Z,{e:{f:J}}),W=j.exports.f;return W},tJ=(J,$)=>{var X=g8(J);if(X)return X;var Z=y8();try{t(Z,J)}catch(W){if(!(W instanceof TypeError))throw W;var j=w8(J,$);t(Z,j)}return O.set(J,Z),Z},e=(J)=>{O.delete(rJ(J)),t(J,null),s.push(J)};{if(Y.noExitRuntime)CJ=Y.noExitRuntime;if(Y.print)b0=Y.print;if(Y.printErr)wJ=Y.printErr;if(Y.wasmBinary)i=Y.wasmBinary;if(Y.arguments)yJ=Y.arguments;if(Y.thisProgram)vJ=Y.thisProgram;if(Y.preInit){if(typeof Y.preInit=="function")Y.preInit=[Y.preInit];while(Y.preInit.length>0)Y.preInit.shift()()}}Y.cwrap=aJ;Y.addFunction=tJ;Y.removeFunction=e;var E8,c8,d8,x8,f8,m8,p8,l8,o8,n8,u8,i8,a8,r8,s8,t8,e8,J$,$$,X$,Z$,Y$,j$,M$,G$,V$,W$,C$,D$,U$,F$,K$,k$,N$,B$,H$,q$,Q$,R$,L$,z$,A$,O$,S$,UJ,L,eJ,J0,$0,X0,T$,P$,d,b;function b$(J){E8=Y._sqlite3_finalize=J.A,c8=Y._sqlite3_reset=J.B,d8=Y._sqlite3_clear_bindings=J.C,x8=Y._sqlite3_value_blob=J.D,f8=Y._sqlite3_value_text=J.E,m8=Y._sqlite3_value_bytes=J.F,p8=Y._sqlite3_value_double=J.G,l8=Y._sqlite3_value_int64=J.H,o8=Y._sqlite3_value_type=J.I,n8=Y._sqlite3_result_blob=J.J,u8=Y._sqlite3_result_blob64=J.K,i8=Y._sqlite3_result_double=J.L,a8=Y._sqlite3_result_error=J.M,r8=Y._sqlite3_result_int=J.N,s8=Y._sqlite3_result_int64=J.O,t8=Y._sqlite3_result_null=J.P,e8=Y._sqlite3_result_text=J.Q,J$=Y._sqlite3_step=J.R,$$=Y._sqlite3_column_count=J.S,X$=Y._sqlite3_column_blob=J.T,Z$=Y._sqlite3_column_bytes=J.U,Y$=Y._sqlite3_column_double=J.V,j$=Y._sqlite3_column_int64=J.W,M$=Y._sqlite3_column_text=J.X,G$=Y._sqlite3_column_type=J.Y,V$=Y._sqlite3_column_name=J.Z,W$=Y._sqlite3_column_table_name=J._,C$=Y._sqlite3_bind_blob=J.$,D$=Y._sqlite3_bind_blob64=J.aa,U$=Y._sqlite3_bind_double=J.ba,F$=Y._sqlite3_bind_int=J.ca,K$=Y._sqlite3_bind_int64=J.da,k$=Y._sqlite3_bind_null=J.ea,N$=Y._sqlite3_bind_text=J.fa,B$=Y._sqlite3_bind_parameter_index=J.ga,H$=Y._sqlite3_exec=J.ha,q$=Y._sqlite3_prepare_v2=J.ia,Q$=Y._sqlite3_errmsg=J.ja,R$=Y._sqlite3_last_insert_rowid=J.ka,L$=Y._sqlite3_changes=J.la,z$=Y._sqlite3_close_v2=J.ma,A$=Y._sqlite3_create_function_v2=J.na,O$=Y._sqlite3_open_v2=J.oa,S$=Y._sqlite3_get_autocommit=J.pa,UJ=Y._malloc=J.qa,L=Y._free=J.ra,eJ=J.ta,J0=J.ua,$0=J.va,X0=J.wa,T$=d=J.y,P$=b=J.sa}var I$={k:o0,j:n0,o:J8,l:j8,p:G8,q:V8,a:oJ,n:U8,w:k8,s:N8,f:B8,x:H8,v:q8,m:Q8,u:R8,h:L8,e:z8,b:A8,c:O8,t:nJ,d:S8,g:T8,r:P8,i:lJ};function _$(){g0();function J(){if(Y.calledRun=!0,x)return;y0(),Y.onRuntimeInitialized?.(),v0()}if(Y.setStatus)Y.setStatus("Running..."),setTimeout(()=>{setTimeout(()=>Y.setStatus(""),1),J()},1);else J()}var y;y=x0();_$()});export default h$();
@@ -1 +0,0 @@
1
- import{$ as c,$a as ca,$b as cb,$c as cc,$d as cd,Aa as D,Ab as Da,Ac as Db,Ad as Dc,Ba as E,Bb as Ea,Bc as Eb,Bd as Ec,Ca as F,Cb as Fa,Cc as Fb,Cd as Fc,Da as G,Db as Ga,Dc as Gb,Dd as Gc,Ea as H,Eb as Ha,Ec as Hb,Ed as Hc,Fa as I,Fb as Ia,Fc as Ib,Fd as Ic,Ga as J,Gb as Ja,Gc as Jb,Gd as Jc,Ha as K,Hb as Ka,Hc as Kb,Hd as Kc,Ia as L,Ib as La,Ic as Lb,Id as Lc,Ja as M,Jb as Ma,Jc as Mb,Jd as Mc,Ka as N,Kb as Na,Kc as Nb,Kd as Nc,La as O,Lb as Oa,Lc as Ob,Ld as Oc,Ma as P,Mb as Pa,Mc as Pb,Md as Pc,Na as Q,Nb as Qa,Nc as Qb,Nd as Qc,Oa as R,Ob as Ra,Oc as Rb,Od as Rc,Pa as S,Pb as Sa,Pc as Sb,Pd as Sc,Qa as T,Qb as Ta,Qc as Tb,Qd as Tc,Ra as U,Rb as Ua,Rc as Ub,Rd as Uc,Sa as V,Sb as Va,Sc as Vb,Sd as Vc,Ta as W,Tb as Wa,Tc as Wb,Td as Wc,Ua as X,Ub as Xa,Uc as Xb,Ud as Xc,Va as Y,Vb as Ya,Vc as Yb,Vd as Yc,Wa as Z,Wb as Za,Wc as Zb,Wd as Zc,Xa as _,Xb as _a,Xc as _b,Xd as _c,Ya as $,Yb as $a,Yc as $b,Yd as $c,Z as a,Za as aa,Zb as ab,Zc as ac,Zd as ad,_ as b,_a as ba,_b as bb,_c as bc,_d as bd,aa as d,ab as da,ac as db,ad as dc,ae as dd,ba as e,bb as ea,bc as eb,bd as ec,be as ed,ca as f,cb as fa,cc as fb,cd as fc,ce as fd,da as g,db as ga,dc as gb,dd as gc,de as gd,ea as h,eb as ha,ec as hb,ed as hc,ee as hd,fa as i,fb as ia,fc as ib,fd as ic,fe as id,ga as j,gb as ja,gc as jb,gd as jc,ge as jd,ha as k,hb as ka,hc as kb,hd as kc,he as kd,ia as l,ib as la,ic as lb,id as lc,ie as ld,ja as m,jb as ma,jc as mb,jd as mc,je as md,ka as n,kb as na,kc as nb,kd as nc,ke as nd,la as o,lb as oa,lc as ob,ld as oc,le as od,ma as p,mb as pa,mc as pb,md as pc,me as pd,na as q,nb as qa,nc as qb,nd as qc,ne as qd,oa as r,ob as ra,oc as rb,od as rc,oe as rd,pa as s,pb as sa,pc as sb,pd as sc,pe as sd,qa as t,qb as ta,qc as tb,qd as tc,qe as td,ra as u,rb as ua,rc as ub,rd as uc,re as ud,sa as v,sb as va,sc as vb,sd as vc,se as vd,ta as w,tb as wa,tc as wb,td as wc,ua as x,ub as xa,uc as xb,ud as xc,va as y,vb as ya,vc as yb,vd as yc,wa as z,wb as za,wc as zb,wd as zc,xa as A,xb as Aa,xc as Ab,xd as Ac,ya as B,yb as Ba,yc as Bb,yd as Bc,za as C,zb as Ca,zc as Cb,zd as Cc}from"./chunk-cnzhxgn5.js";import"./chunk-z3e4c424.js";export{wc as validateTransactionSettings,Jc as sql,sd as replaceWithNoncontingentExpression,td as pushValueIntoList,vd as logOnce,D as isOperator,m as isOperationNodeSource,ya as isNoResultErrorConstructor,Cc as isKyselyProps,H as isJSONOperator,n as isExpression,M as isDynamicReferenceBuilder,zc as isCompilable,F as isComparisonOperator,xb as isColumnDataType,E as isBinaryOperator,G as isArithmeticOperator,o as isAliasedExpression,Bb as isAliasedDynamicTableBuilder,ud as expressionBuilder,fb as createSelectQueryBuilder,Ic as createRawBuilder,kb as createFunctionModule,Pa as WithSchemaPlugin,Na as WithNode,ha as WhereNode,Va as WheneableMergeQueryBuilder,ka as WhenNode,sa as ValuesNode,W as ValueNode,V as ValueListNode,fa as UsingNode,Ja as UpdateResult,ea as UpdateQueryNode,Ka as UpdateQueryBuilder,Qb as UniqueConstraintNode,lb as UnaryOperationNode,A as UNARY_OPERATORS,z as UNARY_FILTER_OPERATORS,vb as TupleNode,tb as TraversedJSONPathBuilder,Ec as TransactionBuilder,Bc as Transaction,Da as TopNode,l as TableNode,vc as TRANSACTION_ISOLATION_LEVELS,uc as TRANSACTION_ACCESS_MODES,Qc as SqliteQueryCompiler,Xc as SqliteIntrospector,Pc as SqliteDriver,Zc as SqliteDialect,Yc as SqliteAdapter,tc as SingleConnectionProvider,$a as SetOperationNode,ra as SelectionNode,oa as SelectQueryNode,p as SelectModifierNode,J as SelectAllNode,g as SchemableIdentifierNode,pc as SchemaModule,ia as ReturningNode,Yb as RenameConstraintNode,Fb as RenameColumnNode,nc as RefreshMaterializedViewNode,oc as RefreshMaterializedViewBuilder,Ib as ReferencesNode,K as ReferenceNode,O as RawNode,na as QueryNode,Ya as QueryCreator,U as PrimitiveValueListNode,Vb as PrimaryKeyConstraintNode,Wb as PrimaryConstraintNode,_c as PostgresQueryCompiler,$c as PostgresIntrospector,gd as PostgresDriver,hd as PostgresDialect,ad as PostgresAdapter,Z as PartitionByNode,qa as PartitionByItemNode,qd as ParseJSONResultsPlugin,X as ParensNode,_ as OverNode,ma as OutputNode,Y as OrderByNode,N as OrderByItemNode,Q as OrderByItemBuilder,cb as OrWrapper,r as OrNode,Ea as OrActionNode,C as OperatorNode,Kc as OperationNodeVisitor,Oa as OperationNodeTransformer,s as OnNode,va as OnDuplicateKeyNode,Ca as OnConflictUpdateBuilder,za as OnConflictNode,Ba as OnConflictDoNothingBuilder,Aa as OnConflictBuilder,Za as OffsetNode,B as OPERATORS,Hb as ON_MODIFY_FOREIGN_ACTIONS,e as ON_COMMIT_ACTIONS,Xa as NotMatchedThenableMergeQueryBuilder,Ra as NoopQueryExecutor,xa as NoResultError,Vc as NO_MIGRATIONS,Sa as NOOP_QUERY_EXECUTOR,cd as MysqlQueryCompiler,dd as MysqlIntrospector,bd as MysqlDriver,fd as MysqlDialect,ed as MysqlAdapter,ld as MssqlQueryCompiler,kd as MssqlIntrospector,jd as MssqlDriver,md as MssqlDialect,id as MssqlAdapter,Mb as ModifyColumnNode,Wc as Migrator,Ta as MergeResult,la as MergeQueryNode,Ua as MergeQueryBuilder,Wa as MatchedThenableMergeQueryBuilder,Qa as MatchedNode,Uc as MIGRATION_LOCK_ID,yc as Log,da as ListNode,Ha as LimitNode,xc as LOG_LEVELS,Ac as Kysely,t as JoinNode,pa as JoinBuilder,x as JSON_OPERATORS,R as JSONReferenceNode,T as JSONPathNode,rb as JSONPathLegNode,sb as JSONPathBuilder,S as JSONOperatorChainNode,wa as InsertResult,ca as InsertQueryNode,Fa as InsertQueryBuilder,b as IdentifierNode,ba as HavingNode,rd as HandleEmptyInListsPlugin,aa as GroupByNode,_a as GroupByItemNode,Jb as GeneratedNode,hb as FunctionNode,$ as FromNode,Nb as ForeignKeyConstraintNode,Ob as ForeignKeyConstraintBuilder,nd as FileMigrationProvider,eb as FetchNode,ab as ExpressionWrapper,ja as ExplainNode,zb as DynamicTableBuilder,L as DynamicReferenceBuilder,qc as DynamicModule,Nc as DummyDriver,hc as DropViewNode,ic as DropViewBuilder,lc as DropTypeNode,mc as DropTypeBuilder,j as DropTableNode,ec as DropTableBuilder,i as DropSchemaNode,dc as DropSchemaBuilder,h as DropIndexNode,cc as DropIndexBuilder,Rb as DropConstraintNode,Eb as DropColumnNode,Oc as DialectAdapterBase,Ga as DeleteResult,ga as DeleteQueryNode,Ia as DeleteQueryBuilder,Kb as DefaultValueNode,sc as DefaultQueryExecutor,Lc as DefaultQueryCompiler,ta as DefaultInsertValueNode,rc as DefaultConnectionProvider,pd as DeduplicateJoinsPlugin,wb as DataTypeNode,Rc as DEFAULT_MIGRATION_TABLE,Sc as DEFAULT_MIGRATION_LOCK_TABLE,Tc as DEFAULT_ALLOW_UNORDERED_MIGRATIONS,fc as CreateViewNode,gc as CreateViewBuilder,jc as CreateTypeNode,kc as CreateTypeBuilder,f as CreateTableNode,bc as CreateTableBuilder,d as CreateSchemaNode,ac as CreateSchemaBuilder,c as CreateIndexNode,$b as CreateIndexBuilder,Fc as ControlledTransactionBuilder,Gc as ControlledTransaction,Dc as ConnectionBuilder,Mc as CompiledQuery,Ma as CommonTableExpressionNode,La as CommonTableExpressionNameNode,Hc as Command,ua as ColumnUpdateNode,I as ColumnNode,Db as ColumnDefinitionNode,Lb as ColumnDefinitionBuilder,P as CollateNode,Gb as CheckConstraintNode,yb as CastNode,pb as CaseWhenBuilder,ob as CaseThenBuilder,mb as CaseNode,qb as CaseEndBuilder,nb as CaseBuilder,od as CamelCasePlugin,v as COMPARISON_OPERATORS,u as BinaryOperationNode,y as BINARY_OPERATORS,db as AndWrapper,q as AndNode,Ub as AlteredColumnBuilder,a as AlterTableNode,_b as AlterTableColumnAlteringBuilder,Zb as AlterTableBuilder,Sb as AlterColumnNode,Tb as AlterColumnBuilder,ub as AliasedJSONPathBuilder,bb as AliasedExpressionWrapper,Ab as AliasedDynamicTableBuilder,jb as AliasedAggregateFunctionBuilder,k as AliasNode,gb as AggregateFunctionNode,ib as AggregateFunctionBuilder,Xb as AddIndexNode,Pb as AddConstraintNode,Cb as AddColumnNode,w as ARITHMETIC_OPERATORS};
@@ -1 +0,0 @@
1
- import{if as a}from"./chunk-znw7fpep.js";import"./chunk-t01t72t2.js";import"./chunk-z3e4c424.js";export{a as FileSystemSkillStore};
@@ -1,3 +0,0 @@
1
- import{writeFileSync as B,readFileSync as C,existsSync as u,mkdirSync as G}from"node:fs";import{join as H,dirname as J}from"node:path";import{randomUUID as K}from"node:crypto";class z{errors=[];filePath;maxEntries;isLoaded=!1;constructor(b){this.filePath=b?.filePath||H(process.cwd(),".zen-code","errors.json"),this.maxEntries=b?.maxEntries||500,this.ensureDirectory()}ensureDirectory(){let b=J(this.filePath);if(!u(b))G(b,{recursive:!0})}loadFromFile(){if(this.isLoaded)return;try{if(u(this.filePath)){let b=C(this.filePath,"utf-8"),q=JSON.parse(b);if(Array.isArray(q))this.errors=q}}catch(b){this.errors=[]}this.isLoaded=!0}saveToFile(){try{let b=JSON.stringify(this.errors,null,2);B(this.filePath,b,"utf-8")}catch(b){process.stderr.write(`[ErrorStore] Failed to save errors: ${b}
2
- `)}}addError(b){this.loadFromFile();let q={...b,id:K(),timestamp:new Date().toISOString()};if(this.errors.unshift(q),this.errors.length>this.maxEntries)this.errors=this.errors.slice(0,this.maxEntries);return this.saveToFile(),q}getErrors(){return this.loadFromFile(),[...this.errors]}getRecentErrors(b=100){return this.loadFromFile(),this.errors.slice(0,b)}clearAll(){this.errors=[],this.saveToFile()}deleteError(b){this.loadFromFile();let q=this.errors.findIndex((A)=>A.id===b);if(q!==-1)return this.errors.splice(q,1),this.saveToFile(),!0;return!1}getStats(){return this.loadFromFile(),{total:this.errors.length,errors:this.errors.filter((b)=>b.level==="error").length,warnings:this.errors.filter((b)=>b.level==="warning").length}}}var O=new z;
3
- export{O as mf};
@@ -1 +0,0 @@
1
- import{j as k}from"./chunk-d72063sm.js";import"./chunk-dx9k6sdd.js";import{Be as g,Ce as r,Ke as B,Le as b,ye as R}from"./chunk-1v863afn.js";import"./chunk-d2770b2z.js";import"./chunk-mv0xzmq8.js";import"./chunk-znw7fpep.js";import"./chunk-pxdgy0vr.js";import"./chunk-k6fxqssr.js";import"./chunk-t01t72t2.js";import"./chunk-b2551zfb.js";import"./chunk-vd8kwzra.js";import{Fl as m}from"./chunk-z3e4c424.js";var w=m(R(),1);var u=m(R(),1);var n=m(b(),1),H=({field:e,value:t,isFocused:o})=>n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:t?"green":"gray",bold:o,children:t?"ON":"OFF"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),J=({field:e,value:t,isFocused:o})=>n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:o?"yellow":void 0,bold:o,children:t??e.min??0},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:" ms"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),L=({field:e,value:t,isFocused:o})=>{let a=e.options?.find((y)=>y.value===t);return n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:o?"yellow":void 0,bold:o,children:a?.label||t},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},Y=({field:e,value:t,isFocused:o})=>n.jsxDEV(g,{flexDirection:"row",children:[n.jsxDEV(r,{bold:o,color:o?"cyan":void 0,children:e.label},void 0,!1,void 0,this),n.jsxDEV(r,{dimColor:!0,children:": "},void 0,!1,void 0,this),n.jsxDEV(r,{color:o?"yellow":"gray",bold:o,children:t||e.placeholder||"-"},void 0,!1,void 0,this)]},void 0,!0,void 0,this),q=(e)=>{switch(e.field.type){case"toggle":return n.jsxDEV(H,{...e},void 0,!1,void 0,this);case"number":return n.jsxDEV(J,{...e},void 0,!1,void 0,this);case"select":return n.jsxDEV(L,{...e},void 0,!1,void 0,this);case"input":return n.jsxDEV(Y,{...e},void 0,!1,void 0,this);default:return n.jsxDEV(r,{color:"red",children:"Unknown"},void 0,!1,void 0,this)}},M=q;var x=[{key:"compact_mode",label:"紧凑模式",type:"toggle",group:"显示",tab:"General",help:"紧凑显示消息 (Ctrl+O)"},{key:"show_detailed_info",label:"系统信息",type:"toggle",group:"显示",tab:"General",help:"显示系统资源信息"},{key:"enable_thinking",label:"思考模式",type:"toggle",group:"模型",tab:"General",help:"启用模型思考"},{key:"streaming",label:"流式输出",type:"toggle",group:"模型",tab:"General",help:"关闭后等待完整响应再显示(适用于不支持流式的模型)"},{key:"stream_refresh_interval",label:"流刷新间隔",type:"number",group:"模型",tab:"General",min:50,max:1000,step:50,help:"流刷新间隔 (ms)"}],S=(()=>{let e=new Map;return x.forEach((t)=>{let o=t.tab||"General";if(!e.has(o))e.set(o,{id:o,label:o,icon:"⚙"})}),Array.from(e.values())})(),D=(()=>{let e=new Map;return x.forEach((t)=>{if(!e.has(t.group))e.set(t.group,{id:t.group,label:t.group,fields:[]});e.get(t.group).fields.push(t)}),Array.from(e.values())})();function z(e){return x.filter((t)=>(t.tab||"General")===e)}function _(e){let t=z(e),o=new Map;return t.forEach((a)=>{if(!o.has(a.group))o.set(a.group,{id:a.group,label:a.group,fields:[]});o.get(a.group).fields.push(a)}),Array.from(o.values())}var f=m(b(),1);function K(e){switch(e.type){case"toggle":return!1;case"number":return e.min??0;case"select":return e.options?.[0]?.value;case"input":return"";default:return}}var Q=({schema:e,config:t,onUpdate:o,activeTab:a="General"})=>{let y=u.useMemo(()=>_(a),[a]),T=u.useMemo(()=>y.flatMap((l)=>l.fields),[y]),[P,h]=u.useState(0),p=T[P],c=u.useCallback((l,i)=>{o(l.key,i)},[o]),G=u.useCallback((l)=>{c(l,!t[l.key])},[t,c]),A=u.useCallback((l,i)=>{let d=t[l.key]??K(l),F=l.step||1,C=l.min??-1/0,I=l.max??1/0;c(l,Math.max(C,Math.min(I,d+i*F)))},[t,c]),U=u.useCallback((l,i)=>{let d=l.options||[];if(!d.length)return;let C=(d.findIndex((I)=>I.value===t[l.key])+i+d.length)%d.length;c(l,d[C].value)},[t,c]);B((l,i)=>{if(i.upArrow)h((d)=>Math.max(0,d-1));else if(i.downArrow)h((d)=>Math.min(T.length-1,d+1));else if(i.leftArrow||i.rightArrow){let d=i.leftArrow?-1:1;if(p?.type==="toggle")G(p);else if(p?.type==="number")A(p,d);else if(p?.type==="select")U(p,d)}},{isActive:!0});let X=0;return f.jsxDEV(g,{flexDirection:"column",paddingX:2,paddingY:1,children:[y.map((l)=>f.jsxDEV(g,{flexDirection:"column",marginBottom:1,children:[f.jsxDEV(r,{bold:!0,color:"gray",children:["[",l.label,"]"]},void 0,!0,void 0,this),l.fields.map((i)=>{let F=X++===P;return f.jsxDEV(g,{flexDirection:"column",children:[f.jsxDEV(M,{field:i,value:t[i.key],onChange:(C)=>c(i,C),isFocused:F},void 0,!1,void 0,this),F&&i.help&&f.jsxDEV(r,{dimColor:!0,color:"yellow",children:[" ","→ ",i.help]},void 0,!0,void 0,this)]},i.key,!0,void 0,this)})]},l.id,!0,void 0,this)),f.jsxDEV(g,{marginTop:1,children:f.jsxDEV(r,{dimColor:!0,children:"↑↓ 导航 | ←→ 修改"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},v=Q;var s=m(b(),1),W=({onClose:e})=>{let{config:t,updateConfig:o}=k(),[a,y]=w.useState("General"),T=S.length>1,P=w.useCallback(async(p,c)=>{await o({[p]:c})},[o]),h=w.useCallback((p)=>{if(!T)return;let G=(S.findIndex((A)=>A.id===a)+p+S.length)%S.length;y(S[G].id)},[a,T]);if(B((p,c)=>{if(c.escape)e();else if(c.leftArrow&&c.alt)h(-1);else if(c.rightArrow&&c.alt)h(1)},{isActive:t!==null}),!t)return s.jsxDEV(g,{padding:2,children:s.jsxDEV(r,{children:"Loading..."},void 0,!1,void 0,this)},void 0,!1,void 0,this);return s.jsxDEV(g,{flexDirection:"column",width:"100%",borderStyle:"single",borderColor:"gray",children:[s.jsxDEV(g,{paddingX:2,borderBottom:!0,borderColor:"gray",children:s.jsxDEV(r,{bold:!0,color:"cyan",children:"⚙ Settings"},void 0,!1,void 0,this)},void 0,!1,void 0,this),T&&s.jsxDEV(g,{flexDirection:"row",gap:2,paddingX:2,borderBottom:!0,borderColor:"gray",children:S.map((p)=>s.jsxDEV(r,{bold:a===p.id,color:a===p.id?"cyan":"gray",children:[p.icon," ",p.label]},p.id,!0,void 0,this))},void 0,!1,void 0,this),s.jsxDEV(v,{schema:x,config:t,onUpdate:P,activeTab:a},void 0,!1,void 0,this),s.jsxDEV(g,{paddingX:2,borderTop:!0,borderColor:"gray",children:s.jsxDEV(r,{dimColor:!0,children:"Esc: Close | Auto-save | Global: Ctrl+O (Compact)"},void 0,!1,void 0,this)},void 0,!1,void 0,this)]},void 0,!0,void 0,this)},N=W;var O=m(b(),1),Z=({onClose:e})=>{return O.jsxDEV(N,{onClose:e},void 0,!1,void 0,this)},ue=Z;export{ue as default};
@@ -1,5 +0,0 @@
1
- import{Ik as m}from"./chunk-n849zsd3.js";var B=Symbol("Let zodToJsonSchema decide on which parser to use");var M={name:void 0,$refStrategy:"root",basePath:["#"],effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",removeAdditionalStrategy:"passthrough",allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref",openAiAnyTypeName:"OpenAiAnyType"},U=(t)=>typeof t==="string"?{...M,name:t}:{...M,...t};var b=(t,n)=>{let r=0;for(;r<t.length&&r<n.length;r++)if(t[r]!==n[r])break;return[(t.length-r).toString(),...n.slice(r)].join("/")};function D(t){if(t.target!=="openAi")return{};let n=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?b(n,t.currentPath):n.join("/")}}function S(t,n,r,o){if(!o?.errorMessages)return;if(r)t.errorMessage={...t.errorMessage,[n]:r}}function e(t,n,r,o,p){t[n]=r,S(t,n,o,p)}function w(t,n){let r={type:"array"};if(t.type?._def&&t.type?._def?.typeName!==m.ZodAny)r.items=i(t.type._def,{...n,currentPath:[...n.currentPath,"items"]});if(t.minLength)e(r,"minItems",t.minLength.value,t.minLength.message,n);if(t.maxLength)e(r,"maxItems",t.maxLength.value,t.maxLength.message,n);if(t.exactLength)e(r,"minItems",t.exactLength.value,t.exactLength.message,n),e(r,"maxItems",t.exactLength.value,t.exactLength.message,n);return r}function E(t,n){let r={type:"integer",format:"int64"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"min":if(n.target==="jsonSchema7")if(o.inclusive)e(r,"minimum",o.value,o.message,n);else e(r,"exclusiveMinimum",o.value,o.message,n);else{if(!o.inclusive)r.exclusiveMinimum=!0;e(r,"minimum",o.value,o.message,n)}break;case"max":if(n.target==="jsonSchema7")if(o.inclusive)e(r,"maximum",o.value,o.message,n);else e(r,"exclusiveMaximum",o.value,o.message,n);else{if(!o.inclusive)r.exclusiveMaximum=!0;e(r,"maximum",o.value,o.message,n)}break;case"multipleOf":e(r,"multipleOf",o.value,o.message,n);break}return r}function K(){return{type:"boolean"}}function N(t,n){return i(t.type._def,n)}var $=(t,n)=>{return i(t.innerType._def,n)};function O(t,n,r){let o=r??n.dateStrategy;if(Array.isArray(o))return{anyOf:o.map((p,u)=>O(t,n,p))};switch(o){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return it(t,n)}}var it=(t,n)=>{let r={type:"integer",format:"unix-time"};if(n.target==="openApi3")return r;for(let o of t.checks)switch(o.kind){case"min":e(r,"minimum",o.value,o.message,n);break;case"max":e(r,"maximum",o.value,o.message,n);break}return r};function J(t,n){return{...i(t.innerType._def,n),default:t.defaultValue()}}function q(t,n){return n.effectStrategy==="input"?i(t.schema._def,n):D(n)}function Q(t){return{type:"string",enum:Array.from(t.values)}}var ut=(t)=>{if("type"in t&&t.type==="string")return!1;return"allOf"in t};function X(t,n){let r=[i(t.left._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),i(t.right._def,{...n,currentPath:[...n.currentPath,"allOf","1"]})].filter((u)=>!!u),o=n.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,p=[];return r.forEach((u)=>{if(ut(u)){if(p.push(...u.allOf),u.unevaluatedProperties===void 0)o=void 0}else{let l=u;if("additionalProperties"in u&&u.additionalProperties===!1){let{additionalProperties:y,...a}=u;l=a}else o=void 0;p.push(l)}}),p.length?{allOf:p,...o}:void 0}function Y(t,n){let r=typeof t.value;if(r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string")return{type:Array.isArray(t.value)?"array":"object"};if(n.target==="openApi3")return{type:r==="bigint"?"integer":r,enum:[t.value]};return{type:r==="bigint"?"integer":r,const:t.value}}var I=void 0,Z={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>{if(I===void 0)I=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u");return I},uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function A(t,n){let r={type:"string"};if(t.checks)for(let o of t.checks)switch(o.kind){case"min":e(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,o.value):o.value,o.message,n);break;case"max":e(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,o.value):o.value,o.message,n);break;case"email":switch(n.emailStrategy){case"format:email":v(r,"email",o.message,n);break;case"format:idn-email":v(r,"idn-email",o.message,n);break;case"pattern:zod":g(r,Z.email,o.message,n);break}break;case"url":v(r,"uri",o.message,n);break;case"uuid":v(r,"uuid",o.message,n);break;case"regex":g(r,o.regex,o.message,n);break;case"cuid":g(r,Z.cuid,o.message,n);break;case"cuid2":g(r,Z.cuid2,o.message,n);break;case"startsWith":g(r,RegExp(`^${L(o.value,n)}`),o.message,n);break;case"endsWith":g(r,RegExp(`${L(o.value,n)}$`),o.message,n);break;case"datetime":v(r,"date-time",o.message,n);break;case"date":v(r,"date",o.message,n);break;case"time":v(r,"time",o.message,n);break;case"duration":v(r,"duration",o.message,n);break;case"length":e(r,"minLength",typeof r.minLength==="number"?Math.max(r.minLength,o.value):o.value,o.message,n),e(r,"maxLength",typeof r.maxLength==="number"?Math.min(r.maxLength,o.value):o.value,o.message,n);break;case"includes":{g(r,RegExp(L(o.value,n)),o.message,n);break}case"ip":{if(o.version!=="v6")v(r,"ipv4",o.message,n);if(o.version!=="v4")v(r,"ipv6",o.message,n);break}case"base64url":g(r,Z.base64url,o.message,n);break;case"jwt":g(r,Z.jwt,o.message,n);break;case"cidr":{if(o.version!=="v6")g(r,Z.ipv4Cidr,o.message,n);if(o.version!=="v4")g(r,Z.ipv6Cidr,o.message,n);break}case"emoji":g(r,Z.emoji(),o.message,n);break;case"ulid":{g(r,Z.ulid,o.message,n);break}case"base64":{switch(n.base64Strategy){case"format:binary":{v(r,"binary",o.message,n);break}case"contentEncoding:base64":{e(r,"contentEncoding","base64",o.message,n);break}case"pattern:zod":{g(r,Z.base64,o.message,n);break}}break}case"nanoid":g(r,Z.nanoid,o.message,n);case"toLowerCase":case"toUpperCase":case"trim":break;default:((p)=>{})(o)}return r}function L(t,n){return n.patternStrategy==="escape"?at(t):t}var mt=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function at(t){let n="";for(let r=0;r<t.length;r++){if(!mt.has(t[r]))n+="\\";n+=t[r]}return n}function v(t,n,r,o){if(t.format||t.anyOf?.some((p)=>p.format)){if(!t.anyOf)t.anyOf=[];if(t.format){if(t.anyOf.push({format:t.format,...t.errorMessage&&o.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage){if(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0)delete t.errorMessage}}t.anyOf.push({format:n,...r&&o.errorMessages&&{errorMessage:{format:r}}})}else e(t,"format",n,r,o)}function g(t,n,r,o){if(t.pattern||t.allOf?.some((p)=>p.pattern)){if(!t.allOf)t.allOf=[];if(t.pattern){if(t.allOf.push({pattern:t.pattern,...t.errorMessage&&o.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage){if(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0)delete t.errorMessage}}t.allOf.push({pattern:H(n,o),...r&&o.errorMessages&&{errorMessage:{pattern:r}}})}else e(t,"pattern",H(n,o),r,o)}function H(t,n){if(!n.applyRegexFlags||!t.flags)return t.source;let r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},o=r.i?t.source.toLowerCase():t.source,p="",u=!1,l=!1,y=!1;for(let a=0;a<o.length;a++){if(u){p+=o[a],u=!1;continue}if(r.i){if(l){if(o[a].match(/[a-z]/)){if(y)p+=o[a],p+=`${o[a-2]}-${o[a]}`.toUpperCase(),y=!1;else if(o[a+1]==="-"&&o[a+2]?.match(/[a-z]/))p+=o[a],y=!0;else p+=`${o[a]}${o[a].toUpperCase()}`;continue}}else if(o[a].match(/[a-z]/)){p+=`[${o[a]}${o[a].toUpperCase()}]`;continue}}if(r.m){if(o[a]==="^"){p+=`(^|(?<=[\r
2
- ]))`;continue}else if(o[a]==="$"){p+=`($|(?=[\r
3
- ]))`;continue}}if(r.s&&o[a]==="."){p+=l?`${o[a]}\r
4
- `:`[${o[a]}\r
5
- ]`;continue}if(p+=o[a],o[a]==="\\")u=!0;else if(l&&o[a]==="]")l=!1;else if(!l&&o[a]==="[")l=!0}try{new RegExp(p)}catch{return console.warn(`Could not convert regex pattern at ${n.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return p}function P(t,n){if(n.target==="openAi")console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.");if(n.target==="openApi3"&&t.keyType?._def.typeName===m.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,p)=>({...o,[p]:i(t.valueType._def,{...n,currentPath:[...n.currentPath,"properties",p]})??D(n)}),{}),additionalProperties:n.rejectedAdditionalProperties};let r={type:"object",additionalProperties:i(t.valueType._def,{...n,currentPath:[...n.currentPath,"additionalProperties"]})??n.allowedAdditionalProperties};if(n.target==="openApi3")return r;if(t.keyType?._def.typeName===m.ZodString&&t.keyType._def.checks?.length){let{type:o,...p}=A(t.keyType._def,n);return{...r,propertyNames:p}}else if(t.keyType?._def.typeName===m.ZodEnum)return{...r,propertyNames:{enum:t.keyType._def.values}};else if(t.keyType?._def.typeName===m.ZodBranded&&t.keyType._def.type._def.typeName===m.ZodString&&t.keyType._def.type._def.checks?.length){let{type:o,...p}=N(t.keyType._def,n);return{...r,propertyNames:p}}return r}function V(t,n){if(n.mapStrategy==="record")return P(t,n);let r=i(t.keyType._def,{...n,currentPath:[...n.currentPath,"items","items","0"]})||D(n),o=i(t.valueType._def,{...n,currentPath:[...n.currentPath,"items","items","1"]})||D(n);return{type:"array",maxItems:125,items:{type:"array",items:[r,o],minItems:2,maxItems:2}}}function W(t){let n=t.values,o=Object.keys(t.values).filter((u)=>{return typeof n[n[u]]!=="number"}).map((u)=>n[u]),p=Array.from(new Set(o.map((u)=>typeof u)));return{type:p.length===1?p[0]==="string"?"string":"number":["string","number"],enum:o}}function z(t){return t.target==="openAi"?void 0:{not:D({...t,currentPath:[...t.currentPath,"not"]})}}function F(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var _={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function G(t,n){if(n.target==="openApi3")return d(t,n);let r=t.options instanceof Map?Array.from(t.options.values()):t.options;if(r.every((o)=>(o._def.typeName in _)&&(!o._def.checks||!o._def.checks.length))){let o=r.reduce((p,u)=>{let l=_[u._def.typeName];return l&&!p.includes(l)?[...p,l]:p},[]);return{type:o.length>1?o:o[0]}}else if(r.every((o)=>o._def.typeName==="ZodLiteral"&&!o.description)){let o=r.reduce((p,u)=>{let l=typeof u._def.value;switch(l){case"string":case"number":case"boolean":return[...p,l];case"bigint":return[...p,"integer"];case"object":if(u._def.value===null)return[...p,"null"];case"symbol":case"undefined":case"function":default:return p}},[]);if(o.length===r.length){let p=o.filter((u,l,y)=>y.indexOf(u)===l);return{type:p.length>1?p:p[0],enum:r.reduce((u,l)=>{return u.includes(l._def.value)?u:[...u,l._def.value]},[])}}}else if(r.every((o)=>o._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((o,p)=>[...o,...p._def.values.filter((u)=>!o.includes(u))],[])};return d(t,n)}var d=(t,n)=>{let r=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((o,p)=>i(o._def,{...n,currentPath:[...n.currentPath,"anyOf",`${p}`]})).filter((o)=>!!o&&(!n.strictUnions||typeof o==="object"&&Object.keys(o).length>0));return r.length?{anyOf:r}:void 0};function j(t,n){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length)){if(n.target==="openApi3")return{type:_[t.innerType._def.typeName],nullable:!0};return{type:[_[t.innerType._def.typeName],"null"]}}if(n.target==="openApi3"){let o=i(t.innerType._def,{...n,currentPath:[...n.currentPath]});if(o&&"$ref"in o)return{allOf:[o],nullable:!0};return o&&{...o,nullable:!0}}let r=i(t.innerType._def,{...n,currentPath:[...n.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function C(t,n){let r={type:"number"};if(!t.checks)return r;for(let o of t.checks)switch(o.kind){case"int":r.type="integer",S(r,"type",o.message,n);break;case"min":if(n.target==="jsonSchema7")if(o.inclusive)e(r,"minimum",o.value,o.message,n);else e(r,"exclusiveMinimum",o.value,o.message,n);else{if(!o.inclusive)r.exclusiveMinimum=!0;e(r,"minimum",o.value,o.message,n)}break;case"max":if(n.target==="jsonSchema7")if(o.inclusive)e(r,"maximum",o.value,o.message,n);else e(r,"exclusiveMaximum",o.value,o.message,n);else{if(!o.inclusive)r.exclusiveMaximum=!0;e(r,"maximum",o.value,o.message,n)}break;case"multipleOf":e(r,"multipleOf",o.value,o.message,n);break}return r}function R(t,n){let r=n.target==="openAi",o={type:"object",properties:{}},p=[],u=t.shape();for(let y in u){let a=u[y];if(a===void 0||a._def===void 0)continue;let x=lt(a);if(x&&r){if(a._def.typeName==="ZodOptional")a=a._def.innerType;if(!a.isNullable())a=a.nullable();x=!1}let T=i(a._def,{...n,currentPath:[...n.currentPath,"properties",y],propertyPath:[...n.currentPath,"properties",y]});if(T===void 0)continue;if(o.properties[y]=T,!x)p.push(y)}if(p.length)o.required=p;let l=et(t,n);if(l!==void 0)o.additionalProperties=l;return o}function et(t,n){if(t.catchall._def.typeName!=="ZodNever")return i(t.catchall._def,{...n,currentPath:[...n.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return n.allowedAdditionalProperties;case"strict":return n.rejectedAdditionalProperties;case"strip":return n.removeAdditionalStrategy==="strict"?n.allowedAdditionalProperties:n.rejectedAdditionalProperties}}function lt(t){try{return t.isOptional()}catch{return!0}}var k=(t,n)=>{if(n.currentPath.toString()===n.propertyPath?.toString())return i(t.innerType._def,n);let r=i(t.innerType._def,{...n,currentPath:[...n.currentPath,"anyOf","1"]});return r?{anyOf:[{not:D(n)},r]}:D(n)};var c=(t,n)=>{if(n.pipeStrategy==="input")return i(t.in._def,n);else if(n.pipeStrategy==="output")return i(t.out._def,n);let r=i(t.in._def,{...n,currentPath:[...n.currentPath,"allOf","0"]}),o=i(t.out._def,{...n,currentPath:[...n.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,o].filter((p)=>p!==void 0)}};function h(t,n){return i(t.type._def,n)}function f(t,n){let o={type:"array",uniqueItems:!0,items:i(t.valueType._def,{...n,currentPath:[...n.currentPath,"items"]})};if(t.minSize)e(o,"minItems",t.minSize.value,t.minSize.message,n);if(t.maxSize)e(o,"maxItems",t.maxSize.value,t.maxSize.message,n);return o}function s(t,n){if(t.rest)return{type:"array",minItems:t.items.length,items:t.items.map((r,o)=>i(r._def,{...n,currentPath:[...n.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[]),additionalItems:i(t.rest._def,{...n,currentPath:[...n.currentPath,"additionalItems"]})};else return{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((r,o)=>i(r._def,{...n,currentPath:[...n.currentPath,"items",`${o}`]})).reduce((r,o)=>o===void 0?r:[...r,o],[])}}function tt(t){return{not:D(t)}}function nt(t){return D(t)}var rt=(t,n)=>{return i(t.innerType._def,n)};var ot=(t,n,r)=>{switch(n){case m.ZodString:return A(t,r);case m.ZodNumber:return C(t,r);case m.ZodObject:return R(t,r);case m.ZodBigInt:return E(t,r);case m.ZodBoolean:return K();case m.ZodDate:return O(t,r);case m.ZodUndefined:return tt(r);case m.ZodNull:return F(r);case m.ZodArray:return w(t,r);case m.ZodUnion:case m.ZodDiscriminatedUnion:return G(t,r);case m.ZodIntersection:return X(t,r);case m.ZodTuple:return s(t,r);case m.ZodRecord:return P(t,r);case m.ZodLiteral:return Y(t,r);case m.ZodEnum:return Q(t);case m.ZodNativeEnum:return W(t);case m.ZodNullable:return j(t,r);case m.ZodOptional:return k(t,r);case m.ZodMap:return V(t,r);case m.ZodSet:return f(t,r);case m.ZodLazy:return()=>t.getter()._def;case m.ZodPromise:return h(t,r);case m.ZodNaN:case m.ZodNever:return z(r);case m.ZodEffects:return q(t,r);case m.ZodAny:return D(r);case m.ZodUnknown:return nt(r);case m.ZodDefault:return J(t,r);case m.ZodBranded:return N(t,r);case m.ZodReadonly:return rt(t,r);case m.ZodCatch:return $(t,r);case m.ZodPipeline:return c(t,r);case m.ZodFunction:case m.ZodVoid:case m.ZodSymbol:return;default:return((o)=>{return})(n)}};function i(t,n,r=!1){let o=n.seen.get(t);if(n.override){let y=n.override?.(t,n,o,r);if(y!==B)return y}if(o&&!r){let y=yt(o,n);if(y!==void 0)return y}let p={def:t,path:n.currentPath,jsonSchema:void 0};n.seen.set(t,p);let u=ot(t,t.typeName,n),l=typeof u==="function"?i(u(),n):u;if(l)Dt(t,n,l);if(n.postProcess){let y=n.postProcess(l,t,n);return p.jsonSchema=l,y}return p.jsonSchema=l,l}var yt=(t,n)=>{switch(n.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:b(n.currentPath,t.path)};case"none":case"seen":{if(t.path.length<n.currentPath.length&&t.path.every((r,o)=>n.currentPath[o]===r))return console.warn(`Recursive reference detected at ${n.currentPath.join("/")}! Defaulting to any`),D(n);return n.$refStrategy==="seen"?D(n):void 0}}},Dt=(t,n,r)=>{if(t.description){if(r.description=t.description,n.markdownDescription)r.markdownDescription=t.description}return r};var pt=(t)=>{let n=U(t),r=n.name!==void 0?[...n.basePath,n.definitionPath,n.name]:n.basePath;return{...n,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(n.definitions).map(([o,p])=>[p._def,{def:p._def,path:[...n.basePath,n.definitionPath,o],jsonSchema:void 0}]))}};var gt=(t,n)=>{let r=pt(n),o=typeof n==="object"&&n.definitions?Object.entries(n.definitions).reduce((a,[x,T])=>({...a,[x]:i(T._def,{...r,currentPath:[...r.basePath,r.definitionPath,x]},!0)??D(r)}),{}):void 0,p=typeof n==="string"?n:n?.nameStrategy==="title"?void 0:n?.name,u=i(t._def,p===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,p]},!1)??D(r),l=typeof n==="object"&&n.name!==void 0&&n.nameStrategy==="title"?n.name:void 0;if(l!==void 0)u.title=l;if(r.flags.hasReferencedOpenAiAnyType){if(!o)o={};if(!o[r.openAiAnyTypeName])o[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}}let y=p===void 0?o?{...u,[r.definitionPath]:o}:u:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,p].join("/"),[r.definitionPath]:{...o,[p]:u}};if(r.target==="jsonSchema7")y.$schema="http://json-schema.org/draft-07/schema#";else if(r.target==="jsonSchema2019-09"||r.target==="openAi")y.$schema="https://json-schema.org/draft/2019-09/schema#";if(r.target==="openAi"&&(("anyOf"in y)||("oneOf"in y)||("allOf"in y)||("type"in y)&&Array.isArray(y.type)))console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.");return y};export{gt as ig};
@@ -1 +0,0 @@
1
- import{jf as a}from"./chunk-pxdgy0vr.js";import"./chunk-z3e4c424.js";export{a as FileSystemPluginStore};
@@ -1 +0,0 @@
1
- import{kf as a,lf as b}from"./chunk-k6fxqssr.js";import"./chunk-b2551zfb.js";import"./chunk-vd8kwzra.js";import"./chunk-z3e4c424.js";export{a as createFSManager,b as createCustomManager};
@@ -1,54 +0,0 @@
1
- import{Ag as w0,Bg as h8,lg as C8,mg as k,ng as M,og as T,pg as p,qg as e0,rg as R8,vg as e,wg as f0,xg as h,yg as R0,zg as D0}from"./chunk-9tgp14v7.js";import{Vg as C0}from"./chunk-hz9yw7cs.js";import{$j as b0,Aj as O0,Ej as D8,Hj as X0,Ij as O8,Qh as i0,Qj as a,Rj as W8,Tj as P8,Wj as E0,Yj as L8,Zi as d0,ai as P,dj as o,dk as P0,ej as V0,ek as i,hi as q,hj as b8,hk as K0,jj as T0,jk as x0,ki as g0,lj as s0,mh as h0,uh as E8,wj as z0,wk as n0,xj as I0,yi as u,yk as f8}from"./chunk-tn356gwf.js";import{Jk as $}from"./chunk-n849zsd3.js";import{Vk as K8,vl as c}from"./chunk-vd8kwzra.js";var _0=Symbol.for("AgentMiddleware");function S(X){return{[_0]:!0,name:X.name,stateSchema:X.stateSchema,contextSchema:X.contextSchema,wrapToolCall:X.wrapToolCall,wrapModelCall:X.wrapModelCall,beforeAgent:X.beforeAgent,beforeModel:X.beforeModel,afterModel:X.afterModel,afterAgent:X.afterAgent,tools:X.tools}}var v0={openai:{package:"@langchain/openai",className:"ChatOpenAI"},anthropic:{package:"@langchain/anthropic",className:"ChatAnthropic"},azure_openai:{package:"@langchain/openai",className:"AzureChatOpenAI"},cohere:{package:"@langchain/cohere",className:"ChatCohere"},"google-vertexai":{package:"@langchain/google-vertexai",className:"ChatVertexAI"},"google-vertexai-web":{package:"@langchain/google-vertexai-web",className:"ChatVertexAI"},"google-genai":{package:"@langchain/google-genai",className:"ChatGoogleGenerativeAI"},ollama:{package:"@langchain/ollama",className:"ChatOllama"},mistralai:{package:"@langchain/mistralai",className:"ChatMistralAI"},mistral:{package:"@langchain/mistralai",className:"ChatMistralAI"},groq:{package:"@langchain/groq",className:"ChatGroq"},cerebras:{package:"@langchain/cerebras",className:"ChatCerebras"},bedrock:{package:"@langchain/aws",className:"ChatBedrockConverse"},deepseek:{package:"@langchain/deepseek",className:"ChatDeepSeek"},xai:{package:"@langchain/xai",className:"ChatXAI"},fireworks:{package:"@langchain/community/chat_models/fireworks",className:"ChatFireworks",hasCircularDependency:!0},together:{package:"@langchain/community/chat_models/togetherai",className:"ChatTogetherAI",hasCircularDependency:!0},perplexity:{package:"@langchain/community/chat_models/perplexity",className:"ChatPerplexity",hasCircularDependency:!0}},t0=Object.keys(v0);async function c8(X,Q){let Z;if(Q)Z=v0[Q];else{let Y=Object.entries(v0).find(([,J])=>J.className===X);Z=Y?Y[1]:void 0}if(!Z)return;try{return(await import(Z.package))[Z.className]}catch(Y){let J=Y;if("code"in J&&J.code?.toString().includes("ERR_MODULE_NOT_FOUND")&&"message"in J&&typeof J.message==="string"){let K=(J.message.startsWith("Error: ")?J.message.slice(7):J.message).split("Cannot find package '")[1].split("'")[0];throw Error(`Unable to import ${K}. Please install with \`npm install ${K}\` or \`pnpm install ${K}\``)}throw Y}}async function g8(X,Q,Z={}){let Y=Q||m8(X);if(!Y)throw Error(`Unable to infer model provider for { model: ${X} }, please specify modelProvider directly.`);let J=v0[Y];if(!J){let V=t0.join(", ");throw Error(`Unsupported { modelProvider: ${Y} }.
2
-
3
- Supported model providers are: ${V}`)}let{modelProvider:K,...G}=Z;return new(await c8(J.className,Y))({model:X,...G})}function m8(X){if(X.startsWith("gpt-3")||X.startsWith("gpt-4")||X.startsWith("gpt-5")||X.startsWith("o1")||X.startsWith("o3")||X.startsWith("o4"))return"openai";else if(X.startsWith("claude"))return"anthropic";else if(X.startsWith("command"))return"cohere";else if(X.startsWith("accounts/fireworks"))return"fireworks";else if(X.startsWith("gemini"))return"google-vertexai";else if(X.startsWith("amazon."))return"bedrock";else if(X.startsWith("mistral"))return"mistralai";else if(X.startsWith("sonar")||X.startsWith("pplx"))return"perplexity";else return}var o0=class X extends C0{_llmType(){return"chat_model"}lc_namespace=["langchain","chat_models"];_defaultConfig={};_configurableFields="any";_configPrefix;_queuedMethodOperations={};_modelInstanceCache=new Map;_profile;constructor(Q){super(Q);if(this._defaultConfig=Q.defaultConfig??{},Q.configurableFields==="any")this._configurableFields="any";else this._configurableFields=Q.configurableFields??["model","modelProvider"];if(Q.configPrefix)this._configPrefix=Q.configPrefix.endsWith("_")?Q.configPrefix:`${Q.configPrefix}_`;else this._configPrefix="";this._queuedMethodOperations=Q.queuedMethodOperations??this._queuedMethodOperations,this._profile=Q.profile??void 0}async _getModelInstance(Q){let Z=this._getCacheKey(Q),Y=this._modelInstanceCache.get(Z);if(Y)return Y;let J={...this._defaultConfig,...this._modelParams(Q)},K=await g8(J.model,J.modelProvider,J);for(let[G,V]of Object.entries(this._queuedMethodOperations))if(G in K&&typeof K[G]==="function")K=await K[G](...V);return this._modelInstanceCache.set(Z,K),K}async _generate(Q,Z,Y){return(await this._getModelInstance(Z))._generate(Q,Z??{},Y)}bindTools(Q,Z){let Y={...this._queuedMethodOperations};return Y.bindTools=[Q,Z],new X({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:Y})}withStructuredOutput=(Q,...Z)=>{let Y={...this._queuedMethodOperations};return Y.withStructuredOutput=[Q,...Z],new X({defaultConfig:this._defaultConfig,configurableFields:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:Y})};_modelParams(Q){let Z=Q?.configurable??{},Y={};for(let[J,K]of Object.entries(Z))if(J.startsWith(this._configPrefix)){let G=this._removePrefix(J,this._configPrefix);Y[G]=K}if(this._configurableFields!=="any")Y=Object.fromEntries(Object.entries(Y).filter(([J])=>this._configurableFields.includes(J)));return Y}_removePrefix(Q,Z){return Q.startsWith(Z)?Q.slice(Z.length):Q}withConfig(Q){let Z={...Q||{}},Y=this._modelParams(Z),J=Object.fromEntries(Object.entries(Z).filter(([K])=>K!=="configurable"));return J.configurable=Object.fromEntries(Object.entries(Z.configurable||{}).filter(([K])=>this._configPrefix&&!Object.keys(Y).includes(this._removePrefix(K,this._configPrefix)))),new i({config:Z,bound:new X({defaultConfig:{...this._defaultConfig,...Y},configurableFields:Array.isArray(this._configurableFields)?[...this._configurableFields]:this._configurableFields,configPrefix:this._configPrefix,queuedMethodOperations:this._queuedMethodOperations})})}async invoke(Q,Z){let Y=await this._getModelInstance(Z),J=V0(Z);return Y.invoke(Q,J)}async stream(Q,Z){let Y=new s0({generator:await(await this._getModelInstance(Z)).stream(Q,Z),config:Z});return await Y.setup,T0.fromAsyncGenerator(Y)}async batch(Q,Z,Y){return super.batch(Q,Z,Y)}async*transform(Q,Z){let Y=await this._getModelInstance(Z),J=V0(Z);yield*Y.transform(Q,J)}async*streamLog(Q,Z,Y){let J=await this._getModelInstance(Z),K=V0(Z);yield*J.streamLog(Q,K,{...Y,_schemaFormat:"original",includeNames:Y?.includeNames,includeTypes:Y?.includeTypes,includeTags:Y?.includeTags,excludeNames:Y?.excludeNames,excludeTypes:Y?.excludeTypes,excludeTags:Y?.excludeTags})}streamEvents(Q,Z,Y){let J=this;async function*K(){let G=await J._getModelInstance(Z),V=V0(Z),U=G.streamEvents(Q,V,Y);for await(let W of U)yield W}return T0.fromAsyncGenerator(K())}get profile(){if(this._profile)return this._profile;let Q=this._getCacheKey({});return this._modelInstanceCache.get(Q)?.profile??{}}_getCacheKey(Q){let Z=Q??{};if(Z.configurable){let{configurable:Y}=Z,J={};for(let[K,G]of Object.entries(Y))if(!K.startsWith("__pregel_"))J[K]=G;Z={...Z,configurable:J}}return JSON.stringify(Z)}};async function s(X,Q){let{configurableFields:Z,configPrefix:Y,modelProvider:J,profile:K,...G}={configPrefix:"",...Q??{}};if(J===void 0&&X?.includes(":")){let[z,...F]=X.split(":"),j=F.length===0?[z]:[z,F.join(":")];if(t0.includes(j[0]))[J,X]=j}let V=Array.isArray(Z)?[...Z]:Z;if(!X&&V===void 0)V=["model","modelProvider"];if(Y&&V===void 0)console.warn(`{ configPrefix: ${Y} } has been set but no fields are configurable. Set { configurableFields: [...] } to specify the model params that are configurable.`);let U={...G},W;if(V===void 0)W=new o0({defaultConfig:{...U,model:X,modelProvider:J},configPrefix:Y,profile:K});else{if(X)U.model=X;if(J)U.modelProvider=J;W=new o0({defaultConfig:U,configPrefix:Y,configurableFields:V,profile:K})}return await W._getModelInstance(),W}var H0=class extends Error{constructor(){super("The provided LLM already has bound tools. Please provide an LLM without bound tools to createAgent. The agent will bind the tools provided in the 'tools' parameter.")}},U0=class extends Error{toolNames;constructor(X){super(`The model has called multiple tools: ${X.join(", ")} to return a structured output. This is not supported. Please provide a single structured output.`);this.toolNames=X}},F0=class extends Error{toolName;errors;constructor(X,Q){super(`Failed to parse structured output for tool '${X}':${Q.map((Z)=>`
4
- - ${Z}`).join("")}.`);this.toolName=X,this.errors=Q}},B0=class extends Error{toolCall;toolError;constructor(X,Q){let Z=X instanceof Error?X:Error(String(X)),Y=JSON.stringify(Q.args);super(`Error invoking tool '${Q.name}' with kwargs ${Y} with error: ${Z.stack}
5
- Please fix the error and try again.`);this.toolCall=Q,this.toolError=Z}},Z0=class X extends Error{static "~brand"="MiddlewareError";constructor(Q,Z){let Y=Q instanceof Error?Q.message:String(Q);super(Y);if(this.name=Q instanceof Error?Q.name:`${Z[0].toUpperCase()+Z.slice(1)}Error`,Q instanceof Error)this.cause=Q}static wrap(Q,Z){if(e0(Q))return Q;return new X(Q,Z)}static isInstance(Q){return Q instanceof Error&&"~brand"in Q&&Q["~brand"]==="MiddlewareError"}};function j0(X){return"invoke"in X&&typeof X.invoke==="function"&&"_streamResponseChunks"in X}function J0(X){return typeof X==="object"&&X!=null&&"_queuedMethodOperations"in X&&"_getModelInstance"in X&&typeof X._getModelInstance==="function"}var X8=!0,d8=0,f=class X{constructor(Q,Z,Y){this.schema=Q,this.tool=Z,this.options=Y}get name(){return this.tool.function.name}static fromSchema(Q,Z){function Y(K){return K??`extract-${++d8}`}if(z0(Q)||O0(Q)){let K=b0(Q);return new X(K,{type:"function",function:{name:Y(K.title),strict:!1,description:K.description??"Tool for extracting structured output from the model's response.",parameters:K}},Z)}let J;if(typeof Q.name==="string"&&typeof Q.parameters==="object"&&Q.parameters!=null)J=Q;else J={name:Y(Q.title),description:Q.description??"",parameters:Q.schema||Q};return new X(b0(Q),{type:"function",function:J},Z)}parse(Q){let Z=new h0(this.schema).validate(Q);if(!Z.valid)throw new F0(this.name,Z.errors.map((Y)=>Y.error));return Q}},r=class X{_schemaType;schema;strict;constructor(Q,Z){if("schema"in Q&&typeof Q.schema==="object"&&Q.schema!==null&&!("type"in Q)){let Y=Q;this.schema=Y.schema,this.strict=Y.strict??X8}else this.schema=Q,this.strict=Z??X8}static fromSchema(Q,Z){return new X(b0(Q),Z)}parse(Q){let Z;if(typeof Q.content==="string")Z=Q.content;else if(Array.isArray(Q.content)){for(let Y of Q.content)if(typeof Y==="object"&&Y!==null&&"type"in Y&&Y.type==="text"&&"text"in Y&&typeof Y.text==="string"){Z=Y.text;break}}if(!Z||Z==="")return;try{let Y=JSON.parse(Z);if(!new h0(this.schema).validate(Y).valid)return;return Y}catch{}}};function Y8(X,Q,Z){if(!X)return[];if(typeof X==="object"&&X!==null&&"__responseFormatUndefined"in X)return[];if(Array.isArray(X)){if(X.every((J)=>J instanceof f||J instanceof r))return X;if(X.every((J)=>z0(J)))return X.map((J)=>f.fromSchema(J,Q));if(X.every((J)=>a(J)))return X.map((J)=>f.fromSchema(J,Q));if(X.every((J)=>typeof J==="object"&&J!==null&&!a(J)&&!z0(J)))return X.map((J)=>f.fromSchema(J,Q));throw Error(`Invalid response format: list contains mixed types.
6
- All items must be either InteropZodObject, Standard Schema, or plain JSON schema objects.`)}if(X instanceof f||X instanceof r)return[X];let Y=Z8(Z);if(z0(X))return Y?[r.fromSchema(X)]:[f.fromSchema(X,Q)];if(a(X))return Y?[r.fromSchema(X)]:[f.fromSchema(X,Q)];if(typeof X==="object"&&X!==null&&"properties"in X)return Y?[r.fromSchema(X)]:[f.fromSchema(X,Q)];throw Error(`Invalid response format: ${String(X)}`)}var i8=["ChatOpenAI","ChatXAI"],Q8=["grok","gpt-5","gpt-4.1","gpt-4o","gpt-oss","o3-pro","o3-mini"];function Z8(X){if(!X)return!1;if(typeof X==="string"){let Z=X.split(":").pop();return Q8.some((Y)=>Z.includes(Y))}if(J0(X))return Z8(X._defaultConfig.model);if(!j0(X))return!1;let Q=X.getName();if(Q==="FakeToolCallingChatModel")return!0;if(i8.includes(Q)&&(("model"in X)&&Q8.some((Z)=>typeof X.model==="string"&&X.model.includes(Z))||Q==="FakeToolCallingModel"&&("structuredResponse"in X)))return!0;return!1}function n(X){if(!X||typeof X==="function")return;return X.canJumpTo}function t(X){if(typeof X==="function")return X;return X.hook}var M0=Symbol.for("langgraph-zod");if(!(M0 in globalThis))globalThis[M0]=new WeakSet;function J8(X){let Q=globalThis[M0];if(Q.has(X))return;Object.defineProperty(X,"langgraph",{get(){let Z=this;return{metadata(Y){return w0(Z,{jsonSchemaExtra:Y})},reducer(Y,J){return w0(Z,{default:E0(Z),reducer:{schema:J,fn:Y}})}}}}),Q.add(X)}try{J8($.ZodType.prototype),J8(c.ZodType.prototype)}catch(X){throw Error("Failed to extend Zod with LangGraph-related methods. This is most likely a bug, consider opening an issue and/or using `withLangGraph` to augment your Zod schema.",{cause:X})}var $8=class extends K8{constructor(X){super();this.parent=X,this._map=this.parent._map}add(X,...Q){let Z=Q[0];if(Z&&!Z?.default){let Y=E0(X);if(Y!=null)Z.default=Y}return super.add(X,...Q)}},l8=new $8(D0);function G8(X=!0,Q,Z=[]){let Y={jumpTo:new f0},J={},K={},G=(V)=>{if(h.isInstance(V)){for(let[W,z]of Object.entries(V.fields))if(!(W in Y)){if(Y[W]=z,W.startsWith("_"))continue;if(e.isInstance(z))J[W]=z.inputSchema||z.valueSchema,K[W]=z.valueSchema;else J[W]=z,K[W]=z}return}let U=W8(V);for(let[W,z]of Object.entries(U)){let F=W.startsWith("_");if(!(W in Y)){if(I0(z)){let j=D0.get(z);if(j?.reducer){if(j.reducer.schema){if(Y[W]=new e(z,{inputSchema:j.reducer.schema,reducer:j.reducer.fn}),!F)J[W]=j.reducer.schema,K[W]=z}else if(Y[W]=new e(z,{reducer:j.reducer.fn}),!F)J[W]=z,K[W]=z;continue}}if(Y[W]=z,!F)J[W]=z,K[W]=z}}};if(Q&&(h.isInstance(Q)||a(Q)))G(Q);for(let V of Z)if(V.stateSchema&&(h.isInstance(V.stateSchema)||a(V.stateSchema)))G(V.stateSchema);if(X)K.structuredResponse=new f0;return{state:new h({messages:R0,...Y}),input:new h({messages:R0,...J}),output:new h({messages:R0,...K})}}var u0=/<name>(.*?)<\/name>/s,p0=/<content>(.*?)<\/content>/s;function r8(X,Q){if(h.isInstance(X)){let Z={};for(let Y of Object.keys(X.fields))if(Y in Q)Z[Y]=Q[Y];return Z}if(O0(X))return X0(X,Q);throw Error(`Invalid state schema type: ${typeof X}`)}function H8(X){if(!q.isInstance(X)||g0.isInstance(X))return X;if(!X.name)return X;let{name:Q}=X;if(typeof X.content==="string")return new q({...X.lc_kwargs,content:`<name>${Q}</name><content>${X.content}</content>`,name:void 0});let Z=[],Y=0;for(let J of X.content)if(typeof J==="string")Y+=1,Z.push(`<name>${Q}</name><content>${J}</content>`);else if(typeof J==="object"&&"type"in J&&J.type==="text")Y+=1,Z.push({...J,text:`<name>${Q}</name><content>${J.text}</content>`});else Z.push(J);if(!Y)Z.unshift({type:"text",text:`<name>${Q}</name><content></content>`});return new q({...X.lc_kwargs,content:Z,name:void 0})}function U8(X){if(!q.isInstance(X)||!X.content)return X;let Q=[],Z;if(Array.isArray(X.content))Q=X.content.filter((Y)=>{if(Y.type==="text"&&typeof Y.text==="string"){let J=Y.text.match(u0),K=Y.text.match(p0);if(J&&(!K||K[1]===""))return Z=J[1],!1;return!0}return!0}).map((Y)=>{if(Y.type==="text"&&typeof Y.text==="string"){let J=Y.text.match(u0),K=Y.text.match(p0);if(!J||!K)return Y;return Z=J[1],{...Y,text:K[1]}}return Y});else{let Y=X.content,J=Y.match(u0),K=Y.match(p0);if(!J||!K)return X;Z=J[1],Q=K[1]}return new q({...Object.keys(X.lc_kwargs??{}).length>0?X.lc_kwargs:X,content:Q,name:Z})}function $0(X){return P0.isRunnable(X)}function V8(X){if(!j0(X))return!1;return"bindTools"in X&&typeof X.bindTools==="function"}var c0=(X,Q,Z={})=>{if(V8(X))return X.bindTools(Q,Z);if(i.isRunnableBinding(X)&&V8(X.bound)){let Y=X.bound.bindTools(Q,Z);if(i.isRunnableBinding(Y))return new i({bound:Y.bound,config:{...X.config,...Y.config},kwargs:{...X.kwargs,...Y.kwargs},configFactories:Y.configFactories??X.configFactories});return new i({bound:Y,config:X.config,kwargs:X.kwargs,configFactories:X.configFactories})}return null};function k0(X){if(typeof X==="function")return;let Q=X;if(K0.isRunnableSequence(Q))Q=Q.steps.find((Z)=>i.isRunnableBinding(Z))||Q;if(J0(Q))return;if(i.isRunnableBinding(Q)){let Z=Q.kwargs!=null&&typeof Q.kwargs==="object"&&"tools"in Q.kwargs&&Array.isArray(Q.kwargs.tools)&&Q.kwargs.tools.length>0,Y=Q.config!=null&&typeof Q.config==="object"&&"tools"in Q.config&&Array.isArray(Q.config.tools)&&Q.config.tools.length>0;if(Z||Y)throw new H0}if("tools"in Q&&Q.tools!==void 0&&Array.isArray(Q.tools)&&Q.tools.length>0)throw new H0}function m0(X){return Boolean(q.isInstance(X)&&X.tool_calls&&X.tool_calls.length>0)}function B8(X){if(X==null)return new u("");if(u.isInstance(X))return X;if(typeof X==="string")return new u({content:[{type:"text",text:X}]});throw Error(`Invalid systemPrompt type: expected string or SystemMessage, got ${typeof X}`)}async function j8(X,Q,Z={}){let Y=c0(X,Q,Z);if(Y)return Y;if(J0(X)){let J=c0(await X._getModelInstance(),Q,Z);if(J)return J}if(K0.isRunnableSequence(X)){let J=X.steps.findIndex((K)=>i.isRunnableBinding(K)||j0(K)||J0(K));if(J>=0){let K=c0(X.steps[J],Q,Z);if(K){let G=X.steps.slice();return G.splice(J,1,K),K0.from(G)}}}throw Error(`llm ${X} must define bindTools method.`)}function a8(X){if(X.length===0)return;if(X.length===1)return X[0];function Q(Y,J){return async(K,G)=>{return Y(K,async(U)=>{return J(U,G)})}}let Z=X[X.length-1];for(let Y=X.length-2;Y>=0;Y--)Z=Q(X[Y],Z);return Z}function z8(X){let Q=X.filter((Z)=>Z.wrapToolCall);if(Q.length===0)return;return a8(Q.map((Z)=>{let Y=Z.wrapToolCall;return async(K,G)=>{let V=K.state,U=async(W)=>{let z={...V,...W.state};return G({...W,state:z})};try{let W=await Y({...K,state:{messages:V.messages,...Z.stateSchema?r8(Z.stateSchema,{...V}):{}}},U);if(!P.isInstance(W)&&!p(W))throw Error(`Invalid response from "wrapToolCall" in middleware "${Z.name}": expected ToolMessage or Command, got ${typeof W}`);return W}catch(W){throw Z0.wrap(W,Z.name)}}}))}async function q8(X,Q){let Z={};for(let Y of X){if(!Y.stateSchema)continue;let J=Y.stateSchema;if(h.isInstance(Y.stateSchema)){let V={};for(let[U,W]of Object.entries(Y.stateSchema.fields))if(e.isInstance(W))V[U]=W.inputSchema||W.valueSchema;else V[U]=W;J=c.object(V)}let K=await D8(L8(J,(V)=>V.startsWith("_")),Q);if(K.success){Object.assign(Z,K.data);continue}let G=K.error.issues.filter((V)=>V.code==="invalid_type").map((V)=>` - ${V.path.join(".")}: Required`).join(`
7
- `);throw Error(`Middleware "${Y.name}" has required state fields that must be initialized:
8
- ${G}
9
-
10
- To fix this, either:
11
- 1. Provide default values in your middleware's state schema using .default():
12
- stateSchema: z.object({
13
- myField: z.string().default("default value")
14
- })
15
-
16
- 2. Or make the fields optional using .optional():
17
- stateSchema: z.object({
18
- myField: z.string().optional()
19
- })
20
-
21
- 3. Or ensure you pass these values when invoking the agent:
22
- agent.invoke({
23
- messages: [...],
24
- ${K.error.issues[0]?.path.join(".")}: "value"
25
- })`)}return Z}function _8(X){let Q={messages:c.custom(()=>[]),structuredResponse:c.any().optional()};if(!X)return c.object(Q);let Z;if(h.isInstance(X)){Z={};for(let[J,K]of Object.entries(X.fields))if(e.isInstance(K))Z[J]=K.inputSchema||K.valueSchema;else Z[J]=K}else Z=X.shape;let Y={...Q};for(let[J,K]of Object.entries(Z))if(J.startsWith("_"))Y[J]=K.optional();else Y[J]=K;return c.object(Y)}function v8(X){if(a(X))return P8(X);if(h.isInstance(X)){let Q={};for(let[Z,Y]of Object.entries(X.fields)){let J;if(e.isInstance(Y))J=Y.inputSchema||Y.valueSchema;else J=Y;Q[Z]=I0(J)?J.optional():c.any().optional()}return c.object(Q)}return c.object({})}function g(X){if(!X)return;if(["model_request","tools",k].includes(X))return X;if(X==="model")return"model_request";if(X==="tools")return"tools";if(X==="end")return k;throw Error(`Invalid jump target: ${X}, must be "model", "tools" or "end".`)}function y0(...X){return AbortSignal.any(X.filter((Q)=>Q!==null&&Q!==void 0&&typeof Q==="object"&&("aborted"in Q)&&typeof Q.aborted==="boolean"))}var W0=class extends P0{lc_namespace=["langgraph"];func;tags;config;trace=!0;recurse=!0;#X;constructor(X){super();this.name=X.name??X.func.name,this.func=X.func,this.config=X.tags?{tags:X.tags}:void 0,this.recurse=X.recurse??this.recurse}getState(){return this.#X}setState(X){this.#X={...this.#X,...X}}async invoke(X,Q){let Z=o(this.config,Q),Y=await d0.runWithConfig(Z,async()=>this.func(X,Z));if(P0.isRunnable(Y)&&this.recurse)return await d0.runWithConfig(Z,async()=>Y.invoke(X,Z));return this.#X=Y,Y}};function F8(X,Q){let Z,Y;if(Q==="inline")Z=H8,Y=U8;else throw Error(`Invalid agent name mode: ${Q}. Needs to be one of: "inline"`);function J(K){return K.map(Z)}return K0.from([x0.from(J),X,x0.from(Y)])}function o8(X){return q.isInstance(X)||p(X)||typeof X==="object"&&X!==null&&"structuredResponse"in X&&"messages"in X}var y="model_request",x8=class extends W0{#X;#Z;constructor(X){super({name:X.name??"model",func:(Q,Z)=>this.#Q(Q,Z)});this.#X=X,this.#Z=X.systemMessage}#J(X){if(!this.#X.responseFormat)return;let Q=Y8(this.#X.responseFormat,void 0,X);if(!Q.every((Z)=>Z instanceof r))return{type:"tool",tools:Q.filter((Z)=>Z instanceof f).reduce((Z,Y)=>{return Z[Y.name]=Y,Z},{})};return{type:"native",strategy:Q[0]}}async#Q(X,Q){let Z=X.messages.at(-1);if(Z&&P.isInstance(Z)&&Z.name&&this.#X.shouldReturnDirect.has(Z.name))return[new T({update:{messages:[]}})];let{response:Y,lastAiMessage:J,collectedCommands:K}=await this.#$(X,Q);if(typeof Y==="object"&&Y!==null&&"structuredResponse"in Y&&"messages"in Y){let{structuredResponse:U,messages:W}=Y;return{messages:[...X.messages,...W],structuredResponse:U}}let G=[],V=q.isInstance(Y)?Y:J;if(V)if(V.name=this.name,V.lc_kwargs.name=this.name,this.#K(X,V))G.push(new T({update:{messages:[new q({content:"Sorry, need more steps to process this request.",name:this.name,id:V.id})]}}));else G.push(new T({update:{messages:[V]}}));if(p(Y)&&!K.includes(Y))G.push(Y);return G.push(...K),G}#Y(){if(typeof this.#X.model==="string")return s(this.#X.model);if(this.#X.model)return this.#X.model;throw Error("No model option was provided, either via `model` option.")}async#$(X,Q,Z={}){let Y=await this.#Y(),J=Q,K=this.#Z,G=null,V=[],U=async(j)=>{k0(j.model);let B=this.#J(j.model),A=await this.#H(j.model,j,B),E=[...K.text===""?[]:[K],...j.messages],_=y0(this.#X.signal,Q.signal),R=await b8(A.invoke(E,{...Q,signal:_}),_);if(G=R,B?.type==="native"){let C=B.strategy.parse(R);if(C)return{structuredResponse:C,messages:[R]};return R}if(!B||!R.tool_calls)return R;let O=R.tool_calls.filter((C)=>(C.name in B.tools));if(O.length===0)return R;if(O.length>1)return this.#G(R,O,B);let m=B.tools[O[0].name]?.options?.toolMessageContent;return this.#V(R,O[0],B,m??Z.lastMessage)},W=this.#X.wrapModelCallHookMiddleware??[],z=U;for(let j=W.length-1;j>=0;j--){let[B,A]=W[j];if(B.wrapModelCall){let E=z,_=B,R=A;z=async(O)=>{let m=K,C=_.contextSchema?X0(_.contextSchema,J?.context||{}):J?.context,d=Object.freeze({context:C,store:J.store,configurable:J.configurable,writer:J.writer,interrupt:J.interrupt,signal:J.signal}),N={...O,state:{...B.stateSchema?X0(v8(B.stateSchema),X):{},...R(),messages:X.messages},runtime:d},G0=async(H)=>{K=m;let L=H.tools??[],w=L.filter((l)=>$0(l)&&!this.#X.toolClasses.some((S0)=>S0.name===l.name));if(w.length>0)throw Error(`You have added a new tool in "wrapModelCall" hook of middleware "${_.name}": ${w.map((l)=>l.name).join(", ")}. This is not supported.`);let b=L.filter((l)=>$0(l)&&this.#X.toolClasses.every((S0)=>S0!==l));if(b.length>0)throw Error(`You have modified a tool in "wrapModelCall" hook of middleware "${_.name}": ${b.map((l)=>l.name).join(", ")}. This is not supported.`);let I=H,D=H.systemPrompt!==K.text,v=H.systemMessage!==K;if(D&&v)throw Error("Cannot change both systemPrompt and systemMessage in the same request.");if(D)K=new u({content:[{type:"text",text:H.systemPrompt}]}),I={...H,systemPrompt:K.text,systemMessage:K};if(v)K=new u({...H.systemMessage}),I={...H,systemPrompt:K.text,systemMessage:K};let q0=await E(I);if(p(q0)&&G){if(!V.includes(q0))V.push(q0);return G}return q0};if(!_.wrapModelCall)return G0(N);try{let H=await _.wrapModelCall(N,G0);if(!o8(H))throw Error(`Invalid response from "wrapModelCall" in middleware "${_.name}": expected AIMessage or Command, got ${typeof H}`);if(q.isInstance(H))G=H;else if(p(H))V.push(H);return H}catch(H){throw Z0.wrap(H,_.name)}}}}K=this.#Z;let F={model:Y,systemPrompt:K?.text,systemMessage:K,messages:X.messages,tools:this.#X.toolClasses,state:X,runtime:Object.freeze({context:J?.context,store:J.store,configurable:J.configurable,writer:J.writer,interrupt:J.interrupt,signal:J.signal})};return{response:await z(F),lastAiMessage:G,collectedCommands:V}}#G(X,Q,Z){let Y=new U0(Q.map((J)=>J.name));return this.#W(Y,X,Q[0],Z)}#V(X,Q,Z,Y){let J=Z.tools[Q.name];try{let K=J.parse(Q.args);return{structuredResponse:K,messages:[X,new P({tool_call_id:Q.id??"",content:JSON.stringify(K),name:Q.name}),new q(Y??`Returning structured response: ${JSON.stringify(K)}`)]}}catch(K){return this.#W(K,X,Q,Z)}}async#W(X,Q,Z,Y){let J=Object.values(Y.tools).at(0)?.options?.handleError,K=Z.id;if(!K)throw Error("Tool call ID is required to handle tool output errors. Please provide a tool call ID.");if(J===!1)throw X;if(J===void 0||typeof J==="boolean"&&J||Array.isArray(J)&&J.some((G)=>G instanceof U0))return new T({update:{messages:[Q,new P({content:X.message,tool_call_id:K})]},goto:y});if(typeof J==="string")return new T({update:{messages:[Q,new P({content:J,tool_call_id:K})]},goto:y});if(typeof J==="function"){let G=await J(X);if(typeof G!=="string")throw Error("Error handler must return a string.");return new T({update:{messages:[Q,new P({content:G,tool_call_id:K})]},goto:y})}return new T({update:{messages:[Q,new P({content:X.message,tool_call_id:K})]},goto:y})}#K(X,Q){let Z=q.isInstance(Q)&&Q.tool_calls?.every((J)=>this.#X.shouldReturnDirect.has(J.name)),Y="remainingSteps"in X?X.remainingSteps:void 0;return Boolean(Y&&(Y<1&&Z||Y<2&&m0(X.messages.at(-1))))}async#H(X,Q,Z){let Y={},J=Object.values(Z&&"tools"in Z?Z.tools:{}),K=[...Q?.tools??this.#X.toolClasses,...J.map((U)=>U.tool)],G=Q?.toolChoice||(J.length>0?"any":void 0);if(Z?.type==="native"){let U=Q?.modelSettings?.strict??Z?.strategy?.strict??!0,W={name:Z.strategy.schema?.name??"extract",description:O8(Z.strategy.schema),schema:Z.strategy.schema,strict:U};Object.assign(Y,{response_format:{type:"json_schema",json_schema:W},outputConfig:{format:{type:"json_schema",schema:Z.strategy.schema}},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:Z.strategy.schema},strict:U})}let V=await j8(X,K,{...Y,...Q?.modelSettings,tool_choice:G});return this.#X.includeAgentName==="inline"?F8(V,this.#X.includeAgentName):V}getState(){let X=super.getState();return{messages:[],...X&&!p(X)?X:{}}}};var w8=(X,Q)=>`Error: ${X} is not a valid tool, try one of [${Q.join(", ")}].`,x="tools",I8=(X)=>Array.isArray(X)&&X.every(i0.isInstance),s8=(X)=>typeof X==="object"&&X!=null&&("messages"in X)&&I8(X.messages),t8=(X)=>typeof X==="object"&&X!=null&&("lg_tool_call"in X);function e8(X,Q){if(X instanceof B0)return new P({content:X.message,tool_call_id:Q.id,name:Q.name});return new P({content:`${X}
26
- Please fix your mistakes.`,tool_call_id:Q.id,name:Q.name})}var k8=class extends W0{tools;trace=!1;signal;handleToolErrors=e8;wrapToolCall;constructor(X,Q){let{name:Z,tags:Y,handleToolErrors:J,signal:K,wrapToolCall:G}=Q??{};super({name:Z,tags:Y,func:(V,U)=>this.run(V,U)});this.options=Q,this.tools=X,this.handleToolErrors=J??this.handleToolErrors,this.signal=K,this.wrapToolCall=G}#X(X,Q,Z){if(R8(X))throw X;if(this.signal?.aborted)throw X;if(Z&&this.handleToolErrors!==!0)throw X;if(!this.handleToolErrors)throw X;if(typeof this.handleToolErrors==="function"){let Y=this.handleToolErrors(X,Q);if(Y&&P.isInstance(Y))return Y;throw X}else if(this.handleToolErrors)return new P({name:Q.name,content:`${X}
27
- Please fix your mistakes.`,tool_call_id:Q.id});throw X}async runTool(X,Q,Z){let Y=Q,J={context:Y?.context,writer:Y?.writer,interrupt:Y?.interrupt,signal:Y?.signal},K=this.tools.find((U)=>U.name===X.name),G=async(U)=>{let{toolCall:W,tool:z}=U,F=z??this.tools.find((B)=>B.name===W.name);if(F===void 0){let B=this.tools.map((A)=>A.name);return new P({content:w8(W.name,B),tool_call_id:W.id,name:W.name,status:"error"})}let j=F;try{let B=await j.invoke({...W,type:"tool_call"},{...Q,config:Q,toolCallId:W.id,state:Q.configurable?.__pregel_scratchpad?.currentTaskInput,signal:y0(this.signal,Q.signal)});if(P.isInstance(B)||p(B))return B;return new P({name:j.name,content:typeof B==="string"?B:JSON.stringify(B),tool_call_id:W.id})}catch(B){if(B instanceof E8)throw new B0(B,W);throw B}},V={toolCall:X,tool:K,state:Z,runtime:J};if(this.wrapToolCall)try{return await this.wrapToolCall(V,G)}catch(U){return this.#X(U,X,!0)}if(!K){let U=this.tools.map((W)=>W.name);return new P({content:w8(X.name,U),tool_call_id:X.id,name:X.name,status:"error"})}try{return await G(V)}catch(U){return this.#X(U,X,!1)}}async run(X,Q){let Z;if(t8(X)){let{lg_tool_call:K,jumpTo:G,...V}=X;Z=[await this.runTool(X.lg_tool_call,Q,V)]}else{let K;if(I8(X))K=X;else if(s8(X))K=X.messages;else throw Error("ToolNode only accepts BaseMessage[] or { messages: BaseMessage[] } as input.");let G=new Set(K.filter((U)=>U.getType()==="tool").map((U)=>U.tool_call_id)),V;for(let U=K.length-1;U>=0;U-=1){let W=K[U];if(q.isInstance(W)){V=W;break}}if(!q.isInstance(V))throw Error("ToolNode only accepts AIMessages as input.");Z=await Promise.all(V.tool_calls?.filter((U)=>U.id==null||!G.has(U.id)).map((U)=>this.runTool(U,Q,X))??[])}if(!Z.some(p))return Array.isArray(X)?Z:{messages:Z};let Y=[],J=null;for(let K of Z)if(p(K))if(K.graph===T.PARENT&&Array.isArray(K.goto)&&K.goto.every((G)=>X6(G)))if(J)J.goto.push(...K.goto);else J=new T({graph:T.PARENT,goto:K.goto});else Y.push(K);else Y.push(Array.isArray(X)?[K]:{messages:[K]});if(J)Y.push(J);return Y}};function X6(X){return X instanceof M}var Q6=class{},Y6=class{},Q0=class extends W0{#X;constructor(X,Q){super(X);this.#X=Q}async invokeMiddleware(X,Q){let Z={};if(this.middleware.contextSchema){let U=this.middleware.contextSchema?.shape;if(U){let W={},z=Q?.context||{};for(let F of Object.keys(U))if(F in z)W[F]=z[F];Z=X0(this.middleware.contextSchema,W)}}let Y={...this.#X.getState(),...X,messages:X.messages},J={context:Z,store:Q?.store,configurable:Q?.configurable,writer:Q?.writer,interrupt:Q?.interrupt,signal:Q?.signal},K=await this.runHook(Y,Object.freeze(Object.assign(new Y6,{...J,context:Object.freeze(Object.assign(new Q6,Z))})));if(!K)return{jumpTo:void 0};let G,V;if(this.name?.startsWith("BeforeAgentNode_"))G=n(this.middleware.beforeAgent),V="beforeAgent.canJumpTo";else if(this.name?.startsWith("BeforeModelNode_"))G=n(this.middleware.beforeModel),V="beforeModel.canJumpTo";else if(this.name?.startsWith("AfterAgentNode_"))G=n(this.middleware.afterAgent),V="afterAgent.canJumpTo";else if(this.name?.startsWith("AfterModelNode_"))G=n(this.middleware.afterModel),V="afterModel.canJumpTo";if(typeof K.jumpTo==="string"&&!G?.includes(K.jumpTo)){let U=G&&G.length>0?`must be one of: ${G?.join(", ")}.`:V?`no ${V} defined in middleware ${this.middleware.name}`:"";throw Error(`Invalid jump target: ${K.jumpTo}, ${U}.`)}if(typeof K==="object"&&"type"in K){if(K.type==="terminate"){if(K.error)throw K.error;return{...Y,...K.result||{},jumpTo:K.jumpTo}}throw Error(`Invalid control action: ${JSON.stringify(K)}`)}return{...Y,...K,jumpTo:K.jumpTo}}get nodeOptions(){return{input:_8(this.middleware.stateSchema)}}};var y8=class extends Q0{lc_namespace=["langchain","agents","beforeAgentNodes"];constructor(X,Q){super({name:`BeforeAgentNode_${X.name}`,func:async(Z,Y)=>this.invokeMiddleware(Z,Y)},Q);this.middleware=X}runHook(X,Q){return t(this.middleware.beforeAgent)(X,Q)}};var A8=class extends Q0{lc_namespace=["langchain","agents","beforeModelNodes"];constructor(X,Q){super({name:`BeforeModelNode_${X.name}`,func:async(Z,Y)=>this.invokeMiddleware(Z,Y)},Q);this.middleware=X}runHook(X,Q){return t(this.middleware.beforeModel)(X,Q)}};var N8=class extends Q0{lc_namespace=["langchain","agents","afterModelNodes"];constructor(X,Q){super({name:`AfterModelNode_${X.name}`,func:async(Z,Y)=>this.invokeMiddleware(Z,Y)},Q);this.middleware=X}runHook(X,Q){return t(this.middleware.afterModel)(X,Q)}};var S8=class extends Q0{lc_namespace=["langchain","agents","afterAgentNodes"];constructor(X,Q){super({name:`AfterAgentNode_${X.name}`,func:async(Z,Y)=>this.invokeMiddleware(Z,Y)},Q);this.middleware=X}runHook(X,Q){return t(this.middleware.afterAgent)(X,Q)}};var T8=class{#X=new Map;addNode(X,Q){this.#X.set(X.name,[...this.#X.get(X.name)??[],Q])}getState(X){let Q=(this.#X.get(X)??[]).reduce((Z,Y)=>{return{...Z,...Y.getState()??{}}},{});return delete Q.jumpTo,Q}};var M8=class X{#X;#Z="v2";#J;#Q=new T8;#Y;constructor(Q,Z){if(this.options=Q,this.#Y=Z??{},Q.name)this.#Y=o(this.#Y,{metadata:{lc_agent_name:Q.name}});if(this.#Z=Q.version??this.#Z,!Q.model)throw Error("`model` option is required to create an agent.");if(typeof Q.model!=="string")k0(Q.model);let Y=this.options.middleware?.filter((H)=>H.tools).flatMap((H)=>H.tools)??[],J=[...Q.tools??[],...Y],K=new Set(J.filter($0).filter((H)=>("returnDirect"in H)&&H.returnDirect).map((H)=>H.name)),{state:G,input:V,output:U}=G8(this.options.responseFormat!==void 0,this.options.stateSchema,this.options.middleware),W=new h8(G,{input:V,output:U,context:this.options.contextSchema}),z=[],F=[],j=[],B=[],A=[];this.#J=new x8({model:this.options.model,systemMessage:B8(this.options.systemPrompt),includeAgentName:this.options.includeAgentName,name:this.options.name,responseFormat:this.options.responseFormat,middleware:this.options.middleware,toolClasses:J,shouldReturnDirect:K,signal:this.options.signal,wrapModelCallHookMiddleware:A});let E=new Set,_=this.options.middleware??[];for(let H=0;H<_.length;H++){let L,w,b,I,D=_[H];if(E.has(D.name))throw Error(`Middleware ${D.name} is defined multiple times`);if(E.add(D.name),D.beforeAgent){L=new y8(D,{getState:()=>this.#Q.getState(D.name)}),this.#Q.addNode(D,L);let v=`${D.name}.before_agent`;z.push({index:H,name:v,allowed:n(D.beforeAgent)}),W.addNode(v,L,L.nodeOptions)}if(D.beforeModel){w=new A8(D,{getState:()=>this.#Q.getState(D.name)}),this.#Q.addNode(D,w);let v=`${D.name}.before_model`;F.push({index:H,name:v,allowed:n(D.beforeModel)}),W.addNode(v,w,w.nodeOptions)}if(D.afterModel){b=new N8(D,{getState:()=>this.#Q.getState(D.name)}),this.#Q.addNode(D,b);let v=`${D.name}.after_model`;j.push({index:H,name:v,allowed:n(D.afterModel)}),W.addNode(v,b,b.nodeOptions)}if(D.afterAgent){I=new S8(D,{getState:()=>this.#Q.getState(D.name)}),this.#Q.addNode(D,I);let v=`${D.name}.after_agent`;B.push({index:H,name:v,allowed:n(D.afterAgent)}),W.addNode(v,I,I.nodeOptions)}if(D.wrapModelCall)A.push([D,()=>this.#Q.getState(D.name)])}W.addNode(y,this.#J);let R=_.some((H)=>H.wrapToolCall),O=J.filter($0);if(O.length>0||R){let H=new k8(O,{signal:this.options.signal,wrapToolCall:z8(_)});W.addNode(x,H)}let m;if(z.length>0)m=z[0].name;else if(F.length>0)m=F[0].name;else m=y;let C=F.length>0?F[0].name:y,d=B.length>0?B[B.length-1].name:k;W.addEdge(C8,m);let N=O.length>0||R;for(let H=0;H<z.length;H++){let L=z[H],w=L.name,b=H===z.length-1?C:z[H+1].name;if(L.allowed&&L.allowed.length>0){let I=L.allowed.map((v)=>g(v)).filter((v)=>v!==x||N),D=Array.from(new Set([b,...I.map((v)=>v===k?d:v)]));W.addConditionalEdges(w,this.#H(O,b,d,N),D)}else W.addEdge(w,b)}for(let H=0;H<F.length;H++){let L=F[H],w=L.name,b=H===F.length-1?y:F[H+1].name;if(L.allowed&&L.allowed.length>0){let I=L.allowed.map((v)=>g(v)).filter((v)=>v!==x||N),D=Array.from(new Set([b,...I]));W.addConditionalEdges(w,this.#B(O,b,N),D)}else W.addEdge(w,b)}let G0=j.at(-1);if(j.length>0&&G0)W.addEdge(y,G0.name);else{let H=this.#$(O,!1,N).map((L)=>L===k?d:L);if(H.length===1)W.addEdge(y,H[0]);else W.addConditionalEdges(y,this.#V(d),H)}for(let H=j.length-1;H>0;H--){let L=j[H],w=L.name,b=j[H-1].name;if(L.allowed&&L.allowed.length>0){let I=L.allowed.map((v)=>g(v)).filter((v)=>v!==x||N),D=Array.from(new Set([b,...I]));W.addConditionalEdges(w,this.#K(O,L.allowed,b,N),D)}else W.addEdge(w,b)}if(j.length>0){let H=j[0],L=H.name,w=this.#$(O,!0,N).filter((D)=>D!==x||N),b=Boolean(H.allowed&&H.allowed.length>0),I=w.map((D)=>D===k?d:D);W.addConditionalEdges(L,this.#W(O,b,d,N),I)}for(let H=B.length-1;H>0;H--){let L=B[H],w=L.name,b=B[H-1].name;if(L.allowed&&L.allowed.length>0){let I=L.allowed.map((v)=>g(v)).filter((v)=>v!==x||N),D=Array.from(new Set([b,...I]));W.addConditionalEdges(w,this.#K(O,L.allowed,b,N),D)}else W.addEdge(w,b)}if(B.length>0){let H=B[0],L=H.name;if(H.allowed&&H.allowed.length>0){let w=H.allowed.map((I)=>g(I)).filter((I)=>I!==x||N),b=Array.from(new Set([k,...w]));W.addConditionalEdges(L,this.#K(O,H.allowed,k,N),b)}else W.addEdge(L,k)}if(N){let H=C;if(K.size>0)W.addConditionalEdges(x,this.#G(K,d),[H,d]);else W.addEdge(x,H)}this.#X=W.compile({checkpointer:this.options.checkpointer,store:this.options.store,name:this.options.name,description:this.options.description})}get graph(){return this.#X}get checkpointer(){return this.#X.checkpointer}set checkpointer(Q){this.#X.checkpointer=Q}get store(){return this.#X.store}set store(Q){this.#X.store=Q}withConfig(Q){return new X(this.options,o(this.#Y,Q))}#$(Q,Z=!1,Y=Q.length>0){let J=[];if(Y)J.push(x);if(Z)J.push(y);return J.push(k),J}#G(Q,Z){return(Y)=>{let J=Y.messages,K=J[J.length-1];if(P.isInstance(K)&&K.name&&Q.has(K.name))return this.options.responseFormat?y:Z;return y}}#V(Q=k){return(Z)=>{let Y=Z.messages.at(-1);if(!q.isInstance(Y)||!Y.tool_calls||Y.tool_calls.length===0)return Q;if(Y.tool_calls.every((K)=>K.name.startsWith("extract-")))return Q;if(this.#Z==="v1")return x;let J=Y.tool_calls.filter((K)=>!K.name.startsWith("extract-"));if(J.length===0)return Q;return J.map((K)=>new M(x,{...Z,lg_tool_call:K}))}}#W(Q,Z,Y,J=Q.length>0){let K=Boolean(this.options.responseFormat);return(G)=>{let V=G,U=V.messages,W=U.at(-1);if(q.isInstance(W)&&(!W.tool_calls||W.tool_calls.length===0))return Y;if(Z&&V.jumpTo){let _=g(V.jumpTo);if(_===k)return Y;if(_===x){if(!J)return Y;return new M(x,{...G,jumpTo:void 0})}return new M(y,{...G,jumpTo:void 0})}let z=U.filter(P.isInstance),F=U.filter(q.isInstance).at(-1),j=F?.tool_calls?.filter((_)=>!z.some((R)=>R.tool_call_id===_.id));if(j&&j.length>0)return j.map((_)=>new M(x,{...G,lg_tool_call:_}));let B=F?.tool_calls?.some((_)=>_.name.startsWith("extract-"));if(j&&j.length===0&&!B&&K)return y;if(!q.isInstance(W)||!W.tool_calls||W.tool_calls.length===0)return Y;let A=W.tool_calls.every((_)=>_.name.startsWith("extract-")),E=W.tool_calls.some((_)=>!_.name.startsWith("extract-"));if(A||!E)return Y;return x}}#K(Q,Z,Y,J=Q.length>0){let K=new Set(Z.map((G)=>g(G)));return(G)=>{let V=G;if(V.jumpTo){let U=g(V.jumpTo);if(U===k&&K.has(k))return k;if(U===x&&K.has(x)){if(!J)return k;return new M(x,{...G,jumpTo:void 0})}if(U===y&&K.has(y))return new M(y,{...G,jumpTo:void 0})}return Y}}#H(Q,Z,Y,J=Q.length>0){return(K)=>{let G=K;if(!G.jumpTo)return Z;let V=g(G.jumpTo);if(V===k)return Y;if(V===x){if(!J)return Y;return new M(x,{...K,jumpTo:void 0})}return new M(y,{...K,jumpTo:void 0})}}#B(Q,Z,Y=Q.length>0){return(J)=>{let K=J;if(!K.jumpTo)return Z;let G=g(K.jumpTo);if(G===k)return k;if(G===x){if(!Y)return k;return new M(x,{...J,jumpTo:void 0})}return new M(y,{...J,jumpTo:void 0})}}async#U(Q,Z){if(!this.options.middleware||this.options.middleware.length===0||Q instanceof T||!Q)return Q;let Y=await q8(this.options.middleware,Q),J={...(await this.#X.getState(Z).catch(()=>({values:{}}))).values,...Q};if(!J)return J;for(let[K,G]of Object.entries(Y))if(!(K in J))J[K]=G;return J}async invoke(Q,Z){let Y=o(this.#Y,Z),J=await this.#U(Q,Y);return this.#X.invoke(J,Y)}async stream(Q,Z){let Y=o(this.#Y,Z),J=await this.#U(Q,Y);return this.#X.stream(J,Y)}async drawMermaidPng(Q){let Z=await(await(await this.#X.getGraphAsync()).drawMermaidPng(Q)).arrayBuffer();return new Uint8Array(Z)}async drawMermaid(Q){return(await this.#X.getGraphAsync()).drawMermaid(Q)}streamEvents(Q,Z,Y){let J=o(this.#Y,Z);return this.#X.streamEvents(Q,{...J,version:Z?.version??"v2"},Y)}getGraphAsync(Q){return this.#X.getGraphAsync(Q)}getState(Q,Z){return this.#X.getState(Q,Z)}getStateHistory(Q,Z){return this.#X.getStateHistory(Q,Z)}getSubgraphs(Q,Z){return this.#X.getSubgraphs(Q,Z)}getSubgraphAsync(Q,Z){return this.#X.getSubgraphsAsync(Q,Z)}updateState(Q,Z,Y){return this.#X.updateState(Q,Z,Y)}get builder(){return this.#X.builder}};function $6(X){return new M8(X)}var W6=$.function().args($.custom(),$.custom(),$.custom()).returns($.union([$.string(),$.promise($.string())])),G6=["approve","edit","reject"],V6=$.enum(G6),H6=$.object({allowedDecisions:$.array(V6),description:$.union([$.string(),W6]).optional(),argsSchema:$.record($.any()).optional()}),h1=$.object({interruptOn:$.record($.union([$.boolean(),H6])).optional(),descriptionPrefix:$.string().default("Tool execution requires approval")});var j6=`<role>
28
- Context Extraction Assistant
29
- </role>
30
-
31
- <primary_objective>
32
- Your sole objective in this task is to extract the highest quality/most relevant context from the conversation history below.
33
- </primary_objective>
34
-
35
- <objective_information>
36
- You're nearing the total number of input tokens you can accept, so you must extract the highest quality/most relevant pieces of information from your conversation history.
37
- This context will then overwrite the conversation history presented below. Because of this, ensure the context you extract is only the most important information to your overall goal.
38
- </objective_information>
39
-
40
- <instructions>
41
- The conversation history below will be replaced with the context you extract in this step. Because of this, you must do your very best to extract and record all of the most important context from the conversation history.
42
- You want to ensure that you don't repeat any actions you've already completed, so the context you extract from the conversation history should be focused on the most important information to your overall goal.
43
- </instructions>
44
-
45
- The user will message you with the full message history you'll be extracting context from, to then replace. Carefully read over it all, and think deeply about what information is most important to your overall goal that should be saved:
46
-
47
- With all of this in mind, please carefully read over the entire conversation history, and extract the most important and relevant context to replace it so that you can free up space in the conversation history.
48
- Respond ONLY with the extracted context. Do not include any additional information, or text before or after the extracted context.
49
-
50
- <messages>
51
- Messages to summarize:
52
- {messages}
53
- </messages>`;var z6=$.function().args($.array($.custom())).returns($.union([$.number(),$.promise($.number())])),L0=$.object({fraction:$.number().gt(0,"Fraction must be greater than 0").max(1,"Fraction must be less than or equal to 1").optional(),tokens:$.number().positive("Tokens must be greater than 0").optional(),messages:$.number().int("Messages must be an integer").positive("Messages must be greater than 0").optional()}).refine((X)=>{return[X.fraction,X.tokens,X.messages].filter((Q)=>Q!==void 0).length>=1},{message:"At least one of fraction, tokens, or messages must be provided"}),r0=$.object({fraction:$.number().min(0,"Messages must be non-negative").max(1,"Fraction must be less than or equal to 1").optional(),tokens:$.number().min(0,"Tokens must be greater than or equal to 0").optional(),messages:$.number().int("Messages must be an integer").min(0,"Messages must be non-negative").optional()}).refine((X)=>{return[X.fraction,X.tokens,X.messages].filter((Q)=>Q!==void 0).length===1},{message:"Exactly one of fraction, tokens, or messages must be provided"}),t1=$.object({model:$.custom(),trigger:$.union([L0,$.array(L0)]).optional(),keep:r0.optional(),tokenCounter:z6.optional(),summaryPrompt:$.string().default(j6),trimTokensToSummarize:$.number().optional(),summaryPrefix:$.string().optional(),maxTokensBeforeSummary:$.number().optional(),messagesToKeep:$.number().optional()});function a0(X){if("profile"in X&&typeof X.profile==="object"&&X.profile&&"maxInputTokens"in X.profile&&(typeof X.profile.maxInputTokens==="number"||X.profile.maxInputTokens==null))return X.profile.maxInputTokens??void 0;if("model"in X&&typeof X.model==="string")return n0(X.model);if("modelName"in X&&typeof X.modelName==="string")return n0(X.modelName)}var GX=$.object({model:$.string().or($.instanceof(f8)).optional(),systemPrompt:$.string().optional(),maxTools:$.number().optional(),alwaysInclude:$.array($.string()).optional()});var DX=$.object({applyToInput:$.boolean().optional(),applyToOutput:$.boolean().optional(),applyToToolResults:$.boolean().optional()});var vX=$.object({rules:$.record($.string(),$.instanceof(RegExp).describe("Regular expression pattern to match PII")).optional()});var D6="[cleared]",P6=1e5,A0=3,u8=class{#X;trigger;keep;clearToolInputs;excludeTools;placeholder;model;clearAtLeast;constructor(X={}){let Q=X.trigger;if(X.triggerTokens!==void 0){if(console.warn("triggerTokens is deprecated. Use `trigger: { tokens: value }` instead."),Q===void 0)Q={tokens:X.triggerTokens}}let Z=X.keep;if(X.keepMessages!==void 0){if(console.warn("keepMessages is deprecated. Use `keep: { messages: value }` instead."),Z===void 0)Z={messages:X.keepMessages}}if(Q===void 0)Q={tokens:P6};if(Z===void 0)Z={messages:A0};if(Array.isArray(Q))this.#X=Q.map((Y)=>L0.parse(Y)),this.trigger=this.#X;else{let Y=L0.parse(Q);this.#X=[Y],this.trigger=Y}if(this.keep=r0.parse(Z),X.clearAtLeast!==void 0)console.warn("clearAtLeast is deprecated and will be removed in a future version. It conflicts with the `keep` property. Use `keep: { tokens: value }` or `keep: { messages: value }` instead to control retention.");this.clearAtLeast=X.clearAtLeast??0,this.clearToolInputs=X.clearToolInputs??!1,this.excludeTools=new Set(X.excludeTools??[]),this.placeholder=X.placeholder??D6}async apply(X){let{messages:Q,model:Z,countTokens:Y}=X,J=await Y(Q),K=[];for(let j=0;j<Q.length;j++){let B=Q[j];if(P.isInstance(B)){let A=this.#Q(Q.slice(0,j),B.tool_call_id);if(!A)K.push(j);else if(!A.tool_calls?.find((E)=>E.id===B.tool_call_id))K.push(j)}}for(let j=K.length-1;j>=0;j--)Q.splice(K[j],1);let G=J;if(K.length>0)G=await Y(Q);if(!this.#Z(Q,G,Z))return;let V=[];for(let j=0;j<Q.length;j++){let B=Q[j];if(P.isInstance(B))V.push({idx:j,msg:B})}if(V.length===0)return;let U=await this.#J(V,Y,Z),W=U>=V.length?[]:U>0?V.slice(0,-U):V,z=0,F=[...W];for(let{idx:j,msg:B}of F){if(B.response_metadata?.context_editing?.cleared)continue;let A=this.#Q(Q.slice(0,j),B.tool_call_id);if(!A)continue;let E=A.tool_calls?.find((O)=>O.id===B.tool_call_id);if(!E)continue;let _=B.name||E.name;if(this.excludeTools.has(_))continue;if(Q[j]=new P({tool_call_id:B.tool_call_id,content:this.placeholder,name:B.name,artifact:void 0,response_metadata:{...B.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){let O=Q.indexOf(A);if(O>=0)Q[O]=this.#Y(A,B.tool_call_id)}let R=await Y(Q);z=Math.max(0,G-R)}if(this.clearAtLeast>0&&z<this.clearAtLeast){let j=U>0&&U<V.length?V.slice(-U):[];for(let B=j.length-1;B>=0;B--){if(z>=this.clearAtLeast)break;let{idx:A,msg:E}=j[B];if(E.response_metadata?.context_editing?.cleared)continue;let _=this.#Q(Q.slice(0,A),E.tool_call_id);if(!_)continue;let R=_.tool_calls?.find((C)=>C.id===E.tool_call_id);if(!R)continue;let O=E.name||R.name;if(this.excludeTools.has(O))continue;if(Q[A]=new P({tool_call_id:E.tool_call_id,content:this.placeholder,name:E.name,artifact:void 0,response_metadata:{...E.response_metadata,context_editing:{cleared:!0,strategy:"clear_tool_uses"}}}),this.clearToolInputs){let C=Q.indexOf(_);if(C>=0)Q[C]=this.#Y(_,E.tool_call_id)}let m=await Y(Q);z=Math.max(0,G-m)}}}#Z(X,Q,Z){for(let Y of this.#X){let J=!0,K=!1;if(Y.messages!==void 0){if(K=!0,X.length<Y.messages)J=!1}if(Y.tokens!==void 0){if(K=!0,Q<Y.tokens)J=!1}if(Y.fraction!==void 0){if(K=!0,!Z)continue;let G=a0(Z);if(typeof G==="number"){let V=Math.floor(G*Y.fraction);if(V<=0)continue;if(Q<V)J=!1}else continue}if(K&&J)return!0}return!1}async#J(X,Q,Z){if("messages"in this.keep&&this.keep.messages!==void 0)return this.keep.messages;if("tokens"in this.keep&&this.keep.tokens!==void 0){let Y=this.keep.tokens,J=0,K=0;for(let G=X.length-1;G>=0;G--){let V=X[G],U=await Q([V.msg]);if(J+U<=Y)J+=U,K++;else break}return K}if("fraction"in this.keep&&this.keep.fraction!==void 0){if(!Z)return A0;let Y=a0(Z);if(typeof Y==="number"){let J=Math.floor(Y*this.keep.fraction);if(J<=0)return A0;let K=0,G=0;for(let V=X.length-1;V>=0;V--){let U=X[V],W=await Q([U.msg]);if(K+W<=J)K+=W,G++;else break}return G}}return A0}#Q(X,Q){for(let Z=X.length-1;Z>=0;Z--){let Y=X[Z];if(q.isInstance(Y)){if(Y.tool_calls?.some((J)=>J.id===Q))return Y}}return null}#Y(X,Q){let Z=X.tool_calls?.map((G)=>{if(G.id===Q)return{...G,args:{}};return G}),Y={...X.response_metadata},J={...Y.context_editing},K=new Set(J.cleared_tool_inputs);return K.add(Q),J.cleared_tool_inputs=Array.from(K).sort(),Y.context_editing=J,new q({content:X.content,tool_calls:Z,response_metadata:Y,id:X.id,name:X.name,additional_kwargs:X.additional_kwargs})}};var L6=["continue","error","end"],q6="continue";var _6=$.enum(L6).default(q6);var AX=$.object({toolName:$.string().optional(),threadLimit:$.number().optional(),runLimit:$.number().optional(),exitBehavior:_6}),NX=$.object({threadToolCallCount:$.record($.string(),$.number()).default({}),runToolCallCount:$.record($.string(),$.number()).default({})});var F6=$.enum(["pending","in_progress","completed"]).describe("Status of the todo"),b6=$.object({content:$.string().describe("Content of the todo item"),status:F6}),pX=$.object({todos:$.array(b6).default([])});var iX=$.object({threadLimit:$.number().optional(),runLimit:$.number().optional(),exitBehavior:$.enum(["error","end"]).optional()}),nX=$.object({threadModelCallCount:$.number().default(0),runModelCallCount:$.number().default(0)});var N0=$.object({maxRetries:$.number().min(0).default(2),retryOn:$.union([$.function().args($.instanceof(Error)).returns($.boolean()),$.array($.custom())]).default(()=>()=>!0),backoffFactor:$.number().min(0).default(2),initialDelayMs:$.number().min(0).default(1000),maxDelayMs:$.number().min(0).default(60000),jitter:$.boolean().default(!0)});var $Q=$.object({onFailure:$.union([$.literal("error"),$.literal("continue"),$.function().args($.instanceof(Error)).returns($.string())]).default("continue")}).merge(N0);var zQ=$.object({tools:$.array($.union([$.custom(),$.custom(),$.string()])).optional(),onFailure:$.union([$.literal("error"),$.literal("continue"),$.literal("raise"),$.literal("return_message"),$.function().args($.instanceof(Error)).returns($.string())]).default("continue")}).merge(N0);var EQ=$.object({enableCaching:$.boolean().optional(),ttl:$.enum(["5m","1h"]).optional(),minMessagesToCache:$.number().optional(),unsupportedModelBehavior:$.enum(["ignore","warn","raise"]).optional()});
54
- export{S as jg,$6 as kg};