文件操作 - index-DuVyY7tb.js
返回文件管理
返回主菜单
删除本文件
文件: E:\HostingSpaces\kimblycr\kimbly.in\wwwroot\assets\index-DuVyY7tb.js
编辑文件内容
var sI=Object.defineProperty;var aI=(t,e,n)=>e in t?sI(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var A=(t,e,n)=>aI(t,typeof e!="symbol"?e+"":e,n);(function(){const e=document.createElement("link").relList;if(e&&e.supports&&e.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const s of i)if(s.type==="childList")for(const a of s.addedNodes)a.tagName==="LINK"&&a.rel==="modulepreload"&&r(a)}).observe(document,{childList:!0,subtree:!0});function n(i){const s={};return i.integrity&&(s.integrity=i.integrity),i.referrerPolicy&&(s.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?s.credentials="include":i.crossOrigin==="anonymous"?s.credentials="omit":s.credentials="same-origin",s}function r(i){if(i.ep)return;i.ep=!0;const s=n(i);fetch(i.href,s)}})();var Hw={exports:{}},Kc={},Zw={exports:{}},de={};/** * @license React * react.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var tu=Symbol.for("react.element"),oI=Symbol.for("react.portal"),uI=Symbol.for("react.fragment"),lI=Symbol.for("react.strict_mode"),cI=Symbol.for("react.profiler"),dI=Symbol.for("react.provider"),fI=Symbol.for("react.context"),hI=Symbol.for("react.forward_ref"),pI=Symbol.for("react.suspense"),mI=Symbol.for("react.memo"),gI=Symbol.for("react.lazy"),Iy=Symbol.iterator;function yI(t){return t===null||typeof t!="object"?null:(t=Iy&&t[Iy]||t["@@iterator"],typeof t=="function"?t:null)}var Vw={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},Kw=Object.assign,qw={};function ga(t,e,n){this.props=t,this.context=e,this.refs=qw,this.updater=n||Vw}ga.prototype.isReactComponent={};ga.prototype.setState=function(t,e){if(typeof t!="object"&&typeof t!="function"&&t!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,t,e,"setState")};ga.prototype.forceUpdate=function(t){this.updater.enqueueForceUpdate(this,t,"forceUpdate")};function Ww(){}Ww.prototype=ga.prototype;function um(t,e,n){this.props=t,this.context=e,this.refs=qw,this.updater=n||Vw}var lm=um.prototype=new Ww;lm.constructor=um;Kw(lm,ga.prototype);lm.isPureReactComponent=!0;var Oy=Array.isArray,Gw=Object.prototype.hasOwnProperty,cm={current:null},Jw={key:!0,ref:!0,__self:!0,__source:!0};function Xw(t,e,n){var r,i={},s=null,a=null;if(e!=null)for(r in e.ref!==void 0&&(a=e.ref),e.key!==void 0&&(s=""+e.key),e)Gw.call(e,r)&&!Jw.hasOwnProperty(r)&&(i[r]=e[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var u=Array(o),l=0;l<o;l++)u[l]=arguments[l+2];i.children=u}if(t&&t.defaultProps)for(r in o=t.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return{$$typeof:tu,type:t,key:s,ref:a,props:i,_owner:cm.current}}function _I(t,e){return{$$typeof:tu,type:t.type,key:e,ref:t.ref,props:t.props,_owner:t._owner}}function dm(t){return typeof t=="object"&&t!==null&&t.$$typeof===tu}function vI(t){var e={"=":"=0",":":"=2"};return"$"+t.replace(/[=:]/g,function(n){return e[n]})}var Cy=/\/+/g;function Bd(t,e){return typeof t=="object"&&t!==null&&t.key!=null?vI(""+t.key):e.toString(36)}function ol(t,e,n,r,i){var s=typeof t;(s==="undefined"||s==="boolean")&&(t=null);var a=!1;if(t===null)a=!0;else switch(s){case"string":case"number":a=!0;break;case"object":switch(t.$$typeof){case tu:case oI:a=!0}}if(a)return a=t,i=i(a),t=r===""?"."+Bd(a,0):r,Oy(i)?(n="",t!=null&&(n=t.replace(Cy,"$&/")+"/"),ol(i,e,n,"",function(l){return l})):i!=null&&(dm(i)&&(i=_I(i,n+(!i.key||a&&a.key===i.key?"":(""+i.key).replace(Cy,"$&/")+"/")+t)),e.push(i)),1;if(a=0,r=r===""?".":r+":",Oy(t))for(var o=0;o<t.length;o++){s=t[o];var u=r+Bd(s,o);a+=ol(s,e,n,u,i)}else if(u=yI(t),typeof u=="function")for(t=u.call(t),o=0;!(s=t.next()).done;)s=s.value,u=r+Bd(s,o++),a+=ol(s,e,n,u,i);else if(s==="object")throw e=String(t),Error("Objects are not valid as a React child (found: "+(e==="[object Object]"?"object with keys {"+Object.keys(t).join(", ")+"}":e)+"). If you meant to render a collection of children, use an array instead.");return a}function gu(t,e,n){if(t==null)return t;var r=[],i=0;return ol(t,r,"","",function(s){return e.call(n,s,i++)}),r}function wI(t){if(t._status===-1){var e=t._result;e=e(),e.then(function(n){(t._status===0||t._status===-1)&&(t._status=1,t._result=n)},function(n){(t._status===0||t._status===-1)&&(t._status=2,t._result=n)}),t._status===-1&&(t._status=0,t._result=e)}if(t._status===1)return t._result.default;throw t._result}var Ut={current:null},ul={transition:null},bI={ReactCurrentDispatcher:Ut,ReactCurrentBatchConfig:ul,ReactCurrentOwner:cm};function Qw(){throw Error("act(...) is not supported in production builds of React.")}de.Children={map:gu,forEach:function(t,e,n){gu(t,function(){e.apply(this,arguments)},n)},count:function(t){var e=0;return gu(t,function(){e++}),e},toArray:function(t){return gu(t,function(e){return e})||[]},only:function(t){if(!dm(t))throw Error("React.Children.only expected to receive a single React element child.");return t}};de.Component=ga;de.Fragment=uI;de.Profiler=cI;de.PureComponent=um;de.StrictMode=lI;de.Suspense=pI;de.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=bI;de.act=Qw;de.cloneElement=function(t,e,n){if(t==null)throw Error("React.cloneElement(...): The argument must be a React element, but you passed "+t+".");var r=Kw({},t.props),i=t.key,s=t.ref,a=t._owner;if(e!=null){if(e.ref!==void 0&&(s=e.ref,a=cm.current),e.key!==void 0&&(i=""+e.key),t.type&&t.type.defaultProps)var o=t.type.defaultProps;for(u in e)Gw.call(e,u)&&!Jw.hasOwnProperty(u)&&(r[u]=e[u]===void 0&&o!==void 0?o[u]:e[u])}var u=arguments.length-2;if(u===1)r.children=n;else if(1<u){o=Array(u);for(var l=0;l<u;l++)o[l]=arguments[l+2];r.children=o}return{$$typeof:tu,type:t.type,key:i,ref:s,props:r,_owner:a}};de.createContext=function(t){return t={$$typeof:fI,_currentValue:t,_currentValue2:t,_threadCount:0,Provider:null,Consumer:null,_defaultValue:null,_globalName:null},t.Provider={$$typeof:dI,_context:t},t.Consumer=t};de.createElement=Xw;de.createFactory=function(t){var e=Xw.bind(null,t);return e.type=t,e};de.createRef=function(){return{current:null}};de.forwardRef=function(t){return{$$typeof:hI,render:t}};de.isValidElement=dm;de.lazy=function(t){return{$$typeof:gI,_payload:{_status:-1,_result:t},_init:wI}};de.memo=function(t,e){return{$$typeof:mI,type:t,compare:e===void 0?null:e}};de.startTransition=function(t){var e=ul.transition;ul.transition={};try{t()}finally{ul.transition=e}};de.unstable_act=Qw;de.useCallback=function(t,e){return Ut.current.useCallback(t,e)};de.useContext=function(t){return Ut.current.useContext(t)};de.useDebugValue=function(){};de.useDeferredValue=function(t){return Ut.current.useDeferredValue(t)};de.useEffect=function(t,e){return Ut.current.useEffect(t,e)};de.useId=function(){return Ut.current.useId()};de.useImperativeHandle=function(t,e,n){return Ut.current.useImperativeHandle(t,e,n)};de.useInsertionEffect=function(t,e){return Ut.current.useInsertionEffect(t,e)};de.useLayoutEffect=function(t,e){return Ut.current.useLayoutEffect(t,e)};de.useMemo=function(t,e){return Ut.current.useMemo(t,e)};de.useReducer=function(t,e,n){return Ut.current.useReducer(t,e,n)};de.useRef=function(t){return Ut.current.useRef(t)};de.useState=function(t){return Ut.current.useState(t)};de.useSyncExternalStore=function(t,e,n){return Ut.current.useSyncExternalStore(t,e,n)};de.useTransition=function(){return Ut.current.useTransition()};de.version="18.3.1";Zw.exports=de;var je=Zw.exports;/** * @license React * react-jsx-runtime.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var xI=je,kI=Symbol.for("react.element"),SI=Symbol.for("react.fragment"),AI=Object.prototype.hasOwnProperty,EI=xI.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED.ReactCurrentOwner,TI={key:!0,ref:!0,__self:!0,__source:!0};function Yw(t,e,n){var r,i={},s=null,a=null;n!==void 0&&(s=""+n),e.key!==void 0&&(s=""+e.key),e.ref!==void 0&&(a=e.ref);for(r in e)AI.call(e,r)&&!TI.hasOwnProperty(r)&&(i[r]=e[r]);if(t&&t.defaultProps)for(r in e=t.defaultProps,e)i[r]===void 0&&(i[r]=e[r]);return{$$typeof:kI,type:t,key:s,ref:a,props:i,_owner:EI.current}}Kc.Fragment=SI;Kc.jsx=Yw;Kc.jsxs=Yw;Hw.exports=Kc;var w=Hw.exports,eb={exports:{}},gn={},tb={exports:{}},nb={};/** * @license React * scheduler.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */(function(t){function e(K,ie){var re=K.length;K.push(ie);e:for(;0<re;){var Pe=re-1>>>1,qe=K[Pe];if(0<i(qe,ie))K[Pe]=ie,K[re]=qe,re=Pe;else break e}}function n(K){return K.length===0?null:K[0]}function r(K){if(K.length===0)return null;var ie=K[0],re=K.pop();if(re!==ie){K[0]=re;e:for(var Pe=0,qe=K.length,$i=qe>>>1;Pe<$i;){var nr=2*(Pe+1)-1,Aa=K[nr],S=nr+1,x=K[S];if(0>i(Aa,re))S<qe&&0>i(x,Aa)?(K[Pe]=x,K[S]=re,Pe=S):(K[Pe]=Aa,K[nr]=re,Pe=nr);else if(S<qe&&0>i(x,re))K[Pe]=x,K[S]=re,Pe=S;else break e}}return ie}function i(K,ie){var re=K.sortIndex-ie.sortIndex;return re!==0?re:K.id-ie.id}if(typeof performance=="object"&&typeof performance.now=="function"){var s=performance;t.unstable_now=function(){return s.now()}}else{var a=Date,o=a.now();t.unstable_now=function(){return a.now()-o}}var u=[],l=[],c=1,d=null,f=3,h=!1,m=!1,_=!1,v=typeof setTimeout=="function"?setTimeout:null,y=typeof clearTimeout=="function"?clearTimeout:null,p=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function g(K){for(var ie=n(l);ie!==null;){if(ie.callback===null)r(l);else if(ie.startTime<=K)r(l),ie.sortIndex=ie.expirationTime,e(u,ie);else break;ie=n(l)}}function b(K){if(_=!1,g(K),!m)if(n(u)!==null)m=!0,ye(E);else{var ie=n(l);ie!==null&&Sa(b,ie.startTime-K)}}function E(K,ie){m=!1,_&&(_=!1,y(k),k=-1),h=!0;var re=f;try{for(g(ie),d=n(u);d!==null&&(!(d.expirationTime>ie)||K&&!L());){var Pe=d.callback;if(typeof Pe=="function"){d.callback=null,f=d.priorityLevel;var qe=Pe(d.expirationTime<=ie);ie=t.unstable_now(),typeof qe=="function"?d.callback=qe:d===n(u)&&r(u),g(ie)}else r(u);d=n(u)}if(d!==null)var $i=!0;else{var nr=n(l);nr!==null&&Sa(b,nr.startTime-ie),$i=!1}return $i}finally{d=null,f=re,h=!1}}var T=!1,I=null,k=-1,j=5,N=-1;function L(){return!(t.unstable_now()-N<j)}function ue(){if(I!==null){var K=t.unstable_now();N=K;var ie=!0;try{ie=I(!0,K)}finally{ie?Ee():(T=!1,I=null)}}else T=!1}var Ee;if(typeof p=="function")Ee=function(){p(ue)};else if(typeof MessageChannel<"u"){var Et=new MessageChannel,tr=Et.port2;Et.port1.onmessage=ue,Ee=function(){tr.postMessage(null)}}else Ee=function(){v(ue,0)};function ye(K){I=K,T||(T=!0,Ee())}function Sa(K,ie){k=v(function(){K(t.unstable_now())},ie)}t.unstable_IdlePriority=5,t.unstable_ImmediatePriority=1,t.unstable_LowPriority=4,t.unstable_NormalPriority=3,t.unstable_Profiling=null,t.unstable_UserBlockingPriority=2,t.unstable_cancelCallback=function(K){K.callback=null},t.unstable_continueExecution=function(){m||h||(m=!0,ye(E))},t.unstable_forceFrameRate=function(K){0>K||125<K?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):j=0<K?Math.floor(1e3/K):5},t.unstable_getCurrentPriorityLevel=function(){return f},t.unstable_getFirstCallbackNode=function(){return n(u)},t.unstable_next=function(K){switch(f){case 1:case 2:case 3:var ie=3;break;default:ie=f}var re=f;f=ie;try{return K()}finally{f=re}},t.unstable_pauseExecution=function(){},t.unstable_requestPaint=function(){},t.unstable_runWithPriority=function(K,ie){switch(K){case 1:case 2:case 3:case 4:case 5:break;default:K=3}var re=f;f=K;try{return ie()}finally{f=re}},t.unstable_scheduleCallback=function(K,ie,re){var Pe=t.unstable_now();switch(typeof re=="object"&&re!==null?(re=re.delay,re=typeof re=="number"&&0<re?Pe+re:Pe):re=Pe,K){case 1:var qe=-1;break;case 2:qe=250;break;case 5:qe=1073741823;break;case 4:qe=1e4;break;default:qe=5e3}return qe=re+qe,K={id:c++,callback:ie,priorityLevel:K,startTime:re,expirationTime:qe,sortIndex:-1},re>Pe?(K.sortIndex=re,e(l,K),n(u)===null&&K===n(l)&&(_?(y(k),k=-1):_=!0,Sa(b,re-Pe))):(K.sortIndex=qe,e(u,K),m||h||(m=!0,ye(E))),K},t.unstable_shouldYield=L,t.unstable_wrapCallback=function(K){var ie=f;return function(){var re=f;f=ie;try{return K.apply(this,arguments)}finally{f=re}}}})(nb);tb.exports=nb;var II=tb.exports;/** * @license React * react-dom.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */var OI=je,hn=II;function U(t){for(var e="https://reactjs.org/docs/error-decoder.html?invariant="+t,n=1;n<arguments.length;n++)e+="&args[]="+encodeURIComponent(arguments[n]);return"Minified React error #"+t+"; visit "+e+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}var rb=new Set,xo={};function os(t,e){Qs(t,e),Qs(t+"Capture",e)}function Qs(t,e){for(xo[t]=e,t=0;t<e.length;t++)rb.add(e[t])}var jr=!(typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),sh=Object.prototype.hasOwnProperty,CI=/^[:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD][:A-Z_a-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\-.0-9\u00B7\u0300-\u036F\u203F-\u2040]*$/,Py={},Ny={};function PI(t){return sh.call(Ny,t)?!0:sh.call(Py,t)?!1:CI.test(t)?Ny[t]=!0:(Py[t]=!0,!1)}function NI(t,e,n,r){if(n!==null&&n.type===0)return!1;switch(typeof e){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(t=t.toLowerCase().slice(0,5),t!=="data-"&&t!=="aria-");default:return!1}}function $I(t,e,n,r){if(e===null||typeof e>"u"||NI(t,e,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!e;case 4:return e===!1;case 5:return isNaN(e);case 6:return isNaN(e)||1>e}return!1}function Ft(t,e,n,r,i,s,a){this.acceptsBooleans=e===2||e===3||e===4,this.attributeName=r,this.attributeNamespace=i,this.mustUseProperty=n,this.propertyName=t,this.type=e,this.sanitizeURL=s,this.removeEmptyString=a}var gt={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(t){gt[t]=new Ft(t,0,!1,t,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(t){var e=t[0];gt[e]=new Ft(e,1,!1,t[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(t){gt[t]=new Ft(t,2,!1,t.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(t){gt[t]=new Ft(t,2,!1,t,null,!1,!1)});"allowFullScreen async autoFocus autoPlay controls default defer disabled disablePictureInPicture disableRemotePlayback formNoValidate hidden loop noModule noValidate open playsInline readOnly required reversed scoped seamless itemScope".split(" ").forEach(function(t){gt[t]=new Ft(t,3,!1,t.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(t){gt[t]=new Ft(t,3,!0,t,null,!1,!1)});["capture","download"].forEach(function(t){gt[t]=new Ft(t,4,!1,t,null,!1,!1)});["cols","rows","size","span"].forEach(function(t){gt[t]=new Ft(t,6,!1,t,null,!1,!1)});["rowSpan","start"].forEach(function(t){gt[t]=new Ft(t,5,!1,t.toLowerCase(),null,!1,!1)});var fm=/[\-:]([a-z])/g;function hm(t){return t[1].toUpperCase()}"accent-height alignment-baseline arabic-form baseline-shift cap-height clip-path clip-rule color-interpolation color-interpolation-filters color-profile color-rendering dominant-baseline enable-background fill-opacity fill-rule flood-color flood-opacity font-family font-size font-size-adjust font-stretch font-style font-variant font-weight glyph-name glyph-orientation-horizontal glyph-orientation-vertical horiz-adv-x horiz-origin-x image-rendering letter-spacing lighting-color marker-end marker-mid marker-start overline-position overline-thickness paint-order panose-1 pointer-events rendering-intent shape-rendering stop-color stop-opacity strikethrough-position strikethrough-thickness stroke-dasharray stroke-dashoffset stroke-linecap stroke-linejoin stroke-miterlimit stroke-opacity stroke-width text-anchor text-decoration text-rendering underline-position underline-thickness unicode-bidi unicode-range units-per-em v-alphabetic v-hanging v-ideographic v-mathematical vector-effect vert-adv-y vert-origin-x vert-origin-y word-spacing writing-mode xmlns:xlink x-height".split(" ").forEach(function(t){var e=t.replace(fm,hm);gt[e]=new Ft(e,1,!1,t,null,!1,!1)});"xlink:actuate xlink:arcrole xlink:role xlink:show xlink:title xlink:type".split(" ").forEach(function(t){var e=t.replace(fm,hm);gt[e]=new Ft(e,1,!1,t,"http://www.w3.org/1999/xlink",!1,!1)});["xml:base","xml:lang","xml:space"].forEach(function(t){var e=t.replace(fm,hm);gt[e]=new Ft(e,1,!1,t,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(t){gt[t]=new Ft(t,1,!1,t.toLowerCase(),null,!1,!1)});gt.xlinkHref=new Ft("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(t){gt[t]=new Ft(t,1,!1,t.toLowerCase(),null,!0,!0)});function pm(t,e,n,r){var i=gt.hasOwnProperty(e)?gt[e]:null;(i!==null?i.type!==0:r||!(2<e.length)||e[0]!=="o"&&e[0]!=="O"||e[1]!=="n"&&e[1]!=="N")&&($I(e,n,i,r)&&(n=null),r||i===null?PI(e)&&(n===null?t.removeAttribute(e):t.setAttribute(e,""+n)):i.mustUseProperty?t[i.propertyName]=n===null?i.type===3?!1:"":n:(e=i.attributeName,r=i.attributeNamespace,n===null?t.removeAttribute(e):(i=i.type,n=i===3||i===4&&n===!0?"":""+n,r?t.setAttributeNS(r,e,n):t.setAttribute(e,n))))}var Hr=OI.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED,yu=Symbol.for("react.element"),ks=Symbol.for("react.portal"),Ss=Symbol.for("react.fragment"),mm=Symbol.for("react.strict_mode"),ah=Symbol.for("react.profiler"),ib=Symbol.for("react.provider"),sb=Symbol.for("react.context"),gm=Symbol.for("react.forward_ref"),oh=Symbol.for("react.suspense"),uh=Symbol.for("react.suspense_list"),ym=Symbol.for("react.memo"),Qr=Symbol.for("react.lazy"),ab=Symbol.for("react.offscreen"),$y=Symbol.iterator;function Ea(t){return t===null||typeof t!="object"?null:(t=$y&&t[$y]||t["@@iterator"],typeof t=="function"?t:null)}var Ue=Object.assign,Hd;function Da(t){if(Hd===void 0)try{throw Error()}catch(n){var e=n.stack.trim().match(/\n( *(at )?)/);Hd=e&&e[1]||""}return` `+Hd+t}var Zd=!1;function Vd(t,e){if(!t||Zd)return"";Zd=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(e)if(e=function(){throw Error()},Object.defineProperty(e.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(e,[])}catch(l){var r=l}Reflect.construct(t,[],e)}else{try{e.call()}catch(l){r=l}t.call(e.prototype)}else{try{throw Error()}catch(l){r=l}t()}}catch(l){if(l&&r&&typeof l.stack=="string"){for(var i=l.stack.split(` `),s=r.stack.split(` `),a=i.length-1,o=s.length-1;1<=a&&0<=o&&i[a]!==s[o];)o--;for(;1<=a&&0<=o;a--,o--)if(i[a]!==s[o]){if(a!==1||o!==1)do if(a--,o--,0>o||i[a]!==s[o]){var u=` `+i[a].replace(" at new "," at ");return t.displayName&&u.includes("<anonymous>")&&(u=u.replace("<anonymous>",t.displayName)),u}while(1<=a&&0<=o);break}}}finally{Zd=!1,Error.prepareStackTrace=n}return(t=t?t.displayName||t.name:"")?Da(t):""}function RI(t){switch(t.tag){case 5:return Da(t.type);case 16:return Da("Lazy");case 13:return Da("Suspense");case 19:return Da("SuspenseList");case 0:case 2:case 15:return t=Vd(t.type,!1),t;case 11:return t=Vd(t.type.render,!1),t;case 1:return t=Vd(t.type,!0),t;default:return""}}function lh(t){if(t==null)return null;if(typeof t=="function")return t.displayName||t.name||null;if(typeof t=="string")return t;switch(t){case Ss:return"Fragment";case ks:return"Portal";case ah:return"Profiler";case mm:return"StrictMode";case oh:return"Suspense";case uh:return"SuspenseList"}if(typeof t=="object")switch(t.$$typeof){case sb:return(t.displayName||"Context")+".Consumer";case ib:return(t._context.displayName||"Context")+".Provider";case gm:var e=t.render;return t=t.displayName,t||(t=e.displayName||e.name||"",t=t!==""?"ForwardRef("+t+")":"ForwardRef"),t;case ym:return e=t.displayName||null,e!==null?e:lh(t.type)||"Memo";case Qr:e=t._payload,t=t._init;try{return lh(t(e))}catch{}}return null}function jI(t){var e=t.type;switch(t.tag){case 24:return"Cache";case 9:return(e.displayName||"Context")+".Consumer";case 10:return(e._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return t=e.render,t=t.displayName||t.name||"",e.displayName||(t!==""?"ForwardRef("+t+")":"ForwardRef");case 7:return"Fragment";case 5:return e;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return lh(e);case 8:return e===mm?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof e=="function")return e.displayName||e.name||null;if(typeof e=="string")return e}return null}function wi(t){switch(typeof t){case"boolean":case"number":case"string":case"undefined":return t;case"object":return t;default:return""}}function ob(t){var e=t.type;return(t=t.nodeName)&&t.toLowerCase()==="input"&&(e==="checkbox"||e==="radio")}function LI(t){var e=ob(t)?"checked":"value",n=Object.getOwnPropertyDescriptor(t.constructor.prototype,e),r=""+t[e];if(!t.hasOwnProperty(e)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var i=n.get,s=n.set;return Object.defineProperty(t,e,{configurable:!0,get:function(){return i.call(this)},set:function(a){r=""+a,s.call(this,a)}}),Object.defineProperty(t,e,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(a){r=""+a},stopTracking:function(){t._valueTracker=null,delete t[e]}}}}function _u(t){t._valueTracker||(t._valueTracker=LI(t))}function ub(t){if(!t)return!1;var e=t._valueTracker;if(!e)return!0;var n=e.getValue(),r="";return t&&(r=ob(t)?t.checked?"true":"false":t.value),t=r,t!==n?(e.setValue(t),!0):!1}function Dl(t){if(t=t||(typeof document<"u"?document:void 0),typeof t>"u")return null;try{return t.activeElement||t.body}catch{return t.body}}function ch(t,e){var n=e.checked;return Ue({},e,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??t._wrapperState.initialChecked})}function Ry(t,e){var n=e.defaultValue==null?"":e.defaultValue,r=e.checked!=null?e.checked:e.defaultChecked;n=wi(e.value!=null?e.value:n),t._wrapperState={initialChecked:r,initialValue:n,controlled:e.type==="checkbox"||e.type==="radio"?e.checked!=null:e.value!=null}}function lb(t,e){e=e.checked,e!=null&&pm(t,"checked",e,!1)}function dh(t,e){lb(t,e);var n=wi(e.value),r=e.type;if(n!=null)r==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+n):t.value!==""+n&&(t.value=""+n);else if(r==="submit"||r==="reset"){t.removeAttribute("value");return}e.hasOwnProperty("value")?fh(t,e.type,n):e.hasOwnProperty("defaultValue")&&fh(t,e.type,wi(e.defaultValue)),e.checked==null&&e.defaultChecked!=null&&(t.defaultChecked=!!e.defaultChecked)}function jy(t,e,n){if(e.hasOwnProperty("value")||e.hasOwnProperty("defaultValue")){var r=e.type;if(!(r!=="submit"&&r!=="reset"||e.value!==void 0&&e.value!==null))return;e=""+t._wrapperState.initialValue,n||e===t.value||(t.value=e),t.defaultValue=e}n=t.name,n!==""&&(t.name=""),t.defaultChecked=!!t._wrapperState.initialChecked,n!==""&&(t.name=n)}function fh(t,e,n){(e!=="number"||Dl(t.ownerDocument)!==t)&&(n==null?t.defaultValue=""+t._wrapperState.initialValue:t.defaultValue!==""+n&&(t.defaultValue=""+n))}var Ua=Array.isArray;function Hs(t,e,n,r){if(t=t.options,e){e={};for(var i=0;i<n.length;i++)e["$"+n[i]]=!0;for(n=0;n<t.length;n++)i=e.hasOwnProperty("$"+t[n].value),t[n].selected!==i&&(t[n].selected=i),i&&r&&(t[n].defaultSelected=!0)}else{for(n=""+wi(n),e=null,i=0;i<t.length;i++){if(t[i].value===n){t[i].selected=!0,r&&(t[i].defaultSelected=!0);return}e!==null||t[i].disabled||(e=t[i])}e!==null&&(e.selected=!0)}}function hh(t,e){if(e.dangerouslySetInnerHTML!=null)throw Error(U(91));return Ue({},e,{value:void 0,defaultValue:void 0,children:""+t._wrapperState.initialValue})}function Ly(t,e){var n=e.value;if(n==null){if(n=e.children,e=e.defaultValue,n!=null){if(e!=null)throw Error(U(92));if(Ua(n)){if(1<n.length)throw Error(U(93));n=n[0]}e=n}e==null&&(e=""),n=e}t._wrapperState={initialValue:wi(n)}}function cb(t,e){var n=wi(e.value),r=wi(e.defaultValue);n!=null&&(n=""+n,n!==t.value&&(t.value=n),e.defaultValue==null&&t.defaultValue!==n&&(t.defaultValue=n)),r!=null&&(t.defaultValue=""+r)}function My(t){var e=t.textContent;e===t._wrapperState.initialValue&&e!==""&&e!==null&&(t.value=e)}function db(t){switch(t){case"svg":return"http://www.w3.org/2000/svg";case"math":return"http://www.w3.org/1998/Math/MathML";default:return"http://www.w3.org/1999/xhtml"}}function ph(t,e){return t==null||t==="http://www.w3.org/1999/xhtml"?db(e):t==="http://www.w3.org/2000/svg"&&e==="foreignObject"?"http://www.w3.org/1999/xhtml":t}var vu,fb=function(t){return typeof MSApp<"u"&&MSApp.execUnsafeLocalFunction?function(e,n,r,i){MSApp.execUnsafeLocalFunction(function(){return t(e,n,r,i)})}:t}(function(t,e){if(t.namespaceURI!=="http://www.w3.org/2000/svg"||"innerHTML"in t)t.innerHTML=e;else{for(vu=vu||document.createElement("div"),vu.innerHTML="<svg>"+e.valueOf().toString()+"</svg>",e=vu.firstChild;t.firstChild;)t.removeChild(t.firstChild);for(;e.firstChild;)t.appendChild(e.firstChild)}});function ko(t,e){if(e){var n=t.firstChild;if(n&&n===t.lastChild&&n.nodeType===3){n.nodeValue=e;return}}t.textContent=e}var io={animationIterationCount:!0,aspectRatio:!0,borderImageOutset:!0,borderImageSlice:!0,borderImageWidth:!0,boxFlex:!0,boxFlexGroup:!0,boxOrdinalGroup:!0,columnCount:!0,columns:!0,flex:!0,flexGrow:!0,flexPositive:!0,flexShrink:!0,flexNegative:!0,flexOrder:!0,gridArea:!0,gridRow:!0,gridRowEnd:!0,gridRowSpan:!0,gridRowStart:!0,gridColumn:!0,gridColumnEnd:!0,gridColumnSpan:!0,gridColumnStart:!0,fontWeight:!0,lineClamp:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,tabSize:!0,widows:!0,zIndex:!0,zoom:!0,fillOpacity:!0,floodOpacity:!0,stopOpacity:!0,strokeDasharray:!0,strokeDashoffset:!0,strokeMiterlimit:!0,strokeOpacity:!0,strokeWidth:!0},MI=["Webkit","ms","Moz","O"];Object.keys(io).forEach(function(t){MI.forEach(function(e){e=e+t.charAt(0).toUpperCase()+t.substring(1),io[e]=io[t]})});function hb(t,e,n){return e==null||typeof e=="boolean"||e===""?"":n||typeof e!="number"||e===0||io.hasOwnProperty(t)&&io[t]?(""+e).trim():e+"px"}function pb(t,e){t=t.style;for(var n in e)if(e.hasOwnProperty(n)){var r=n.indexOf("--")===0,i=hb(n,e[n],r);n==="float"&&(n="cssFloat"),r?t.setProperty(n,i):t[n]=i}}var zI=Ue({menuitem:!0},{area:!0,base:!0,br:!0,col:!0,embed:!0,hr:!0,img:!0,input:!0,keygen:!0,link:!0,meta:!0,param:!0,source:!0,track:!0,wbr:!0});function mh(t,e){if(e){if(zI[t]&&(e.children!=null||e.dangerouslySetInnerHTML!=null))throw Error(U(137,t));if(e.dangerouslySetInnerHTML!=null){if(e.children!=null)throw Error(U(60));if(typeof e.dangerouslySetInnerHTML!="object"||!("__html"in e.dangerouslySetInnerHTML))throw Error(U(61))}if(e.style!=null&&typeof e.style!="object")throw Error(U(62))}}function gh(t,e){if(t.indexOf("-")===-1)return typeof e.is=="string";switch(t){case"annotation-xml":case"color-profile":case"font-face":case"font-face-src":case"font-face-uri":case"font-face-format":case"font-face-name":case"missing-glyph":return!1;default:return!0}}var yh=null;function _m(t){return t=t.target||t.srcElement||window,t.correspondingUseElement&&(t=t.correspondingUseElement),t.nodeType===3?t.parentNode:t}var _h=null,Zs=null,Vs=null;function zy(t){if(t=iu(t)){if(typeof _h!="function")throw Error(U(280));var e=t.stateNode;e&&(e=Xc(e),_h(t.stateNode,t.type,e))}}function mb(t){Zs?Vs?Vs.push(t):Vs=[t]:Zs=t}function gb(){if(Zs){var t=Zs,e=Vs;if(Vs=Zs=null,zy(t),e)for(t=0;t<e.length;t++)zy(e[t])}}function yb(t,e){return t(e)}function _b(){}var Kd=!1;function vb(t,e,n){if(Kd)return t(e,n);Kd=!0;try{return yb(t,e,n)}finally{Kd=!1,(Zs!==null||Vs!==null)&&(_b(),gb())}}function So(t,e){var n=t.stateNode;if(n===null)return null;var r=Xc(n);if(r===null)return null;n=r[e];e:switch(e){case"onClick":case"onClickCapture":case"onDoubleClick":case"onDoubleClickCapture":case"onMouseDown":case"onMouseDownCapture":case"onMouseMove":case"onMouseMoveCapture":case"onMouseUp":case"onMouseUpCapture":case"onMouseEnter":(r=!r.disabled)||(t=t.type,r=!(t==="button"||t==="input"||t==="select"||t==="textarea")),t=!r;break e;default:t=!1}if(t)return null;if(n&&typeof n!="function")throw Error(U(231,e,typeof n));return n}var vh=!1;if(jr)try{var Ta={};Object.defineProperty(Ta,"passive",{get:function(){vh=!0}}),window.addEventListener("test",Ta,Ta),window.removeEventListener("test",Ta,Ta)}catch{vh=!1}function DI(t,e,n,r,i,s,a,o,u){var l=Array.prototype.slice.call(arguments,3);try{e.apply(n,l)}catch(c){this.onError(c)}}var so=!1,Ul=null,Fl=!1,wh=null,UI={onError:function(t){so=!0,Ul=t}};function FI(t,e,n,r,i,s,a,o,u){so=!1,Ul=null,DI.apply(UI,arguments)}function BI(t,e,n,r,i,s,a,o,u){if(FI.apply(this,arguments),so){if(so){var l=Ul;so=!1,Ul=null}else throw Error(U(198));Fl||(Fl=!0,wh=l)}}function us(t){var e=t,n=t;if(t.alternate)for(;e.return;)e=e.return;else{t=e;do e=t,e.flags&4098&&(n=e.return),t=e.return;while(t)}return e.tag===3?n:null}function wb(t){if(t.tag===13){var e=t.memoizedState;if(e===null&&(t=t.alternate,t!==null&&(e=t.memoizedState)),e!==null)return e.dehydrated}return null}function Dy(t){if(us(t)!==t)throw Error(U(188))}function HI(t){var e=t.alternate;if(!e){if(e=us(t),e===null)throw Error(U(188));return e!==t?null:t}for(var n=t,r=e;;){var i=n.return;if(i===null)break;var s=i.alternate;if(s===null){if(r=i.return,r!==null){n=r;continue}break}if(i.child===s.child){for(s=i.child;s;){if(s===n)return Dy(i),t;if(s===r)return Dy(i),e;s=s.sibling}throw Error(U(188))}if(n.return!==r.return)n=i,r=s;else{for(var a=!1,o=i.child;o;){if(o===n){a=!0,n=i,r=s;break}if(o===r){a=!0,r=i,n=s;break}o=o.sibling}if(!a){for(o=s.child;o;){if(o===n){a=!0,n=s,r=i;break}if(o===r){a=!0,r=s,n=i;break}o=o.sibling}if(!a)throw Error(U(189))}}if(n.alternate!==r)throw Error(U(190))}if(n.tag!==3)throw Error(U(188));return n.stateNode.current===n?t:e}function bb(t){return t=HI(t),t!==null?xb(t):null}function xb(t){if(t.tag===5||t.tag===6)return t;for(t=t.child;t!==null;){var e=xb(t);if(e!==null)return e;t=t.sibling}return null}var kb=hn.unstable_scheduleCallback,Uy=hn.unstable_cancelCallback,ZI=hn.unstable_shouldYield,VI=hn.unstable_requestPaint,We=hn.unstable_now,KI=hn.unstable_getCurrentPriorityLevel,vm=hn.unstable_ImmediatePriority,Sb=hn.unstable_UserBlockingPriority,Bl=hn.unstable_NormalPriority,qI=hn.unstable_LowPriority,Ab=hn.unstable_IdlePriority,qc=null,yr=null;function WI(t){if(yr&&typeof yr.onCommitFiberRoot=="function")try{yr.onCommitFiberRoot(qc,t,void 0,(t.current.flags&128)===128)}catch{}}var Wn=Math.clz32?Math.clz32:XI,GI=Math.log,JI=Math.LN2;function XI(t){return t>>>=0,t===0?32:31-(GI(t)/JI|0)|0}var wu=64,bu=4194304;function Fa(t){switch(t&-t){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return t&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return t}}function Hl(t,e){var n=t.pendingLanes;if(n===0)return 0;var r=0,i=t.suspendedLanes,s=t.pingedLanes,a=n&268435455;if(a!==0){var o=a&~i;o!==0?r=Fa(o):(s&=a,s!==0&&(r=Fa(s)))}else a=n&~i,a!==0?r=Fa(a):s!==0&&(r=Fa(s));if(r===0)return 0;if(e!==0&&e!==r&&!(e&i)&&(i=r&-r,s=e&-e,i>=s||i===16&&(s&4194240)!==0))return e;if(r&4&&(r|=n&16),e=t.entangledLanes,e!==0)for(t=t.entanglements,e&=r;0<e;)n=31-Wn(e),i=1<<n,r|=t[n],e&=~i;return r}function QI(t,e){switch(t){case 1:case 2:case 4:return e+250;case 8:case 16:case 32:case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return e+5e3;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return-1;case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function YI(t,e){for(var n=t.suspendedLanes,r=t.pingedLanes,i=t.expirationTimes,s=t.pendingLanes;0<s;){var a=31-Wn(s),o=1<<a,u=i[a];u===-1?(!(o&n)||o&r)&&(i[a]=QI(o,e)):u<=e&&(t.expiredLanes|=o),s&=~o}}function bh(t){return t=t.pendingLanes&-1073741825,t!==0?t:t&1073741824?1073741824:0}function Eb(){var t=wu;return wu<<=1,!(wu&4194240)&&(wu=64),t}function qd(t){for(var e=[],n=0;31>n;n++)e.push(t);return e}function nu(t,e,n){t.pendingLanes|=e,e!==536870912&&(t.suspendedLanes=0,t.pingedLanes=0),t=t.eventTimes,e=31-Wn(e),t[e]=n}function eO(t,e){var n=t.pendingLanes&~e;t.pendingLanes=e,t.suspendedLanes=0,t.pingedLanes=0,t.expiredLanes&=e,t.mutableReadLanes&=e,t.entangledLanes&=e,e=t.entanglements;var r=t.eventTimes;for(t=t.expirationTimes;0<n;){var i=31-Wn(n),s=1<<i;e[i]=0,r[i]=-1,t[i]=-1,n&=~s}}function wm(t,e){var n=t.entangledLanes|=e;for(t=t.entanglements;n;){var r=31-Wn(n),i=1<<r;i&e|t[r]&e&&(t[r]|=e),n&=~i}}var Ae=0;function Tb(t){return t&=-t,1<t?4<t?t&268435455?16:536870912:4:1}var Ib,bm,Ob,Cb,Pb,xh=!1,xu=[],oi=null,ui=null,li=null,Ao=new Map,Eo=new Map,ri=[],tO="mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset submit".split(" ");function Fy(t,e){switch(t){case"focusin":case"focusout":oi=null;break;case"dragenter":case"dragleave":ui=null;break;case"mouseover":case"mouseout":li=null;break;case"pointerover":case"pointerout":Ao.delete(e.pointerId);break;case"gotpointercapture":case"lostpointercapture":Eo.delete(e.pointerId)}}function Ia(t,e,n,r,i,s){return t===null||t.nativeEvent!==s?(t={blockedOn:e,domEventName:n,eventSystemFlags:r,nativeEvent:s,targetContainers:[i]},e!==null&&(e=iu(e),e!==null&&bm(e)),t):(t.eventSystemFlags|=r,e=t.targetContainers,i!==null&&e.indexOf(i)===-1&&e.push(i),t)}function nO(t,e,n,r,i){switch(e){case"focusin":return oi=Ia(oi,t,e,n,r,i),!0;case"dragenter":return ui=Ia(ui,t,e,n,r,i),!0;case"mouseover":return li=Ia(li,t,e,n,r,i),!0;case"pointerover":var s=i.pointerId;return Ao.set(s,Ia(Ao.get(s)||null,t,e,n,r,i)),!0;case"gotpointercapture":return s=i.pointerId,Eo.set(s,Ia(Eo.get(s)||null,t,e,n,r,i)),!0}return!1}function Nb(t){var e=Zi(t.target);if(e!==null){var n=us(e);if(n!==null){if(e=n.tag,e===13){if(e=wb(n),e!==null){t.blockedOn=e,Pb(t.priority,function(){Ob(n)});return}}else if(e===3&&n.stateNode.current.memoizedState.isDehydrated){t.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}t.blockedOn=null}function ll(t){if(t.blockedOn!==null)return!1;for(var e=t.targetContainers;0<e.length;){var n=kh(t.domEventName,t.eventSystemFlags,e[0],t.nativeEvent);if(n===null){n=t.nativeEvent;var r=new n.constructor(n.type,n);yh=r,n.target.dispatchEvent(r),yh=null}else return e=iu(n),e!==null&&bm(e),t.blockedOn=n,!1;e.shift()}return!0}function By(t,e,n){ll(t)&&n.delete(e)}function rO(){xh=!1,oi!==null&&ll(oi)&&(oi=null),ui!==null&&ll(ui)&&(ui=null),li!==null&&ll(li)&&(li=null),Ao.forEach(By),Eo.forEach(By)}function Oa(t,e){t.blockedOn===e&&(t.blockedOn=null,xh||(xh=!0,hn.unstable_scheduleCallback(hn.unstable_NormalPriority,rO)))}function To(t){function e(i){return Oa(i,t)}if(0<xu.length){Oa(xu[0],t);for(var n=1;n<xu.length;n++){var r=xu[n];r.blockedOn===t&&(r.blockedOn=null)}}for(oi!==null&&Oa(oi,t),ui!==null&&Oa(ui,t),li!==null&&Oa(li,t),Ao.forEach(e),Eo.forEach(e),n=0;n<ri.length;n++)r=ri[n],r.blockedOn===t&&(r.blockedOn=null);for(;0<ri.length&&(n=ri[0],n.blockedOn===null);)Nb(n),n.blockedOn===null&&ri.shift()}var Ks=Hr.ReactCurrentBatchConfig,Zl=!0;function iO(t,e,n,r){var i=Ae,s=Ks.transition;Ks.transition=null;try{Ae=1,xm(t,e,n,r)}finally{Ae=i,Ks.transition=s}}function sO(t,e,n,r){var i=Ae,s=Ks.transition;Ks.transition=null;try{Ae=4,xm(t,e,n,r)}finally{Ae=i,Ks.transition=s}}function xm(t,e,n,r){if(Zl){var i=kh(t,e,n,r);if(i===null)rf(t,e,r,Vl,n),Fy(t,r);else if(nO(i,t,e,n,r))r.stopPropagation();else if(Fy(t,r),e&4&&-1<tO.indexOf(t)){for(;i!==null;){var s=iu(i);if(s!==null&&Ib(s),s=kh(t,e,n,r),s===null&&rf(t,e,r,Vl,n),s===i)break;i=s}i!==null&&r.stopPropagation()}else rf(t,e,r,null,n)}}var Vl=null;function kh(t,e,n,r){if(Vl=null,t=_m(r),t=Zi(t),t!==null)if(e=us(t),e===null)t=null;else if(n=e.tag,n===13){if(t=wb(e),t!==null)return t;t=null}else if(n===3){if(e.stateNode.current.memoizedState.isDehydrated)return e.tag===3?e.stateNode.containerInfo:null;t=null}else e!==t&&(t=null);return Vl=t,null}function $b(t){switch(t){case"cancel":case"click":case"close":case"contextmenu":case"copy":case"cut":case"auxclick":case"dblclick":case"dragend":case"dragstart":case"drop":case"focusin":case"focusout":case"input":case"invalid":case"keydown":case"keypress":case"keyup":case"mousedown":case"mouseup":case"paste":case"pause":case"play":case"pointercancel":case"pointerdown":case"pointerup":case"ratechange":case"reset":case"resize":case"seeked":case"submit":case"touchcancel":case"touchend":case"touchstart":case"volumechange":case"change":case"selectionchange":case"textInput":case"compositionstart":case"compositionend":case"compositionupdate":case"beforeblur":case"afterblur":case"beforeinput":case"blur":case"fullscreenchange":case"focus":case"hashchange":case"popstate":case"select":case"selectstart":return 1;case"drag":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"mousemove":case"mouseout":case"mouseover":case"pointermove":case"pointerout":case"pointerover":case"scroll":case"toggle":case"touchmove":case"wheel":case"mouseenter":case"mouseleave":case"pointerenter":case"pointerleave":return 4;case"message":switch(KI()){case vm:return 1;case Sb:return 4;case Bl:case qI:return 16;case Ab:return 536870912;default:return 16}default:return 16}}var si=null,km=null,cl=null;function Rb(){if(cl)return cl;var t,e=km,n=e.length,r,i="value"in si?si.value:si.textContent,s=i.length;for(t=0;t<n&&e[t]===i[t];t++);var a=n-t;for(r=1;r<=a&&e[n-r]===i[s-r];r++);return cl=i.slice(t,1<r?1-r:void 0)}function dl(t){var e=t.keyCode;return"charCode"in t?(t=t.charCode,t===0&&e===13&&(t=13)):t=e,t===10&&(t=13),32<=t||t===13?t:0}function ku(){return!0}function Hy(){return!1}function yn(t){function e(n,r,i,s,a){this._reactName=n,this._targetInst=i,this.type=r,this.nativeEvent=s,this.target=a,this.currentTarget=null;for(var o in t)t.hasOwnProperty(o)&&(n=t[o],this[o]=n?n(s):s[o]);return this.isDefaultPrevented=(s.defaultPrevented!=null?s.defaultPrevented:s.returnValue===!1)?ku:Hy,this.isPropagationStopped=Hy,this}return Ue(e.prototype,{preventDefault:function(){this.defaultPrevented=!0;var n=this.nativeEvent;n&&(n.preventDefault?n.preventDefault():typeof n.returnValue!="unknown"&&(n.returnValue=!1),this.isDefaultPrevented=ku)},stopPropagation:function(){var n=this.nativeEvent;n&&(n.stopPropagation?n.stopPropagation():typeof n.cancelBubble!="unknown"&&(n.cancelBubble=!0),this.isPropagationStopped=ku)},persist:function(){},isPersistent:ku}),e}var ya={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(t){return t.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},Sm=yn(ya),ru=Ue({},ya,{view:0,detail:0}),aO=yn(ru),Wd,Gd,Ca,Wc=Ue({},ru,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Am,button:0,buttons:0,relatedTarget:function(t){return t.relatedTarget===void 0?t.fromElement===t.srcElement?t.toElement:t.fromElement:t.relatedTarget},movementX:function(t){return"movementX"in t?t.movementX:(t!==Ca&&(Ca&&t.type==="mousemove"?(Wd=t.screenX-Ca.screenX,Gd=t.screenY-Ca.screenY):Gd=Wd=0,Ca=t),Wd)},movementY:function(t){return"movementY"in t?t.movementY:Gd}}),Zy=yn(Wc),oO=Ue({},Wc,{dataTransfer:0}),uO=yn(oO),lO=Ue({},ru,{relatedTarget:0}),Jd=yn(lO),cO=Ue({},ya,{animationName:0,elapsedTime:0,pseudoElement:0}),dO=yn(cO),fO=Ue({},ya,{clipboardData:function(t){return"clipboardData"in t?t.clipboardData:window.clipboardData}}),hO=yn(fO),pO=Ue({},ya,{data:0}),Vy=yn(pO),mO={Esc:"Escape",Spacebar:" ",Left:"ArrowLeft",Up:"ArrowUp",Right:"ArrowRight",Down:"ArrowDown",Del:"Delete",Win:"OS",Menu:"ContextMenu",Apps:"ContextMenu",Scroll:"ScrollLock",MozPrintableKey:"Unidentified"},gO={8:"Backspace",9:"Tab",12:"Clear",13:"Enter",16:"Shift",17:"Control",18:"Alt",19:"Pause",20:"CapsLock",27:"Escape",32:" ",33:"PageUp",34:"PageDown",35:"End",36:"Home",37:"ArrowLeft",38:"ArrowUp",39:"ArrowRight",40:"ArrowDown",45:"Insert",46:"Delete",112:"F1",113:"F2",114:"F3",115:"F4",116:"F5",117:"F6",118:"F7",119:"F8",120:"F9",121:"F10",122:"F11",123:"F12",144:"NumLock",145:"ScrollLock",224:"Meta"},yO={Alt:"altKey",Control:"ctrlKey",Meta:"metaKey",Shift:"shiftKey"};function _O(t){var e=this.nativeEvent;return e.getModifierState?e.getModifierState(t):(t=yO[t])?!!e[t]:!1}function Am(){return _O}var vO=Ue({},ru,{key:function(t){if(t.key){var e=mO[t.key]||t.key;if(e!=="Unidentified")return e}return t.type==="keypress"?(t=dl(t),t===13?"Enter":String.fromCharCode(t)):t.type==="keydown"||t.type==="keyup"?gO[t.keyCode]||"Unidentified":""},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Am,charCode:function(t){return t.type==="keypress"?dl(t):0},keyCode:function(t){return t.type==="keydown"||t.type==="keyup"?t.keyCode:0},which:function(t){return t.type==="keypress"?dl(t):t.type==="keydown"||t.type==="keyup"?t.keyCode:0}}),wO=yn(vO),bO=Ue({},Wc,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0}),Ky=yn(bO),xO=Ue({},ru,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Am}),kO=yn(xO),SO=Ue({},ya,{propertyName:0,elapsedTime:0,pseudoElement:0}),AO=yn(SO),EO=Ue({},Wc,{deltaX:function(t){return"deltaX"in t?t.deltaX:"wheelDeltaX"in t?-t.wheelDeltaX:0},deltaY:function(t){return"deltaY"in t?t.deltaY:"wheelDeltaY"in t?-t.wheelDeltaY:"wheelDelta"in t?-t.wheelDelta:0},deltaZ:0,deltaMode:0}),TO=yn(EO),IO=[9,13,27,32],Em=jr&&"CompositionEvent"in window,ao=null;jr&&"documentMode"in document&&(ao=document.documentMode);var OO=jr&&"TextEvent"in window&&!ao,jb=jr&&(!Em||ao&&8<ao&&11>=ao),qy=" ",Wy=!1;function Lb(t,e){switch(t){case"keyup":return IO.indexOf(e.keyCode)!==-1;case"keydown":return e.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Mb(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var As=!1;function CO(t,e){switch(t){case"compositionend":return Mb(e);case"keypress":return e.which!==32?null:(Wy=!0,qy);case"textInput":return t=e.data,t===qy&&Wy?null:t;default:return null}}function PO(t,e){if(As)return t==="compositionend"||!Em&&Lb(t,e)?(t=Rb(),cl=km=si=null,As=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(e.ctrlKey||e.altKey||e.metaKey)||e.ctrlKey&&e.altKey){if(e.char&&1<e.char.length)return e.char;if(e.which)return String.fromCharCode(e.which)}return null;case"compositionend":return jb&&e.locale!=="ko"?null:e.data;default:return null}}var NO={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function Gy(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e==="input"?!!NO[t.type]:e==="textarea"}function zb(t,e,n,r){mb(r),e=Kl(e,"onChange"),0<e.length&&(n=new Sm("onChange","change",null,n,r),t.push({event:n,listeners:e}))}var oo=null,Io=null;function $O(t){Gb(t,0)}function Gc(t){var e=Is(t);if(ub(e))return t}function RO(t,e){if(t==="change")return e}var Db=!1;if(jr){var Xd;if(jr){var Qd="oninput"in document;if(!Qd){var Jy=document.createElement("div");Jy.setAttribute("oninput","return;"),Qd=typeof Jy.oninput=="function"}Xd=Qd}else Xd=!1;Db=Xd&&(!document.documentMode||9<document.documentMode)}function Xy(){oo&&(oo.detachEvent("onpropertychange",Ub),Io=oo=null)}function Ub(t){if(t.propertyName==="value"&&Gc(Io)){var e=[];zb(e,Io,t,_m(t)),vb($O,e)}}function jO(t,e,n){t==="focusin"?(Xy(),oo=e,Io=n,oo.attachEvent("onpropertychange",Ub)):t==="focusout"&&Xy()}function LO(t){if(t==="selectionchange"||t==="keyup"||t==="keydown")return Gc(Io)}function MO(t,e){if(t==="click")return Gc(e)}function zO(t,e){if(t==="input"||t==="change")return Gc(e)}function DO(t,e){return t===e&&(t!==0||1/t===1/e)||t!==t&&e!==e}var Qn=typeof Object.is=="function"?Object.is:DO;function Oo(t,e){if(Qn(t,e))return!0;if(typeof t!="object"||t===null||typeof e!="object"||e===null)return!1;var n=Object.keys(t),r=Object.keys(e);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var i=n[r];if(!sh.call(e,i)||!Qn(t[i],e[i]))return!1}return!0}function Qy(t){for(;t&&t.firstChild;)t=t.firstChild;return t}function Yy(t,e){var n=Qy(t);t=0;for(var r;n;){if(n.nodeType===3){if(r=t+n.textContent.length,t<=e&&r>=e)return{node:n,offset:e-t};t=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Qy(n)}}function Fb(t,e){return t&&e?t===e?!0:t&&t.nodeType===3?!1:e&&e.nodeType===3?Fb(t,e.parentNode):"contains"in t?t.contains(e):t.compareDocumentPosition?!!(t.compareDocumentPosition(e)&16):!1:!1}function Bb(){for(var t=window,e=Dl();e instanceof t.HTMLIFrameElement;){try{var n=typeof e.contentWindow.location.href=="string"}catch{n=!1}if(n)t=e.contentWindow;else break;e=Dl(t.document)}return e}function Tm(t){var e=t&&t.nodeName&&t.nodeName.toLowerCase();return e&&(e==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||e==="textarea"||t.contentEditable==="true")}function UO(t){var e=Bb(),n=t.focusedElem,r=t.selectionRange;if(e!==n&&n&&n.ownerDocument&&Fb(n.ownerDocument.documentElement,n)){if(r!==null&&Tm(n)){if(e=r.start,t=r.end,t===void 0&&(t=e),"selectionStart"in n)n.selectionStart=e,n.selectionEnd=Math.min(t,n.value.length);else if(t=(e=n.ownerDocument||document)&&e.defaultView||window,t.getSelection){t=t.getSelection();var i=n.textContent.length,s=Math.min(r.start,i);r=r.end===void 0?s:Math.min(r.end,i),!t.extend&&s>r&&(i=r,r=s,s=i),i=Yy(n,s);var a=Yy(n,r);i&&a&&(t.rangeCount!==1||t.anchorNode!==i.node||t.anchorOffset!==i.offset||t.focusNode!==a.node||t.focusOffset!==a.offset)&&(e=e.createRange(),e.setStart(i.node,i.offset),t.removeAllRanges(),s>r?(t.addRange(e),t.extend(a.node,a.offset)):(e.setEnd(a.node,a.offset),t.addRange(e)))}}for(e=[],t=n;t=t.parentNode;)t.nodeType===1&&e.push({element:t,left:t.scrollLeft,top:t.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n<e.length;n++)t=e[n],t.element.scrollLeft=t.left,t.element.scrollTop=t.top}}var FO=jr&&"documentMode"in document&&11>=document.documentMode,Es=null,Sh=null,uo=null,Ah=!1;function e_(t,e,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ah||Es==null||Es!==Dl(r)||(r=Es,"selectionStart"in r&&Tm(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),uo&&Oo(uo,r)||(uo=r,r=Kl(Sh,"onSelect"),0<r.length&&(e=new Sm("onSelect","select",null,e,n),t.push({event:e,listeners:r}),e.target=Es)))}function Su(t,e){var n={};return n[t.toLowerCase()]=e.toLowerCase(),n["Webkit"+t]="webkit"+e,n["Moz"+t]="moz"+e,n}var Ts={animationend:Su("Animation","AnimationEnd"),animationiteration:Su("Animation","AnimationIteration"),animationstart:Su("Animation","AnimationStart"),transitionend:Su("Transition","TransitionEnd")},Yd={},Hb={};jr&&(Hb=document.createElement("div").style,"AnimationEvent"in window||(delete Ts.animationend.animation,delete Ts.animationiteration.animation,delete Ts.animationstart.animation),"TransitionEvent"in window||delete Ts.transitionend.transition);function Jc(t){if(Yd[t])return Yd[t];if(!Ts[t])return t;var e=Ts[t],n;for(n in e)if(e.hasOwnProperty(n)&&n in Hb)return Yd[t]=e[n];return t}var Zb=Jc("animationend"),Vb=Jc("animationiteration"),Kb=Jc("animationstart"),qb=Jc("transitionend"),Wb=new Map,t_="abort auxClick cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel".split(" ");function Oi(t,e){Wb.set(t,e),os(e,[t])}for(var ef=0;ef<t_.length;ef++){var tf=t_[ef],BO=tf.toLowerCase(),HO=tf[0].toUpperCase()+tf.slice(1);Oi(BO,"on"+HO)}Oi(Zb,"onAnimationEnd");Oi(Vb,"onAnimationIteration");Oi(Kb,"onAnimationStart");Oi("dblclick","onDoubleClick");Oi("focusin","onFocus");Oi("focusout","onBlur");Oi(qb,"onTransitionEnd");Qs("onMouseEnter",["mouseout","mouseover"]);Qs("onMouseLeave",["mouseout","mouseover"]);Qs("onPointerEnter",["pointerout","pointerover"]);Qs("onPointerLeave",["pointerout","pointerover"]);os("onChange","change click focusin focusout input keydown keyup selectionchange".split(" "));os("onSelect","focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange".split(" "));os("onBeforeInput",["compositionend","keypress","textInput","paste"]);os("onCompositionEnd","compositionend focusout keydown keypress keyup mousedown".split(" "));os("onCompositionStart","compositionstart focusout keydown keypress keyup mousedown".split(" "));os("onCompositionUpdate","compositionupdate focusout keydown keypress keyup mousedown".split(" "));var Ba="abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting".split(" "),ZO=new Set("cancel close invalid load scroll toggle".split(" ").concat(Ba));function n_(t,e,n){var r=t.type||"unknown-event";t.currentTarget=n,BI(r,e,void 0,t),t.currentTarget=null}function Gb(t,e){e=(e&4)!==0;for(var n=0;n<t.length;n++){var r=t[n],i=r.event;r=r.listeners;e:{var s=void 0;if(e)for(var a=r.length-1;0<=a;a--){var o=r[a],u=o.instance,l=o.currentTarget;if(o=o.listener,u!==s&&i.isPropagationStopped())break e;n_(i,o,l),s=u}else for(a=0;a<r.length;a++){if(o=r[a],u=o.instance,l=o.currentTarget,o=o.listener,u!==s&&i.isPropagationStopped())break e;n_(i,o,l),s=u}}}if(Fl)throw t=wh,Fl=!1,wh=null,t}function Ne(t,e){var n=e[Ch];n===void 0&&(n=e[Ch]=new Set);var r=t+"__bubble";n.has(r)||(Jb(e,t,2,!1),n.add(r))}function nf(t,e,n){var r=0;e&&(r|=4),Jb(n,t,r,e)}var Au="_reactListening"+Math.random().toString(36).slice(2);function Co(t){if(!t[Au]){t[Au]=!0,rb.forEach(function(n){n!=="selectionchange"&&(ZO.has(n)||nf(n,!1,t),nf(n,!0,t))});var e=t.nodeType===9?t:t.ownerDocument;e===null||e[Au]||(e[Au]=!0,nf("selectionchange",!1,e))}}function Jb(t,e,n,r){switch($b(e)){case 1:var i=iO;break;case 4:i=sO;break;default:i=xm}n=i.bind(null,e,n,t),i=void 0,!vh||e!=="touchstart"&&e!=="touchmove"&&e!=="wheel"||(i=!0),r?i!==void 0?t.addEventListener(e,n,{capture:!0,passive:i}):t.addEventListener(e,n,!0):i!==void 0?t.addEventListener(e,n,{passive:i}):t.addEventListener(e,n,!1)}function rf(t,e,n,r,i){var s=r;if(!(e&1)&&!(e&2)&&r!==null)e:for(;;){if(r===null)return;var a=r.tag;if(a===3||a===4){var o=r.stateNode.containerInfo;if(o===i||o.nodeType===8&&o.parentNode===i)break;if(a===4)for(a=r.return;a!==null;){var u=a.tag;if((u===3||u===4)&&(u=a.stateNode.containerInfo,u===i||u.nodeType===8&&u.parentNode===i))return;a=a.return}for(;o!==null;){if(a=Zi(o),a===null)return;if(u=a.tag,u===5||u===6){r=s=a;continue e}o=o.parentNode}}r=r.return}vb(function(){var l=s,c=_m(n),d=[];e:{var f=Wb.get(t);if(f!==void 0){var h=Sm,m=t;switch(t){case"keypress":if(dl(n)===0)break e;case"keydown":case"keyup":h=wO;break;case"focusin":m="focus",h=Jd;break;case"focusout":m="blur",h=Jd;break;case"beforeblur":case"afterblur":h=Jd;break;case"click":if(n.button===2)break e;case"auxclick":case"dblclick":case"mousedown":case"mousemove":case"mouseup":case"mouseout":case"mouseover":case"contextmenu":h=Zy;break;case"drag":case"dragend":case"dragenter":case"dragexit":case"dragleave":case"dragover":case"dragstart":case"drop":h=uO;break;case"touchcancel":case"touchend":case"touchmove":case"touchstart":h=kO;break;case Zb:case Vb:case Kb:h=dO;break;case qb:h=AO;break;case"scroll":h=aO;break;case"wheel":h=TO;break;case"copy":case"cut":case"paste":h=hO;break;case"gotpointercapture":case"lostpointercapture":case"pointercancel":case"pointerdown":case"pointermove":case"pointerout":case"pointerover":case"pointerup":h=Ky}var _=(e&4)!==0,v=!_&&t==="scroll",y=_?f!==null?f+"Capture":null:f;_=[];for(var p=l,g;p!==null;){g=p;var b=g.stateNode;if(g.tag===5&&b!==null&&(g=b,y!==null&&(b=So(p,y),b!=null&&_.push(Po(p,b,g)))),v)break;p=p.return}0<_.length&&(f=new h(f,m,null,n,c),d.push({event:f,listeners:_}))}}if(!(e&7)){e:{if(f=t==="mouseover"||t==="pointerover",h=t==="mouseout"||t==="pointerout",f&&n!==yh&&(m=n.relatedTarget||n.fromElement)&&(Zi(m)||m[Lr]))break e;if((h||f)&&(f=c.window===c?c:(f=c.ownerDocument)?f.defaultView||f.parentWindow:window,h?(m=n.relatedTarget||n.toElement,h=l,m=m?Zi(m):null,m!==null&&(v=us(m),m!==v||m.tag!==5&&m.tag!==6)&&(m=null)):(h=null,m=l),h!==m)){if(_=Zy,b="onMouseLeave",y="onMouseEnter",p="mouse",(t==="pointerout"||t==="pointerover")&&(_=Ky,b="onPointerLeave",y="onPointerEnter",p="pointer"),v=h==null?f:Is(h),g=m==null?f:Is(m),f=new _(b,p+"leave",h,n,c),f.target=v,f.relatedTarget=g,b=null,Zi(c)===l&&(_=new _(y,p+"enter",m,n,c),_.target=g,_.relatedTarget=v,b=_),v=b,h&&m)t:{for(_=h,y=m,p=0,g=_;g;g=fs(g))p++;for(g=0,b=y;b;b=fs(b))g++;for(;0<p-g;)_=fs(_),p--;for(;0<g-p;)y=fs(y),g--;for(;p--;){if(_===y||y!==null&&_===y.alternate)break t;_=fs(_),y=fs(y)}_=null}else _=null;h!==null&&r_(d,f,h,_,!1),m!==null&&v!==null&&r_(d,v,m,_,!0)}}e:{if(f=l?Is(l):window,h=f.nodeName&&f.nodeName.toLowerCase(),h==="select"||h==="input"&&f.type==="file")var E=RO;else if(Gy(f))if(Db)E=zO;else{E=LO;var T=jO}else(h=f.nodeName)&&h.toLowerCase()==="input"&&(f.type==="checkbox"||f.type==="radio")&&(E=MO);if(E&&(E=E(t,l))){zb(d,E,n,c);break e}T&&T(t,f,l),t==="focusout"&&(T=f._wrapperState)&&T.controlled&&f.type==="number"&&fh(f,"number",f.value)}switch(T=l?Is(l):window,t){case"focusin":(Gy(T)||T.contentEditable==="true")&&(Es=T,Sh=l,uo=null);break;case"focusout":uo=Sh=Es=null;break;case"mousedown":Ah=!0;break;case"contextmenu":case"mouseup":case"dragend":Ah=!1,e_(d,n,c);break;case"selectionchange":if(FO)break;case"keydown":case"keyup":e_(d,n,c)}var I;if(Em)e:{switch(t){case"compositionstart":var k="onCompositionStart";break e;case"compositionend":k="onCompositionEnd";break e;case"compositionupdate":k="onCompositionUpdate";break e}k=void 0}else As?Lb(t,n)&&(k="onCompositionEnd"):t==="keydown"&&n.keyCode===229&&(k="onCompositionStart");k&&(jb&&n.locale!=="ko"&&(As||k!=="onCompositionStart"?k==="onCompositionEnd"&&As&&(I=Rb()):(si=c,km="value"in si?si.value:si.textContent,As=!0)),T=Kl(l,k),0<T.length&&(k=new Vy(k,t,null,n,c),d.push({event:k,listeners:T}),I?k.data=I:(I=Mb(n),I!==null&&(k.data=I)))),(I=OO?CO(t,n):PO(t,n))&&(l=Kl(l,"onBeforeInput"),0<l.length&&(c=new Vy("onBeforeInput","beforeinput",null,n,c),d.push({event:c,listeners:l}),c.data=I))}Gb(d,e)})}function Po(t,e,n){return{instance:t,listener:e,currentTarget:n}}function Kl(t,e){for(var n=e+"Capture",r=[];t!==null;){var i=t,s=i.stateNode;i.tag===5&&s!==null&&(i=s,s=So(t,n),s!=null&&r.unshift(Po(t,s,i)),s=So(t,e),s!=null&&r.push(Po(t,s,i))),t=t.return}return r}function fs(t){if(t===null)return null;do t=t.return;while(t&&t.tag!==5);return t||null}function r_(t,e,n,r,i){for(var s=e._reactName,a=[];n!==null&&n!==r;){var o=n,u=o.alternate,l=o.stateNode;if(u!==null&&u===r)break;o.tag===5&&l!==null&&(o=l,i?(u=So(n,s),u!=null&&a.unshift(Po(n,u,o))):i||(u=So(n,s),u!=null&&a.push(Po(n,u,o)))),n=n.return}a.length!==0&&t.push({event:e,listeners:a})}var VO=/\r\n?/g,KO=/\u0000|\uFFFD/g;function i_(t){return(typeof t=="string"?t:""+t).replace(VO,` `).replace(KO,"")}function Eu(t,e,n){if(e=i_(e),i_(t)!==e&&n)throw Error(U(425))}function ql(){}var Eh=null,Th=null;function Ih(t,e){return t==="textarea"||t==="noscript"||typeof e.children=="string"||typeof e.children=="number"||typeof e.dangerouslySetInnerHTML=="object"&&e.dangerouslySetInnerHTML!==null&&e.dangerouslySetInnerHTML.__html!=null}var Oh=typeof setTimeout=="function"?setTimeout:void 0,qO=typeof clearTimeout=="function"?clearTimeout:void 0,s_=typeof Promise=="function"?Promise:void 0,WO=typeof queueMicrotask=="function"?queueMicrotask:typeof s_<"u"?function(t){return s_.resolve(null).then(t).catch(GO)}:Oh;function GO(t){setTimeout(function(){throw t})}function sf(t,e){var n=e,r=0;do{var i=n.nextSibling;if(t.removeChild(n),i&&i.nodeType===8)if(n=i.data,n==="/$"){if(r===0){t.removeChild(i),To(e);return}r--}else n!=="$"&&n!=="$?"&&n!=="$!"||r++;n=i}while(n);To(e)}function ci(t){for(;t!=null;t=t.nextSibling){var e=t.nodeType;if(e===1||e===3)break;if(e===8){if(e=t.data,e==="$"||e==="$!"||e==="$?")break;if(e==="/$")return null}}return t}function a_(t){t=t.previousSibling;for(var e=0;t;){if(t.nodeType===8){var n=t.data;if(n==="$"||n==="$!"||n==="$?"){if(e===0)return t;e--}else n==="/$"&&e++}t=t.previousSibling}return null}var _a=Math.random().toString(36).slice(2),dr="__reactFiber$"+_a,No="__reactProps$"+_a,Lr="__reactContainer$"+_a,Ch="__reactEvents$"+_a,JO="__reactListeners$"+_a,XO="__reactHandles$"+_a;function Zi(t){var e=t[dr];if(e)return e;for(var n=t.parentNode;n;){if(e=n[Lr]||n[dr]){if(n=e.alternate,e.child!==null||n!==null&&n.child!==null)for(t=a_(t);t!==null;){if(n=t[dr])return n;t=a_(t)}return e}t=n,n=t.parentNode}return null}function iu(t){return t=t[dr]||t[Lr],!t||t.tag!==5&&t.tag!==6&&t.tag!==13&&t.tag!==3?null:t}function Is(t){if(t.tag===5||t.tag===6)return t.stateNode;throw Error(U(33))}function Xc(t){return t[No]||null}var Ph=[],Os=-1;function Ci(t){return{current:t}}function Re(t){0>Os||(t.current=Ph[Os],Ph[Os]=null,Os--)}function Oe(t,e){Os++,Ph[Os]=t.current,t.current=e}var bi={},kt=Ci(bi),Xt=Ci(!1),Yi=bi;function Ys(t,e){var n=t.type.contextTypes;if(!n)return bi;var r=t.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===e)return r.__reactInternalMemoizedMaskedChildContext;var i={},s;for(s in n)i[s]=e[s];return r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=e,t.__reactInternalMemoizedMaskedChildContext=i),i}function Qt(t){return t=t.childContextTypes,t!=null}function Wl(){Re(Xt),Re(kt)}function o_(t,e,n){if(kt.current!==bi)throw Error(U(168));Oe(kt,e),Oe(Xt,n)}function Xb(t,e,n){var r=t.stateNode;if(e=e.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var i in r)if(!(i in e))throw Error(U(108,jI(t)||"Unknown",i));return Ue({},n,r)}function Gl(t){return t=(t=t.stateNode)&&t.__reactInternalMemoizedMergedChildContext||bi,Yi=kt.current,Oe(kt,t),Oe(Xt,Xt.current),!0}function u_(t,e,n){var r=t.stateNode;if(!r)throw Error(U(169));n?(t=Xb(t,e,Yi),r.__reactInternalMemoizedMergedChildContext=t,Re(Xt),Re(kt),Oe(kt,t)):Re(Xt),Oe(Xt,n)}var Er=null,Qc=!1,af=!1;function Qb(t){Er===null?Er=[t]:Er.push(t)}function QO(t){Qc=!0,Qb(t)}function Pi(){if(!af&&Er!==null){af=!0;var t=0,e=Ae;try{var n=Er;for(Ae=1;t<n.length;t++){var r=n[t];do r=r(!0);while(r!==null)}Er=null,Qc=!1}catch(i){throw Er!==null&&(Er=Er.slice(t+1)),kb(vm,Pi),i}finally{Ae=e,af=!1}}return null}var Cs=[],Ps=0,Jl=null,Xl=0,kn=[],Sn=0,es=null,Or=1,Cr="";function Mi(t,e){Cs[Ps++]=Xl,Cs[Ps++]=Jl,Jl=t,Xl=e}function Yb(t,e,n){kn[Sn++]=Or,kn[Sn++]=Cr,kn[Sn++]=es,es=t;var r=Or;t=Cr;var i=32-Wn(r)-1;r&=~(1<<i),n+=1;var s=32-Wn(e)+i;if(30<s){var a=i-i%5;s=(r&(1<<a)-1).toString(32),r>>=a,i-=a,Or=1<<32-Wn(e)+i|n<<i|r,Cr=s+t}else Or=1<<s|n<<i|r,Cr=t}function Im(t){t.return!==null&&(Mi(t,1),Yb(t,1,0))}function Om(t){for(;t===Jl;)Jl=Cs[--Ps],Cs[Ps]=null,Xl=Cs[--Ps],Cs[Ps]=null;for(;t===es;)es=kn[--Sn],kn[Sn]=null,Cr=kn[--Sn],kn[Sn]=null,Or=kn[--Sn],kn[Sn]=null}var fn=null,cn=null,Le=!1,Kn=null;function ex(t,e){var n=An(5,null,null,0);n.elementType="DELETED",n.stateNode=e,n.return=t,e=t.deletions,e===null?(t.deletions=[n],t.flags|=16):e.push(n)}function l_(t,e){switch(t.tag){case 5:var n=t.type;return e=e.nodeType!==1||n.toLowerCase()!==e.nodeName.toLowerCase()?null:e,e!==null?(t.stateNode=e,fn=t,cn=ci(e.firstChild),!0):!1;case 6:return e=t.pendingProps===""||e.nodeType!==3?null:e,e!==null?(t.stateNode=e,fn=t,cn=null,!0):!1;case 13:return e=e.nodeType!==8?null:e,e!==null?(n=es!==null?{id:Or,overflow:Cr}:null,t.memoizedState={dehydrated:e,treeContext:n,retryLane:1073741824},n=An(18,null,null,0),n.stateNode=e,n.return=t,t.child=n,fn=t,cn=null,!0):!1;default:return!1}}function Nh(t){return(t.mode&1)!==0&&(t.flags&128)===0}function $h(t){if(Le){var e=cn;if(e){var n=e;if(!l_(t,e)){if(Nh(t))throw Error(U(418));e=ci(n.nextSibling);var r=fn;e&&l_(t,e)?ex(r,n):(t.flags=t.flags&-4097|2,Le=!1,fn=t)}}else{if(Nh(t))throw Error(U(418));t.flags=t.flags&-4097|2,Le=!1,fn=t}}}function c_(t){for(t=t.return;t!==null&&t.tag!==5&&t.tag!==3&&t.tag!==13;)t=t.return;fn=t}function Tu(t){if(t!==fn)return!1;if(!Le)return c_(t),Le=!0,!1;var e;if((e=t.tag!==3)&&!(e=t.tag!==5)&&(e=t.type,e=e!=="head"&&e!=="body"&&!Ih(t.type,t.memoizedProps)),e&&(e=cn)){if(Nh(t))throw tx(),Error(U(418));for(;e;)ex(t,e),e=ci(e.nextSibling)}if(c_(t),t.tag===13){if(t=t.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(U(317));e:{for(t=t.nextSibling,e=0;t;){if(t.nodeType===8){var n=t.data;if(n==="/$"){if(e===0){cn=ci(t.nextSibling);break e}e--}else n!=="$"&&n!=="$!"&&n!=="$?"||e++}t=t.nextSibling}cn=null}}else cn=fn?ci(t.stateNode.nextSibling):null;return!0}function tx(){for(var t=cn;t;)t=ci(t.nextSibling)}function ea(){cn=fn=null,Le=!1}function Cm(t){Kn===null?Kn=[t]:Kn.push(t)}var YO=Hr.ReactCurrentBatchConfig;function Pa(t,e,n){if(t=n.ref,t!==null&&typeof t!="function"&&typeof t!="object"){if(n._owner){if(n=n._owner,n){if(n.tag!==1)throw Error(U(309));var r=n.stateNode}if(!r)throw Error(U(147,t));var i=r,s=""+t;return e!==null&&e.ref!==null&&typeof e.ref=="function"&&e.ref._stringRef===s?e.ref:(e=function(a){var o=i.refs;a===null?delete o[s]:o[s]=a},e._stringRef=s,e)}if(typeof t!="string")throw Error(U(284));if(!n._owner)throw Error(U(290,t))}return t}function Iu(t,e){throw t=Object.prototype.toString.call(e),Error(U(31,t==="[object Object]"?"object with keys {"+Object.keys(e).join(", ")+"}":t))}function d_(t){var e=t._init;return e(t._payload)}function nx(t){function e(y,p){if(t){var g=y.deletions;g===null?(y.deletions=[p],y.flags|=16):g.push(p)}}function n(y,p){if(!t)return null;for(;p!==null;)e(y,p),p=p.sibling;return null}function r(y,p){for(y=new Map;p!==null;)p.key!==null?y.set(p.key,p):y.set(p.index,p),p=p.sibling;return y}function i(y,p){return y=pi(y,p),y.index=0,y.sibling=null,y}function s(y,p,g){return y.index=g,t?(g=y.alternate,g!==null?(g=g.index,g<p?(y.flags|=2,p):g):(y.flags|=2,p)):(y.flags|=1048576,p)}function a(y){return t&&y.alternate===null&&(y.flags|=2),y}function o(y,p,g,b){return p===null||p.tag!==6?(p=hf(g,y.mode,b),p.return=y,p):(p=i(p,g),p.return=y,p)}function u(y,p,g,b){var E=g.type;return E===Ss?c(y,p,g.props.children,b,g.key):p!==null&&(p.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Qr&&d_(E)===p.type)?(b=i(p,g.props),b.ref=Pa(y,p,g),b.return=y,b):(b=_l(g.type,g.key,g.props,null,y.mode,b),b.ref=Pa(y,p,g),b.return=y,b)}function l(y,p,g,b){return p===null||p.tag!==4||p.stateNode.containerInfo!==g.containerInfo||p.stateNode.implementation!==g.implementation?(p=pf(g,y.mode,b),p.return=y,p):(p=i(p,g.children||[]),p.return=y,p)}function c(y,p,g,b,E){return p===null||p.tag!==7?(p=Xi(g,y.mode,b,E),p.return=y,p):(p=i(p,g),p.return=y,p)}function d(y,p,g){if(typeof p=="string"&&p!==""||typeof p=="number")return p=hf(""+p,y.mode,g),p.return=y,p;if(typeof p=="object"&&p!==null){switch(p.$$typeof){case yu:return g=_l(p.type,p.key,p.props,null,y.mode,g),g.ref=Pa(y,null,p),g.return=y,g;case ks:return p=pf(p,y.mode,g),p.return=y,p;case Qr:var b=p._init;return d(y,b(p._payload),g)}if(Ua(p)||Ea(p))return p=Xi(p,y.mode,g,null),p.return=y,p;Iu(y,p)}return null}function f(y,p,g,b){var E=p!==null?p.key:null;if(typeof g=="string"&&g!==""||typeof g=="number")return E!==null?null:o(y,p,""+g,b);if(typeof g=="object"&&g!==null){switch(g.$$typeof){case yu:return g.key===E?u(y,p,g,b):null;case ks:return g.key===E?l(y,p,g,b):null;case Qr:return E=g._init,f(y,p,E(g._payload),b)}if(Ua(g)||Ea(g))return E!==null?null:c(y,p,g,b,null);Iu(y,g)}return null}function h(y,p,g,b,E){if(typeof b=="string"&&b!==""||typeof b=="number")return y=y.get(g)||null,o(p,y,""+b,E);if(typeof b=="object"&&b!==null){switch(b.$$typeof){case yu:return y=y.get(b.key===null?g:b.key)||null,u(p,y,b,E);case ks:return y=y.get(b.key===null?g:b.key)||null,l(p,y,b,E);case Qr:var T=b._init;return h(y,p,g,T(b._payload),E)}if(Ua(b)||Ea(b))return y=y.get(g)||null,c(p,y,b,E,null);Iu(p,b)}return null}function m(y,p,g,b){for(var E=null,T=null,I=p,k=p=0,j=null;I!==null&&k<g.length;k++){I.index>k?(j=I,I=null):j=I.sibling;var N=f(y,I,g[k],b);if(N===null){I===null&&(I=j);break}t&&I&&N.alternate===null&&e(y,I),p=s(N,p,k),T===null?E=N:T.sibling=N,T=N,I=j}if(k===g.length)return n(y,I),Le&&Mi(y,k),E;if(I===null){for(;k<g.length;k++)I=d(y,g[k],b),I!==null&&(p=s(I,p,k),T===null?E=I:T.sibling=I,T=I);return Le&&Mi(y,k),E}for(I=r(y,I);k<g.length;k++)j=h(I,y,k,g[k],b),j!==null&&(t&&j.alternate!==null&&I.delete(j.key===null?k:j.key),p=s(j,p,k),T===null?E=j:T.sibling=j,T=j);return t&&I.forEach(function(L){return e(y,L)}),Le&&Mi(y,k),E}function _(y,p,g,b){var E=Ea(g);if(typeof E!="function")throw Error(U(150));if(g=E.call(g),g==null)throw Error(U(151));for(var T=E=null,I=p,k=p=0,j=null,N=g.next();I!==null&&!N.done;k++,N=g.next()){I.index>k?(j=I,I=null):j=I.sibling;var L=f(y,I,N.value,b);if(L===null){I===null&&(I=j);break}t&&I&&L.alternate===null&&e(y,I),p=s(L,p,k),T===null?E=L:T.sibling=L,T=L,I=j}if(N.done)return n(y,I),Le&&Mi(y,k),E;if(I===null){for(;!N.done;k++,N=g.next())N=d(y,N.value,b),N!==null&&(p=s(N,p,k),T===null?E=N:T.sibling=N,T=N);return Le&&Mi(y,k),E}for(I=r(y,I);!N.done;k++,N=g.next())N=h(I,y,k,N.value,b),N!==null&&(t&&N.alternate!==null&&I.delete(N.key===null?k:N.key),p=s(N,p,k),T===null?E=N:T.sibling=N,T=N);return t&&I.forEach(function(ue){return e(y,ue)}),Le&&Mi(y,k),E}function v(y,p,g,b){if(typeof g=="object"&&g!==null&&g.type===Ss&&g.key===null&&(g=g.props.children),typeof g=="object"&&g!==null){switch(g.$$typeof){case yu:e:{for(var E=g.key,T=p;T!==null;){if(T.key===E){if(E=g.type,E===Ss){if(T.tag===7){n(y,T.sibling),p=i(T,g.props.children),p.return=y,y=p;break e}}else if(T.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===Qr&&d_(E)===T.type){n(y,T.sibling),p=i(T,g.props),p.ref=Pa(y,T,g),p.return=y,y=p;break e}n(y,T);break}else e(y,T);T=T.sibling}g.type===Ss?(p=Xi(g.props.children,y.mode,b,g.key),p.return=y,y=p):(b=_l(g.type,g.key,g.props,null,y.mode,b),b.ref=Pa(y,p,g),b.return=y,y=b)}return a(y);case ks:e:{for(T=g.key;p!==null;){if(p.key===T)if(p.tag===4&&p.stateNode.containerInfo===g.containerInfo&&p.stateNode.implementation===g.implementation){n(y,p.sibling),p=i(p,g.children||[]),p.return=y,y=p;break e}else{n(y,p);break}else e(y,p);p=p.sibling}p=pf(g,y.mode,b),p.return=y,y=p}return a(y);case Qr:return T=g._init,v(y,p,T(g._payload),b)}if(Ua(g))return m(y,p,g,b);if(Ea(g))return _(y,p,g,b);Iu(y,g)}return typeof g=="string"&&g!==""||typeof g=="number"?(g=""+g,p!==null&&p.tag===6?(n(y,p.sibling),p=i(p,g),p.return=y,y=p):(n(y,p),p=hf(g,y.mode,b),p.return=y,y=p),a(y)):n(y,p)}return v}var ta=nx(!0),rx=nx(!1),Ql=Ci(null),Yl=null,Ns=null,Pm=null;function Nm(){Pm=Ns=Yl=null}function $m(t){var e=Ql.current;Re(Ql),t._currentValue=e}function Rh(t,e,n){for(;t!==null;){var r=t.alternate;if((t.childLanes&e)!==e?(t.childLanes|=e,r!==null&&(r.childLanes|=e)):r!==null&&(r.childLanes&e)!==e&&(r.childLanes|=e),t===n)break;t=t.return}}function qs(t,e){Yl=t,Pm=Ns=null,t=t.dependencies,t!==null&&t.firstContext!==null&&(t.lanes&e&&(Gt=!0),t.firstContext=null)}function In(t){var e=t._currentValue;if(Pm!==t)if(t={context:t,memoizedValue:e,next:null},Ns===null){if(Yl===null)throw Error(U(308));Ns=t,Yl.dependencies={lanes:0,firstContext:t}}else Ns=Ns.next=t;return e}var Vi=null;function Rm(t){Vi===null?Vi=[t]:Vi.push(t)}function ix(t,e,n,r){var i=e.interleaved;return i===null?(n.next=n,Rm(e)):(n.next=i.next,i.next=n),e.interleaved=n,Mr(t,r)}function Mr(t,e){t.lanes|=e;var n=t.alternate;for(n!==null&&(n.lanes|=e),n=t,t=t.return;t!==null;)t.childLanes|=e,n=t.alternate,n!==null&&(n.childLanes|=e),n=t,t=t.return;return n.tag===3?n.stateNode:null}var Yr=!1;function jm(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function sx(t,e){t=t.updateQueue,e.updateQueue===t&&(e.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,effects:t.effects})}function Nr(t,e){return{eventTime:t,lane:e,tag:0,payload:null,callback:null,next:null}}function di(t,e,n){var r=t.updateQueue;if(r===null)return null;if(r=r.shared,he&2){var i=r.pending;return i===null?e.next=e:(e.next=i.next,i.next=e),r.pending=e,Mr(t,n)}return i=r.interleaved,i===null?(e.next=e,Rm(r)):(e.next=i.next,i.next=e),r.interleaved=e,Mr(t,n)}function fl(t,e,n){if(e=e.updateQueue,e!==null&&(e=e.shared,(n&4194240)!==0)){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,wm(t,n)}}function f_(t,e){var n=t.updateQueue,r=t.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,s=null;if(n=n.firstBaseUpdate,n!==null){do{var a={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};s===null?i=s=a:s=s.next=a,n=n.next}while(n!==null);s===null?i=s=e:s=s.next=e}else i=s=e;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:s,shared:r.shared,effects:r.effects},t.updateQueue=n;return}t=n.lastBaseUpdate,t===null?n.firstBaseUpdate=e:t.next=e,n.lastBaseUpdate=e}function ec(t,e,n,r){var i=t.updateQueue;Yr=!1;var s=i.firstBaseUpdate,a=i.lastBaseUpdate,o=i.shared.pending;if(o!==null){i.shared.pending=null;var u=o,l=u.next;u.next=null,a===null?s=l:a.next=l,a=u;var c=t.alternate;c!==null&&(c=c.updateQueue,o=c.lastBaseUpdate,o!==a&&(o===null?c.firstBaseUpdate=l:o.next=l,c.lastBaseUpdate=u))}if(s!==null){var d=i.baseState;a=0,c=l=u=null,o=s;do{var f=o.lane,h=o.eventTime;if((r&f)===f){c!==null&&(c=c.next={eventTime:h,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var m=t,_=o;switch(f=e,h=n,_.tag){case 1:if(m=_.payload,typeof m=="function"){d=m.call(h,d,f);break e}d=m;break e;case 3:m.flags=m.flags&-65537|128;case 0:if(m=_.payload,f=typeof m=="function"?m.call(h,d,f):m,f==null)break e;d=Ue({},d,f);break e;case 2:Yr=!0}}o.callback!==null&&o.lane!==0&&(t.flags|=64,f=i.effects,f===null?i.effects=[o]:f.push(o))}else h={eventTime:h,lane:f,tag:o.tag,payload:o.payload,callback:o.callback,next:null},c===null?(l=c=h,u=d):c=c.next=h,a|=f;if(o=o.next,o===null){if(o=i.shared.pending,o===null)break;f=o,o=f.next,f.next=null,i.lastBaseUpdate=f,i.shared.pending=null}}while(!0);if(c===null&&(u=d),i.baseState=u,i.firstBaseUpdate=l,i.lastBaseUpdate=c,e=i.shared.interleaved,e!==null){i=e;do a|=i.lane,i=i.next;while(i!==e)}else s===null&&(i.shared.lanes=0);ns|=a,t.lanes=a,t.memoizedState=d}}function h_(t,e,n){if(t=e.effects,e.effects=null,t!==null)for(e=0;e<t.length;e++){var r=t[e],i=r.callback;if(i!==null){if(r.callback=null,r=n,typeof i!="function")throw Error(U(191,i));i.call(r)}}}var su={},_r=Ci(su),$o=Ci(su),Ro=Ci(su);function Ki(t){if(t===su)throw Error(U(174));return t}function Lm(t,e){switch(Oe(Ro,e),Oe($o,t),Oe(_r,su),t=e.nodeType,t){case 9:case 11:e=(e=e.documentElement)?e.namespaceURI:ph(null,"");break;default:t=t===8?e.parentNode:e,e=t.namespaceURI||null,t=t.tagName,e=ph(e,t)}Re(_r),Oe(_r,e)}function na(){Re(_r),Re($o),Re(Ro)}function ax(t){Ki(Ro.current);var e=Ki(_r.current),n=ph(e,t.type);e!==n&&(Oe($o,t),Oe(_r,n))}function Mm(t){$o.current===t&&(Re(_r),Re($o))}var ze=Ci(0);function tc(t){for(var e=t;e!==null;){if(e.tag===13){var n=e.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||n.data==="$?"||n.data==="$!"))return e}else if(e.tag===19&&e.memoizedProps.revealOrder!==void 0){if(e.flags&128)return e}else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break;for(;e.sibling===null;){if(e.return===null||e.return===t)return null;e=e.return}e.sibling.return=e.return,e=e.sibling}return null}var of=[];function zm(){for(var t=0;t<of.length;t++)of[t]._workInProgressVersionPrimary=null;of.length=0}var hl=Hr.ReactCurrentDispatcher,uf=Hr.ReactCurrentBatchConfig,ts=0,De=null,nt=null,at=null,nc=!1,lo=!1,jo=0,eC=0;function vt(){throw Error(U(321))}function Dm(t,e){if(e===null)return!1;for(var n=0;n<e.length&&n<t.length;n++)if(!Qn(t[n],e[n]))return!1;return!0}function Um(t,e,n,r,i,s){if(ts=s,De=e,e.memoizedState=null,e.updateQueue=null,e.lanes=0,hl.current=t===null||t.memoizedState===null?iC:sC,t=n(r,i),lo){s=0;do{if(lo=!1,jo=0,25<=s)throw Error(U(301));s+=1,at=nt=null,e.updateQueue=null,hl.current=aC,t=n(r,i)}while(lo)}if(hl.current=rc,e=nt!==null&&nt.next!==null,ts=0,at=nt=De=null,nc=!1,e)throw Error(U(300));return t}function Fm(){var t=jo!==0;return jo=0,t}function ur(){var t={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return at===null?De.memoizedState=at=t:at=at.next=t,at}function On(){if(nt===null){var t=De.alternate;t=t!==null?t.memoizedState:null}else t=nt.next;var e=at===null?De.memoizedState:at.next;if(e!==null)at=e,nt=t;else{if(t===null)throw Error(U(310));nt=t,t={memoizedState:nt.memoizedState,baseState:nt.baseState,baseQueue:nt.baseQueue,queue:nt.queue,next:null},at===null?De.memoizedState=at=t:at=at.next=t}return at}function Lo(t,e){return typeof e=="function"?e(t):e}function lf(t){var e=On(),n=e.queue;if(n===null)throw Error(U(311));n.lastRenderedReducer=t;var r=nt,i=r.baseQueue,s=n.pending;if(s!==null){if(i!==null){var a=i.next;i.next=s.next,s.next=a}r.baseQueue=i=s,n.pending=null}if(i!==null){s=i.next,r=r.baseState;var o=a=null,u=null,l=s;do{var c=l.lane;if((ts&c)===c)u!==null&&(u=u.next={lane:0,action:l.action,hasEagerState:l.hasEagerState,eagerState:l.eagerState,next:null}),r=l.hasEagerState?l.eagerState:t(r,l.action);else{var d={lane:c,action:l.action,hasEagerState:l.hasEagerState,eagerState:l.eagerState,next:null};u===null?(o=u=d,a=r):u=u.next=d,De.lanes|=c,ns|=c}l=l.next}while(l!==null&&l!==s);u===null?a=r:u.next=o,Qn(r,e.memoizedState)||(Gt=!0),e.memoizedState=r,e.baseState=a,e.baseQueue=u,n.lastRenderedState=r}if(t=n.interleaved,t!==null){i=t;do s=i.lane,De.lanes|=s,ns|=s,i=i.next;while(i!==t)}else i===null&&(n.lanes=0);return[e.memoizedState,n.dispatch]}function cf(t){var e=On(),n=e.queue;if(n===null)throw Error(U(311));n.lastRenderedReducer=t;var r=n.dispatch,i=n.pending,s=e.memoizedState;if(i!==null){n.pending=null;var a=i=i.next;do s=t(s,a.action),a=a.next;while(a!==i);Qn(s,e.memoizedState)||(Gt=!0),e.memoizedState=s,e.baseQueue===null&&(e.baseState=s),n.lastRenderedState=s}return[s,r]}function ox(){}function ux(t,e){var n=De,r=On(),i=e(),s=!Qn(r.memoizedState,i);if(s&&(r.memoizedState=i,Gt=!0),r=r.queue,Bm(dx.bind(null,n,r,t),[t]),r.getSnapshot!==e||s||at!==null&&at.memoizedState.tag&1){if(n.flags|=2048,Mo(9,cx.bind(null,n,r,i,e),void 0,null),ut===null)throw Error(U(349));ts&30||lx(n,e,i)}return i}function lx(t,e,n){t.flags|=16384,t={getSnapshot:e,value:n},e=De.updateQueue,e===null?(e={lastEffect:null,stores:null},De.updateQueue=e,e.stores=[t]):(n=e.stores,n===null?e.stores=[t]:n.push(t))}function cx(t,e,n,r){e.value=n,e.getSnapshot=r,fx(e)&&hx(t)}function dx(t,e,n){return n(function(){fx(e)&&hx(t)})}function fx(t){var e=t.getSnapshot;t=t.value;try{var n=e();return!Qn(t,n)}catch{return!0}}function hx(t){var e=Mr(t,1);e!==null&&Gn(e,t,1,-1)}function p_(t){var e=ur();return typeof t=="function"&&(t=t()),e.memoizedState=e.baseState=t,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Lo,lastRenderedState:t},e.queue=t,t=t.dispatch=rC.bind(null,De,t),[e.memoizedState,t]}function Mo(t,e,n,r){return t={tag:t,create:e,destroy:n,deps:r,next:null},e=De.updateQueue,e===null?(e={lastEffect:null,stores:null},De.updateQueue=e,e.lastEffect=t.next=t):(n=e.lastEffect,n===null?e.lastEffect=t.next=t:(r=n.next,n.next=t,t.next=r,e.lastEffect=t)),t}function px(){return On().memoizedState}function pl(t,e,n,r){var i=ur();De.flags|=t,i.memoizedState=Mo(1|e,n,void 0,r===void 0?null:r)}function Yc(t,e,n,r){var i=On();r=r===void 0?null:r;var s=void 0;if(nt!==null){var a=nt.memoizedState;if(s=a.destroy,r!==null&&Dm(r,a.deps)){i.memoizedState=Mo(e,n,s,r);return}}De.flags|=t,i.memoizedState=Mo(1|e,n,s,r)}function m_(t,e){return pl(8390656,8,t,e)}function Bm(t,e){return Yc(2048,8,t,e)}function mx(t,e){return Yc(4,2,t,e)}function gx(t,e){return Yc(4,4,t,e)}function yx(t,e){if(typeof e=="function")return t=t(),e(t),function(){e(null)};if(e!=null)return t=t(),e.current=t,function(){e.current=null}}function _x(t,e,n){return n=n!=null?n.concat([t]):null,Yc(4,4,yx.bind(null,e,t),n)}function Hm(){}function vx(t,e){var n=On();e=e===void 0?null:e;var r=n.memoizedState;return r!==null&&e!==null&&Dm(e,r[1])?r[0]:(n.memoizedState=[t,e],t)}function wx(t,e){var n=On();e=e===void 0?null:e;var r=n.memoizedState;return r!==null&&e!==null&&Dm(e,r[1])?r[0]:(t=t(),n.memoizedState=[t,e],t)}function bx(t,e,n){return ts&21?(Qn(n,e)||(n=Eb(),De.lanes|=n,ns|=n,t.baseState=!0),e):(t.baseState&&(t.baseState=!1,Gt=!0),t.memoizedState=n)}function tC(t,e){var n=Ae;Ae=n!==0&&4>n?n:4,t(!0);var r=uf.transition;uf.transition={};try{t(!1),e()}finally{Ae=n,uf.transition=r}}function xx(){return On().memoizedState}function nC(t,e,n){var r=hi(t);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},kx(t))Sx(e,n);else if(n=ix(t,e,n,r),n!==null){var i=Mt();Gn(n,t,r,i),Ax(n,e,r)}}function rC(t,e,n){var r=hi(t),i={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(kx(t))Sx(e,i);else{var s=t.alternate;if(t.lanes===0&&(s===null||s.lanes===0)&&(s=e.lastRenderedReducer,s!==null))try{var a=e.lastRenderedState,o=s(a,n);if(i.hasEagerState=!0,i.eagerState=o,Qn(o,a)){var u=e.interleaved;u===null?(i.next=i,Rm(e)):(i.next=u.next,u.next=i),e.interleaved=i;return}}catch{}finally{}n=ix(t,e,i,r),n!==null&&(i=Mt(),Gn(n,t,r,i),Ax(n,e,r))}}function kx(t){var e=t.alternate;return t===De||e!==null&&e===De}function Sx(t,e){lo=nc=!0;var n=t.pending;n===null?e.next=e:(e.next=n.next,n.next=e),t.pending=e}function Ax(t,e,n){if(n&4194240){var r=e.lanes;r&=t.pendingLanes,n|=r,e.lanes=n,wm(t,n)}}var rc={readContext:In,useCallback:vt,useContext:vt,useEffect:vt,useImperativeHandle:vt,useInsertionEffect:vt,useLayoutEffect:vt,useMemo:vt,useReducer:vt,useRef:vt,useState:vt,useDebugValue:vt,useDeferredValue:vt,useTransition:vt,useMutableSource:vt,useSyncExternalStore:vt,useId:vt,unstable_isNewReconciler:!1},iC={readContext:In,useCallback:function(t,e){return ur().memoizedState=[t,e===void 0?null:e],t},useContext:In,useEffect:m_,useImperativeHandle:function(t,e,n){return n=n!=null?n.concat([t]):null,pl(4194308,4,yx.bind(null,e,t),n)},useLayoutEffect:function(t,e){return pl(4194308,4,t,e)},useInsertionEffect:function(t,e){return pl(4,2,t,e)},useMemo:function(t,e){var n=ur();return e=e===void 0?null:e,t=t(),n.memoizedState=[t,e],t},useReducer:function(t,e,n){var r=ur();return e=n!==void 0?n(e):e,r.memoizedState=r.baseState=e,t={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:e},r.queue=t,t=t.dispatch=nC.bind(null,De,t),[r.memoizedState,t]},useRef:function(t){var e=ur();return t={current:t},e.memoizedState=t},useState:p_,useDebugValue:Hm,useDeferredValue:function(t){return ur().memoizedState=t},useTransition:function(){var t=p_(!1),e=t[0];return t=tC.bind(null,t[1]),ur().memoizedState=t,[e,t]},useMutableSource:function(){},useSyncExternalStore:function(t,e,n){var r=De,i=ur();if(Le){if(n===void 0)throw Error(U(407));n=n()}else{if(n=e(),ut===null)throw Error(U(349));ts&30||lx(r,e,n)}i.memoizedState=n;var s={value:n,getSnapshot:e};return i.queue=s,m_(dx.bind(null,r,s,t),[t]),r.flags|=2048,Mo(9,cx.bind(null,r,s,n,e),void 0,null),n},useId:function(){var t=ur(),e=ut.identifierPrefix;if(Le){var n=Cr,r=Or;n=(r&~(1<<32-Wn(r)-1)).toString(32)+n,e=":"+e+"R"+n,n=jo++,0<n&&(e+="H"+n.toString(32)),e+=":"}else n=eC++,e=":"+e+"r"+n.toString(32)+":";return t.memoizedState=e},unstable_isNewReconciler:!1},sC={readContext:In,useCallback:vx,useContext:In,useEffect:Bm,useImperativeHandle:_x,useInsertionEffect:mx,useLayoutEffect:gx,useMemo:wx,useReducer:lf,useRef:px,useState:function(){return lf(Lo)},useDebugValue:Hm,useDeferredValue:function(t){var e=On();return bx(e,nt.memoizedState,t)},useTransition:function(){var t=lf(Lo)[0],e=On().memoizedState;return[t,e]},useMutableSource:ox,useSyncExternalStore:ux,useId:xx,unstable_isNewReconciler:!1},aC={readContext:In,useCallback:vx,useContext:In,useEffect:Bm,useImperativeHandle:_x,useInsertionEffect:mx,useLayoutEffect:gx,useMemo:wx,useReducer:cf,useRef:px,useState:function(){return cf(Lo)},useDebugValue:Hm,useDeferredValue:function(t){var e=On();return nt===null?e.memoizedState=t:bx(e,nt.memoizedState,t)},useTransition:function(){var t=cf(Lo)[0],e=On().memoizedState;return[t,e]},useMutableSource:ox,useSyncExternalStore:ux,useId:xx,unstable_isNewReconciler:!1};function Bn(t,e){if(t&&t.defaultProps){e=Ue({},e),t=t.defaultProps;for(var n in t)e[n]===void 0&&(e[n]=t[n]);return e}return e}function jh(t,e,n,r){e=t.memoizedState,n=n(r,e),n=n==null?e:Ue({},e,n),t.memoizedState=n,t.lanes===0&&(t.updateQueue.baseState=n)}var ed={isMounted:function(t){return(t=t._reactInternals)?us(t)===t:!1},enqueueSetState:function(t,e,n){t=t._reactInternals;var r=Mt(),i=hi(t),s=Nr(r,i);s.payload=e,n!=null&&(s.callback=n),e=di(t,s,i),e!==null&&(Gn(e,t,i,r),fl(e,t,i))},enqueueReplaceState:function(t,e,n){t=t._reactInternals;var r=Mt(),i=hi(t),s=Nr(r,i);s.tag=1,s.payload=e,n!=null&&(s.callback=n),e=di(t,s,i),e!==null&&(Gn(e,t,i,r),fl(e,t,i))},enqueueForceUpdate:function(t,e){t=t._reactInternals;var n=Mt(),r=hi(t),i=Nr(n,r);i.tag=2,e!=null&&(i.callback=e),e=di(t,i,r),e!==null&&(Gn(e,t,r,n),fl(e,t,r))}};function g_(t,e,n,r,i,s,a){return t=t.stateNode,typeof t.shouldComponentUpdate=="function"?t.shouldComponentUpdate(r,s,a):e.prototype&&e.prototype.isPureReactComponent?!Oo(n,r)||!Oo(i,s):!0}function Ex(t,e,n){var r=!1,i=bi,s=e.contextType;return typeof s=="object"&&s!==null?s=In(s):(i=Qt(e)?Yi:kt.current,r=e.contextTypes,s=(r=r!=null)?Ys(t,i):bi),e=new e(n,s),t.memoizedState=e.state!==null&&e.state!==void 0?e.state:null,e.updater=ed,t.stateNode=e,e._reactInternals=t,r&&(t=t.stateNode,t.__reactInternalMemoizedUnmaskedChildContext=i,t.__reactInternalMemoizedMaskedChildContext=s),e}function y_(t,e,n,r){t=e.state,typeof e.componentWillReceiveProps=="function"&&e.componentWillReceiveProps(n,r),typeof e.UNSAFE_componentWillReceiveProps=="function"&&e.UNSAFE_componentWillReceiveProps(n,r),e.state!==t&&ed.enqueueReplaceState(e,e.state,null)}function Lh(t,e,n,r){var i=t.stateNode;i.props=n,i.state=t.memoizedState,i.refs={},jm(t);var s=e.contextType;typeof s=="object"&&s!==null?i.context=In(s):(s=Qt(e)?Yi:kt.current,i.context=Ys(t,s)),i.state=t.memoizedState,s=e.getDerivedStateFromProps,typeof s=="function"&&(jh(t,e,s,n),i.state=t.memoizedState),typeof e.getDerivedStateFromProps=="function"||typeof i.getSnapshotBeforeUpdate=="function"||typeof i.UNSAFE_componentWillMount!="function"&&typeof i.componentWillMount!="function"||(e=i.state,typeof i.componentWillMount=="function"&&i.componentWillMount(),typeof i.UNSAFE_componentWillMount=="function"&&i.UNSAFE_componentWillMount(),e!==i.state&&ed.enqueueReplaceState(i,i.state,null),ec(t,n,i,r),i.state=t.memoizedState),typeof i.componentDidMount=="function"&&(t.flags|=4194308)}function ra(t,e){try{var n="",r=e;do n+=RI(r),r=r.return;while(r);var i=n}catch(s){i=` Error generating stack: `+s.message+` `+s.stack}return{value:t,source:e,stack:i,digest:null}}function df(t,e,n){return{value:t,source:null,stack:n??null,digest:e??null}}function Mh(t,e){try{console.error(e.value)}catch(n){setTimeout(function(){throw n})}}var oC=typeof WeakMap=="function"?WeakMap:Map;function Tx(t,e,n){n=Nr(-1,n),n.tag=3,n.payload={element:null};var r=e.value;return n.callback=function(){sc||(sc=!0,qh=r),Mh(t,e)},n}function Ix(t,e,n){n=Nr(-1,n),n.tag=3;var r=t.type.getDerivedStateFromError;if(typeof r=="function"){var i=e.value;n.payload=function(){return r(i)},n.callback=function(){Mh(t,e)}}var s=t.stateNode;return s!==null&&typeof s.componentDidCatch=="function"&&(n.callback=function(){Mh(t,e),typeof r!="function"&&(fi===null?fi=new Set([this]):fi.add(this));var a=e.stack;this.componentDidCatch(e.value,{componentStack:a!==null?a:""})}),n}function __(t,e,n){var r=t.pingCache;if(r===null){r=t.pingCache=new oC;var i=new Set;r.set(e,i)}else i=r.get(e),i===void 0&&(i=new Set,r.set(e,i));i.has(n)||(i.add(n),t=bC.bind(null,t,e,n),e.then(t,t))}function v_(t){do{var e;if((e=t.tag===13)&&(e=t.memoizedState,e=e!==null?e.dehydrated!==null:!0),e)return t;t=t.return}while(t!==null);return null}function w_(t,e,n,r,i){return t.mode&1?(t.flags|=65536,t.lanes=i,t):(t===e?t.flags|=65536:(t.flags|=128,n.flags|=131072,n.flags&=-52805,n.tag===1&&(n.alternate===null?n.tag=17:(e=Nr(-1,1),e.tag=2,di(n,e,1))),n.lanes|=1),t)}var uC=Hr.ReactCurrentOwner,Gt=!1;function Rt(t,e,n,r){e.child=t===null?rx(e,null,n,r):ta(e,t.child,n,r)}function b_(t,e,n,r,i){n=n.render;var s=e.ref;return qs(e,i),r=Um(t,e,n,r,s,i),n=Fm(),t!==null&&!Gt?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~i,zr(t,e,i)):(Le&&n&&Im(e),e.flags|=1,Rt(t,e,r,i),e.child)}function x_(t,e,n,r,i){if(t===null){var s=n.type;return typeof s=="function"&&!Xm(s)&&s.defaultProps===void 0&&n.compare===null&&n.defaultProps===void 0?(e.tag=15,e.type=s,Ox(t,e,s,r,i)):(t=_l(n.type,null,r,e,e.mode,i),t.ref=e.ref,t.return=e,e.child=t)}if(s=t.child,!(t.lanes&i)){var a=s.memoizedProps;if(n=n.compare,n=n!==null?n:Oo,n(a,r)&&t.ref===e.ref)return zr(t,e,i)}return e.flags|=1,t=pi(s,r),t.ref=e.ref,t.return=e,e.child=t}function Ox(t,e,n,r,i){if(t!==null){var s=t.memoizedProps;if(Oo(s,r)&&t.ref===e.ref)if(Gt=!1,e.pendingProps=r=s,(t.lanes&i)!==0)t.flags&131072&&(Gt=!0);else return e.lanes=t.lanes,zr(t,e,i)}return zh(t,e,n,r,i)}function Cx(t,e,n){var r=e.pendingProps,i=r.children,s=t!==null?t.memoizedState:null;if(r.mode==="hidden")if(!(e.mode&1))e.memoizedState={baseLanes:0,cachePool:null,transitions:null},Oe(Rs,ln),ln|=n;else{if(!(n&1073741824))return t=s!==null?s.baseLanes|n:n,e.lanes=e.childLanes=1073741824,e.memoizedState={baseLanes:t,cachePool:null,transitions:null},e.updateQueue=null,Oe(Rs,ln),ln|=t,null;e.memoizedState={baseLanes:0,cachePool:null,transitions:null},r=s!==null?s.baseLanes:n,Oe(Rs,ln),ln|=r}else s!==null?(r=s.baseLanes|n,e.memoizedState=null):r=n,Oe(Rs,ln),ln|=r;return Rt(t,e,i,n),e.child}function Px(t,e){var n=e.ref;(t===null&&n!==null||t!==null&&t.ref!==n)&&(e.flags|=512,e.flags|=2097152)}function zh(t,e,n,r,i){var s=Qt(n)?Yi:kt.current;return s=Ys(e,s),qs(e,i),n=Um(t,e,n,r,s,i),r=Fm(),t!==null&&!Gt?(e.updateQueue=t.updateQueue,e.flags&=-2053,t.lanes&=~i,zr(t,e,i)):(Le&&r&&Im(e),e.flags|=1,Rt(t,e,n,i),e.child)}function k_(t,e,n,r,i){if(Qt(n)){var s=!0;Gl(e)}else s=!1;if(qs(e,i),e.stateNode===null)ml(t,e),Ex(e,n,r),Lh(e,n,r,i),r=!0;else if(t===null){var a=e.stateNode,o=e.memoizedProps;a.props=o;var u=a.context,l=n.contextType;typeof l=="object"&&l!==null?l=In(l):(l=Qt(n)?Yi:kt.current,l=Ys(e,l));var c=n.getDerivedStateFromProps,d=typeof c=="function"||typeof a.getSnapshotBeforeUpdate=="function";d||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(o!==r||u!==l)&&y_(e,a,r,l),Yr=!1;var f=e.memoizedState;a.state=f,ec(e,r,a,i),u=e.memoizedState,o!==r||f!==u||Xt.current||Yr?(typeof c=="function"&&(jh(e,n,c,r),u=e.memoizedState),(o=Yr||g_(e,n,o,r,f,u,l))?(d||typeof a.UNSAFE_componentWillMount!="function"&&typeof a.componentWillMount!="function"||(typeof a.componentWillMount=="function"&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount=="function"&&a.UNSAFE_componentWillMount()),typeof a.componentDidMount=="function"&&(e.flags|=4194308)):(typeof a.componentDidMount=="function"&&(e.flags|=4194308),e.memoizedProps=r,e.memoizedState=u),a.props=r,a.state=u,a.context=l,r=o):(typeof a.componentDidMount=="function"&&(e.flags|=4194308),r=!1)}else{a=e.stateNode,sx(t,e),o=e.memoizedProps,l=e.type===e.elementType?o:Bn(e.type,o),a.props=l,d=e.pendingProps,f=a.context,u=n.contextType,typeof u=="object"&&u!==null?u=In(u):(u=Qt(n)?Yi:kt.current,u=Ys(e,u));var h=n.getDerivedStateFromProps;(c=typeof h=="function"||typeof a.getSnapshotBeforeUpdate=="function")||typeof a.UNSAFE_componentWillReceiveProps!="function"&&typeof a.componentWillReceiveProps!="function"||(o!==d||f!==u)&&y_(e,a,r,u),Yr=!1,f=e.memoizedState,a.state=f,ec(e,r,a,i);var m=e.memoizedState;o!==d||f!==m||Xt.current||Yr?(typeof h=="function"&&(jh(e,n,h,r),m=e.memoizedState),(l=Yr||g_(e,n,l,r,f,m,u)||!1)?(c||typeof a.UNSAFE_componentWillUpdate!="function"&&typeof a.componentWillUpdate!="function"||(typeof a.componentWillUpdate=="function"&&a.componentWillUpdate(r,m,u),typeof a.UNSAFE_componentWillUpdate=="function"&&a.UNSAFE_componentWillUpdate(r,m,u)),typeof a.componentDidUpdate=="function"&&(e.flags|=4),typeof a.getSnapshotBeforeUpdate=="function"&&(e.flags|=1024)):(typeof a.componentDidUpdate!="function"||o===t.memoizedProps&&f===t.memoizedState||(e.flags|=4),typeof a.getSnapshotBeforeUpdate!="function"||o===t.memoizedProps&&f===t.memoizedState||(e.flags|=1024),e.memoizedProps=r,e.memoizedState=m),a.props=r,a.state=m,a.context=u,r=l):(typeof a.componentDidUpdate!="function"||o===t.memoizedProps&&f===t.memoizedState||(e.flags|=4),typeof a.getSnapshotBeforeUpdate!="function"||o===t.memoizedProps&&f===t.memoizedState||(e.flags|=1024),r=!1)}return Dh(t,e,n,r,s,i)}function Dh(t,e,n,r,i,s){Px(t,e);var a=(e.flags&128)!==0;if(!r&&!a)return i&&u_(e,n,!1),zr(t,e,s);r=e.stateNode,uC.current=e;var o=a&&typeof n.getDerivedStateFromError!="function"?null:r.render();return e.flags|=1,t!==null&&a?(e.child=ta(e,t.child,null,s),e.child=ta(e,null,o,s)):Rt(t,e,o,s),e.memoizedState=r.state,i&&u_(e,n,!0),e.child}function Nx(t){var e=t.stateNode;e.pendingContext?o_(t,e.pendingContext,e.pendingContext!==e.context):e.context&&o_(t,e.context,!1),Lm(t,e.containerInfo)}function S_(t,e,n,r,i){return ea(),Cm(i),e.flags|=256,Rt(t,e,n,r),e.child}var Uh={dehydrated:null,treeContext:null,retryLane:0};function Fh(t){return{baseLanes:t,cachePool:null,transitions:null}}function $x(t,e,n){var r=e.pendingProps,i=ze.current,s=!1,a=(e.flags&128)!==0,o;if((o=a)||(o=t!==null&&t.memoizedState===null?!1:(i&2)!==0),o?(s=!0,e.flags&=-129):(t===null||t.memoizedState!==null)&&(i|=1),Oe(ze,i&1),t===null)return $h(e),t=e.memoizedState,t!==null&&(t=t.dehydrated,t!==null)?(e.mode&1?t.data==="$!"?e.lanes=8:e.lanes=1073741824:e.lanes=1,null):(a=r.children,t=r.fallback,s?(r=e.mode,s=e.child,a={mode:"hidden",children:a},!(r&1)&&s!==null?(s.childLanes=0,s.pendingProps=a):s=rd(a,r,0,null),t=Xi(t,r,n,null),s.return=e,t.return=e,s.sibling=t,e.child=s,e.child.memoizedState=Fh(n),e.memoizedState=Uh,t):Zm(e,a));if(i=t.memoizedState,i!==null&&(o=i.dehydrated,o!==null))return lC(t,e,a,r,o,i,n);if(s){s=r.fallback,a=e.mode,i=t.child,o=i.sibling;var u={mode:"hidden",children:r.children};return!(a&1)&&e.child!==i?(r=e.child,r.childLanes=0,r.pendingProps=u,e.deletions=null):(r=pi(i,u),r.subtreeFlags=i.subtreeFlags&14680064),o!==null?s=pi(o,s):(s=Xi(s,a,n,null),s.flags|=2),s.return=e,r.return=e,r.sibling=s,e.child=r,r=s,s=e.child,a=t.child.memoizedState,a=a===null?Fh(n):{baseLanes:a.baseLanes|n,cachePool:null,transitions:a.transitions},s.memoizedState=a,s.childLanes=t.childLanes&~n,e.memoizedState=Uh,r}return s=t.child,t=s.sibling,r=pi(s,{mode:"visible",children:r.children}),!(e.mode&1)&&(r.lanes=n),r.return=e,r.sibling=null,t!==null&&(n=e.deletions,n===null?(e.deletions=[t],e.flags|=16):n.push(t)),e.child=r,e.memoizedState=null,r}function Zm(t,e){return e=rd({mode:"visible",children:e},t.mode,0,null),e.return=t,t.child=e}function Ou(t,e,n,r){return r!==null&&Cm(r),ta(e,t.child,null,n),t=Zm(e,e.pendingProps.children),t.flags|=2,e.memoizedState=null,t}function lC(t,e,n,r,i,s,a){if(n)return e.flags&256?(e.flags&=-257,r=df(Error(U(422))),Ou(t,e,a,r)):e.memoizedState!==null?(e.child=t.child,e.flags|=128,null):(s=r.fallback,i=e.mode,r=rd({mode:"visible",children:r.children},i,0,null),s=Xi(s,i,a,null),s.flags|=2,r.return=e,s.return=e,r.sibling=s,e.child=r,e.mode&1&&ta(e,t.child,null,a),e.child.memoizedState=Fh(a),e.memoizedState=Uh,s);if(!(e.mode&1))return Ou(t,e,a,null);if(i.data==="$!"){if(r=i.nextSibling&&i.nextSibling.dataset,r)var o=r.dgst;return r=o,s=Error(U(419)),r=df(s,r,void 0),Ou(t,e,a,r)}if(o=(a&t.childLanes)!==0,Gt||o){if(r=ut,r!==null){switch(a&-a){case 4:i=2;break;case 16:i=8;break;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:i=32;break;case 536870912:i=268435456;break;default:i=0}i=i&(r.suspendedLanes|a)?0:i,i!==0&&i!==s.retryLane&&(s.retryLane=i,Mr(t,i),Gn(r,t,i,-1))}return Jm(),r=df(Error(U(421))),Ou(t,e,a,r)}return i.data==="$?"?(e.flags|=128,e.child=t.child,e=xC.bind(null,t),i._reactRetry=e,null):(t=s.treeContext,cn=ci(i.nextSibling),fn=e,Le=!0,Kn=null,t!==null&&(kn[Sn++]=Or,kn[Sn++]=Cr,kn[Sn++]=es,Or=t.id,Cr=t.overflow,es=e),e=Zm(e,r.children),e.flags|=4096,e)}function A_(t,e,n){t.lanes|=e;var r=t.alternate;r!==null&&(r.lanes|=e),Rh(t.return,e,n)}function ff(t,e,n,r,i){var s=t.memoizedState;s===null?t.memoizedState={isBackwards:e,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i}:(s.isBackwards=e,s.rendering=null,s.renderingStartTime=0,s.last=r,s.tail=n,s.tailMode=i)}function Rx(t,e,n){var r=e.pendingProps,i=r.revealOrder,s=r.tail;if(Rt(t,e,r.children,n),r=ze.current,r&2)r=r&1|2,e.flags|=128;else{if(t!==null&&t.flags&128)e:for(t=e.child;t!==null;){if(t.tag===13)t.memoizedState!==null&&A_(t,n,e);else if(t.tag===19)A_(t,n,e);else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break e;for(;t.sibling===null;){if(t.return===null||t.return===e)break e;t=t.return}t.sibling.return=t.return,t=t.sibling}r&=1}if(Oe(ze,r),!(e.mode&1))e.memoizedState=null;else switch(i){case"forwards":for(n=e.child,i=null;n!==null;)t=n.alternate,t!==null&&tc(t)===null&&(i=n),n=n.sibling;n=i,n===null?(i=e.child,e.child=null):(i=n.sibling,n.sibling=null),ff(e,!1,i,n,s);break;case"backwards":for(n=null,i=e.child,e.child=null;i!==null;){if(t=i.alternate,t!==null&&tc(t)===null){e.child=i;break}t=i.sibling,i.sibling=n,n=i,i=t}ff(e,!0,n,null,s);break;case"together":ff(e,!1,null,null,void 0);break;default:e.memoizedState=null}return e.child}function ml(t,e){!(e.mode&1)&&t!==null&&(t.alternate=null,e.alternate=null,e.flags|=2)}function zr(t,e,n){if(t!==null&&(e.dependencies=t.dependencies),ns|=e.lanes,!(n&e.childLanes))return null;if(t!==null&&e.child!==t.child)throw Error(U(153));if(e.child!==null){for(t=e.child,n=pi(t,t.pendingProps),e.child=n,n.return=e;t.sibling!==null;)t=t.sibling,n=n.sibling=pi(t,t.pendingProps),n.return=e;n.sibling=null}return e.child}function cC(t,e,n){switch(e.tag){case 3:Nx(e),ea();break;case 5:ax(e);break;case 1:Qt(e.type)&&Gl(e);break;case 4:Lm(e,e.stateNode.containerInfo);break;case 10:var r=e.type._context,i=e.memoizedProps.value;Oe(Ql,r._currentValue),r._currentValue=i;break;case 13:if(r=e.memoizedState,r!==null)return r.dehydrated!==null?(Oe(ze,ze.current&1),e.flags|=128,null):n&e.child.childLanes?$x(t,e,n):(Oe(ze,ze.current&1),t=zr(t,e,n),t!==null?t.sibling:null);Oe(ze,ze.current&1);break;case 19:if(r=(n&e.childLanes)!==0,t.flags&128){if(r)return Rx(t,e,n);e.flags|=128}if(i=e.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),Oe(ze,ze.current),r)break;return null;case 22:case 23:return e.lanes=0,Cx(t,e,n)}return zr(t,e,n)}var jx,Bh,Lx,Mx;jx=function(t,e){for(var n=e.child;n!==null;){if(n.tag===5||n.tag===6)t.appendChild(n.stateNode);else if(n.tag!==4&&n.child!==null){n.child.return=n,n=n.child;continue}if(n===e)break;for(;n.sibling===null;){if(n.return===null||n.return===e)return;n=n.return}n.sibling.return=n.return,n=n.sibling}};Bh=function(){};Lx=function(t,e,n,r){var i=t.memoizedProps;if(i!==r){t=e.stateNode,Ki(_r.current);var s=null;switch(n){case"input":i=ch(t,i),r=ch(t,r),s=[];break;case"select":i=Ue({},i,{value:void 0}),r=Ue({},r,{value:void 0}),s=[];break;case"textarea":i=hh(t,i),r=hh(t,r),s=[];break;default:typeof i.onClick!="function"&&typeof r.onClick=="function"&&(t.onclick=ql)}mh(n,r);var a;n=null;for(l in i)if(!r.hasOwnProperty(l)&&i.hasOwnProperty(l)&&i[l]!=null)if(l==="style"){var o=i[l];for(a in o)o.hasOwnProperty(a)&&(n||(n={}),n[a]="")}else l!=="dangerouslySetInnerHTML"&&l!=="children"&&l!=="suppressContentEditableWarning"&&l!=="suppressHydrationWarning"&&l!=="autoFocus"&&(xo.hasOwnProperty(l)?s||(s=[]):(s=s||[]).push(l,null));for(l in r){var u=r[l];if(o=i!=null?i[l]:void 0,r.hasOwnProperty(l)&&u!==o&&(u!=null||o!=null))if(l==="style")if(o){for(a in o)!o.hasOwnProperty(a)||u&&u.hasOwnProperty(a)||(n||(n={}),n[a]="");for(a in u)u.hasOwnProperty(a)&&o[a]!==u[a]&&(n||(n={}),n[a]=u[a])}else n||(s||(s=[]),s.push(l,n)),n=u;else l==="dangerouslySetInnerHTML"?(u=u?u.__html:void 0,o=o?o.__html:void 0,u!=null&&o!==u&&(s=s||[]).push(l,u)):l==="children"?typeof u!="string"&&typeof u!="number"||(s=s||[]).push(l,""+u):l!=="suppressContentEditableWarning"&&l!=="suppressHydrationWarning"&&(xo.hasOwnProperty(l)?(u!=null&&l==="onScroll"&&Ne("scroll",t),s||o===u||(s=[])):(s=s||[]).push(l,u))}n&&(s=s||[]).push("style",n);var l=s;(e.updateQueue=l)&&(e.flags|=4)}};Mx=function(t,e,n,r){n!==r&&(e.flags|=4)};function Na(t,e){if(!Le)switch(t.tailMode){case"hidden":e=t.tail;for(var n=null;e!==null;)e.alternate!==null&&(n=e),e=e.sibling;n===null?t.tail=null:n.sibling=null;break;case"collapsed":n=t.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?e||t.tail===null?t.tail=null:t.tail.sibling=null:r.sibling=null}}function wt(t){var e=t.alternate!==null&&t.alternate.child===t.child,n=0,r=0;if(e)for(var i=t.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags&14680064,r|=i.flags&14680064,i.return=t,i=i.sibling;else for(i=t.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=t,i=i.sibling;return t.subtreeFlags|=r,t.childLanes=n,e}function dC(t,e,n){var r=e.pendingProps;switch(Om(e),e.tag){case 2:case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return wt(e),null;case 1:return Qt(e.type)&&Wl(),wt(e),null;case 3:return r=e.stateNode,na(),Re(Xt),Re(kt),zm(),r.pendingContext&&(r.context=r.pendingContext,r.pendingContext=null),(t===null||t.child===null)&&(Tu(e)?e.flags|=4:t===null||t.memoizedState.isDehydrated&&!(e.flags&256)||(e.flags|=1024,Kn!==null&&(Jh(Kn),Kn=null))),Bh(t,e),wt(e),null;case 5:Mm(e);var i=Ki(Ro.current);if(n=e.type,t!==null&&e.stateNode!=null)Lx(t,e,n,r,i),t.ref!==e.ref&&(e.flags|=512,e.flags|=2097152);else{if(!r){if(e.stateNode===null)throw Error(U(166));return wt(e),null}if(t=Ki(_r.current),Tu(e)){r=e.stateNode,n=e.type;var s=e.memoizedProps;switch(r[dr]=e,r[No]=s,t=(e.mode&1)!==0,n){case"dialog":Ne("cancel",r),Ne("close",r);break;case"iframe":case"object":case"embed":Ne("load",r);break;case"video":case"audio":for(i=0;i<Ba.length;i++)Ne(Ba[i],r);break;case"source":Ne("error",r);break;case"img":case"image":case"link":Ne("error",r),Ne("load",r);break;case"details":Ne("toggle",r);break;case"input":Ry(r,s),Ne("invalid",r);break;case"select":r._wrapperState={wasMultiple:!!s.multiple},Ne("invalid",r);break;case"textarea":Ly(r,s),Ne("invalid",r)}mh(n,s),i=null;for(var a in s)if(s.hasOwnProperty(a)){var o=s[a];a==="children"?typeof o=="string"?r.textContent!==o&&(s.suppressHydrationWarning!==!0&&Eu(r.textContent,o,t),i=["children",o]):typeof o=="number"&&r.textContent!==""+o&&(s.suppressHydrationWarning!==!0&&Eu(r.textContent,o,t),i=["children",""+o]):xo.hasOwnProperty(a)&&o!=null&&a==="onScroll"&&Ne("scroll",r)}switch(n){case"input":_u(r),jy(r,s,!0);break;case"textarea":_u(r),My(r);break;case"select":case"option":break;default:typeof s.onClick=="function"&&(r.onclick=ql)}r=i,e.updateQueue=r,r!==null&&(e.flags|=4)}else{a=i.nodeType===9?i:i.ownerDocument,t==="http://www.w3.org/1999/xhtml"&&(t=db(n)),t==="http://www.w3.org/1999/xhtml"?n==="script"?(t=a.createElement("div"),t.innerHTML="<script><\/script>",t=t.removeChild(t.firstChild)):typeof r.is=="string"?t=a.createElement(n,{is:r.is}):(t=a.createElement(n),n==="select"&&(a=t,r.multiple?a.multiple=!0:r.size&&(a.size=r.size))):t=a.createElementNS(t,n),t[dr]=e,t[No]=r,jx(t,e,!1,!1),e.stateNode=t;e:{switch(a=gh(n,r),n){case"dialog":Ne("cancel",t),Ne("close",t),i=r;break;case"iframe":case"object":case"embed":Ne("load",t),i=r;break;case"video":case"audio":for(i=0;i<Ba.length;i++)Ne(Ba[i],t);i=r;break;case"source":Ne("error",t),i=r;break;case"img":case"image":case"link":Ne("error",t),Ne("load",t),i=r;break;case"details":Ne("toggle",t),i=r;break;case"input":Ry(t,r),i=ch(t,r),Ne("invalid",t);break;case"option":i=r;break;case"select":t._wrapperState={wasMultiple:!!r.multiple},i=Ue({},r,{value:void 0}),Ne("invalid",t);break;case"textarea":Ly(t,r),i=hh(t,r),Ne("invalid",t);break;default:i=r}mh(n,i),o=i;for(s in o)if(o.hasOwnProperty(s)){var u=o[s];s==="style"?pb(t,u):s==="dangerouslySetInnerHTML"?(u=u?u.__html:void 0,u!=null&&fb(t,u)):s==="children"?typeof u=="string"?(n!=="textarea"||u!=="")&&ko(t,u):typeof u=="number"&&ko(t,""+u):s!=="suppressContentEditableWarning"&&s!=="suppressHydrationWarning"&&s!=="autoFocus"&&(xo.hasOwnProperty(s)?u!=null&&s==="onScroll"&&Ne("scroll",t):u!=null&&pm(t,s,u,a))}switch(n){case"input":_u(t),jy(t,r,!1);break;case"textarea":_u(t),My(t);break;case"option":r.value!=null&&t.setAttribute("value",""+wi(r.value));break;case"select":t.multiple=!!r.multiple,s=r.value,s!=null?Hs(t,!!r.multiple,s,!1):r.defaultValue!=null&&Hs(t,!!r.multiple,r.defaultValue,!0);break;default:typeof i.onClick=="function"&&(t.onclick=ql)}switch(n){case"button":case"input":case"select":case"textarea":r=!!r.autoFocus;break e;case"img":r=!0;break e;default:r=!1}}r&&(e.flags|=4)}e.ref!==null&&(e.flags|=512,e.flags|=2097152)}return wt(e),null;case 6:if(t&&e.stateNode!=null)Mx(t,e,t.memoizedProps,r);else{if(typeof r!="string"&&e.stateNode===null)throw Error(U(166));if(n=Ki(Ro.current),Ki(_r.current),Tu(e)){if(r=e.stateNode,n=e.memoizedProps,r[dr]=e,(s=r.nodeValue!==n)&&(t=fn,t!==null))switch(t.tag){case 3:Eu(r.nodeValue,n,(t.mode&1)!==0);break;case 5:t.memoizedProps.suppressHydrationWarning!==!0&&Eu(r.nodeValue,n,(t.mode&1)!==0)}s&&(e.flags|=4)}else r=(n.nodeType===9?n:n.ownerDocument).createTextNode(r),r[dr]=e,e.stateNode=r}return wt(e),null;case 13:if(Re(ze),r=e.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(Le&&cn!==null&&e.mode&1&&!(e.flags&128))tx(),ea(),e.flags|=98560,s=!1;else if(s=Tu(e),r!==null&&r.dehydrated!==null){if(t===null){if(!s)throw Error(U(318));if(s=e.memoizedState,s=s!==null?s.dehydrated:null,!s)throw Error(U(317));s[dr]=e}else ea(),!(e.flags&128)&&(e.memoizedState=null),e.flags|=4;wt(e),s=!1}else Kn!==null&&(Jh(Kn),Kn=null),s=!0;if(!s)return e.flags&65536?e:null}return e.flags&128?(e.lanes=n,e):(r=r!==null,r!==(t!==null&&t.memoizedState!==null)&&r&&(e.child.flags|=8192,e.mode&1&&(t===null||ze.current&1?rt===0&&(rt=3):Jm())),e.updateQueue!==null&&(e.flags|=4),wt(e),null);case 4:return na(),Bh(t,e),t===null&&Co(e.stateNode.containerInfo),wt(e),null;case 10:return $m(e.type._context),wt(e),null;case 17:return Qt(e.type)&&Wl(),wt(e),null;case 19:if(Re(ze),s=e.memoizedState,s===null)return wt(e),null;if(r=(e.flags&128)!==0,a=s.rendering,a===null)if(r)Na(s,!1);else{if(rt!==0||t!==null&&t.flags&128)for(t=e.child;t!==null;){if(a=tc(t),a!==null){for(e.flags|=128,Na(s,!1),r=a.updateQueue,r!==null&&(e.updateQueue=r,e.flags|=4),e.subtreeFlags=0,r=n,n=e.child;n!==null;)s=n,t=r,s.flags&=14680066,a=s.alternate,a===null?(s.childLanes=0,s.lanes=t,s.child=null,s.subtreeFlags=0,s.memoizedProps=null,s.memoizedState=null,s.updateQueue=null,s.dependencies=null,s.stateNode=null):(s.childLanes=a.childLanes,s.lanes=a.lanes,s.child=a.child,s.subtreeFlags=0,s.deletions=null,s.memoizedProps=a.memoizedProps,s.memoizedState=a.memoizedState,s.updateQueue=a.updateQueue,s.type=a.type,t=a.dependencies,s.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),n=n.sibling;return Oe(ze,ze.current&1|2),e.child}t=t.sibling}s.tail!==null&&We()>ia&&(e.flags|=128,r=!0,Na(s,!1),e.lanes=4194304)}else{if(!r)if(t=tc(a),t!==null){if(e.flags|=128,r=!0,n=t.updateQueue,n!==null&&(e.updateQueue=n,e.flags|=4),Na(s,!0),s.tail===null&&s.tailMode==="hidden"&&!a.alternate&&!Le)return wt(e),null}else 2*We()-s.renderingStartTime>ia&&n!==1073741824&&(e.flags|=128,r=!0,Na(s,!1),e.lanes=4194304);s.isBackwards?(a.sibling=e.child,e.child=a):(n=s.last,n!==null?n.sibling=a:e.child=a,s.last=a)}return s.tail!==null?(e=s.tail,s.rendering=e,s.tail=e.sibling,s.renderingStartTime=We(),e.sibling=null,n=ze.current,Oe(ze,r?n&1|2:n&1),e):(wt(e),null);case 22:case 23:return Gm(),r=e.memoizedState!==null,t!==null&&t.memoizedState!==null!==r&&(e.flags|=8192),r&&e.mode&1?ln&1073741824&&(wt(e),e.subtreeFlags&6&&(e.flags|=8192)):wt(e),null;case 24:return null;case 25:return null}throw Error(U(156,e.tag))}function fC(t,e){switch(Om(e),e.tag){case 1:return Qt(e.type)&&Wl(),t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 3:return na(),Re(Xt),Re(kt),zm(),t=e.flags,t&65536&&!(t&128)?(e.flags=t&-65537|128,e):null;case 5:return Mm(e),null;case 13:if(Re(ze),t=e.memoizedState,t!==null&&t.dehydrated!==null){if(e.alternate===null)throw Error(U(340));ea()}return t=e.flags,t&65536?(e.flags=t&-65537|128,e):null;case 19:return Re(ze),null;case 4:return na(),null;case 10:return $m(e.type._context),null;case 22:case 23:return Gm(),null;case 24:return null;default:return null}}var Cu=!1,bt=!1,hC=typeof WeakSet=="function"?WeakSet:Set,W=null;function $s(t,e){var n=t.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ze(t,e,r)}else n.current=null}function Hh(t,e,n){try{n()}catch(r){Ze(t,e,r)}}var E_=!1;function pC(t,e){if(Eh=Zl,t=Bb(),Tm(t)){if("selectionStart"in t)var n={start:t.selectionStart,end:t.selectionEnd};else e:{n=(n=t.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var i=r.anchorOffset,s=r.focusNode;r=r.focusOffset;try{n.nodeType,s.nodeType}catch{n=null;break e}var a=0,o=-1,u=-1,l=0,c=0,d=t,f=null;t:for(;;){for(var h;d!==n||i!==0&&d.nodeType!==3||(o=a+i),d!==s||r!==0&&d.nodeType!==3||(u=a+r),d.nodeType===3&&(a+=d.nodeValue.length),(h=d.firstChild)!==null;)f=d,d=h;for(;;){if(d===t)break t;if(f===n&&++l===i&&(o=a),f===s&&++c===r&&(u=a),(h=d.nextSibling)!==null)break;d=f,f=d.parentNode}d=h}n=o===-1||u===-1?null:{start:o,end:u}}else n=null}n=n||{start:0,end:0}}else n=null;for(Th={focusedElem:t,selectionRange:n},Zl=!1,W=e;W!==null;)if(e=W,t=e.child,(e.subtreeFlags&1028)!==0&&t!==null)t.return=e,W=t;else for(;W!==null;){e=W;try{var m=e.alternate;if(e.flags&1024)switch(e.tag){case 0:case 11:case 15:break;case 1:if(m!==null){var _=m.memoizedProps,v=m.memoizedState,y=e.stateNode,p=y.getSnapshotBeforeUpdate(e.elementType===e.type?_:Bn(e.type,_),v);y.__reactInternalSnapshotBeforeUpdate=p}break;case 3:var g=e.stateNode.containerInfo;g.nodeType===1?g.textContent="":g.nodeType===9&&g.documentElement&&g.removeChild(g.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(U(163))}}catch(b){Ze(e,e.return,b)}if(t=e.sibling,t!==null){t.return=e.return,W=t;break}W=e.return}return m=E_,E_=!1,m}function co(t,e,n){var r=e.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var i=r=r.next;do{if((i.tag&t)===t){var s=i.destroy;i.destroy=void 0,s!==void 0&&Hh(e,n,s)}i=i.next}while(i!==r)}}function td(t,e){if(e=e.updateQueue,e=e!==null?e.lastEffect:null,e!==null){var n=e=e.next;do{if((n.tag&t)===t){var r=n.create;n.destroy=r()}n=n.next}while(n!==e)}}function Zh(t){var e=t.ref;if(e!==null){var n=t.stateNode;switch(t.tag){case 5:t=n;break;default:t=n}typeof e=="function"?e(t):e.current=t}}function zx(t){var e=t.alternate;e!==null&&(t.alternate=null,zx(e)),t.child=null,t.deletions=null,t.sibling=null,t.tag===5&&(e=t.stateNode,e!==null&&(delete e[dr],delete e[No],delete e[Ch],delete e[JO],delete e[XO])),t.stateNode=null,t.return=null,t.dependencies=null,t.memoizedProps=null,t.memoizedState=null,t.pendingProps=null,t.stateNode=null,t.updateQueue=null}function Dx(t){return t.tag===5||t.tag===3||t.tag===4}function T_(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||Dx(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Vh(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.nodeType===8?n.parentNode.insertBefore(t,e):n.insertBefore(t,e):(n.nodeType===8?(e=n.parentNode,e.insertBefore(t,n)):(e=n,e.appendChild(t)),n=n._reactRootContainer,n!=null||e.onclick!==null||(e.onclick=ql));else if(r!==4&&(t=t.child,t!==null))for(Vh(t,e,n),t=t.sibling;t!==null;)Vh(t,e,n),t=t.sibling}function Kh(t,e,n){var r=t.tag;if(r===5||r===6)t=t.stateNode,e?n.insertBefore(t,e):n.appendChild(t);else if(r!==4&&(t=t.child,t!==null))for(Kh(t,e,n),t=t.sibling;t!==null;)Kh(t,e,n),t=t.sibling}var dt=null,Vn=!1;function qr(t,e,n){for(n=n.child;n!==null;)Ux(t,e,n),n=n.sibling}function Ux(t,e,n){if(yr&&typeof yr.onCommitFiberUnmount=="function")try{yr.onCommitFiberUnmount(qc,n)}catch{}switch(n.tag){case 5:bt||$s(n,e);case 6:var r=dt,i=Vn;dt=null,qr(t,e,n),dt=r,Vn=i,dt!==null&&(Vn?(t=dt,n=n.stateNode,t.nodeType===8?t.parentNode.removeChild(n):t.removeChild(n)):dt.removeChild(n.stateNode));break;case 18:dt!==null&&(Vn?(t=dt,n=n.stateNode,t.nodeType===8?sf(t.parentNode,n):t.nodeType===1&&sf(t,n),To(t)):sf(dt,n.stateNode));break;case 4:r=dt,i=Vn,dt=n.stateNode.containerInfo,Vn=!0,qr(t,e,n),dt=r,Vn=i;break;case 0:case 11:case 14:case 15:if(!bt&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){i=r=r.next;do{var s=i,a=s.destroy;s=s.tag,a!==void 0&&(s&2||s&4)&&Hh(n,e,a),i=i.next}while(i!==r)}qr(t,e,n);break;case 1:if(!bt&&($s(n,e),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){Ze(n,e,o)}qr(t,e,n);break;case 21:qr(t,e,n);break;case 22:n.mode&1?(bt=(r=bt)||n.memoizedState!==null,qr(t,e,n),bt=r):qr(t,e,n);break;default:qr(t,e,n)}}function I_(t){var e=t.updateQueue;if(e!==null){t.updateQueue=null;var n=t.stateNode;n===null&&(n=t.stateNode=new hC),e.forEach(function(r){var i=kC.bind(null,t,r);n.has(r)||(n.add(r),r.then(i,i))})}}function Rn(t,e){var n=e.deletions;if(n!==null)for(var r=0;r<n.length;r++){var i=n[r];try{var s=t,a=e,o=a;e:for(;o!==null;){switch(o.tag){case 5:dt=o.stateNode,Vn=!1;break e;case 3:dt=o.stateNode.containerInfo,Vn=!0;break e;case 4:dt=o.stateNode.containerInfo,Vn=!0;break e}o=o.return}if(dt===null)throw Error(U(160));Ux(s,a,i),dt=null,Vn=!1;var u=i.alternate;u!==null&&(u.return=null),i.return=null}catch(l){Ze(i,e,l)}}if(e.subtreeFlags&12854)for(e=e.child;e!==null;)Fx(e,t),e=e.sibling}function Fx(t,e){var n=t.alternate,r=t.flags;switch(t.tag){case 0:case 11:case 14:case 15:if(Rn(e,t),rr(t),r&4){try{co(3,t,t.return),td(3,t)}catch(_){Ze(t,t.return,_)}try{co(5,t,t.return)}catch(_){Ze(t,t.return,_)}}break;case 1:Rn(e,t),rr(t),r&512&&n!==null&&$s(n,n.return);break;case 5:if(Rn(e,t),rr(t),r&512&&n!==null&&$s(n,n.return),t.flags&32){var i=t.stateNode;try{ko(i,"")}catch(_){Ze(t,t.return,_)}}if(r&4&&(i=t.stateNode,i!=null)){var s=t.memoizedProps,a=n!==null?n.memoizedProps:s,o=t.type,u=t.updateQueue;if(t.updateQueue=null,u!==null)try{o==="input"&&s.type==="radio"&&s.name!=null&&lb(i,s),gh(o,a);var l=gh(o,s);for(a=0;a<u.length;a+=2){var c=u[a],d=u[a+1];c==="style"?pb(i,d):c==="dangerouslySetInnerHTML"?fb(i,d):c==="children"?ko(i,d):pm(i,c,d,l)}switch(o){case"input":dh(i,s);break;case"textarea":cb(i,s);break;case"select":var f=i._wrapperState.wasMultiple;i._wrapperState.wasMultiple=!!s.multiple;var h=s.value;h!=null?Hs(i,!!s.multiple,h,!1):f!==!!s.multiple&&(s.defaultValue!=null?Hs(i,!!s.multiple,s.defaultValue,!0):Hs(i,!!s.multiple,s.multiple?[]:"",!1))}i[No]=s}catch(_){Ze(t,t.return,_)}}break;case 6:if(Rn(e,t),rr(t),r&4){if(t.stateNode===null)throw Error(U(162));i=t.stateNode,s=t.memoizedProps;try{i.nodeValue=s}catch(_){Ze(t,t.return,_)}}break;case 3:if(Rn(e,t),rr(t),r&4&&n!==null&&n.memoizedState.isDehydrated)try{To(e.containerInfo)}catch(_){Ze(t,t.return,_)}break;case 4:Rn(e,t),rr(t);break;case 13:Rn(e,t),rr(t),i=t.child,i.flags&8192&&(s=i.memoizedState!==null,i.stateNode.isHidden=s,!s||i.alternate!==null&&i.alternate.memoizedState!==null||(qm=We())),r&4&&I_(t);break;case 22:if(c=n!==null&&n.memoizedState!==null,t.mode&1?(bt=(l=bt)||c,Rn(e,t),bt=l):Rn(e,t),rr(t),r&8192){if(l=t.memoizedState!==null,(t.stateNode.isHidden=l)&&!c&&t.mode&1)for(W=t,c=t.child;c!==null;){for(d=W=c;W!==null;){switch(f=W,h=f.child,f.tag){case 0:case 11:case 14:case 15:co(4,f,f.return);break;case 1:$s(f,f.return);var m=f.stateNode;if(typeof m.componentWillUnmount=="function"){r=f,n=f.return;try{e=r,m.props=e.memoizedProps,m.state=e.memoizedState,m.componentWillUnmount()}catch(_){Ze(r,n,_)}}break;case 5:$s(f,f.return);break;case 22:if(f.memoizedState!==null){C_(d);continue}}h!==null?(h.return=f,W=h):C_(d)}c=c.sibling}e:for(c=null,d=t;;){if(d.tag===5){if(c===null){c=d;try{i=d.stateNode,l?(s=i.style,typeof s.setProperty=="function"?s.setProperty("display","none","important"):s.display="none"):(o=d.stateNode,u=d.memoizedProps.style,a=u!=null&&u.hasOwnProperty("display")?u.display:null,o.style.display=hb("display",a))}catch(_){Ze(t,t.return,_)}}}else if(d.tag===6){if(c===null)try{d.stateNode.nodeValue=l?"":d.memoizedProps}catch(_){Ze(t,t.return,_)}}else if((d.tag!==22&&d.tag!==23||d.memoizedState===null||d===t)&&d.child!==null){d.child.return=d,d=d.child;continue}if(d===t)break e;for(;d.sibling===null;){if(d.return===null||d.return===t)break e;c===d&&(c=null),d=d.return}c===d&&(c=null),d.sibling.return=d.return,d=d.sibling}}break;case 19:Rn(e,t),rr(t),r&4&&I_(t);break;case 21:break;default:Rn(e,t),rr(t)}}function rr(t){var e=t.flags;if(e&2){try{e:{for(var n=t.return;n!==null;){if(Dx(n)){var r=n;break e}n=n.return}throw Error(U(160))}switch(r.tag){case 5:var i=r.stateNode;r.flags&32&&(ko(i,""),r.flags&=-33);var s=T_(t);Kh(t,s,i);break;case 3:case 4:var a=r.stateNode.containerInfo,o=T_(t);Vh(t,o,a);break;default:throw Error(U(161))}}catch(u){Ze(t,t.return,u)}t.flags&=-3}e&4096&&(t.flags&=-4097)}function mC(t,e,n){W=t,Bx(t)}function Bx(t,e,n){for(var r=(t.mode&1)!==0;W!==null;){var i=W,s=i.child;if(i.tag===22&&r){var a=i.memoizedState!==null||Cu;if(!a){var o=i.alternate,u=o!==null&&o.memoizedState!==null||bt;o=Cu;var l=bt;if(Cu=a,(bt=u)&&!l)for(W=i;W!==null;)a=W,u=a.child,a.tag===22&&a.memoizedState!==null?P_(i):u!==null?(u.return=a,W=u):P_(i);for(;s!==null;)W=s,Bx(s),s=s.sibling;W=i,Cu=o,bt=l}O_(t)}else i.subtreeFlags&8772&&s!==null?(s.return=i,W=s):O_(t)}}function O_(t){for(;W!==null;){var e=W;if(e.flags&8772){var n=e.alternate;try{if(e.flags&8772)switch(e.tag){case 0:case 11:case 15:bt||td(5,e);break;case 1:var r=e.stateNode;if(e.flags&4&&!bt)if(n===null)r.componentDidMount();else{var i=e.elementType===e.type?n.memoizedProps:Bn(e.type,n.memoizedProps);r.componentDidUpdate(i,n.memoizedState,r.__reactInternalSnapshotBeforeUpdate)}var s=e.updateQueue;s!==null&&h_(e,s,r);break;case 3:var a=e.updateQueue;if(a!==null){if(n=null,e.child!==null)switch(e.child.tag){case 5:n=e.child.stateNode;break;case 1:n=e.child.stateNode}h_(e,a,n)}break;case 5:var o=e.stateNode;if(n===null&&e.flags&4){n=o;var u=e.memoizedProps;switch(e.type){case"button":case"input":case"select":case"textarea":u.autoFocus&&n.focus();break;case"img":u.src&&(n.src=u.src)}}break;case 6:break;case 4:break;case 12:break;case 13:if(e.memoizedState===null){var l=e.alternate;if(l!==null){var c=l.memoizedState;if(c!==null){var d=c.dehydrated;d!==null&&To(d)}}}break;case 19:case 17:case 21:case 22:case 23:case 25:break;default:throw Error(U(163))}bt||e.flags&512&&Zh(e)}catch(f){Ze(e,e.return,f)}}if(e===t){W=null;break}if(n=e.sibling,n!==null){n.return=e.return,W=n;break}W=e.return}}function C_(t){for(;W!==null;){var e=W;if(e===t){W=null;break}var n=e.sibling;if(n!==null){n.return=e.return,W=n;break}W=e.return}}function P_(t){for(;W!==null;){var e=W;try{switch(e.tag){case 0:case 11:case 15:var n=e.return;try{td(4,e)}catch(u){Ze(e,n,u)}break;case 1:var r=e.stateNode;if(typeof r.componentDidMount=="function"){var i=e.return;try{r.componentDidMount()}catch(u){Ze(e,i,u)}}var s=e.return;try{Zh(e)}catch(u){Ze(e,s,u)}break;case 5:var a=e.return;try{Zh(e)}catch(u){Ze(e,a,u)}}}catch(u){Ze(e,e.return,u)}if(e===t){W=null;break}var o=e.sibling;if(o!==null){o.return=e.return,W=o;break}W=e.return}}var gC=Math.ceil,ic=Hr.ReactCurrentDispatcher,Vm=Hr.ReactCurrentOwner,Tn=Hr.ReactCurrentBatchConfig,he=0,ut=null,Qe=null,pt=0,ln=0,Rs=Ci(0),rt=0,zo=null,ns=0,nd=0,Km=0,fo=null,Kt=null,qm=0,ia=1/0,Ar=null,sc=!1,qh=null,fi=null,Pu=!1,ai=null,ac=0,ho=0,Wh=null,gl=-1,yl=0;function Mt(){return he&6?We():gl!==-1?gl:gl=We()}function hi(t){return t.mode&1?he&2&&pt!==0?pt&-pt:YO.transition!==null?(yl===0&&(yl=Eb()),yl):(t=Ae,t!==0||(t=window.event,t=t===void 0?16:$b(t.type)),t):1}function Gn(t,e,n,r){if(50<ho)throw ho=0,Wh=null,Error(U(185));nu(t,n,r),(!(he&2)||t!==ut)&&(t===ut&&(!(he&2)&&(nd|=n),rt===4&&ii(t,pt)),Yt(t,r),n===1&&he===0&&!(e.mode&1)&&(ia=We()+500,Qc&&Pi()))}function Yt(t,e){var n=t.callbackNode;YI(t,e);var r=Hl(t,t===ut?pt:0);if(r===0)n!==null&&Uy(n),t.callbackNode=null,t.callbackPriority=0;else if(e=r&-r,t.callbackPriority!==e){if(n!=null&&Uy(n),e===1)t.tag===0?QO(N_.bind(null,t)):Qb(N_.bind(null,t)),WO(function(){!(he&6)&&Pi()}),n=null;else{switch(Tb(r)){case 1:n=vm;break;case 4:n=Sb;break;case 16:n=Bl;break;case 536870912:n=Ab;break;default:n=Bl}n=Jx(n,Hx.bind(null,t))}t.callbackPriority=e,t.callbackNode=n}}function Hx(t,e){if(gl=-1,yl=0,he&6)throw Error(U(327));var n=t.callbackNode;if(Ws()&&t.callbackNode!==n)return null;var r=Hl(t,t===ut?pt:0);if(r===0)return null;if(r&30||r&t.expiredLanes||e)e=oc(t,r);else{e=r;var i=he;he|=2;var s=Vx();(ut!==t||pt!==e)&&(Ar=null,ia=We()+500,Ji(t,e));do try{vC();break}catch(o){Zx(t,o)}while(!0);Nm(),ic.current=s,he=i,Qe!==null?e=0:(ut=null,pt=0,e=rt)}if(e!==0){if(e===2&&(i=bh(t),i!==0&&(r=i,e=Gh(t,i))),e===1)throw n=zo,Ji(t,0),ii(t,r),Yt(t,We()),n;if(e===6)ii(t,r);else{if(i=t.current.alternate,!(r&30)&&!yC(i)&&(e=oc(t,r),e===2&&(s=bh(t),s!==0&&(r=s,e=Gh(t,s))),e===1))throw n=zo,Ji(t,0),ii(t,r),Yt(t,We()),n;switch(t.finishedWork=i,t.finishedLanes=r,e){case 0:case 1:throw Error(U(345));case 2:zi(t,Kt,Ar);break;case 3:if(ii(t,r),(r&130023424)===r&&(e=qm+500-We(),10<e)){if(Hl(t,0)!==0)break;if(i=t.suspendedLanes,(i&r)!==r){Mt(),t.pingedLanes|=t.suspendedLanes&i;break}t.timeoutHandle=Oh(zi.bind(null,t,Kt,Ar),e);break}zi(t,Kt,Ar);break;case 4:if(ii(t,r),(r&4194240)===r)break;for(e=t.eventTimes,i=-1;0<r;){var a=31-Wn(r);s=1<<a,a=e[a],a>i&&(i=a),r&=~s}if(r=i,r=We()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*gC(r/1960))-r,10<r){t.timeoutHandle=Oh(zi.bind(null,t,Kt,Ar),r);break}zi(t,Kt,Ar);break;case 5:zi(t,Kt,Ar);break;default:throw Error(U(329))}}}return Yt(t,We()),t.callbackNode===n?Hx.bind(null,t):null}function Gh(t,e){var n=fo;return t.current.memoizedState.isDehydrated&&(Ji(t,e).flags|=256),t=oc(t,e),t!==2&&(e=Kt,Kt=n,e!==null&&Jh(e)),t}function Jh(t){Kt===null?Kt=t:Kt.push.apply(Kt,t)}function yC(t){for(var e=t;;){if(e.flags&16384){var n=e.updateQueue;if(n!==null&&(n=n.stores,n!==null))for(var r=0;r<n.length;r++){var i=n[r],s=i.getSnapshot;i=i.value;try{if(!Qn(s(),i))return!1}catch{return!1}}}if(n=e.child,e.subtreeFlags&16384&&n!==null)n.return=e,e=n;else{if(e===t)break;for(;e.sibling===null;){if(e.return===null||e.return===t)return!0;e=e.return}e.sibling.return=e.return,e=e.sibling}}return!0}function ii(t,e){for(e&=~Km,e&=~nd,t.suspendedLanes|=e,t.pingedLanes&=~e,t=t.expirationTimes;0<e;){var n=31-Wn(e),r=1<<n;t[n]=-1,e&=~r}}function N_(t){if(he&6)throw Error(U(327));Ws();var e=Hl(t,0);if(!(e&1))return Yt(t,We()),null;var n=oc(t,e);if(t.tag!==0&&n===2){var r=bh(t);r!==0&&(e=r,n=Gh(t,r))}if(n===1)throw n=zo,Ji(t,0),ii(t,e),Yt(t,We()),n;if(n===6)throw Error(U(345));return t.finishedWork=t.current.alternate,t.finishedLanes=e,zi(t,Kt,Ar),Yt(t,We()),null}function Wm(t,e){var n=he;he|=1;try{return t(e)}finally{he=n,he===0&&(ia=We()+500,Qc&&Pi())}}function rs(t){ai!==null&&ai.tag===0&&!(he&6)&&Ws();var e=he;he|=1;var n=Tn.transition,r=Ae;try{if(Tn.transition=null,Ae=1,t)return t()}finally{Ae=r,Tn.transition=n,he=e,!(he&6)&&Pi()}}function Gm(){ln=Rs.current,Re(Rs)}function Ji(t,e){t.finishedWork=null,t.finishedLanes=0;var n=t.timeoutHandle;if(n!==-1&&(t.timeoutHandle=-1,qO(n)),Qe!==null)for(n=Qe.return;n!==null;){var r=n;switch(Om(r),r.tag){case 1:r=r.type.childContextTypes,r!=null&&Wl();break;case 3:na(),Re(Xt),Re(kt),zm();break;case 5:Mm(r);break;case 4:na();break;case 13:Re(ze);break;case 19:Re(ze);break;case 10:$m(r.type._context);break;case 22:case 23:Gm()}n=n.return}if(ut=t,Qe=t=pi(t.current,null),pt=ln=e,rt=0,zo=null,Km=nd=ns=0,Kt=fo=null,Vi!==null){for(e=0;e<Vi.length;e++)if(n=Vi[e],r=n.interleaved,r!==null){n.interleaved=null;var i=r.next,s=n.pending;if(s!==null){var a=s.next;s.next=i,r.next=a}n.pending=r}Vi=null}return t}function Zx(t,e){do{var n=Qe;try{if(Nm(),hl.current=rc,nc){for(var r=De.memoizedState;r!==null;){var i=r.queue;i!==null&&(i.pending=null),r=r.next}nc=!1}if(ts=0,at=nt=De=null,lo=!1,jo=0,Vm.current=null,n===null||n.return===null){rt=1,zo=e,Qe=null;break}e:{var s=t,a=n.return,o=n,u=e;if(e=pt,o.flags|=32768,u!==null&&typeof u=="object"&&typeof u.then=="function"){var l=u,c=o,d=c.tag;if(!(c.mode&1)&&(d===0||d===11||d===15)){var f=c.alternate;f?(c.updateQueue=f.updateQueue,c.memoizedState=f.memoizedState,c.lanes=f.lanes):(c.updateQueue=null,c.memoizedState=null)}var h=v_(a);if(h!==null){h.flags&=-257,w_(h,a,o,s,e),h.mode&1&&__(s,l,e),e=h,u=l;var m=e.updateQueue;if(m===null){var _=new Set;_.add(u),e.updateQueue=_}else m.add(u);break e}else{if(!(e&1)){__(s,l,e),Jm();break e}u=Error(U(426))}}else if(Le&&o.mode&1){var v=v_(a);if(v!==null){!(v.flags&65536)&&(v.flags|=256),w_(v,a,o,s,e),Cm(ra(u,o));break e}}s=u=ra(u,o),rt!==4&&(rt=2),fo===null?fo=[s]:fo.push(s),s=a;do{switch(s.tag){case 3:s.flags|=65536,e&=-e,s.lanes|=e;var y=Tx(s,u,e);f_(s,y);break e;case 1:o=u;var p=s.type,g=s.stateNode;if(!(s.flags&128)&&(typeof p.getDerivedStateFromError=="function"||g!==null&&typeof g.componentDidCatch=="function"&&(fi===null||!fi.has(g)))){s.flags|=65536,e&=-e,s.lanes|=e;var b=Ix(s,o,e);f_(s,b);break e}}s=s.return}while(s!==null)}qx(n)}catch(E){e=E,Qe===n&&n!==null&&(Qe=n=n.return);continue}break}while(!0)}function Vx(){var t=ic.current;return ic.current=rc,t===null?rc:t}function Jm(){(rt===0||rt===3||rt===2)&&(rt=4),ut===null||!(ns&268435455)&&!(nd&268435455)||ii(ut,pt)}function oc(t,e){var n=he;he|=2;var r=Vx();(ut!==t||pt!==e)&&(Ar=null,Ji(t,e));do try{_C();break}catch(i){Zx(t,i)}while(!0);if(Nm(),he=n,ic.current=r,Qe!==null)throw Error(U(261));return ut=null,pt=0,rt}function _C(){for(;Qe!==null;)Kx(Qe)}function vC(){for(;Qe!==null&&!ZI();)Kx(Qe)}function Kx(t){var e=Gx(t.alternate,t,ln);t.memoizedProps=t.pendingProps,e===null?qx(t):Qe=e,Vm.current=null}function qx(t){var e=t;do{var n=e.alternate;if(t=e.return,e.flags&32768){if(n=fC(n,e),n!==null){n.flags&=32767,Qe=n;return}if(t!==null)t.flags|=32768,t.subtreeFlags=0,t.deletions=null;else{rt=6,Qe=null;return}}else if(n=dC(n,e,ln),n!==null){Qe=n;return}if(e=e.sibling,e!==null){Qe=e;return}Qe=e=t}while(e!==null);rt===0&&(rt=5)}function zi(t,e,n){var r=Ae,i=Tn.transition;try{Tn.transition=null,Ae=1,wC(t,e,n,r)}finally{Tn.transition=i,Ae=r}return null}function wC(t,e,n,r){do Ws();while(ai!==null);if(he&6)throw Error(U(327));n=t.finishedWork;var i=t.finishedLanes;if(n===null)return null;if(t.finishedWork=null,t.finishedLanes=0,n===t.current)throw Error(U(177));t.callbackNode=null,t.callbackPriority=0;var s=n.lanes|n.childLanes;if(eO(t,s),t===ut&&(Qe=ut=null,pt=0),!(n.subtreeFlags&2064)&&!(n.flags&2064)||Pu||(Pu=!0,Jx(Bl,function(){return Ws(),null})),s=(n.flags&15990)!==0,n.subtreeFlags&15990||s){s=Tn.transition,Tn.transition=null;var a=Ae;Ae=1;var o=he;he|=4,Vm.current=null,pC(t,n),Fx(n,t),UO(Th),Zl=!!Eh,Th=Eh=null,t.current=n,mC(n),VI(),he=o,Ae=a,Tn.transition=s}else t.current=n;if(Pu&&(Pu=!1,ai=t,ac=i),s=t.pendingLanes,s===0&&(fi=null),WI(n.stateNode),Yt(t,We()),e!==null)for(r=t.onRecoverableError,n=0;n<e.length;n++)i=e[n],r(i.value,{componentStack:i.stack,digest:i.digest});if(sc)throw sc=!1,t=qh,qh=null,t;return ac&1&&t.tag!==0&&Ws(),s=t.pendingLanes,s&1?t===Wh?ho++:(ho=0,Wh=t):ho=0,Pi(),null}function Ws(){if(ai!==null){var t=Tb(ac),e=Tn.transition,n=Ae;try{if(Tn.transition=null,Ae=16>t?16:t,ai===null)var r=!1;else{if(t=ai,ai=null,ac=0,he&6)throw Error(U(331));var i=he;for(he|=4,W=t.current;W!==null;){var s=W,a=s.child;if(W.flags&16){var o=s.deletions;if(o!==null){for(var u=0;u<o.length;u++){var l=o[u];for(W=l;W!==null;){var c=W;switch(c.tag){case 0:case 11:case 15:co(8,c,s)}var d=c.child;if(d!==null)d.return=c,W=d;else for(;W!==null;){c=W;var f=c.sibling,h=c.return;if(zx(c),c===l){W=null;break}if(f!==null){f.return=h,W=f;break}W=h}}}var m=s.alternate;if(m!==null){var _=m.child;if(_!==null){m.child=null;do{var v=_.sibling;_.sibling=null,_=v}while(_!==null)}}W=s}}if(s.subtreeFlags&2064&&a!==null)a.return=s,W=a;else e:for(;W!==null;){if(s=W,s.flags&2048)switch(s.tag){case 0:case 11:case 15:co(9,s,s.return)}var y=s.sibling;if(y!==null){y.return=s.return,W=y;break e}W=s.return}}var p=t.current;for(W=p;W!==null;){a=W;var g=a.child;if(a.subtreeFlags&2064&&g!==null)g.return=a,W=g;else e:for(a=p;W!==null;){if(o=W,o.flags&2048)try{switch(o.tag){case 0:case 11:case 15:td(9,o)}}catch(E){Ze(o,o.return,E)}if(o===a){W=null;break e}var b=o.sibling;if(b!==null){b.return=o.return,W=b;break e}W=o.return}}if(he=i,Pi(),yr&&typeof yr.onPostCommitFiberRoot=="function")try{yr.onPostCommitFiberRoot(qc,t)}catch{}r=!0}return r}finally{Ae=n,Tn.transition=e}}return!1}function $_(t,e,n){e=ra(n,e),e=Tx(t,e,1),t=di(t,e,1),e=Mt(),t!==null&&(nu(t,1,e),Yt(t,e))}function Ze(t,e,n){if(t.tag===3)$_(t,t,n);else for(;e!==null;){if(e.tag===3){$_(e,t,n);break}else if(e.tag===1){var r=e.stateNode;if(typeof e.type.getDerivedStateFromError=="function"||typeof r.componentDidCatch=="function"&&(fi===null||!fi.has(r))){t=ra(n,t),t=Ix(e,t,1),e=di(e,t,1),t=Mt(),e!==null&&(nu(e,1,t),Yt(e,t));break}}e=e.return}}function bC(t,e,n){var r=t.pingCache;r!==null&&r.delete(e),e=Mt(),t.pingedLanes|=t.suspendedLanes&n,ut===t&&(pt&n)===n&&(rt===4||rt===3&&(pt&130023424)===pt&&500>We()-qm?Ji(t,0):Km|=n),Yt(t,e)}function Wx(t,e){e===0&&(t.mode&1?(e=bu,bu<<=1,!(bu&130023424)&&(bu=4194304)):e=1);var n=Mt();t=Mr(t,e),t!==null&&(nu(t,e,n),Yt(t,n))}function xC(t){var e=t.memoizedState,n=0;e!==null&&(n=e.retryLane),Wx(t,n)}function kC(t,e){var n=0;switch(t.tag){case 13:var r=t.stateNode,i=t.memoizedState;i!==null&&(n=i.retryLane);break;case 19:r=t.stateNode;break;default:throw Error(U(314))}r!==null&&r.delete(e),Wx(t,n)}var Gx;Gx=function(t,e,n){if(t!==null)if(t.memoizedProps!==e.pendingProps||Xt.current)Gt=!0;else{if(!(t.lanes&n)&&!(e.flags&128))return Gt=!1,cC(t,e,n);Gt=!!(t.flags&131072)}else Gt=!1,Le&&e.flags&1048576&&Yb(e,Xl,e.index);switch(e.lanes=0,e.tag){case 2:var r=e.type;ml(t,e),t=e.pendingProps;var i=Ys(e,kt.current);qs(e,n),i=Um(null,e,r,t,i,n);var s=Fm();return e.flags|=1,typeof i=="object"&&i!==null&&typeof i.render=="function"&&i.$$typeof===void 0?(e.tag=1,e.memoizedState=null,e.updateQueue=null,Qt(r)?(s=!0,Gl(e)):s=!1,e.memoizedState=i.state!==null&&i.state!==void 0?i.state:null,jm(e),i.updater=ed,e.stateNode=i,i._reactInternals=e,Lh(e,r,t,n),e=Dh(null,e,r,!0,s,n)):(e.tag=0,Le&&s&&Im(e),Rt(null,e,i,n),e=e.child),e;case 16:r=e.elementType;e:{switch(ml(t,e),t=e.pendingProps,i=r._init,r=i(r._payload),e.type=r,i=e.tag=AC(r),t=Bn(r,t),i){case 0:e=zh(null,e,r,t,n);break e;case 1:e=k_(null,e,r,t,n);break e;case 11:e=b_(null,e,r,t,n);break e;case 14:e=x_(null,e,r,Bn(r.type,t),n);break e}throw Error(U(306,r,""))}return e;case 0:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Bn(r,i),zh(t,e,r,i,n);case 1:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Bn(r,i),k_(t,e,r,i,n);case 3:e:{if(Nx(e),t===null)throw Error(U(387));r=e.pendingProps,s=e.memoizedState,i=s.element,sx(t,e),ec(e,r,null,n);var a=e.memoizedState;if(r=a.element,s.isDehydrated)if(s={element:r,isDehydrated:!1,cache:a.cache,pendingSuspenseBoundaries:a.pendingSuspenseBoundaries,transitions:a.transitions},e.updateQueue.baseState=s,e.memoizedState=s,e.flags&256){i=ra(Error(U(423)),e),e=S_(t,e,r,n,i);break e}else if(r!==i){i=ra(Error(U(424)),e),e=S_(t,e,r,n,i);break e}else for(cn=ci(e.stateNode.containerInfo.firstChild),fn=e,Le=!0,Kn=null,n=rx(e,null,r,n),e.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(ea(),r===i){e=zr(t,e,n);break e}Rt(t,e,r,n)}e=e.child}return e;case 5:return ax(e),t===null&&$h(e),r=e.type,i=e.pendingProps,s=t!==null?t.memoizedProps:null,a=i.children,Ih(r,i)?a=null:s!==null&&Ih(r,s)&&(e.flags|=32),Px(t,e),Rt(t,e,a,n),e.child;case 6:return t===null&&$h(e),null;case 13:return $x(t,e,n);case 4:return Lm(e,e.stateNode.containerInfo),r=e.pendingProps,t===null?e.child=ta(e,null,r,n):Rt(t,e,r,n),e.child;case 11:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Bn(r,i),b_(t,e,r,i,n);case 7:return Rt(t,e,e.pendingProps,n),e.child;case 8:return Rt(t,e,e.pendingProps.children,n),e.child;case 12:return Rt(t,e,e.pendingProps.children,n),e.child;case 10:e:{if(r=e.type._context,i=e.pendingProps,s=e.memoizedProps,a=i.value,Oe(Ql,r._currentValue),r._currentValue=a,s!==null)if(Qn(s.value,a)){if(s.children===i.children&&!Xt.current){e=zr(t,e,n);break e}}else for(s=e.child,s!==null&&(s.return=e);s!==null;){var o=s.dependencies;if(o!==null){a=s.child;for(var u=o.firstContext;u!==null;){if(u.context===r){if(s.tag===1){u=Nr(-1,n&-n),u.tag=2;var l=s.updateQueue;if(l!==null){l=l.shared;var c=l.pending;c===null?u.next=u:(u.next=c.next,c.next=u),l.pending=u}}s.lanes|=n,u=s.alternate,u!==null&&(u.lanes|=n),Rh(s.return,n,e),o.lanes|=n;break}u=u.next}}else if(s.tag===10)a=s.type===e.type?null:s.child;else if(s.tag===18){if(a=s.return,a===null)throw Error(U(341));a.lanes|=n,o=a.alternate,o!==null&&(o.lanes|=n),Rh(a,n,e),a=s.sibling}else a=s.child;if(a!==null)a.return=s;else for(a=s;a!==null;){if(a===e){a=null;break}if(s=a.sibling,s!==null){s.return=a.return,a=s;break}a=a.return}s=a}Rt(t,e,i.children,n),e=e.child}return e;case 9:return i=e.type,r=e.pendingProps.children,qs(e,n),i=In(i),r=r(i),e.flags|=1,Rt(t,e,r,n),e.child;case 14:return r=e.type,i=Bn(r,e.pendingProps),i=Bn(r.type,i),x_(t,e,r,i,n);case 15:return Ox(t,e,e.type,e.pendingProps,n);case 17:return r=e.type,i=e.pendingProps,i=e.elementType===r?i:Bn(r,i),ml(t,e),e.tag=1,Qt(r)?(t=!0,Gl(e)):t=!1,qs(e,n),Ex(e,r,i),Lh(e,r,i,n),Dh(null,e,r,!0,t,n);case 19:return Rx(t,e,n);case 22:return Cx(t,e,n)}throw Error(U(156,e.tag))};function Jx(t,e){return kb(t,e)}function SC(t,e,n,r){this.tag=t,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=e,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function An(t,e,n,r){return new SC(t,e,n,r)}function Xm(t){return t=t.prototype,!(!t||!t.isReactComponent)}function AC(t){if(typeof t=="function")return Xm(t)?1:0;if(t!=null){if(t=t.$$typeof,t===gm)return 11;if(t===ym)return 14}return 2}function pi(t,e){var n=t.alternate;return n===null?(n=An(t.tag,e,t.key,t.mode),n.elementType=t.elementType,n.type=t.type,n.stateNode=t.stateNode,n.alternate=t,t.alternate=n):(n.pendingProps=e,n.type=t.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=t.flags&14680064,n.childLanes=t.childLanes,n.lanes=t.lanes,n.child=t.child,n.memoizedProps=t.memoizedProps,n.memoizedState=t.memoizedState,n.updateQueue=t.updateQueue,e=t.dependencies,n.dependencies=e===null?null:{lanes:e.lanes,firstContext:e.firstContext},n.sibling=t.sibling,n.index=t.index,n.ref=t.ref,n}function _l(t,e,n,r,i,s){var a=2;if(r=t,typeof t=="function")Xm(t)&&(a=1);else if(typeof t=="string")a=5;else e:switch(t){case Ss:return Xi(n.children,i,s,e);case mm:a=8,i|=8;break;case ah:return t=An(12,n,e,i|2),t.elementType=ah,t.lanes=s,t;case oh:return t=An(13,n,e,i),t.elementType=oh,t.lanes=s,t;case uh:return t=An(19,n,e,i),t.elementType=uh,t.lanes=s,t;case ab:return rd(n,i,s,e);default:if(typeof t=="object"&&t!==null)switch(t.$$typeof){case ib:a=10;break e;case sb:a=9;break e;case gm:a=11;break e;case ym:a=14;break e;case Qr:a=16,r=null;break e}throw Error(U(130,t==null?t:typeof t,""))}return e=An(a,n,e,i),e.elementType=t,e.type=r,e.lanes=s,e}function Xi(t,e,n,r){return t=An(7,t,r,e),t.lanes=n,t}function rd(t,e,n,r){return t=An(22,t,r,e),t.elementType=ab,t.lanes=n,t.stateNode={isHidden:!1},t}function hf(t,e,n){return t=An(6,t,null,e),t.lanes=n,t}function pf(t,e,n){return e=An(4,t.children!==null?t.children:[],t.key,e),e.lanes=n,e.stateNode={containerInfo:t.containerInfo,pendingChildren:null,implementation:t.implementation},e}function EC(t,e,n,r,i){this.tag=e,this.containerInfo=t,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=qd(0),this.expirationTimes=qd(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=qd(0),this.identifierPrefix=r,this.onRecoverableError=i,this.mutableSourceEagerHydrationData=null}function Qm(t,e,n,r,i,s,a,o,u){return t=new EC(t,e,n,o,u),e===1?(e=1,s===!0&&(e|=8)):e=0,s=An(3,null,null,e),t.current=s,s.stateNode=t,s.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},jm(s),t}function TC(t,e,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:ks,key:r==null?null:""+r,children:t,containerInfo:e,implementation:n}}function Xx(t){if(!t)return bi;t=t._reactInternals;e:{if(us(t)!==t||t.tag!==1)throw Error(U(170));var e=t;do{switch(e.tag){case 3:e=e.stateNode.context;break e;case 1:if(Qt(e.type)){e=e.stateNode.__reactInternalMemoizedMergedChildContext;break e}}e=e.return}while(e!==null);throw Error(U(171))}if(t.tag===1){var n=t.type;if(Qt(n))return Xb(t,n,e)}return e}function Qx(t,e,n,r,i,s,a,o,u){return t=Qm(n,r,!0,t,i,s,a,o,u),t.context=Xx(null),n=t.current,r=Mt(),i=hi(n),s=Nr(r,i),s.callback=e??null,di(n,s,i),t.current.lanes=i,nu(t,i,r),Yt(t,r),t}function id(t,e,n,r){var i=e.current,s=Mt(),a=hi(i);return n=Xx(n),e.context===null?e.context=n:e.pendingContext=n,e=Nr(s,a),e.payload={element:t},r=r===void 0?null:r,r!==null&&(e.callback=r),t=di(i,e,a),t!==null&&(Gn(t,i,a,s),fl(t,i,a)),a}function uc(t){if(t=t.current,!t.child)return null;switch(t.child.tag){case 5:return t.child.stateNode;default:return t.child.stateNode}}function R_(t,e){if(t=t.memoizedState,t!==null&&t.dehydrated!==null){var n=t.retryLane;t.retryLane=n!==0&&n<e?n:e}}function Ym(t,e){R_(t,e),(t=t.alternate)&&R_(t,e)}function IC(){return null}var Yx=typeof reportError=="function"?reportError:function(t){console.error(t)};function eg(t){this._internalRoot=t}sd.prototype.render=eg.prototype.render=function(t){var e=this._internalRoot;if(e===null)throw Error(U(409));id(t,e,null,null)};sd.prototype.unmount=eg.prototype.unmount=function(){var t=this._internalRoot;if(t!==null){this._internalRoot=null;var e=t.containerInfo;rs(function(){id(null,t,null,null)}),e[Lr]=null}};function sd(t){this._internalRoot=t}sd.prototype.unstable_scheduleHydration=function(t){if(t){var e=Cb();t={blockedOn:null,target:t,priority:e};for(var n=0;n<ri.length&&e!==0&&e<ri[n].priority;n++);ri.splice(n,0,t),n===0&&Nb(t)}};function tg(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)}function ad(t){return!(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11&&(t.nodeType!==8||t.nodeValue!==" react-mount-point-unstable "))}function j_(){}function OC(t,e,n,r,i){if(i){if(typeof r=="function"){var s=r;r=function(){var l=uc(a);s.call(l)}}var a=Qx(e,r,t,0,null,!1,!1,"",j_);return t._reactRootContainer=a,t[Lr]=a.current,Co(t.nodeType===8?t.parentNode:t),rs(),a}for(;i=t.lastChild;)t.removeChild(i);if(typeof r=="function"){var o=r;r=function(){var l=uc(u);o.call(l)}}var u=Qm(t,0,!1,null,null,!1,!1,"",j_);return t._reactRootContainer=u,t[Lr]=u.current,Co(t.nodeType===8?t.parentNode:t),rs(function(){id(e,u,n,r)}),u}function od(t,e,n,r,i){var s=n._reactRootContainer;if(s){var a=s;if(typeof i=="function"){var o=i;i=function(){var u=uc(a);o.call(u)}}id(e,a,t,i)}else a=OC(n,e,t,i,r);return uc(a)}Ib=function(t){switch(t.tag){case 3:var e=t.stateNode;if(e.current.memoizedState.isDehydrated){var n=Fa(e.pendingLanes);n!==0&&(wm(e,n|1),Yt(e,We()),!(he&6)&&(ia=We()+500,Pi()))}break;case 13:rs(function(){var r=Mr(t,1);if(r!==null){var i=Mt();Gn(r,t,1,i)}}),Ym(t,1)}};bm=function(t){if(t.tag===13){var e=Mr(t,134217728);if(e!==null){var n=Mt();Gn(e,t,134217728,n)}Ym(t,134217728)}};Ob=function(t){if(t.tag===13){var e=hi(t),n=Mr(t,e);if(n!==null){var r=Mt();Gn(n,t,e,r)}Ym(t,e)}};Cb=function(){return Ae};Pb=function(t,e){var n=Ae;try{return Ae=t,e()}finally{Ae=n}};_h=function(t,e,n){switch(e){case"input":if(dh(t,n),e=n.name,n.type==="radio"&&e!=null){for(n=t;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll("input[name="+JSON.stringify(""+e)+'][type="radio"]'),e=0;e<n.length;e++){var r=n[e];if(r!==t&&r.form===t.form){var i=Xc(r);if(!i)throw Error(U(90));ub(r),dh(r,i)}}}break;case"textarea":cb(t,n);break;case"select":e=n.value,e!=null&&Hs(t,!!n.multiple,e,!1)}};yb=Wm;_b=rs;var CC={usingClientEntryPoint:!1,Events:[iu,Is,Xc,mb,gb,Wm]},$a={findFiberByHostInstance:Zi,bundleType:0,version:"18.3.1",rendererPackageName:"react-dom"},PC={bundleType:$a.bundleType,version:$a.version,rendererPackageName:$a.rendererPackageName,rendererConfig:$a.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:Hr.ReactCurrentDispatcher,findHostInstanceByFiber:function(t){return t=bb(t),t===null?null:t.stateNode},findFiberByHostInstance:$a.findFiberByHostInstance||IC,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1-next-f1338f8080-20240426"};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<"u"){var Nu=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Nu.isDisabled&&Nu.supportsFiber)try{qc=Nu.inject(PC),yr=Nu}catch{}}gn.__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED=CC;gn.createPortal=function(t,e){var n=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!tg(e))throw Error(U(200));return TC(t,e,null,n)};gn.createRoot=function(t,e){if(!tg(t))throw Error(U(299));var n=!1,r="",i=Yx;return e!=null&&(e.unstable_strictMode===!0&&(n=!0),e.identifierPrefix!==void 0&&(r=e.identifierPrefix),e.onRecoverableError!==void 0&&(i=e.onRecoverableError)),e=Qm(t,1,!1,null,null,n,!1,r,i),t[Lr]=e.current,Co(t.nodeType===8?t.parentNode:t),new eg(e)};gn.findDOMNode=function(t){if(t==null)return null;if(t.nodeType===1)return t;var e=t._reactInternals;if(e===void 0)throw typeof t.render=="function"?Error(U(188)):(t=Object.keys(t).join(","),Error(U(268,t)));return t=bb(e),t=t===null?null:t.stateNode,t};gn.flushSync=function(t){return rs(t)};gn.hydrate=function(t,e,n){if(!ad(e))throw Error(U(200));return od(null,t,e,!0,n)};gn.hydrateRoot=function(t,e,n){if(!tg(t))throw Error(U(405));var r=n!=null&&n.hydratedSources||null,i=!1,s="",a=Yx;if(n!=null&&(n.unstable_strictMode===!0&&(i=!0),n.identifierPrefix!==void 0&&(s=n.identifierPrefix),n.onRecoverableError!==void 0&&(a=n.onRecoverableError)),e=Qx(e,null,t,1,n??null,i,!1,s,a),t[Lr]=e.current,Co(t),r)for(t=0;t<r.length;t++)n=r[t],i=n._getVersion,i=i(n._source),e.mutableSourceEagerHydrationData==null?e.mutableSourceEagerHydrationData=[n,i]:e.mutableSourceEagerHydrationData.push(n,i);return new sd(e)};gn.render=function(t,e,n){if(!ad(e))throw Error(U(200));return od(null,t,e,!1,n)};gn.unmountComponentAtNode=function(t){if(!ad(t))throw Error(U(40));return t._reactRootContainer?(rs(function(){od(null,null,t,!1,function(){t._reactRootContainer=null,t[Lr]=null})}),!0):!1};gn.unstable_batchedUpdates=Wm;gn.unstable_renderSubtreeIntoContainer=function(t,e,n,r){if(!ad(n))throw Error(U(200));if(t==null||t._reactInternals===void 0)throw Error(U(38));return od(t,e,n,!1,r)};gn.version="18.3.1-next-f1338f8080-20240426";function e1(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e1)}catch(t){console.error(t)}}e1(),eb.exports=gn;var NC=eb.exports,t1,L_=NC;t1=L_.createRoot,L_.hydrateRoot;/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var $C={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RC=t=>t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase().trim(),fe=(t,e)=>{const n=je.forwardRef(({color:r="currentColor",size:i=24,strokeWidth:s=2,absoluteStrokeWidth:a,className:o="",children:u,...l},c)=>je.createElement("svg",{ref:c,...$C,width:i,height:i,stroke:r,strokeWidth:a?Number(s)*24/Number(i):s,className:["lucide",`lucide-${RC(t)}`,o].join(" "),...l},[...e.map(([d,f])=>je.createElement(d,f)),...Array.isArray(u)?u:[u]]));return n.displayName=`${t}`,n};/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Do=fe("Activity",[["path",{d:"M22 12h-4l-3 9L9 3l-3 9H2",key:"d5dnw9"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jC=fe("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LC=fe("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n1=fe("Award",[["circle",{cx:"12",cy:"8",r:"6",key:"1vp47v"}],["path",{d:"M15.477 12.89 17 22l-5-3-5 3 1.523-9.11",key:"em7aur"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sa=fe("BarChart3",[["path",{d:"M3 3v18h18",key:"1s2lah"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MC=fe("BookOpen",[["path",{d:"M2 3h6a4 4 0 0 1 4 4v14a3 3 0 0 0-3-3H2z",key:"vv98re"}],["path",{d:"M22 3h-6a4 4 0 0 0-4 4v14a3 3 0 0 1 3-3h7z",key:"1cyq3y"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vl=fe("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zC=fe("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M_=fe("Briefcase",[["rect",{width:"20",height:"14",x:"2",y:"7",rx:"2",ry:"2",key:"eto64e"}],["path",{d:"M16 21V5a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"zwj3tp"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DC=fe("CheckCircle",[["path",{d:"M22 11.08V12a10 10 0 1 1-5.93-9.14",key:"g774vq"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UC=fe("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FC=fe("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xh=fe("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BC=fe("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HC=fe("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZC=fe("GraduationCap",[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VC=fe("Home",[["path",{d:"m3 9 9-7 9 7v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"y5dka4"}],["polyline",{points:"9 22 9 12 15 12 15 22",key:"e2us08"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KC=fe("Linkedin",[["path",{d:"M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z",key:"c2jq9f"}],["rect",{width:"4",height:"12",x:"2",y:"9",key:"mk3on5"}],["circle",{cx:"4",cy:"4",r:"2",key:"bt5ra8"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qC=fe("Loader2",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ng=fe("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const r1=fe("MapPin",[["path",{d:"M20 10c0 6-8 12-8 12s-8-6-8-12a8 8 0 0 1 16 0Z",key:"2oe9fu"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WC=fe("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GC=fe("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JC=fe("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const po=fe("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XC=fe("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QC=fe("Send",[["path",{d:"m22 2-7 20-4-9-9-4Z",key:"1q3vgg"}],["path",{d:"M22 2 11 13",key:"nzbqef"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YC=fe("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eP=fe("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tP=fe("Star",[["polygon",{points:"12 2 15.09 8.26 22 9.27 17 14.14 18.18 21.02 12 17.77 5.82 21.02 7 14.14 2 9.27 8.91 8.26 12 2",key:"8f66p6"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const i1=fe("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const va=fe("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const s1=fe("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rg=fe("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lc=fe("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nP=fe("Youtube",[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]]);/** * @license lucide-react v0.344.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a1=fe("Zap",[["polygon",{points:"13 2 3 14 12 14 11 22 21 10 12 10 13 2",key:"45s27k"}]]),rP=()=>{const[t,e]=je.useState(!1),[n,r]=je.useState("home");je.useEffect(()=>{const o=()=>{const l=["home","about","services","portfolio","dashboard","team","contact"].find(c=>{const d=document.getElementById(c);if(d){const f=d.getBoundingClientRect();return f.top<=100&&f.bottom>100}return!1});l&&r(l)};return window.addEventListener("scroll",o),()=>window.removeEventListener("scroll",o)},[]);const i=o=>{const u=document.getElementById(o);u&&u.scrollIntoView({behavior:"smooth"}),e(!1)},s=[{id:"home",label:"Home",icon:VC},{id:"about",label:"About",icon:s1},{id:"services",label:"Services",icon:M_},{id:"portfolio",label:"Features",icon:va},{id:"dashboard",label:"Live Demo",icon:Do},{id:"team",label:"Team",icon:rg},{id:"contact",label:"Contact",icon:ng}],a=[{name:"Upwork",url:"https://www.upwork.com/freelancers/~0105706470b53c8f2e?viewMode=1",icon:M_,color:"hover:text-green-600"},{name:"LinkedIn",url:"https://www.linkedin.com/in/satyapal-singh-a50308247",icon:KC,color:"hover:text-blue-600"},{name:"Udemy",url:"https://www.udemy.com/user/satyapal-singh-132/",icon:ZC,color:"hover:text-purple-600"},{name:"YouTube",url:"https://www.youtube.com/@kimblylabs7137",icon:nP,color:"hover:text-red-600"}];return w.jsxs("header",{className:"fixed top-0 left-0 right-0 z-50 bg-white/95 backdrop-blur-md border-b border-gray-200/50 shadow-sm",children:[w.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:w.jsxs("div",{className:"flex justify-between items-center h-16",children:[w.jsx("div",{className:"flex-shrink-0",children:w.jsxs("div",{className:"text-2xl font-bold",children:[w.jsx("span",{className:"text-blue-900",children:"Kimbly"}),w.jsx("span",{className:"text-emerald-600",children:"Labs"})]})}),w.jsx("nav",{className:"hidden md:flex space-x-8",children:s.map(o=>{const u=o.icon;return w.jsxs("button",{onClick:()=>i(o.id),className:`flex items-center space-x-2 px-3 py-2 rounded-lg transition-all duration-200 ${n===o.id?"text-emerald-600 bg-emerald-50":"text-gray-600 hover:text-emerald-600 hover:bg-gray-50"}`,children:[w.jsx(u,{className:"h-4 w-4"}),w.jsx("span",{className:"font-medium",children:o.label})]},o.id)})}),w.jsxs("div",{className:"flex items-center space-x-4",children:[w.jsx("div",{className:"hidden lg:flex items-center space-x-3",children:a.map(o=>{const u=o.icon;return w.jsx("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:`p-2 rounded-lg text-gray-600 ${o.color} transition-all duration-200 hover:bg-gray-50`,"aria-label":o.name,children:w.jsx(u,{className:"h-5 w-5"})},o.name)})}),w.jsx("div",{className:"md:hidden",children:w.jsx("button",{onClick:()=>e(!t),className:"text-gray-600 hover:text-emerald-600 transition-colors duration-200",children:t?w.jsx(lc,{className:"h-6 w-6"}):w.jsx(WC,{className:"h-6 w-6"})})})]})]})}),t&&w.jsx("div",{className:"md:hidden bg-white/95 backdrop-blur-md border-t border-gray-200/50",children:w.jsxs("div",{className:"px-2 pt-2 pb-3 space-y-1",children:[s.map(o=>{const u=o.icon;return w.jsxs("button",{onClick:()=>i(o.id),className:`flex items-center space-x-3 w-full px-3 py-2 rounded-lg transition-all duration-200 ${n===o.id?"text-emerald-600 bg-emerald-50":"text-gray-600 hover:text-emerald-600 hover:bg-gray-50"}`,children:[w.jsx(u,{className:"h-5 w-5"}),w.jsx("span",{className:"font-medium",children:o.label})]},o.id)}),w.jsxs("div",{className:"pt-4 border-t border-gray-200",children:[w.jsx("div",{className:"px-3 py-2",children:w.jsx("span",{className:"text-sm font-medium text-gray-500",children:"Follow Us"})}),w.jsx("div",{className:"flex items-center justify-center space-x-4 px-3 py-2",children:a.map(o=>{const u=o.icon;return w.jsx("a",{href:o.url,target:"_blank",rel:"noopener noreferrer",className:`p-2 rounded-lg text-gray-600 ${o.color} transition-all duration-200 hover:bg-gray-50`,"aria-label":o.name,children:w.jsx(u,{className:"h-5 w-5"})},o.name)})})]})]})})]})},iP=()=>{const[t,e]=je.useState({sp500:4850.25,nasdaq:15420.3,dow:38250.75,vix:18.45}),[n,r]=je.useState({totalClients:0,successRate:0,activeStrategies:0,yearsExperience:0});je.useEffect(()=>{const a=setInterval(()=>{e(u=>({sp500:u.sp500+(Math.random()-.5)*10,nasdaq:u.nasdaq+(Math.random()-.5)*50,dow:u.dow+(Math.random()-.5)*30,vix:Math.max(10,u.vix+(Math.random()-.5)*2)}))},2e3),o=(u,l)=>{let c=0;const d=u/100,f=setInterval(()=>{c+=d,c>=u&&(c=u,clearInterval(f)),r(h=>({...h,[l]:Math.floor(c)}))},30)};return o(500,"totalClients"),o(95,"successRate"),o(50,"activeStrategies"),o(10,"yearsExperience"),()=>clearInterval(a)},[]);const i=()=>{const a=document.getElementById("about");a&&a.scrollIntoView({behavior:"smooth"})},s=()=>{const a=document.getElementById("services");a&&a.scrollIntoView({behavior:"smooth"})};return w.jsxs("section",{id:"home",className:"relative min-h-screen flex items-center justify-center overflow-hidden bg-white",children:[w.jsxs("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-50 via-white to-blue-50/30",children:[w.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,rgba(14,165,233,0.05),transparent_50%)]"}),w.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_70%_80%,rgba(16,185,129,0.05),transparent_50%)]"})]}),w.jsx("div",{className:"absolute top-16 left-0 right-0 bg-slate-900 text-white py-3 overflow-hidden border-b border-slate-800",children:w.jsx("div",{className:"flex animate-scroll whitespace-nowrap",children:w.jsxs("div",{className:"flex space-x-12 text-sm font-medium",children:[w.jsxs("span",{className:"flex items-center space-x-2",children:[w.jsx("span",{className:"text-slate-400",children:"S&P 500:"}),w.jsxs("span",{className:t.sp500>4850?"text-emerald-400":"text-red-400",children:["$",t.sp500.toFixed(2)]}),w.jsx("span",{className:`text-xs ${t.sp500>4850?"text-emerald-400":"text-red-400"}`,children:t.sp500>4850?"↗":"↘"})]}),w.jsxs("span",{className:"flex items-center space-x-2",children:[w.jsx("span",{className:"text-slate-400",children:"NASDAQ:"}),w.jsxs("span",{className:t.nasdaq>15420?"text-emerald-400":"text-red-400",children:["$",t.nasdaq.toFixed(2)]}),w.jsx("span",{className:`text-xs ${t.nasdaq>15420?"text-emerald-400":"text-red-400"}`,children:t.nasdaq>15420?"↗":"↘"})]}),w.jsxs("span",{className:"flex items-center space-x-2",children:[w.jsx("span",{className:"text-slate-400",children:"DOW:"}),w.jsxs("span",{className:t.dow>38250?"text-emerald-400":"text-red-400",children:["$",t.dow.toFixed(2)]}),w.jsx("span",{className:`text-xs ${t.dow>38250?"text-emerald-400":"text-red-400"}`,children:t.dow>38250?"↗":"↘"})]}),w.jsxs("span",{className:"flex items-center space-x-2",children:[w.jsx("span",{className:"text-slate-400",children:"VIX:"}),w.jsx("span",{className:t.vix<20?"text-emerald-400":"text-red-400",children:t.vix.toFixed(2)}),w.jsx("span",{className:`text-xs ${t.vix<20?"text-emerald-400":"text-red-400"}`,children:t.vix<20?"↘":"↗"})]})]})})}),w.jsxs("div",{className:"relative z-10 text-center px-4 sm:px-6 lg:px-8 max-w-6xl mx-auto mt-20",children:[w.jsx("div",{className:"flex justify-center mb-8",children:w.jsxs("div",{className:"flex items-center space-x-3 px-6 py-3 bg-white/80 backdrop-blur-sm rounded-full border border-slate-200/50 shadow-lg",children:[w.jsx("div",{className:"w-2 h-2 bg-emerald-500 rounded-full animate-pulse"}),w.jsx("span",{className:"text-slate-700 text-sm font-medium",children:"Live Trading Solutions"}),w.jsx(Do,{className:"h-4 w-4 text-emerald-600"})]})}),w.jsx("div",{className:"mb-8",children:w.jsxs("h1",{className:"text-5xl md:text-7xl lg:text-8xl font-bold leading-[1.1] pb-4",children:[w.jsx("span",{className:"block bg-gradient-to-r from-teal-600 via-blue-600 to-indigo-600 bg-clip-text text-transparent pb-2",children:"Algorithmic Trading"}),w.jsx("span",{className:"block text-slate-800 mt-2",children:"Solutions"})]})}),w.jsx("p",{className:"text-xl md:text-2xl text-slate-600 mb-12 leading-relaxed max-w-4xl mx-auto font-light",children:"Advanced algorithmic trading solutions for modern traders. Specializing in strategy backtesting, trading bots,market scanners and consultancy."}),w.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-center gap-6 mb-16",children:[w.jsxs("button",{onClick:i,className:"group bg-gradient-to-r from-teal-600 to-blue-600 text-white px-8 py-4 rounded-xl font-semibold transition-all duration-300 hover:scale-105 hover:shadow-2xl flex items-center space-x-3 min-w-[200px]",children:[w.jsx("span",{children:"Get Started"}),w.jsx(jC,{className:"h-5 w-5 group-hover:translate-x-1 transition-transform duration-300"})]}),w.jsxs("button",{onClick:s,className:"group bg-white/90 backdrop-blur-sm text-slate-800 px-8 py-4 rounded-xl font-semibold border border-slate-200 transition-all duration-300 hover:bg-slate-50 hover:border-slate-300 hover:shadow-xl flex items-center space-x-3 min-w-[200px]",children:[w.jsx(sa,{className:"h-5 w-5 group-hover:text-teal-600 transition-colors duration-300"}),w.jsx("span",{children:"View Services"})]})]}),w.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-6 max-w-5xl mx-auto",children:[w.jsxs("div",{className:"bg-white/70 backdrop-blur-sm rounded-2xl p-6 border border-slate-200/50 shadow-lg hover:shadow-xl transition-all duration-300",children:[w.jsx("div",{className:"flex items-center justify-center mb-3",children:w.jsx("div",{className:"w-12 h-12 bg-gradient-to-r from-emerald-500 to-teal-500 rounded-xl flex items-center justify-center",children:w.jsx(HC,{className:"h-6 w-6 text-white"})})}),w.jsxs("div",{className:"text-3xl font-bold text-slate-800 mb-2",children:[n.totalClients,"+"]}),w.jsx("div",{className:"text-slate-600 text-sm font-medium",children:"Happy Clients"})]}),w.jsxs("div",{className:"bg-white/70 backdrop-blur-sm rounded-2xl p-6 border border-slate-200/50 shadow-lg hover:shadow-xl transition-all duration-300",children:[w.jsx("div",{className:"flex items-center justify-center mb-3",children:w.jsx("div",{className:"w-12 h-12 bg-gradient-to-r from-blue-500 to-indigo-500 rounded-xl flex items-center justify-center",children:w.jsx(i1,{className:"h-6 w-6 text-white"})})}),w.jsxs("div",{className:"text-3xl font-bold text-slate-800 mb-2",children:[n.successRate,"%"]}),w.jsx("div",{className:"text-slate-600 text-sm font-medium",children:"Success Rate"})]}),w.jsxs("div",{className:"bg-white/70 backdrop-blur-sm rounded-2xl p-6 border border-slate-200/50 shadow-lg hover:shadow-xl transition-all duration-300",children:[w.jsx("div",{className:"flex items-center justify-center mb-3",children:w.jsx("div",{className:"w-12 h-12 bg-gradient-to-r from-orange-500 to-red-500 rounded-xl flex items-center justify-center",children:w.jsx(a1,{className:"h-6 w-6 text-white"})})}),w.jsxs("div",{className:"text-3xl font-bold text-slate-800 mb-2",children:[n.activeStrategies,"+"]}),w.jsx("div",{className:"text-slate-600 text-sm font-medium",children:"Bots"})]}),w.jsxs("div",{className:"bg-white/70 backdrop-blur-sm rounded-2xl p-6 border border-slate-200/50 shadow-lg hover:shadow-xl transition-all duration-300",children:[w.jsx("div",{className:"flex items-center justify-center mb-3",children:w.jsx("div",{className:"w-12 h-12 bg-gradient-to-r from-purple-500 to-pink-500 rounded-xl flex items-center justify-center",children:w.jsx(Do,{className:"h-6 w-6 text-white"})})}),w.jsxs("div",{className:"text-3xl font-bold text-slate-800 mb-2",children:[n.yearsExperience,"+"]}),w.jsx("div",{className:"text-slate-600 text-sm font-medium",children:"Years Experience"})]})]})]}),w.jsx("div",{className:"absolute bottom-8 left-1/2 transform -translate-x-1/2",children:w.jsx("button",{onClick:i,className:"animate-bounce text-slate-400 hover:text-teal-600 transition-colors duration-300",children:w.jsx(UC,{className:"h-8 w-8"})})})]})},sP=()=>w.jsx("section",{id:"about",className:"py-20 bg-gray-50",children:w.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[w.jsxs("div",{className:"text-center mb-16",children:[w.jsxs("h2",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:["About ",w.jsx("span",{className:"text-emerald-600",children:"Kimbly Labs"})]}),w.jsx("p",{className:"text-xl text-gray-600 max-w-3xl mx-auto",children:"Advanced algorithmic trading solutions for modern traders. Technology-driven company specializing in Algorithmic Trading, Data Science, HRMS, and Hospitality Solutions."})]}),w.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center",children:[w.jsxs("div",{children:[w.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-6",children:"Our Story"}),w.jsxs("div",{className:"space-y-4 text-gray-600",children:[w.jsx("p",{children:"Kimbly Labs is a technology-driven company specializing in Algorithmic Trading, Data Science, HRMS, and Hospitality Solutions. With over a decade of experience, we have developed business-critical applications for clients in India and abroad, including renowned brands."}),w.jsx("p",{children:"Founded by seasoned traders and software engineers, we understand the complexities of modern trading and strive to simplify them. Our team combines deep market knowledge with cutting-edge technology to deliver solutions that work."}),w.jsx("p",{children:"We have successfully served clients across various industries, building robust trading systems, analytical tools, and custom applications that drive business growth and operational efficiency."})]})]}),w.jsx("div",{className:"relative",children:w.jsxs("div",{className:"bg-gradient-to-r from-emerald-600 to-blue-600 rounded-2xl p-8 text-white",children:[w.jsx("h4",{className:"text-xl font-bold mb-4",children:"Our Mission"}),w.jsx("p",{className:"mb-6",children:"We are on a mission to democratize algorithmic trading, making professional-grade tools accessible to traders of all levels—whether you're a day trader, swing trader, or long-term investor."}),w.jsxs("div",{className:"flex items-center space-x-4",children:[w.jsx("div",{className:"w-12 h-12 bg-white/20 rounded-full flex items-center justify-center",children:w.jsx(sa,{className:"h-6 w-6"})}),w.jsxs("div",{children:[w.jsx("div",{className:"font-semibold",children:"Performance & Reliability"}),w.jsx("div",{className:"text-white/80 text-sm",children:"Your trusted partner in financial markets"})]})]})]})})]})]})}),aP=()=>{const t=[{icon:sa,title:"Strategy Backtesting",description:"Test your trading strategies against historical data to validate performance before risking real capital.",features:["Customized backtesting code","Ultra fast backtesting","Parameter optimization","Detailed analytics & metrics"]},{icon:vl,title:"Trading Bot Creation",description:"Custom-built algorithmic trading bots designed to execute your strategies with precision.",features:["24/7 automated trading","Emotion-free execution","Equities & Derivatives","Commodities trading"]},{icon:XC,title:"Market Scanners",description:"Advanced analytical tools to identify market trends, patterns, and potential trading opportunities.",features:["Real-time scanning","Pattern recognition","Trend analysis","Data-driven decisions"]},{icon:rg,title:"Consultancy",description:"Comprehensive algo trading consultancy including technology integration and custom strategy creation.",features:["Technology integration","Custom strategies","Backtesting services","Cloud deployment"]},{icon:MC,title:"Training",description:"Online & offline expert-led courses on strategy development, backtesting techniques, and programming.",features:["Strategy development","Backtesting techniques","Programming skills","Deployment strategies"]},{icon:Xh,title:"Custom Indicators",description:"TradingView indicators customized from Pine Script to Python to identify market patterns.",features:["Pine Script to Python","Pattern identification","Custom indicators","Decision-making tools"]}],e=[{icon:va,title:"Algorithmic Trading",description:"Custom trading bots and automated strategies"},{icon:zC,title:"Artificial Intelligence",description:"Algorithmic Trading & Portfolio Optimization"},{icon:sa,title:"Data Science",description:"Advanced analytics and machine learning solutions"},{icon:Xh,title:"HRMS Solutions",description:"Human resource management systems"},{icon:BC,title:"Hospitality Solutions",description:"Custom applications for hospitality industry"}];return w.jsx("section",{id:"services",className:"py-20 bg-white",children:w.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[w.jsxs("div",{className:"text-center mb-16",children:[w.jsxs("h2",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:["Our ",w.jsx("span",{className:"text-emerald-600",children:"Services"})]}),w.jsx("p",{className:"text-xl text-gray-600 max-w-3xl mx-auto",children:"Comprehensive algorithmic trading solutions designed for traders of all levels. From strategy development to deployment, we've got you covered."})]}),w.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-8 mb-20",children:t.map((n,r)=>{const i=n.icon;return w.jsxs("div",{className:"group bg-gradient-to-br from-white to-gray-50 rounded-xl p-8 shadow-lg hover:shadow-2xl transition-all duration-300 hover:-translate-y-2 border border-gray-100",children:[w.jsx("div",{className:"bg-gradient-to-r from-emerald-600 to-blue-600 w-16 h-16 rounded-xl flex items-center justify-center mb-6 group-hover:scale-110 transition-transform duration-300",children:w.jsx(i,{className:"h-8 w-8 text-white"})}),w.jsx("h3",{className:"text-xl font-bold text-gray-900 mb-3",children:n.title}),w.jsx("p",{className:"text-gray-600 mb-6",children:n.description}),w.jsx("ul",{className:"space-y-2",children:n.features.map((s,a)=>w.jsxs("li",{className:"flex items-center text-sm text-gray-600",children:[w.jsx("div",{className:"w-1.5 h-1.5 bg-emerald-600 rounded-full mr-3"}),s]},a))})]},r)})}),w.jsxs("div",{className:"text-center mb-12",children:[w.jsx("h3",{className:"text-3xl font-bold text-gray-900 mb-4",children:"Industries"}),w.jsx("p",{className:"text-lg text-gray-600 max-w-2xl mx-auto",children:"We serve clients across various industries with specialized solutions"})]}),w.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-6",children:e.map((n,r)=>{const i=n.icon;return w.jsxs("div",{className:"text-center p-6 bg-white rounded-xl shadow-lg hover:shadow-xl transition-all duration-300 border border-gray-100",children:[w.jsx("div",{className:"w-16 h-16 bg-gradient-to-r from-emerald-600 to-blue-600 rounded-xl flex items-center justify-center mx-auto mb-4",children:w.jsx(i,{className:"h-8 w-8 text-white"})}),w.jsx("h4",{className:"font-semibold text-gray-900 mb-2",children:n.title}),w.jsx("p",{className:"text-sm text-gray-600",children:n.description})]},r)})})]})})},oP=()=>{const[t,e]=je.useState("all"),n=[{id:1,title:"High Accuracy",category:"performance",description:"Advanced algorithms designed for precision trading in any market condition.",icon:i1,highlight:"Advanced Algorithms",image:"https://images.pexels.com/photos/590022/pexels-photo-590022.jpeg?auto=compress&cs=tinysrgb&w=800",benefits:["Precision trading","Market adaptability","Consistent performance","Risk optimization"]},{id:2,title:"Multi-Platform Integration",category:"integration",description:"Seamless integration with major exchanges and trading platforms worldwide.",icon:sa,highlight:"Universal Compatibility",image:"https://images.pexels.com/photos/730547/pexels-photo-730547.jpeg?auto=compress&cs=tinysrgb&w=800",benefits:["Major exchanges","Multiple platforms","Easy integration","Global reach"]},{id:3,title:"Real-Time Execution",category:"performance",description:"Low-latency execution system to seize fleeting market opportunities instantly.",icon:a1,highlight:"Lightning Fast",image:"https://res.cloudinary.com/dpciocqjv/image/upload/v1751091055/axblc9jtwpcm3pbbhekd.gif",benefits:["Low latency","Instant execution","Market opportunities","Speed advantage"]},{id:4,title:"Web Based UI",category:"interface",description:"Fast and interactive bot management through intuitive web-based interface.",icon:Do,highlight:"User Friendly",image:"https://images.pexels.com/photos/159888/pexels-photo-159888.jpeg?auto=compress&cs=tinysrgb&w=800",benefits:["Interactive UI","Easy management","Real-time monitoring","Intuitive design"]},{id:5,title:"Bank-Level Security",category:"security",description:"Enterprise-grade encryption ensuring complete protection of your data and assets.",icon:YC,highlight:"Maximum Security",image:"https://images.pexels.com/photos/210607/pexels-photo-210607.jpeg?auto=compress&cs=tinysrgb&w=800",benefits:["Bank-level encryption","Data protection","Asset security","Privacy assured"]},{id:6,title:"Advanced Analytics",category:"analytics",description:"Comprehensive visualizations and performance metrics for informed decision making.",icon:va,highlight:"Data Insights",image:"https://res.cloudinary.com/dpciocqjv/video/upload/v1751091574/nz7j6txjbkv0wrln5xkt.mp4",benefits:["Visual analytics","Performance metrics","Data insights","Smart decisions"],isVideo:!0},{id:7,title:"Cloud Deployment",category:"infrastructure",description:"VPS-based execution ensuring 24/7 uptime and reliable trading operations.",icon:FC,highlight:"24/7 Uptime",image:"https://images.pexels.com/photos/325229/pexels-photo-325229.jpeg?auto=compress&cs=tinysrgb&w=800",benefits:["VPS deployment","24/7 operation","High reliability","Cloud infrastructure"]},{id:8,title:"Mobile Notifications",category:"alerts",description:"Real-time alerts and notifications via Telegram and Pushover for instant updates.",icon:eP,highlight:"Instant Alerts",image:"https://images.pexels.com/photos/607812/pexels-photo-607812.jpeg?auto=compress&cs=tinysrgb&w=800",benefits:["Telegram alerts","Pushover notifications","Real-time updates","Mobile friendly"]}],r=[{id:"all",label:"All Features"},{id:"performance",label:"Performance"},{id:"security",label:"Security"},{id:"integration",label:"Integration"},{id:"analytics",label:"Analytics"}],i=t==="all"?n:n.filter(s=>s.category===t);return w.jsx("section",{id:"portfolio",className:"py-20 bg-gray-50",children:w.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[w.jsxs("div",{className:"text-center mb-16",children:[w.jsxs("h2",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:["Key ",w.jsx("span",{className:"text-emerald-600",children:"Features"})]}),w.jsx("p",{className:"text-xl text-gray-600 max-w-3xl mx-auto mb-8",children:"Discover the powerful features that make Kimbly Labs the preferred choice for algorithmic trading solutions across the globe."}),w.jsx("div",{className:"flex flex-wrap justify-center gap-4",children:r.map(s=>w.jsx("button",{onClick:()=>e(s.id),className:`px-6 py-3 rounded-lg font-medium transition-all duration-300 ${t===s.id?"bg-emerald-600 text-white shadow-lg":"bg-white text-gray-600 hover:bg-emerald-50 hover:text-emerald-600"}`,children:s.label},s.id))})]}),w.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-8",children:i.map(s=>{const a=s.icon;return w.jsxs("div",{className:"group bg-white rounded-xl overflow-hidden shadow-lg hover:shadow-2xl transition-all duration-300 hover:-translate-y-2",children:[w.jsxs("div",{className:"relative overflow-hidden",children:[s.isVideo?w.jsx("video",{src:s.image,autoPlay:!0,loop:!0,muted:!0,playsInline:!0,className:"w-full h-48 object-cover group-hover:scale-110 transition-transform duration-500"}):w.jsx("img",{src:s.image,alt:s.title,className:"w-full h-48 object-cover group-hover:scale-110 transition-transform duration-500"}),w.jsx("div",{className:"absolute top-4 right-4",children:w.jsx("span",{className:"px-3 py-1 rounded-full text-xs font-medium bg-emerald-100 text-emerald-700",children:s.highlight})}),w.jsx("div",{className:"absolute bottom-4 left-4 right-4",children:w.jsxs("div",{className:"flex items-center space-x-2",children:[w.jsx(a,{className:"h-6 w-6 text-white"}),w.jsx("span",{className:"font-bold text-lg text-white",children:s.title})]})})]}),w.jsxs("div",{className:"p-6",children:[w.jsx("p",{className:"text-gray-600 mb-4",children:s.description}),w.jsx("div",{className:"flex flex-wrap gap-2 mb-4",children:s.benefits.map((o,u)=>w.jsx("span",{className:"px-2 py-1 bg-emerald-50 text-emerald-600 text-xs rounded-full",children:o},u))}),w.jsxs("div",{className:"flex items-center justify-between",children:[w.jsxs("div",{className:"flex items-center text-emerald-600 font-medium",children:[w.jsx(Do,{className:"h-4 w-4 mr-2"}),w.jsx("span",{children:"Learn More"})]}),w.jsx(a,{className:"h-5 w-5 text-gray-400"})]})]})]},s.id)})})]})})},uP=()=>w.jsx("section",{id:"team",className:"py-20 bg-white",children:w.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[w.jsxs("div",{className:"text-center mb-16",children:[w.jsxs("h2",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:["Our ",w.jsx("span",{className:"text-emerald-600",children:"Team"})]}),w.jsx("p",{className:"text-xl text-gray-600 max-w-3xl mx-auto",children:"Meet the experienced professionals behind Kimbly Labs' innovative algorithmic trading solutions."})]}),w.jsx("div",{className:"mb-16 flex justify-center",children:w.jsx("div",{className:"relative rounded-2xl overflow-hidden shadow-xl w-full max-w-[60%]",children:w.jsx("img",{src:"/Kimbly Team Edited.png",alt:"Kimbly Labs Team",className:"w-full h-auto object-cover"})})}),w.jsxs("div",{className:"grid md:grid-cols-3 gap-8",children:[w.jsxs("div",{className:"text-center p-6 bg-gray-50 rounded-xl",children:[w.jsx("div",{className:"w-16 h-16 bg-gradient-to-r from-emerald-600 to-blue-600 rounded-xl flex items-center justify-center mx-auto mb-4",children:w.jsx(n1,{className:"h-8 w-8 text-white"})}),w.jsx("h4",{className:"text-xl font-bold text-gray-900 mb-3",children:"Expert Leadership"}),w.jsx("p",{className:"text-gray-600",children:"Led by seasoned traders and software engineers with over a decade of combined experience in financial markets and technology."})]}),w.jsxs("div",{className:"text-center p-6 bg-gray-50 rounded-xl",children:[w.jsx("div",{className:"w-16 h-16 bg-gradient-to-r from-blue-600 to-purple-600 rounded-xl flex items-center justify-center mx-auto mb-4",children:w.jsx(va,{className:"h-8 w-8 text-white"})}),w.jsx("h4",{className:"text-xl font-bold text-gray-900 mb-3",children:"Market Expertise"}),w.jsx("p",{className:"text-gray-600",children:"Deep understanding of market dynamics, trading strategies, and risk management across various asset classes and market conditions."})]}),w.jsxs("div",{className:"text-center p-6 bg-gray-50 rounded-xl",children:[w.jsx("div",{className:"w-16 h-16 bg-gradient-to-r from-purple-600 to-pink-600 rounded-xl flex items-center justify-center mx-auto mb-4",children:w.jsx(Xh,{className:"h-8 w-8 text-white"})}),w.jsx("h4",{className:"text-xl font-bold text-gray-900 mb-3",children:"Technical Excellence"}),w.jsx("p",{className:"text-gray-600",children:"Cutting-edge technology stack and development practices ensure robust, scalable, and high-performance trading solutions."})]})]})]})}),lP=()=>{const t=[{icon:ng,title:"Email Us",detail:"kimblylabs@gmail.com",description:"Get in touch for trading solutions"},{icon:po,title:"Call Us",detail:"+91 9873098686",description:"Mon-Fri 9am to 6pm IST"},{icon:r1,title:"Visit Us",detail:"UG-178, Palam Corporate Plaza, Gurugram",description:"Our Development Center"}],e=[{name:"Sai Krishna Boyina",role:"Head BPA Digital Processes – Operations & Day Trader",message:"Thank you for a wonderful job done. Very clear communication, clarity, and professional service provided... Very prompt in bug fixing too.",rating:5},{name:"Jason Coleman",role:"Trader, United States",message:"Great Work!",rating:5},{name:"Leon Leon",role:"Researcher, United States",message:"Great Experience, looking forward to work again!",rating:5},{name:"Jarvis Jones",role:"Trader, United States",message:"Keep Doing the Great Work!",rating:5}];return w.jsx("section",{id:"contact",className:"py-20 bg-gray-50",children:w.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8",children:[w.jsxs("div",{className:"text-center mb-16",children:[w.jsxs("h2",{className:"text-4xl md:text-5xl font-bold text-gray-900 mb-4",children:["Contact ",w.jsx("span",{className:"text-emerald-600",children:"Us"})]}),w.jsx("p",{className:"text-xl text-gray-600 max-w-3xl mx-auto",children:"Ready to transform your trading with algorithmic solutions? Get in touch with our experts to discuss your requirements."})]}),w.jsxs("div",{className:"grid lg:grid-cols-2 gap-12",children:[w.jsxs("div",{className:"space-y-8",children:[w.jsxs("div",{children:[w.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-6",children:"Get In Touch"}),w.jsx("p",{className:"text-gray-600 mb-8",children:"Our team of experienced developers and traders are ready to help you build the perfect algorithmic trading solution for your needs."})]}),t.map((n,r)=>{const i=n.icon;return w.jsxs("div",{className:"flex items-start space-x-4",children:[w.jsx("div",{className:"bg-gradient-to-r from-emerald-600 to-blue-600 w-12 h-12 rounded-lg flex items-center justify-center flex-shrink-0",children:w.jsx(i,{className:"h-6 w-6 text-white"})}),w.jsxs("div",{children:[w.jsx("h4",{className:"font-semibold text-gray-900 mb-1",children:n.title}),w.jsx("p",{className:"text-emerald-600 font-medium mb-1",children:n.detail}),w.jsx("p",{className:"text-gray-600 text-sm",children:n.description})]})]},r)})]}),w.jsxs("div",{className:"relative",children:[w.jsx("div",{className:"absolute -top-4 -right-4 w-24 h-24 bg-gradient-to-br from-emerald-100 to-blue-100 rounded-full opacity-60"}),w.jsx("div",{className:"absolute top-1/2 -left-6 w-16 h-16 bg-gradient-to-br from-blue-100 to-purple-100 rounded-full opacity-40"}),w.jsx("div",{className:"absolute -bottom-6 right-1/4 w-20 h-20 bg-gradient-to-br from-emerald-50 to-teal-100 rounded-full opacity-50"}),w.jsx("div",{className:"absolute -top-2 left-1/2 transform -translate-x-1/2 w-12 h-12 bg-gradient-to-r from-emerald-500 to-blue-500 rounded-full flex items-center justify-center shadow-lg",children:w.jsx(rg,{className:"h-6 w-6 text-white"})}),w.jsxs("div",{className:"relative bg-gradient-to-br from-white via-gray-50 to-white rounded-2xl p-8 shadow-xl border border-gray-100",children:[w.jsxs("div",{className:"text-center mb-6",children:[w.jsx("h3",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Ready to Get Started?"}),w.jsx("div",{className:"w-16 h-1 bg-gradient-to-r from-emerald-500 to-blue-500 rounded-full mx-auto"})]}),w.jsxs("div",{className:"space-y-6",children:[w.jsxs("div",{className:"bg-gradient-to-r from-emerald-50 to-emerald-100 border border-emerald-200 rounded-xl p-6 relative overflow-hidden",children:[w.jsx("div",{className:"absolute top-0 right-0 w-20 h-20 bg-emerald-200 rounded-full opacity-20 transform translate-x-8 -translate-y-8"}),w.jsxs("div",{className:"relative",children:[w.jsxs("div",{className:"flex items-center space-x-3 mb-4",children:[w.jsx(DC,{className:"h-6 w-6 text-emerald-500"}),w.jsx("span",{className:"text-emerald-700 font-semibold",children:"Free Consultation Available"})]}),w.jsx("p",{className:"text-emerald-600 text-sm",children:"Schedule a free 30-minute consultation to discuss your algorithmic trading requirements and get expert advice."})]})]}),w.jsxs("div",{className:"space-y-4",children:[w.jsxs("div",{className:"flex items-center space-x-2 mb-3",children:[w.jsx(va,{className:"h-5 w-5 text-gray-600"}),w.jsx("h4",{className:"font-semibold text-gray-900",children:"Our Services Include:"})]}),w.jsx("div",{className:"grid grid-cols-2 gap-2",children:["Strategy Backtesting","Trading Bot Creation","Market Scanners","Consultancy","Training","Custom Indicators"].map((n,r)=>w.jsxs("div",{className:"flex items-center text-gray-600 bg-gray-50 rounded-lg px-3 py-2",children:[w.jsx("div",{className:"w-2 h-2 bg-emerald-600 rounded-full mr-2 flex-shrink-0"}),w.jsx("span",{className:"text-sm",children:n})]},r))})]})]})]})]})]}),w.jsxs("div",{className:"pt-8 border-t border-gray-200",children:[w.jsxs("h3",{className:"text-2xl font-bold text-gray-900 mb-6 flex items-center",children:[w.jsx(JC,{className:"h-6 w-6 mr-3 text-emerald-600"}),"Client Testimonials"]}),w.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:e.map((n,r)=>w.jsxs("div",{className:"bg-white p-4 rounded-lg shadow-sm",children:[w.jsx("div",{className:"flex items-center mb-2",children:[...Array(n.rating)].map((i,s)=>w.jsx(tP,{className:"h-4 w-4 text-yellow-400 fill-current"},s))}),w.jsxs("p",{className:"text-gray-600 text-sm mb-2",children:['"',n.message,'"']}),w.jsxs("div",{className:"text-xs text-gray-500",children:[w.jsx("div",{className:"font-medium",children:n.name}),w.jsx("div",{children:n.role})]})]},r))})]})]})})},cP=()=>{const t=()=>{window.scrollTo({top:0,behavior:"smooth"})},e=new Date().getFullYear(),n={Services:["Strategy Backtesting","Trading Bot Creation","Market Scanners","Consultancy","Training","Custom Indicators"],Solutions:["Algorithmic Trading","Artificial Intelligence","Data Science","HRMS Solutions","Hospitality Solutions"],Resources:["Documentation","API Reference","Trainings","Case Studies"],Company:["About Us","Our Team","Careers","Contact Us"]},r=[{name:"Industry Expert",icon:n1},{name:"Proven Track Record",icon:va}];return w.jsx("footer",{className:"bg-gray-900 text-white",children:w.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12",children:[w.jsxs("div",{className:"grid md:grid-cols-2 lg:grid-cols-6 gap-8",children:[w.jsxs("div",{className:"lg:col-span-2",children:[w.jsxs("div",{className:"flex items-center space-x-3 mb-4",children:[w.jsx("div",{className:"w-8 h-8 bg-gradient-to-r from-emerald-400 to-blue-400 rounded-lg flex items-center justify-center",children:w.jsx(sa,{className:"h-5 w-5 text-white"})}),w.jsx("h3",{className:"text-2xl font-bold bg-gradient-to-r from-emerald-400 to-blue-400 bg-clip-text text-transparent",children:"Kimbly Labs"})]}),w.jsx("p",{className:"text-gray-300 mb-6 max-w-md",children:"Advanced algorithmic trading solutions for modern traders. Technology-driven company specializing in Algorithmic Trading, Data Science, HRMS, and Hospitality Solutions."}),w.jsxs("div",{className:"space-y-3 mb-6",children:[w.jsxs("div",{className:"flex items-center space-x-2 text-sm text-gray-400",children:[w.jsx(ng,{className:"h-4 w-4 text-emerald-400"}),w.jsx("span",{children:"kimblylabs@gmail.com"})]}),w.jsxs("div",{className:"flex items-center space-x-2 text-sm text-gray-400",children:[w.jsx(po,{className:"h-4 w-4 text-emerald-400"}),w.jsx("span",{children:"+91 9873098686"})]}),w.jsxs("div",{className:"flex items-start space-x-2 text-sm text-gray-400",children:[w.jsx(r1,{className:"h-4 w-4 text-emerald-400 mt-0.5"}),w.jsx("span",{children:"UG-178, Palam Corporate Plaza, Gurugram"})]})]}),w.jsxs("div",{className:"space-y-3",children:[w.jsx("h4",{className:"font-semibold text-white text-sm",children:"Our Credentials"}),r.map((i,s)=>{const a=i.icon;return w.jsxs("div",{className:"flex items-center space-x-2 text-sm text-gray-400",children:[w.jsx(a,{className:"h-4 w-4 text-emerald-400"}),w.jsx("span",{children:i.name})]},s)})]})]}),Object.entries(n).map(([i,s])=>w.jsxs("div",{children:[w.jsx("h4",{className:"font-semibold text-white mb-4",children:i}),w.jsx("ul",{className:"space-y-3",children:s.map(a=>w.jsx("li",{children:a==="Our Team"?w.jsx("a",{href:"#team",className:"text-gray-400 hover:text-emerald-400 transition-colors duration-200 text-sm",children:a}):a==="Careers"?w.jsx("a",{href:"/files/kimbly-careers.pdf",target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-emerald-400 transition-colors duration-200 text-sm",children:a}):w.jsx("a",{href:"#",className:"text-gray-400 hover:text-emerald-400 transition-colors duration-200 text-sm",children:a})},a))})]},i))]}),w.jsx("div",{className:"border-t border-gray-800 mt-12 pt-8",children:w.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-center",children:[w.jsx("div",{className:"flex items-center space-x-2 text-gray-400 mb-4 md:mb-0",children:w.jsxs("span",{children:["© ",e," Kimbly Labs. All rights reserved."]})}),w.jsxs("div",{className:"flex items-center space-x-4",children:[w.jsx("div",{className:"text-xs text-gray-500",children:"Made with ❤️ in India"}),w.jsx("button",{onClick:t,className:"bg-emerald-600 hover:bg-emerald-700 text-white p-3 rounded-lg transition-colors duration-200","aria-label":"Scroll to top",children:w.jsx(LC,{className:"h-5 w-5"})})]})]})})]})})},dP="+917971442242",fP="+91 7971442242";function hP(){const[t,e]=je.useState(!1);return w.jsxs("div",{className:"fixed bottom-28 right-6 z-50 flex flex-col items-end",children:[t&&w.jsxs("div",{className:"mb-3 bg-white rounded-2xl shadow-2xl border border-gray-100 w-64 overflow-hidden animate-fade-in",children:[w.jsxs("div",{className:"bg-green-500 px-4 py-3 flex items-center justify-between",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx(po,{size:16,className:"text-white"}),w.jsx("span",{className:"text-white font-semibold text-sm",children:"Call Support"})]}),w.jsx("button",{onClick:()=>e(!1),className:"text-white/80 hover:text-white transition-colors",children:w.jsx(lc,{size:16})})]}),w.jsxs("div",{className:"p-4",children:[w.jsx("p",{className:"text-gray-500 text-xs mb-2",children:"Tap to call us directly"}),w.jsxs("a",{href:`tel:${dP}`,className:"flex items-center gap-3 bg-green-50 hover:bg-green-100 border border-green-200 rounded-xl px-4 py-3 transition-colors group",children:[w.jsx("div",{className:"w-9 h-9 bg-green-500 rounded-full flex items-center justify-center flex-shrink-0 group-hover:bg-green-600 transition-colors",children:w.jsx(po,{size:16,className:"text-white"})}),w.jsxs("div",{children:[w.jsx("p",{className:"text-green-700 font-bold text-base",children:fP}),w.jsx("p",{className:"text-gray-400 text-xs",children:"Mon–Fri, 9am–6pm IST"})]})]}),w.jsxs("p",{className:"text-gray-400 text-xs text-center mt-3",children:["Or email us at"," ",w.jsx("a",{href:"mailto:kimblylabs@gmail.com",className:"text-green-600 hover:underline",children:"kimblylabs@gmail.com"})]})]})]}),w.jsx("button",{onClick:()=>e(!t),className:`w-14 h-14 rounded-full shadow-lg flex items-center justify-center transition-all duration-200 ${t?"bg-gray-600 hover:bg-gray-700 rotate-[15deg]":"bg-green-500 hover:bg-green-600 hover:scale-110"}`,"aria-label":"Call support",title:"Call Support",children:w.jsx(po,{size:22,className:"text-white"})})]})}function $u(t,e){return t.lc_error_code=e,t.message=`${t.message} Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/ `,t}function ne(t,e,n,r,i){if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function P(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)}let o1=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return o1=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function Qh(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Yh=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class Y extends Error{}let St=class ep extends Y{constructor(e,n,r,i){super(`${ep.makeMessage(e,n,r)}`),this.status=e,this.headers=i,this.requestID=i==null?void 0:i.get("x-request-id"),this.error=n;const s=n;this.code=s==null?void 0:s.code,this.param=s==null?void 0:s.param,this.type=s==null?void 0:s.type}static makeMessage(e,n,r){const i=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,n,r,i){if(!e||!i)return new ud({message:r,cause:Yh(n)});const s=n==null?void 0:n.error;return e===400?new u1(e,s,r,i):e===401?new l1(e,s,r,i):e===403?new c1(e,s,r,i):e===404?new d1(e,s,r,i):e===409?new f1(e,s,r,i):e===422?new h1(e,s,r,i):e===429?new p1(e,s,r,i):e>=500?new m1(e,s,r,i):new ep(e,s,r,i)}},dn=class extends St{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},ud=class extends St{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}},ld=class extends ud{constructor({message:e}={}){super({message:e??"Request timed out."})}},u1=class extends St{},l1=class extends St{},c1=class extends St{},d1=class extends St{},f1=class extends St{},h1=class extends St{},p1=class extends St{},m1=class extends St{};class g1 extends Y{constructor(){super("Could not parse response content as the length limit was reached")}}class y1 extends Y{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Ha extends Error{constructor(e){super(e)}}class _1 extends St{constructor(e,n,r){let i="OAuth2 authentication error",s;if(n&&typeof n=="object"){const a=n;s=a.error;const o=a.error_description;o&&typeof o=="string"?i=o:s&&(i=s)}super(e,n,i,r),this.error_code=s}}class pP extends Y{constructor(e,n,r){super(e),this.provider=n,this.cause=r}}const mP=/^[a-z][a-z0-9+.-]*:/i,gP=t=>mP.test(t);let Zt=t=>(Zt=Array.isArray,Zt(t)),z_=Zt;function ig(t){return typeof t!="object"?{}:t??{}}function D_(t){if(!t)return!0;for(const e in t)return!1;return!0}function yP(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function mf(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const _P=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Y(`${t} must be an integer`);if(e<0)throw new Y(`${t} must be a positive integer`);return e},vP=t=>{try{return JSON.parse(t)}catch{return}},au=t=>new Promise(e=>setTimeout(e,t)),_s="6.44.0",wP=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function bP(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const xP=()=>{var n;const t=bP();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_s,"X-Stainless-OS":F_(Deno.build.os),"X-Stainless-Arch":U_(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_s,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_s,"X-Stainless-OS":F_(globalThis.process.platform??"unknown"),"X-Stainless-Arch":U_(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=kP();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_s,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":_s,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function kP(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const r=n.exec(navigator.userAgent);if(r){const i=r[1]||0,s=r[2]||0,a=r[3]||0;return{browser:e,version:`${i}.${s}.${a}`}}}return null}const U_=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",F_=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let B_;const SP=()=>B_??(B_=xP());function v1(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function w1(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function b1(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return w1({start(){},async pull(n){const{done:r,value:i}=await e.next();r?n.close():n.enqueue(i)},async cancel(){var n;await((n=e.return)==null?void 0:n.call(e))}})}function x1(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n!=null&&n.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function H_(t){var r,i;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((i=(r=t[Symbol.asyncIterator]()).return)==null?void 0:i.call(r));return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const AP=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),k1="RFC3986",S1=t=>String(t),Z_={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:S1},EP="RFC1738";let tp=(t,e)=>(tp=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),tp(t,e));const ir=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),gf=1024,TP=(t,e,n,r,i)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),n==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let a="";for(let o=0;o<s.length;o+=gf){const u=s.length>=gf?s.slice(o,o+gf):s,l=[];for(let c=0;c<u.length;++c){let d=u.charCodeAt(c);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||i===EP&&(d===40||d===41)){l[l.length]=u.charAt(c);continue}if(d<128){l[l.length]=ir[d];continue}if(d<2048){l[l.length]=ir[192|d>>6]+ir[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=ir[224|d>>12]+ir[128|d>>6&63]+ir[128|d&63];continue}c+=1,d=65536+((d&1023)<<10|u.charCodeAt(c)&1023),l[l.length]=ir[240|d>>18]+ir[128|d>>12&63]+ir[128|d>>6&63]+ir[128|d&63]}a+=l.join("")}return a};function IP(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function V_(t,e){if(Zt(t)){const n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}const A1={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},E1=function(t,e){Array.prototype.push.apply(t,Zt(e)?e:[e])};let K_;const et={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:TP,encodeValuesOnly:!1,format:k1,formatter:S1,indices:!1,serializeDate(t){return(K_??(K_=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function OP(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const yf={};function T1(t,e,n,r,i,s,a,o,u,l,c,d,f,h,m,_,v,y){let p=t,g=y,b=0,E=!1;for(;(g=g.get(yf))!==void 0&&!E;){const N=g.get(t);if(b+=1,typeof N<"u"){if(N===b)throw new RangeError("Cyclic object value");E=!0}typeof g.get(yf)>"u"&&(b=0)}if(typeof l=="function"?p=l(e,p):p instanceof Date?p=f==null?void 0:f(p):n==="comma"&&Zt(p)&&(p=V_(p,function(N){return N instanceof Date?f==null?void 0:f(N):N})),p===null){if(s)return u&&!_?u(e,et.encoder,v,"key",h):e;p=""}if(OP(p)||IP(p)){if(u){const N=_?e:u(e,et.encoder,v,"key",h);return[(m==null?void 0:m(N))+"="+(m==null?void 0:m(u(p,et.encoder,v,"value",h)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(p)))]}const T=[];if(typeof p>"u")return T;let I;if(n==="comma"&&Zt(p))_&&u&&(p=V_(p,u)),I=[{value:p.length>0?p.join(",")||null:void 0}];else if(Zt(l))I=l;else{const N=Object.keys(p);I=c?N.sort(c):N}const k=o?String(e).replace(/\./g,"%2E"):String(e),j=r&&Zt(p)&&p.length===1?k+"[]":k;if(i&&Zt(p)&&p.length===0)return j+"[]";for(let N=0;N<I.length;++N){const L=I[N],ue=typeof L=="object"&&typeof L.value<"u"?L.value:p[L];if(a&&ue===null)continue;const Ee=d&&o?L.replace(/\./g,"%2E"):L,Et=Zt(p)?typeof n=="function"?n(j,Ee):j:j+(d?"."+Ee:"["+Ee+"]");y.set(t,b);const tr=new WeakMap;tr.set(yf,y),E1(T,T1(ue,Et,n,r,i,s,a,o,n==="comma"&&_&&Zt(p)?null:u,l,c,d,f,h,m,_,v,tr))}return T}function CP(t=et){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||et.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=k1;if(typeof t.format<"u"){if(!tp(Z_,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const r=Z_[n];let i=et.filter;(typeof t.filter=="function"||Zt(t.filter))&&(i=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in A1?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=et.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:et.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:et.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:et.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:et.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?et.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:et.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:et.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:et.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:et.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:et.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:et.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:et.strictNullHandling}}function PP(t,e={}){let n=t;const r=CP(e);let i,s;typeof r.filter=="function"?(s=r.filter,n=s("",n)):Zt(r.filter)&&(s=r.filter,i=s);const a=[];if(typeof n!="object"||n===null)return"";const o=A1[r.arrayFormat],u=o==="comma"&&r.commaRoundTrip;i||(i=Object.keys(n)),r.sort&&i.sort(r.sort);const l=new WeakMap;for(let f=0;f<i.length;++f){const h=i[f];r.skipNulls&&n[h]===null||E1(a,T1(n[h],h,o,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}const c=a.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),c.length>0?d+c:""}function NP(t){return PP(t,{arrayFormat:"brackets"})}function $P(t){let e=0;for(const i of t)e+=i.length;const n=new Uint8Array(e);let r=0;for(const i of t)n.set(i,r),r+=i.length;return n}let q_;function sg(t){let e;return(q_??(e=new globalThis.TextEncoder,q_=e.encode.bind(e)))(t)}let W_;function G_(t){let e;return(W_??(e=new globalThis.TextDecoder,W_=e.decode.bind(e)))(t)}var sn,an;class cd{constructor(){sn.set(this,void 0),an.set(this,void 0),ne(this,sn,new Uint8Array),ne(this,an,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?sg(e):e;ne(this,sn,$P([P(this,sn,"f"),n]));const r=[];let i;for(;(i=RP(P(this,sn,"f"),P(this,an,"f")))!=null;){if(i.carriage&&P(this,an,"f")==null){ne(this,an,i.index);continue}if(P(this,an,"f")!=null&&(i.index!==P(this,an,"f")+1||i.carriage)){r.push(G_(P(this,sn,"f").subarray(0,P(this,an,"f")-1))),ne(this,sn,P(this,sn,"f").subarray(P(this,an,"f"))),ne(this,an,null);continue}const s=P(this,an,"f")!==null?i.preceding-1:i.preceding,a=G_(P(this,sn,"f").subarray(0,s));r.push(a),ne(this,sn,P(this,sn,"f").subarray(i.index)),ne(this,an,null)}return r}flush(){return P(this,sn,"f").length?this.decode(` `):[]}}sn=new WeakMap,an=new WeakMap;cd.NEWLINE_CHARS=new Set([` `,"\r"]);cd.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function RP(t,e){for(let i=e??0;i<t.length;i++){if(t[i]===10)return{preceding:i,index:i+1,carriage:!1};if(t[i]===13)return{preceding:i,index:i+1,carriage:!0}}return null}function jP(t){for(let r=0;r<t.length-1;r++){if(t[r]===10&&t[r+1]===10||t[r]===13&&t[r+1]===13)return r+2;if(t[r]===13&&t[r+1]===10&&r+3<t.length&&t[r+2]===13&&t[r+3]===10)return r+4}return-1}const cc={off:0,error:200,warn:300,info:400,debug:500},J_=(t,e,n)=>{if(t){if(yP(cc,t))return t;ft(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(cc))}`)}};function Za(){}function Ru(t,e,n){return!e||cc[t]>cc[n]?Za:e[t].bind(e)}const LP={error:Za,warn:Za,info:Za,debug:Za};let X_=new WeakMap;function ft(t){const e=t.logger,n=t.logLevel??"off";if(!e)return LP;const r=X_.get(e);if(r&&r[0]===n)return r[1];const i={error:Ru("error",e,n),warn:Ru("warn",e,n),info:Ru("info",e,n),debug:Ru("debug",e,n)};return X_.set(e,[n,i]),i}const Di=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Ra;class hr{constructor(e,n,r){this.iterator=e,Ra.set(this,void 0),this.controller=n,ne(this,Ra,r)}static fromSSEResponse(e,n,r,i){let s=!1;const a=r?ft(r):console;async function*o(){if(s)throw new Y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let u=!1;try{for await(const l of MP(e,n))if(!u){if(l.data.startsWith("[DONE]")){u=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(d){throw a.error("Could not parse message into JSON:",l.data),a.error("From chunk:",l.raw),d}if(c&&c.error)throw new St(void 0,c.error,void 0,e.headers);yield i?{event:l.event,data:c}:c}else{let c;try{c=JSON.parse(l.data)}catch(d){throw console.error("Could not parse message into JSON:",l.data),console.error("From chunk:",l.raw),d}if(l.event=="error")throw new St(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}u=!0}catch(l){if(Qh(l))return;throw l}finally{u||n.abort()}}return new hr(o,n,r)}static fromReadableStream(e,n,r){let i=!1;async function*s(){const o=new cd,u=x1(e);for await(const l of u)for(const c of o.decode(l))yield c;for(const l of o.flush())yield l}async function*a(){if(i)throw new Y("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let o=!1;try{for await(const u of s())o||u&&(yield JSON.parse(u));o=!0}catch(u){if(Qh(u))return;throw u}finally{o||n.abort()}}return new hr(a,n,r)}[(Ra=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],r=this.iterator(),i=s=>({next:()=>{if(s.length===0){const a=r.next();e.push(a),n.push(a)}return s.shift()}});return[new hr(()=>i(e),this.controller,P(this,Ra,"f")),new hr(()=>i(n),this.controller,P(this,Ra,"f"))]}toReadableStream(){const e=this;let n;return w1({async start(){n=e[Symbol.asyncIterator]()},async pull(r){try{const{value:i,done:s}=await n.next();if(s)return r.close();const a=sg(JSON.stringify(i)+` `);r.enqueue(a)}catch(i){r.error(i)}},async cancel(){var r;await((r=n.return)==null?void 0:r.call(n))}})}}async function*MP(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new Y("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new Y("Attempted to iterate over a response with no body");const n=new DP,r=new cd,i=x1(t.body);for await(const s of zP(i))for(const a of r.decode(s)){const o=n.decode(a);o&&(yield o)}for(const s of r.flush()){const a=n.decode(s);a&&(yield a)}}async function*zP(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const r=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?sg(n):n;let i=new Uint8Array(e.length+r.length);i.set(e),i.set(r,e.length),e=i;let s;for(;(s=jP(e))!==-1;)yield e.slice(0,s),e=e.slice(s)}e.length>0&&(yield e)}class DP{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const s={event:this.event,data:this.data.join(` `),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],s}if(this.chunks.push(e),e.startsWith(":"))return null;let[n,r,i]=UP(e,":");return i.startsWith(" ")&&(i=i.substring(1)),n==="event"?this.event=i:n==="data"&&this.data.push(i),null}}function UP(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function I1(t,e){const{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:s}=e,a=await(async()=>{var d;if(e.options.stream)return ft(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData):hr.fromSSEResponse(n,e.controller,t,e.options.__synthesizeEventData);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const o=n.headers.get("content-type"),u=(d=o==null?void 0:o.split(";")[0])==null?void 0:d.trim();if((u==null?void 0:u.includes("application/json"))||(u==null?void 0:u.endsWith("+json"))){if(n.headers.get("content-length")==="0")return;const h=await n.json();return O1(h,n)}return await n.text()})();return ft(t).debug(`[${r}] response parsed`,Di({retryOfRequestLogID:i,url:n.url,status:n.status,body:a,durationMs:Date.now()-s})),a}function O1(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Va;let C1=class P1 extends Promise{constructor(e,n,r=I1){super(i=>{i(null)}),this.responsePromise=n,this.parseResponse=r,Va.set(this,void 0),ne(this,Va,e)}_thenUnwrap(e){return new P1(P(this,Va,"f"),this.responsePromise,async(n,r)=>O1(e(await this.parseResponse(n,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(P(this,Va,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};Va=new WeakMap;var ju;let dd=class{constructor(e,n,r,i){ju.set(this,void 0),ne(this,ju,e),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new Y("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await P(this,ju,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ju=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}},FP=class extends C1{constructor(e,n,r){super(e,n,async(i,s)=>new r(i,s.response,await I1(i,s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}};class xi extends dd{constructor(e,n,r,i){super(e,n,r,i),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class Fe extends dd{constructor(e,n,r,i){super(e,n,r,i),this.data=r.data||[],this.has_more=r.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;const e=this.getPaginatedItems(),n=(r=e[e.length-1])==null?void 0:r.id;return n?{...this.options,query:{...ig(this.options.query),after:n}}:null}}class yt extends dd{constructor(e,n,r,i){super(e,n,r,i),this.data=r.data||[],this.has_more=r.has_more||!1,this.last_id=r.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...ig(this.options.query),after:e}}:null}}class Zr extends dd{constructor(e,n,r,i){super(e,n,r,i),this.data=r.data||[],this.has_more=r.has_more||!1,this.next=r.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.next;return e?{...this.options,query:{...ig(this.options.query),after:e}}:null}}const BP={jwt:"urn:ietf:params:oauth:token-type:jwt",id:"urn:ietf:params:oauth:token-type:id_token"},HP="urn:ietf:params:oauth:grant-type:token-exchange";class ZP{constructor(e,n){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl="https://auth.openai.com/oauth/token",this.config=e,this.fetch=n??v1()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){const e=await this.config.provider.getToken(),n={grant_type:HP,subject_token:e,subject_token_type:BP[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(n.client_id=this.config.clientId);const r=await this.fetch(this.tokenExchangeUrl,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n)});if(!r.ok){const o=await r.text();let u;try{u=JSON.parse(o)}catch{}throw r.status===400||r.status===401||r.status===403?new _1(r.status,u,r.headers):St.generate(r.status,u,`Token exchange failed with status ${r.status}`,r.headers)}const i=await r.json(),s=i.expires_in||3600,a=Date.now()+s*1e3;return this.cachedToken={token:i.access_token,expiresAt:a},i.access_token}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){const r=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-r}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}const N1=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function mo(t,e,n){return N1(),new File(t,e??"unknown_file",n)}function wl(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const ag=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",fd=async(t,e)=>np(t.body)?{...t,body:await $1(t.body,e)}:t,pr=async(t,e)=>({...t,body:await $1(t.body,e)}),Q_=new WeakMap;function VP(t){const e=typeof t=="function"?t:t.fetch,n=Q_.get(e);if(n)return n;const r=(async()=>{try{const i="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new i(s).text()}catch{return!0}})();return Q_.set(e,r),r}const $1=async(t,e)=>{if(!await VP(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,i])=>rp(n,r,i))),n},R1=t=>t instanceof Blob&&"name"in t,KP=t=>typeof t=="object"&&t!==null&&(t instanceof Response||ag(t)||R1(t)),np=t=>{if(KP(t))return!0;if(Array.isArray(t))return t.some(np);if(t&&typeof t=="object"){for(const e in t)if(np(t[e]))return!0}return!1},rp=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,mo([await n.blob()],wl(n)));else if(ag(n))t.append(e,mo([await new Response(b1(n)).blob()],wl(n)));else if(R1(n))t.append(e,n,wl(n));else if(Array.isArray(n))await Promise.all(n.map(r=>rp(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,i])=>rp(t,`${e}[${r}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},j1=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",qP=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&j1(t),WP=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function GP(t,e,n){if(N1(),t=await t,qP(t))return t instanceof File?t:mo([await t.arrayBuffer()],t.name);if(WP(t)){const i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),mo(await ip(i),e,n)}const r=await ip(t);if(e||(e=wl(t)),!(n!=null&&n.type)){const i=r.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(n={...n,type:i})}return mo(r,e,n)}async function ip(t){var n;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(j1(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(ag(t))for await(const r of t)e.push(...await ip(r));else{const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${JP(t)}`)}return e}function JP(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}let F=class{constructor(e){this._client=e}};function L1(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const Y_=Object.freeze(Object.create(null)),XP=(t=L1)=>function(n,...r){if(n.length===1)return n[0];let i=!1;const s=[],a=n.reduce((c,d,f)=>{var _;/[?#]/.test(d)&&(i=!0);const h=r[f];let m=(i?encodeURIComponent:t)(""+h);return f!==r.length&&(h==null||typeof h=="object"&&h.toString===((_=Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??Y_)??Y_))==null?void 0:_.toString))&&(m=h+"",s.push({start:c.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),c+d+(f===r.length?"":m)},""),o=a.split(/[?#]/,1)[0],u=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let l;for(;(l=u.exec(o))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((c,d)=>c.start-d.start),s.length>0){let c=0;const d=s.reduce((f,h)=>{const m=" ".repeat(h.start-c),_="^".repeat(h.length);return c=h.start+h.length,f+m+_},"");throw new Y(`Path parameters result in path with invalid segments: ${s.map(f=>f.error).join(` `)} ${a} ${d}`)}return a},O=XP(L1);let M1=class extends F{list(e,n={},r){return this._client.getAPIList(O`/chat/completions/${e}/messages`,Fe,{query:n,...r,__security:{bearerAuth:!0}})}};function dc(t){return t!==void 0&&"function"in t&&t.function!==void 0}function QP(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function og(t){return(t==null?void 0:t.$brand)==="auto-parseable-response-format"}function ou(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function YP(t,e){return!e||!z1(e)?{...t,choices:t.choices.map(n=>(D1(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:ug(t,e)}function ug(t,e){const n=t.choices.map(r=>{var i;if(r.finish_reason==="length")throw new g1;if(r.finish_reason==="content_filter")throw new y1;return D1(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:((i=r.message.tool_calls)==null?void 0:i.map(s=>tN(e,s)))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?eN(e,r.message.content):null}}});return{...t,choices:n}}function eN(t,e){var n,r;return((n=t.response_format)==null?void 0:n.type)!=="json_schema"?null:((r=t.response_format)==null?void 0:r.type)==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function tN(t,e){var r;const n=(r=t.tools)==null?void 0:r.find(i=>{var s;return dc(i)&&((s=i.function)==null?void 0:s.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:ou(n)?n.$parseRaw(e.function.arguments):n!=null&&n.function.strict?JSON.parse(e.function.arguments):null}}}function nN(t,e){var r;if(!t||!("tools"in t)||!t.tools)return!1;const n=(r=t.tools)==null?void 0:r.find(i=>{var s;return dc(i)&&((s=i.function)==null?void 0:s.name)===e.function.name});return dc(n)&&(ou(n)||(n==null?void 0:n.function.strict)||!1)}function z1(t){var e;return og(t.response_format)?!0:((e=t.tools)==null?void 0:e.some(n=>ou(n)||n.type==="function"&&n.function.strict===!0))??!1}function D1(t){for(const e of t||[])if(e.type!=="function")throw new Y(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function rN(t){for(const e of t??[]){if(e.type!=="function")throw new Y(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new Y(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const fc=t=>(t==null?void 0:t.role)==="assistant",U1=t=>(t==null?void 0:t.role)==="tool";var sp,bl,xl,Ka,qa,kl,Wa,kr,Ga,hc,pc,vs,F1;class lg{constructor(){sp.add(this),this.controller=new AbortController,bl.set(this,void 0),xl.set(this,()=>{}),Ka.set(this,()=>{}),qa.set(this,void 0),kl.set(this,()=>{}),Wa.set(this,()=>{}),kr.set(this,{}),Ga.set(this,!1),hc.set(this,!1),pc.set(this,!1),vs.set(this,!1),ne(this,bl,new Promise((e,n)=>{ne(this,xl,e,"f"),ne(this,Ka,n,"f")})),ne(this,qa,new Promise((e,n)=>{ne(this,kl,e,"f"),ne(this,Wa,n,"f")})),P(this,bl,"f").catch(()=>{}),P(this,qa,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},P(this,sp,"m",F1).bind(this))},0)}_connected(){this.ended||(P(this,xl,"f").call(this),this._emit("connect"))}get ended(){return P(this,Ga,"f")}get errored(){return P(this,hc,"f")}get aborted(){return P(this,pc,"f")}abort(){this.controller.abort()}on(e,n){return(P(this,kr,"f")[e]||(P(this,kr,"f")[e]=[])).push({listener:n}),this}off(e,n){const r=P(this,kr,"f")[e];if(!r)return this;const i=r.findIndex(s=>s.listener===n);return i>=0&&r.splice(i,1),this}once(e,n){return(P(this,kr,"f")[e]||(P(this,kr,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,r)=>{ne(this,vs,!0),e!=="error"&&this.once("error",r),this.once(e,n)})}async done(){ne(this,vs,!0),await P(this,qa,"f")}_emit(e,...n){if(P(this,Ga,"f"))return;e==="end"&&(ne(this,Ga,!0),P(this,kl,"f").call(this));const r=P(this,kr,"f")[e];if(r&&(P(this,kr,"f")[e]=r.filter(i=>!i.once),r.forEach(({listener:i})=>i(...n))),e==="abort"){const i=n[0];!P(this,vs,"f")&&!(r!=null&&r.length)&&Promise.reject(i),P(this,Ka,"f").call(this,i),P(this,Wa,"f").call(this,i),this._emit("end");return}if(e==="error"){const i=n[0];!P(this,vs,"f")&&!(r!=null&&r.length)&&Promise.reject(i),P(this,Ka,"f").call(this,i),P(this,Wa,"f").call(this,i),this._emit("end")}}_emitFinal(){}}bl=new WeakMap,xl=new WeakMap,Ka=new WeakMap,qa=new WeakMap,kl=new WeakMap,Wa=new WeakMap,kr=new WeakMap,Ga=new WeakMap,hc=new WeakMap,pc=new WeakMap,vs=new WeakMap,sp=new WeakSet,F1=function(e){if(ne(this,hc,!0),e instanceof Error&&e.name==="AbortError"&&(e=new dn),e instanceof dn)return ne(this,pc,!0),this._emit("abort",e);if(e instanceof Y)return this._emit("error",e);if(e instanceof Error){const n=new Y(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new Y(String(e)))};function iN(t){return typeof t.parse=="function"}var $t,ap,mc,op,up,lp,B1,H1;const sN=10;class Z1 extends lg{constructor(){super(...arguments),$t.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var r;this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=(r=e.choices[0])==null?void 0:r.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),U1(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(fc(e)&&e.tool_calls)for(const r of e.tool_calls)r.type==="function"&&this._emit("functionToolCall",r.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new Y("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),P(this,$t,"m",ap).call(this)}async finalMessage(){return await this.done(),P(this,$t,"m",mc).call(this)}async finalFunctionToolCall(){return await this.done(),P(this,$t,"m",op).call(this)}async finalFunctionToolCallResult(){return await this.done(),P(this,$t,"m",up).call(this)}async totalUsage(){return await this.done(),P(this,$t,"m",lp).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=P(this,$t,"m",mc).call(this);n&&this._emit("finalMessage",n);const r=P(this,$t,"m",ap).call(this);r&&this._emit("finalContent",r);const i=P(this,$t,"m",op).call(this);i&&this._emit("finalFunctionToolCall",i);const s=P(this,$t,"m",up).call(this);s!=null&&this._emit("finalFunctionToolCallResult",s),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",P(this,$t,"m",lp).call(this))}async _createChatCompletion(e,n,r){const i=r==null?void 0:r.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),P(this,$t,"m",B1).call(this,n);const s=await e.chat.completions.create({...n,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ug(s,n))}async _runChatCompletion(e,n,r){for(const i of n.messages)this._addMessage(i,!1);return await this._createChatCompletion(e,n,r)}async _runTools(e,n,r){var h,m,_;const i="tool",{tool_choice:s="auto",stream:a,...o}=n,u=typeof s!="string"&&s.type==="function"&&((h=s==null?void 0:s.function)==null?void 0:h.name),{maxChatCompletions:l=sN}=r||{},c=n.tools.map(v=>{if(ou(v)){if(!v.$callback)throw new Y("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:v.$callback,name:v.function.name,description:v.function.description||"",parameters:v.function.parameters,parse:v.$parseRaw,strict:!0}}}return v}),d={};for(const v of c)v.type==="function"&&(d[v.function.name||v.function.function.name]=v.function);const f="tools"in n?c.map(v=>v.type==="function"?{type:"function",function:{name:v.function.name||v.function.function.name,parameters:v.function.parameters,description:v.function.description,strict:v.function.strict}}:v):void 0;for(const v of n.messages)this._addMessage(v,!1);for(let v=0;v<l;++v){const p=(m=(await this._createChatCompletion(e,{...o,tool_choice:s,tools:f,messages:[...this.messages]},r)).choices[0])==null?void 0:m.message;if(!p)throw new Y("missing message in ChatCompletion response");if(!((_=p.tool_calls)!=null&&_.length))return;for(const g of p.tool_calls){if(g.type!=="function")continue;const b=g.id,{name:E,arguments:T}=g.function,I=d[E];if(I){if(u&&u!==E){const L=`Invalid tool_call: ${JSON.stringify(E)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:i,tool_call_id:b,content:L});continue}}else{const L=`Invalid tool_call: ${JSON.stringify(E)}. Available options are: ${Object.keys(d).map(ue=>JSON.stringify(ue)).join(", ")}. Please try again`;this._addMessage({role:i,tool_call_id:b,content:L});continue}let k;try{k=iN(I)?await I.parse(T):T}catch(L){const ue=L instanceof Error?L.message:String(L);this._addMessage({role:i,tool_call_id:b,content:ue});continue}const j=await I.function(k,this),N=P(this,$t,"m",H1).call(this,j);if(this._addMessage({role:i,tool_call_id:b,content:N}),u)return}}}}$t=new WeakSet,ap=function(){return P(this,$t,"m",mc).call(this).content??null},mc=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(fc(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new Y("stream ended without producing a ChatCompletionMessage with role=assistant")},op=function(){var e;for(let n=this.messages.length-1;n>=0;n--){const r=this.messages[n];if(fc(r)&&((e=r==null?void 0:r.tool_calls)!=null&&e.length))for(let i=r.tool_calls.length-1;i>=0;i--){const s=r.tool_calls[i];if((s==null?void 0:s.type)==="function")return s.function}}},up=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(U1(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(r=>{var i;return r.role==="assistant"&&((i=r.tool_calls)==null?void 0:i.some(s=>s.type==="function"&&s.id===n.tool_call_id))}))return n.content}},lp=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},B1=function(e){if(e.n!=null&&e.n>1)throw new Y("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},H1=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class cg extends Z1{static runTools(e,n,r){const i=new cg,s={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,n,s)),i}_addMessage(e,n=!0){super._addMessage(e,n),fc(e)&&e.content&&this._emit("content",e.content)}}const V1=1,K1=2,q1=4,W1=8,G1=16,J1=32,X1=64,Q1=128,Y1=256,ek=Q1|Y1,tk=G1|J1|ek|X1,nk=V1|K1|tk,rk=q1|W1,aN=nk|rk,st={STR:V1,NUM:K1,ARR:q1,OBJ:W1,NULL:G1,BOOL:J1,NAN:X1,INFINITY:Q1,MINUS_INFINITY:Y1,INF:ek,SPECIAL:tk,ATOM:nk,COLLECTION:rk,ALL:aN};class oN extends Error{}class uN extends Error{}function lN(t,e=st.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return cN(t.trim(),e)}const cN=(t,e)=>{const n=t.length;let r=0;const i=f=>{throw new oN(`${f} at position ${r}`)},s=f=>{throw new uN(`${f} at position ${r}`)},a=()=>(d(),r>=n&&i("Unexpected end of input"),t[r]==='"'?o():t[r]==="{"?u():t[r]==="["?l():t.substring(r,r+4)==="null"||st.NULL&e&&n-r<4&&"null".startsWith(t.substring(r))?(r+=4,null):t.substring(r,r+4)==="true"||st.BOOL&e&&n-r<4&&"true".startsWith(t.substring(r))?(r+=4,!0):t.substring(r,r+5)==="false"||st.BOOL&e&&n-r<5&&"false".startsWith(t.substring(r))?(r+=5,!1):t.substring(r,r+8)==="Infinity"||st.INFINITY&e&&n-r<8&&"Infinity".startsWith(t.substring(r))?(r+=8,1/0):t.substring(r,r+9)==="-Infinity"||st.MINUS_INFINITY&e&&1<n-r&&n-r<9&&"-Infinity".startsWith(t.substring(r))?(r+=9,-1/0):t.substring(r,r+3)==="NaN"||st.NAN&e&&n-r<3&&"NaN".startsWith(t.substring(r))?(r+=3,NaN):c()),o=()=>{const f=r;let h=!1;for(r++;r<n&&(t[r]!=='"'||h&&t[r-1]==="\\");)h=t[r]==="\\"?!h:!1,r++;if(t.charAt(r)=='"')try{return JSON.parse(t.substring(f,++r-Number(h)))}catch(m){s(String(m))}else if(st.STR&e)try{return JSON.parse(t.substring(f,r-Number(h))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}i("Unterminated string literal")},u=()=>{r++,d();const f={};try{for(;t[r]!=="}";){if(d(),r>=n&&st.OBJ&e)return f;const h=o();d(),r++;try{const m=a();Object.defineProperty(f,h,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(st.OBJ&e)return f;throw m}d(),t[r]===","&&r++}}catch{if(st.OBJ&e)return f;i("Expected '}' at end of object")}return r++,f},l=()=>{r++;const f=[];try{for(;t[r]!=="]";)f.push(a()),d(),t[r]===","&&r++}catch{if(st.ARR&e)return f;i("Expected ']' at end of array")}return r++,f},c=()=>{if(r===0){t==="-"&&st.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(st.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}s(String(h))}}const f=r;for(t[r]==="-"&&r++;t[r]&&!",]}".includes(t[r]);)r++;r==n&&!(st.NUM&e)&&i("Unterminated number literal");try{return JSON.parse(t.substring(f,r))}catch{t.substring(f,r)==="-"&&st.NUM&e&&i("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(m){s(String(m))}}},d=()=>{for(;r<n&&` \r `.includes(t[r]);)r++};return a()},ev=t=>lN(t,st.ALL^st.NUM);var Ye,xr,hs,Wr,_f,Lu,vf,wf,bf,Mu,xf,tv;class Uo extends Z1{constructor(e){super(),Ye.add(this),xr.set(this,void 0),hs.set(this,void 0),Wr.set(this,void 0),ne(this,xr,e),ne(this,hs,[])}get currentChatCompletionSnapshot(){return P(this,Wr,"f")}static fromReadableStream(e){const n=new Uo(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,r){const i=new Uo(n);return i._run(()=>i._runChatCompletion(e,{...n,stream:!0},{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createChatCompletion(e,n,r){var a;super._createChatCompletion;const i=r==null?void 0:r.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),P(this,Ye,"m",_f).call(this);const s=await e.chat.completions.create({...n,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const o of s)P(this,Ye,"m",vf).call(this,o);if((a=s.controller.signal)!=null&&a.aborted)throw new dn;return this._addChatCompletion(P(this,Ye,"m",Mu).call(this))}async _fromReadableStream(e,n){var a;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),P(this,Ye,"m",_f).call(this),this._connected();const i=hr.fromReadableStream(e,this.controller);let s;for await(const o of i)s&&s!==o.id&&this._addChatCompletion(P(this,Ye,"m",Mu).call(this)),P(this,Ye,"m",vf).call(this,o),s=o.id;if((a=i.controller.signal)!=null&&a.aborted)throw new dn;return this._addChatCompletion(P(this,Ye,"m",Mu).call(this))}[(xr=new WeakMap,hs=new WeakMap,Wr=new WeakMap,Ye=new WeakSet,_f=function(){this.ended||ne(this,Wr,void 0)},Lu=function(n){let r=P(this,hs,"f")[n.index];return r||(r={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},P(this,hs,"f")[n.index]=r,r)},vf=function(n){var i,s,a,o,u,l,c,d,f,h,m,_,v,y,p;if(this.ended)return;const r=P(this,Ye,"m",tv).call(this,n);this._emit("chunk",n,r);for(const g of n.choices){const b=r.choices[g.index];g.delta.content!=null&&((i=b.message)==null?void 0:i.role)==="assistant"&&((s=b.message)!=null&&s.content)&&(this._emit("content",g.delta.content,b.message.content),this._emit("content.delta",{delta:g.delta.content,snapshot:b.message.content,parsed:b.message.parsed})),g.delta.refusal!=null&&((a=b.message)==null?void 0:a.role)==="assistant"&&((o=b.message)!=null&&o.refusal)&&this._emit("refusal.delta",{delta:g.delta.refusal,snapshot:b.message.refusal}),((u=g.logprobs)==null?void 0:u.content)!=null&&((l=b.message)==null?void 0:l.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(c=g.logprobs)==null?void 0:c.content,snapshot:((d=b.logprobs)==null?void 0:d.content)??[]}),((f=g.logprobs)==null?void 0:f.refusal)!=null&&((h=b.message)==null?void 0:h.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(m=g.logprobs)==null?void 0:m.refusal,snapshot:((_=b.logprobs)==null?void 0:_.refusal)??[]});const E=P(this,Ye,"m",Lu).call(this,b);b.finish_reason&&(P(this,Ye,"m",bf).call(this,b),E.current_tool_call_index!=null&&P(this,Ye,"m",wf).call(this,b,E.current_tool_call_index));for(const T of g.delta.tool_calls??[])E.current_tool_call_index!==T.index&&(P(this,Ye,"m",bf).call(this,b),E.current_tool_call_index!=null&&P(this,Ye,"m",wf).call(this,b,E.current_tool_call_index)),E.current_tool_call_index=T.index;for(const T of g.delta.tool_calls??[]){const I=(v=b.message.tool_calls)==null?void 0:v[T.index];I!=null&&I.type&&((I==null?void 0:I.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(y=I.function)==null?void 0:y.name,index:T.index,arguments:I.function.arguments,parsed_arguments:I.function.parsed_arguments,arguments_delta:((p=T.function)==null?void 0:p.arguments)??""}):(I==null||I.type,void 0))}}},wf=function(n,r){var a,o,u;if(P(this,Ye,"m",Lu).call(this,n).done_tool_calls.has(r))return;const s=(a=n.message.tool_calls)==null?void 0:a[r];if(!s)throw new Error("no tool call snapshot");if(!s.type)throw new Error("tool call snapshot missing `type`");if(s.type==="function"){const l=(u=(o=P(this,xr,"f"))==null?void 0:o.tools)==null?void 0:u.find(c=>dc(c)&&c.function.name===s.function.name);this._emit("tool_calls.function.arguments.done",{name:s.function.name,index:r,arguments:s.function.arguments,parsed_arguments:ou(l)?l.$parseRaw(s.function.arguments):l!=null&&l.function.strict?JSON.parse(s.function.arguments):null})}else s.type},bf=function(n){var i,s;const r=P(this,Ye,"m",Lu).call(this,n);if(n.message.content&&!r.content_done){r.content_done=!0;const a=P(this,Ye,"m",xf).call(this);this._emit("content.done",{content:n.message.content,parsed:a?a.$parseRaw(n.message.content):null})}n.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),(i=n.logprobs)!=null&&i.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),(s=n.logprobs)!=null&&s.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},Mu=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");const n=P(this,Wr,"f");if(!n)throw new Y("request ended without sending any chunks");return ne(this,Wr,void 0),ne(this,hs,[]),dN(n,P(this,xr,"f"))},xf=function(){var r;const n=(r=P(this,xr,"f"))==null?void 0:r.response_format;return og(n)?n:null},tv=function(n){var r,i,s,a;let o=P(this,Wr,"f");const{choices:u,...l}=n;o?Object.assign(o,l):o=ne(this,Wr,{...l,choices:[]});for(const{delta:c,finish_reason:d,index:f,logprobs:h=null,...m}of n.choices){let _=o.choices[f];if(_||(_=o.choices[f]={finish_reason:d,index:f,message:{},logprobs:h,...m}),h)if(!_.logprobs)_.logprobs=Object.assign({},h);else{const{content:T,refusal:I,...k}=h;Object.assign(_.logprobs,k),T&&((r=_.logprobs).content??(r.content=[]),_.logprobs.content.push(...T)),I&&((i=_.logprobs).refusal??(i.refusal=[]),_.logprobs.refusal.push(...I))}if(d&&(_.finish_reason=d,P(this,xr,"f")&&z1(P(this,xr,"f")))){if(d==="length")throw new g1;if(d==="content_filter")throw new y1}if(Object.assign(_,m),!c)continue;const{content:v,refusal:y,function_call:p,role:g,tool_calls:b,...E}=c;if(Object.assign(_.message,E),y&&(_.message.refusal=(_.message.refusal||"")+y),g&&(_.message.role=g),p&&(_.message.function_call?(p.name&&(_.message.function_call.name=p.name),p.arguments&&((s=_.message.function_call).arguments??(s.arguments=""),_.message.function_call.arguments+=p.arguments)):_.message.function_call=p),v&&(_.message.content=(_.message.content||"")+v,!_.message.refusal&&P(this,Ye,"m",xf).call(this)&&(_.message.parsed=ev(_.message.content))),b){_.message.tool_calls||(_.message.tool_calls=[]);for(const{index:T,id:I,type:k,function:j,...N}of b){const L=(a=_.message.tool_calls)[T]??(a[T]={});Object.assign(L,N),I&&(L.id=I),k&&(L.type=k),j&&(L.function??(L.function={name:j.name??"",arguments:""})),j!=null&&j.name&&(L.function.name=j.name),j!=null&&j.arguments&&(L.function.arguments+=j.arguments,nN(P(this,xr,"f"),L)&&(L.function.parsed_arguments=ev(L.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("chunk",i=>{const s=n.shift();s?s.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(const i of n)i.resolve(void 0);n.length=0}),this.on("abort",i=>{r=!0;for(const s of n)s.reject(i);n.length=0}),this.on("error",i=>{r=!0;for(const s of n)s.reject(i);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((s,a)=>n.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new hr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function dN(t,e){const{id:n,choices:r,created:i,model:s,system_fingerprint:a,...o}=t,u={...o,id:n,choices:r.map(({message:l,finish_reason:c,index:d,logprobs:f,...h})=>{if(!c)throw new Y(`missing finish_reason for choice ${d}`);const{content:m=null,function_call:_,tool_calls:v,...y}=l,p=l.role;if(!p)throw new Y(`missing role for choice ${d}`);if(_){const{arguments:g,name:b}=_;if(g==null)throw new Y(`missing function_call.arguments for choice ${d}`);if(!b)throw new Y(`missing function_call.name for choice ${d}`);return{...h,message:{content:m,function_call:{arguments:g,name:b},role:p,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}return v?{...h,index:d,finish_reason:c,logprobs:f,message:{...y,role:p,content:m,refusal:l.refusal??null,tool_calls:v.map((g,b)=>{const{function:E,type:T,id:I,...k}=g,{arguments:j,name:N,...L}=E||{};if(I==null)throw new Y(`missing choices[${d}].tool_calls[${b}].id ${zu(t)}`);if(T==null)throw new Y(`missing choices[${d}].tool_calls[${b}].type ${zu(t)}`);if(N==null)throw new Y(`missing choices[${d}].tool_calls[${b}].function.name ${zu(t)}`);if(j==null)throw new Y(`missing choices[${d}].tool_calls[${b}].function.arguments ${zu(t)}`);return{...k,id:I,type:T,function:{...L,name:N,arguments:j}}})}}:{...h,message:{...y,content:m,role:p,refusal:l.refusal??null},finish_reason:c,index:d,logprobs:f}}),created:i,model:s,object:"chat.completion",...a?{system_fingerprint:a}:{}};return YP(u,e)}function zu(t){return JSON.stringify(t)}class gc extends Uo{static fromReadableStream(e){const n=new gc(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,r){const i=new gc(n),s={...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"runTools"}};return i._run(()=>i._runTools(e,n,s)),i}}let dg=class extends F{constructor(){super(...arguments),this.messages=new M1(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(O`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(O`/chat/completions/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chat/completions",Fe,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/chat/completions/${e}`,{...n,__security:{bearerAuth:!0}})}parse(e,n){return rN(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>ug(r,e))}runTools(e,n){return e.stream?gc.runTools(this._client,e,n):cg.runTools(this._client,e,n)}stream(e,n){return Uo.createChatCompletion(this._client,e,n)}};dg.Messages=M1;class fg extends F{constructor(){super(...arguments),this.completions=new dg(this._client)}}fg.Completions=dg;class ik extends F{create(e,n){return this._client.post("/organization/admin_api_keys",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(O`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/admin_api_keys",Fe,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(O`/organization/admin_api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}class sk extends F{list(e={},n){return this._client.getAPIList("/organization/audit_logs",yt,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}}let ak=class extends F{create(e,n){return this._client.post("/organization/certificates",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(O`/organization/certificates/${e}`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(O`/organization/certificates/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/certificates",yt,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(O`/organization/certificates/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}activate(e,n){return this._client.getAPIList("/organization/certificates/activate",xi,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n){return this._client.getAPIList("/organization/certificates/deactivate",xi,{body:e,method:"post",...n,__security:{adminAPIKeyAuth:!0}})}},ok=class extends F{retrieve(e){return this._client.get("/organization/data_retention",{...e,__security:{adminAPIKeyAuth:!0}})}update(e,n){return this._client.post("/organization/data_retention",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}};class uk extends F{create(e,n){return this._client.post("/organization/invites",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(O`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/invites",yt,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(O`/organization/invites/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}let lk=class extends F{create(e,n){return this._client.post("/organization/roles",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(O`/organization/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(O`/organization/roles/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/roles",Zr,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(O`/organization/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},ck=class extends F{create(e,n){return this._client.post("/organization/spend_alerts",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(O`/organization/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(O`/organization/spend_alerts/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/spend_alerts",yt,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(O`/organization/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};class dk extends F{audioSpeeches(e,n){return this._client.get("/organization/usage/audio_speeches",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,n){return this._client.get("/organization/usage/audio_transcriptions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,n){return this._client.get("/organization/usage/code_interpreter_sessions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}completions(e,n){return this._client.get("/organization/usage/completions",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}costs(e,n){return this._client.get("/organization/costs",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}embeddings(e,n){return this._client.get("/organization/usage/embeddings",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,n){return this._client.get("/organization/usage/file_search_calls",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}images(e,n){return this._client.get("/organization/usage/images",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}moderations(e,n){return this._client.get("/organization/usage/moderations",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,n){return this._client.get("/organization/usage/vector_stores",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,n){return this._client.get("/organization/usage/web_search_calls",{query:e,...n,__security:{adminAPIKeyAuth:!0}})}}let fk=class extends F{create(e,n,r){return this._client.post(O`/organization/groups/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{group_id:i}=n;return this._client.get(O`/organization/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/organization/groups/${e}/roles`,Zr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{group_id:i}=n;return this._client.delete(O`/organization/groups/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}},hk=class extends F{create(e,n,r){return this._client.post(O`/organization/groups/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{group_id:i}=n;return this._client.get(O`/organization/groups/${i}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/organization/groups/${e}/users`,Zr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{group_id:i}=n;return this._client.delete(O`/organization/groups/${i}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}},hd=class extends F{constructor(){super(...arguments),this.users=new hk(this._client),this.roles=new fk(this._client)}create(e,n){return this._client.post("/organization/groups",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(O`/organization/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(O`/organization/groups/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/groups",Zr,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(O`/organization/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}};hd.Users=hk;hd.Roles=fk;class pk extends F{retrieve(e,n,r){const{project_id:i}=n;return this._client.get(O`/organization/projects/${i}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/organization/projects/${e}/api_keys`,yt,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:i}=n;return this._client.delete(O`/organization/projects/${i}/api_keys/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}class mk extends F{list(e,n={},r){return this._client.getAPIList(O`/organization/projects/${e}/certificates`,yt,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}activate(e,n,r){return this._client.getAPIList(O`/organization/projects/${e}/certificates/activate`,xi,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}deactivate(e,n,r){return this._client.getAPIList(O`/organization/projects/${e}/certificates/deactivate`,xi,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}}class gk extends F{retrieve(e,n){return this._client.get(O`/organization/projects/${e}/data_retention`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(O`/organization/projects/${e}/data_retention`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}}class yk extends F{retrieve(e,n){return this._client.get(O`/organization/projects/${e}/hosted_tool_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(O`/organization/projects/${e}/hosted_tool_permissions`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}}class _k extends F{retrieve(e,n){return this._client.get(O`/organization/projects/${e}/model_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(O`/organization/projects/${e}/model_permissions`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(O`/organization/projects/${e}/model_permissions`,{...n,__security:{adminAPIKeyAuth:!0}})}}class vk extends F{listRateLimits(e,n={},r){return this._client.getAPIList(O`/organization/projects/${e}/rate_limits`,yt,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,n,r){const{project_id:i,...s}=n;return this._client.post(O`/organization/projects/${i}/rate_limits/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}}let wk=class extends F{create(e,n,r){return this._client.post(O`/projects/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:i}=n;return this._client.get(O`/projects/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){const{project_id:i,...s}=n;return this._client.post(O`/projects/${i}/roles/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/projects/${e}/roles`,Zr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:i}=n;return this._client.delete(O`/projects/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};class bk extends F{create(e,n,r){return this._client.post(O`/organization/projects/${e}/service_accounts`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:i}=n;return this._client.get(O`/organization/projects/${i}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){const{project_id:i,...s}=n;return this._client.post(O`/organization/projects/${i}/service_accounts/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/organization/projects/${e}/service_accounts`,yt,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:i}=n;return this._client.delete(O`/organization/projects/${i}/service_accounts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}class xk extends F{create(e,n,r){return this._client.post(O`/organization/projects/${e}/spend_alerts`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:i}=n;return this._client.get(O`/organization/projects/${i}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){const{project_id:i,...s}=n;return this._client.post(O`/organization/projects/${i}/spend_alerts/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/organization/projects/${e}/spend_alerts`,yt,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:i}=n;return this._client.delete(O`/organization/projects/${i}/spend_alerts/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}let kk=class extends F{create(e,n,r){const{project_id:i,...s}=n;return this._client.post(O`/projects/${i}/groups/${e}/roles`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:i,group_id:s}=n;return this._client.get(O`/projects/${i}/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){const{project_id:i,...s}=n;return this._client.getAPIList(O`/projects/${i}/groups/${e}/roles`,Zr,{query:s,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:i,group_id:s}=n;return this._client.delete(O`/projects/${i}/groups/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};class hg extends F{constructor(){super(...arguments),this.roles=new kk(this._client)}create(e,n,r){return this._client.post(O`/organization/projects/${e}/groups`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:i,...s}=n;return this._client.get(O`/organization/projects/${i}/groups/${e}`,{query:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/organization/projects/${e}/groups`,Zr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:i}=n;return this._client.delete(O`/organization/projects/${i}/groups/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}hg.Roles=kk;let Sk=class extends F{create(e,n,r){const{project_id:i,...s}=n;return this._client.post(O`/projects/${i}/users/${e}/roles`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:i,user_id:s}=n;return this._client.get(O`/projects/${i}/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n,r){const{project_id:i,...s}=n;return this._client.getAPIList(O`/projects/${i}/users/${e}/roles`,Zr,{query:s,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:i,user_id:s}=n;return this._client.delete(O`/projects/${i}/users/${s}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}},pg=class extends F{constructor(){super(...arguments),this.roles=new Sk(this._client)}create(e,n,r){return this._client.post(O`/organization/projects/${e}/users`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{project_id:i}=n;return this._client.get(O`/organization/projects/${i}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){const{project_id:i,...s}=n;return this._client.post(O`/organization/projects/${i}/users/${e}`,{body:s,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/organization/projects/${e}/users`,yt,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{project_id:i}=n;return this._client.delete(O`/organization/projects/${i}/users/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}};pg.Roles=Sk;class _n extends F{constructor(){super(...arguments),this.users=new pg(this._client),this.serviceAccounts=new bk(this._client),this.apiKeys=new pk(this._client),this.rateLimits=new vk(this._client),this.modelPermissions=new _k(this._client),this.hostedToolPermissions=new yk(this._client),this.groups=new hg(this._client),this.roles=new wk(this._client),this.dataRetention=new gk(this._client),this.spendAlerts=new xk(this._client),this.certificates=new mk(this._client)}create(e,n){return this._client.post("/organization/projects",{body:e,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n){return this._client.get(O`/organization/projects/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(O`/organization/projects/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/projects",yt,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}archive(e,n){return this._client.post(O`/organization/projects/${e}/archive`,{...n,__security:{adminAPIKeyAuth:!0}})}}_n.Users=pg;_n.ServiceAccounts=bk;_n.APIKeys=pk;_n.RateLimits=vk;_n.ModelPermissions=_k;_n.HostedToolPermissions=yk;_n.Groups=hg;_n.Roles=wk;_n.DataRetention=gk;_n.SpendAlerts=xk;_n.Certificates=mk;class Ak extends F{create(e,n,r){return this._client.post(O`/organization/users/${e}/roles`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n,r){const{user_id:i}=n;return this._client.get(O`/organization/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/organization/users/${e}/roles`,Zr,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{user_id:i}=n;return this._client.delete(O`/organization/users/${i}/roles/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}class mg extends F{constructor(){super(...arguments),this.roles=new Ak(this._client)}retrieve(e,n){return this._client.get(O`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,n,r){return this._client.post(O`/organization/users/${e}`,{body:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e={},n){return this._client.getAPIList("/organization/users",yt,{query:e,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,n){return this._client.delete(O`/organization/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}mg.Roles=Ak;class vn extends F{constructor(){super(...arguments),this.auditLogs=new sk(this._client),this.adminAPIKeys=new ik(this._client),this.usage=new dk(this._client),this.invites=new uk(this._client),this.users=new mg(this._client),this.groups=new hd(this._client),this.roles=new lk(this._client),this.dataRetention=new ok(this._client),this.spendAlerts=new ck(this._client),this.certificates=new ak(this._client),this.projects=new _n(this._client)}}vn.AuditLogs=sk;vn.AdminAPIKeys=ik;vn.Usage=dk;vn.Invites=uk;vn.Users=mg;vn.Groups=hd;vn.Roles=lk;vn.DataRetention=ok;vn.SpendAlerts=ck;vn.Certificates=ak;vn.Projects=_n;class gg extends F{constructor(){super(...arguments),this.organization=new vn(this._client)}}gg.Organization=vn;const Ek=Symbol("brand.privateNullableHeaders");function*fN(t){if(!t)return;if(Ek in t){const{values:r,nulls:i}=t;yield*r.entries();for(const s of i)yield[s,null];return}let e=!1,n;t instanceof Headers?n=t.entries():z_(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){const i=r[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");const s=z_(r[1])?r[1]:[r[1]];let a=!1;for(const o of s)o!==void 0&&(e&&!a&&(a=!0,yield[i,null]),yield[i,o])}}const Z=t=>{const e=new Headers,n=new Set;for(const r of t){const i=new Set;for(const[s,a]of fN(r)){const o=s.toLowerCase();i.has(o)||(e.delete(s),i.add(o)),a===null?(e.delete(s),n.add(o)):(e.append(s,a),n.delete(o))}}return{[Ek]:!0,values:e,nulls:n}};class Tk extends F{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:Z([{Accept:"application/octet-stream"},n==null?void 0:n.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}class Ik extends F{create(e,n){return this._client.post("/audio/transcriptions",pr({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class Ok extends F{create(e,n){return this._client.post("/audio/translations",pr({body:e,...n,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}class uu extends F{constructor(){super(...arguments),this.transcriptions=new Ik(this._client),this.translations=new Ok(this._client),this.speech=new Tk(this._client)}}uu.Transcriptions=Ik;uu.Translations=Ok;uu.Speech=Tk;class Ck extends F{create(e,n){return this._client.post("/batches",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(O`/batches/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/batches",Fe,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(O`/batches/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}}class Pk extends F{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(O`/assistants/${e}`,{...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(O`/assistants/${e}`,{body:n,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/assistants",Fe,{query:e,...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/assistants/${e}`,{...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}}let Nk=class extends F{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}};class $k extends F{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}}let pd=class extends F{constructor(){super(...arguments),this.sessions=new Nk(this._client),this.transcriptionSessions=new $k(this._client)}};pd.Sessions=Nk;pd.TranscriptionSessions=$k;let Rk=class extends F{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:Z([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(O`/chatkit/sessions/${e}/cancel`,{...n,headers:Z([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}},jk=class extends F{retrieve(e,n){return this._client.get(O`/chatkit/threads/${e}`,{...n,headers:Z([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/chatkit/threads",yt,{query:e,...n,headers:Z([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/chatkit/threads/${e}`,{...n,headers:Z([{"OpenAI-Beta":"chatkit_beta=v1"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}listItems(e,n={},r){return this._client.getAPIList(O`/chatkit/threads/${e}/items`,yt,{query:n,...r,headers:Z([{"OpenAI-Beta":"chatkit_beta=v1"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};class md extends F{constructor(){super(...arguments),this.sessions=new Rk(this._client),this.threads=new jk(this._client)}}md.Sessions=Rk;md.Threads=jk;class Lk extends F{create(e,n,r){return this._client.post(O`/threads/${e}/messages`,{body:n,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){const{thread_id:i}=n;return this._client.get(O`/threads/${i}/messages/${e}`,{...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}update(e,n,r){const{thread_id:i,...s}=n;return this._client.post(O`/threads/${i}/messages/${e}`,{body:s,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/threads/${e}/messages`,Fe,{query:n,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){const{thread_id:i}=n;return this._client.delete(O`/threads/${i}/messages/${e}`,{...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}class Mk extends F{retrieve(e,n,r){const{thread_id:i,run_id:s,...a}=n;return this._client.get(O`/threads/${i}/runs/${s}/steps/${e}`,{query:a,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,n,r){const{thread_id:i,...s}=n;return this._client.getAPIList(O`/threads/${i}/runs/${e}/steps`,Fe,{query:s,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}const hN=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,r=new Uint8Array(n);for(let i=0;i<n;i++)r[i]=e.charCodeAt(i);return Array.from(new Float32Array(r.buffer))}};var kf={};const Gr=t=>{var e,n,r,i;if(typeof globalThis.process<"u")return((e=kf==null?void 0:kf[t])==null?void 0:e.trim())||void 0;if(typeof globalThis.Deno<"u")return((i=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,t))==null?void 0:i.trim())||void 0};var ht,qi,cp,lr,Sl,Hn,Wi,js,Hi,yc,on,Al,El,go,Ja,Xa,nv,rv,iv,sv,av,ov,uv;class yo extends lg{constructor(){super(...arguments),ht.add(this),cp.set(this,[]),lr.set(this,{}),Sl.set(this,{}),Hn.set(this,void 0),Wi.set(this,void 0),js.set(this,void 0),Hi.set(this,void 0),yc.set(this,void 0),on.set(this,void 0),Al.set(this,void 0),El.set(this,void 0),go.set(this,void 0)}[(cp=new WeakMap,lr=new WeakMap,Sl=new WeakMap,Hn=new WeakMap,Wi=new WeakMap,js=new WeakMap,Hi=new WeakMap,yc=new WeakMap,on=new WeakMap,Al=new WeakMap,El=new WeakMap,go=new WeakMap,ht=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",i=>{const s=n.shift();s?s.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(const i of n)i.resolve(void 0);n.length=0}),this.on("abort",i=>{r=!0;for(const s of n)s.reject(i);n.length=0}),this.on("error",i=>{r=!0;for(const s of n)s.reject(i);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((s,a)=>n.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const n=new qi;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){var s;const r=n==null?void 0:n.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const i=hr.fromReadableStream(e,this.controller);for await(const a of i)P(this,ht,"m",Ja).call(this,a);if((s=i.controller.signal)!=null&&s.aborted)throw new dn;return this._addRun(P(this,ht,"m",Xa).call(this))}toReadableStream(){return new hr(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,r,i){const s=new qi;return s._run(()=>s._runToolAssistantStream(e,n,r,{...i,headers:{...i==null?void 0:i.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createToolAssistantStream(e,n,r,i){var u;const s=i==null?void 0:i.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},o=await e.submitToolOutputs(n,a,{...i,signal:this.controller.signal});this._connected();for await(const l of o)P(this,ht,"m",Ja).call(this,l);if((u=o.controller.signal)!=null&&u.aborted)throw new dn;return this._addRun(P(this,ht,"m",Xa).call(this))}static createThreadAssistantStream(e,n,r){const i=new qi;return i._run(()=>i._threadAssistantStream(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),i}static createAssistantStream(e,n,r,i){const s=new qi;return s._run(()=>s._runAssistantStream(e,n,r,{...i,headers:{...i==null?void 0:i.headers,"X-Stainless-Helper-Method":"stream"}})),s}currentEvent(){return P(this,Al,"f")}currentRun(){return P(this,El,"f")}currentMessageSnapshot(){return P(this,Hn,"f")}currentRunStepSnapshot(){return P(this,go,"f")}async finalRunSteps(){return await this.done(),Object.values(P(this,lr,"f"))}async finalMessages(){return await this.done(),Object.values(P(this,Sl,"f"))}async finalRun(){if(await this.done(),!P(this,Wi,"f"))throw Error("Final run was not received.");return P(this,Wi,"f")}async _createThreadAssistantStream(e,n,r){var o;const i=r==null?void 0:r.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const s={...n,stream:!0},a=await e.createAndRun(s,{...r,signal:this.controller.signal});this._connected();for await(const u of a)P(this,ht,"m",Ja).call(this,u);if((o=a.controller.signal)!=null&&o.aborted)throw new dn;return this._addRun(P(this,ht,"m",Xa).call(this))}async _createAssistantStream(e,n,r,i){var u;const s=i==null?void 0:i.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...r,stream:!0},o=await e.create(n,a,{...i,signal:this.controller.signal});this._connected();for await(const l of o)P(this,ht,"m",Ja).call(this,l);if((u=o.controller.signal)!=null&&u.aborted)throw new dn;return this._addRun(P(this,ht,"m",Xa).call(this))}static accumulateDelta(e,n){for(const[r,i]of Object.entries(n)){if(!e.hasOwnProperty(r)){e[r]=i;continue}let s=e[r];if(s==null){e[r]=i;continue}if(r==="index"||r==="type"){e[r]=i;continue}if(typeof s=="string"&&typeof i=="string")s+=i;else if(typeof s=="number"&&typeof i=="number")s+=i;else if(mf(s)&&mf(i))s=this.accumulateDelta(s,i);else if(Array.isArray(s)&&Array.isArray(i)){if(s.every(a=>typeof a=="string"||typeof a=="number")){s.push(...i);continue}for(const a of i){if(!mf(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const o=a.index;if(o==null)throw console.error(a),new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const u=s[o];u==null?s.push(a):s[o]=this.accumulateDelta(u,a)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${i}, accValue: ${s}`);e[r]=s}return e}_addRun(e){return e}async _threadAssistantStream(e,n,r){return await this._createThreadAssistantStream(n,e,r)}async _runAssistantStream(e,n,r,i){return await this._createAssistantStream(n,e,r,i)}async _runToolAssistantStream(e,n,r,i){return await this._createToolAssistantStream(n,e,r,i)}}qi=yo,Ja=function(e){if(!this.ended)switch(ne(this,Al,e),P(this,ht,"m",iv).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":P(this,ht,"m",uv).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":P(this,ht,"m",rv).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":P(this,ht,"m",nv).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Xa=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");if(!P(this,Wi,"f"))throw Error("Final run has not been received");return P(this,Wi,"f")},nv=function(e){const[n,r]=P(this,ht,"m",av).call(this,e,P(this,Hn,"f"));ne(this,Hn,n),P(this,Sl,"f")[n.id]=n;for(const i of r){const s=n.content[i.index];(s==null?void 0:s.type)=="text"&&this._emit("textCreated",s.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,n),e.data.delta.content)for(const i of e.data.delta.content){if(i.type=="text"&&i.text){let s=i.text,a=n.content[i.index];if(a&&a.type=="text")this._emit("textDelta",s,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(i.index!=P(this,js,"f")){if(P(this,Hi,"f"))switch(P(this,Hi,"f").type){case"text":this._emit("textDone",P(this,Hi,"f").text,P(this,Hn,"f"));break;case"image_file":this._emit("imageFileDone",P(this,Hi,"f").image_file,P(this,Hn,"f"));break}ne(this,js,i.index)}ne(this,Hi,n.content[i.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(P(this,js,"f")!==void 0){const i=e.data.content[P(this,js,"f")];if(i)switch(i.type){case"image_file":this._emit("imageFileDone",i.image_file,P(this,Hn,"f"));break;case"text":this._emit("textDone",i.text,P(this,Hn,"f"));break}}P(this,Hn,"f")&&this._emit("messageDone",e.data),ne(this,Hn,void 0)}},rv=function(e){const n=P(this,ht,"m",sv).call(this,e);switch(ne(this,go,n),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const r=e.data.delta;if(r.step_details&&r.step_details.type=="tool_calls"&&r.step_details.tool_calls&&n.step_details.type=="tool_calls")for(const s of r.step_details.tool_calls)s.index==P(this,yc,"f")?this._emit("toolCallDelta",s,n.step_details.tool_calls[s.index]):(P(this,on,"f")&&this._emit("toolCallDone",P(this,on,"f")),ne(this,yc,s.index),ne(this,on,n.step_details.tool_calls[s.index]),P(this,on,"f")&&this._emit("toolCallCreated",P(this,on,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":ne(this,go,void 0),e.data.step_details.type=="tool_calls"&&P(this,on,"f")&&(this._emit("toolCallDone",P(this,on,"f")),ne(this,on,void 0)),this._emit("runStepDone",e.data,n);break}},iv=function(e){P(this,cp,"f").push(e),this._emit("event",e)},sv=function(e){switch(e.event){case"thread.run.step.created":return P(this,lr,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=P(this,lr,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const i=qi.accumulateDelta(n,r.delta);P(this,lr,"f")[e.data.id]=i}return P(this,lr,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":P(this,lr,"f")[e.data.id]=e.data;break}if(P(this,lr,"f")[e.data.id])return P(this,lr,"f")[e.data.id];throw new Error("No snapshot available")},av=function(e,n){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!n)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let i=e.data;if(i.delta.content)for(const s of i.delta.content)if(s.index in n.content){let a=n.content[s.index];n.content[s.index]=P(this,ht,"m",ov).call(this,s,a)}else n.content[s.index]=s,r.push(s);return[n,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},ov=function(e,n){return qi.accumulateDelta(n,e)},uv=function(e){switch(ne(this,El,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":ne(this,Wi,e.data),P(this,on,"f")&&(this._emit("toolCallDone",P(this,on,"f")),ne(this,on,void 0));break}};let yg=class extends F{constructor(){super(...arguments),this.steps=new Mk(this._client)}create(e,n,r){const{include:i,...s}=n;return this._client.post(O`/threads/${e}/runs`,{query:{include:i},body:s,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,n,r){const{thread_id:i}=n;return this._client.get(O`/threads/${i}/runs/${e}`,{...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}update(e,n,r){const{thread_id:i,...s}=n;return this._client.post(O`/threads/${i}/runs/${e}`,{body:s,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/threads/${e}/runs`,Fe,{query:n,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){const{thread_id:i}=n;return this._client.post(O`/threads/${i}/runs/${e}/cancel`,{...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){const i=await this.create(e,n,r);return await this.poll(i.id,{thread_id:e},r)}createAndStream(e,n,r){return yo.createAssistantStream(e,this._client.beta.threads.runs,n,r)}async poll(e,n,r){var s;const i=Z([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((s=r==null?void 0:r.pollIntervalMs)==null?void 0:s.toString())??void 0}]);for(;;){const{data:a,response:o}=await this.retrieve(e,n,{...r,headers:{...r==null?void 0:r.headers,...i}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const l=o.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(u=c)}}await au(u);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,n,r){return yo.createAssistantStream(e,this._client.beta.threads.runs,n,r)}submitToolOutputs(e,n,r){const{thread_id:i,...s}=n;return this._client.post(O`/threads/${i}/runs/${e}/submit_tool_outputs`,{body:s,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:n.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,n,r){const i=await this.submitToolOutputs(e,n,r);return await this.poll(i.id,n,r)}submitToolOutputsStream(e,n,r){return yo.createToolAssistantStream(e,this._client.beta.threads.runs,n,r)}};yg.Steps=Mk;class gd extends F{constructor(){super(...arguments),this.runs=new yg(this._client),this.messages=new Lk(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(O`/threads/${e}`,{...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(O`/threads/${e}`,{body:n,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/threads/${e}`,{...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,n){const r=await this.createAndRun(e,n);return await this.runs.poll(r.id,{thread_id:r.thread_id},n)}createAndRunStream(e,n){return yo.createThreadAssistantStream(e,this._client.beta.threads,n)}}gd.Runs=yg;gd.Messages=Lk;class wa extends F{constructor(){super(...arguments),this.realtime=new pd(this._client),this.chatkit=new md(this._client),this.assistants=new Pk(this._client),this.threads=new gd(this._client)}}wa.Realtime=pd;wa.ChatKit=md;wa.Assistants=Pk;wa.Threads=gd;class zk extends F{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}}let Dk=class extends F{retrieve(e,n,r){const{container_id:i}=n;return this._client.get(O`/containers/${i}/files/${e}/content`,{...r,headers:Z([{Accept:"application/binary"},r==null?void 0:r.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}},_g=class extends F{constructor(){super(...arguments),this.content=new Dk(this._client)}create(e,n,r){return this._client.post(O`/containers/${e}/files`,fd({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){const{container_id:i}=n;return this._client.get(O`/containers/${i}/files/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/containers/${e}/files`,Fe,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){const{container_id:i}=n;return this._client.delete(O`/containers/${i}/files/${e}`,{...r,headers:Z([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}};_g.Content=Dk;class vg extends F{constructor(){super(...arguments),this.files=new _g(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(O`/containers/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/containers",Fe,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/containers/${e}`,{...n,headers:Z([{Accept:"*/*"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}}vg.Files=_g;class Uk extends F{create(e,n,r){const{include:i,...s}=n;return this._client.post(O`/conversations/${e}/items`,{query:{include:i},body:s,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){const{conversation_id:i,...s}=n;return this._client.get(O`/conversations/${i}/items/${e}`,{query:s,...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/conversations/${e}/items`,yt,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){const{conversation_id:i}=n;return this._client.delete(O`/conversations/${i}/items/${e}`,{...r,__security:{bearerAuth:!0}})}}class wg extends F{constructor(){super(...arguments),this.items=new Uk(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(O`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(O`/conversations/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/conversations/${e}`,{...n,__security:{bearerAuth:!0}})}}wg.Items=Uk;let Fk=class extends F{create(e,n){const r=!!e.encoding_format;let i=r?e.encoding_format:"base64";r&&ft(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const s=this._client.post("/embeddings",{body:{...e,encoding_format:i},...n,__security:{bearerAuth:!0}});return r?s:(ft(this._client).debug("embeddings/decoding base64 embeddings from base64"),s._thenUnwrap(a=>(a&&a.data&&a.data.forEach(o=>{const u=o.embedding;o.embedding=hN(u)}),a)))}};class Bk extends F{retrieve(e,n,r){const{eval_id:i,run_id:s}=n;return this._client.get(O`/evals/${i}/runs/${s}/output_items/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n,r){const{eval_id:i,...s}=n;return this._client.getAPIList(O`/evals/${i}/runs/${e}/output_items`,Fe,{query:s,...r,__security:{bearerAuth:!0}})}}let bg=class extends F{constructor(){super(...arguments),this.outputItems=new Bk(this._client)}create(e,n,r){return this._client.post(O`/evals/${e}/runs`,{body:n,...r,__security:{bearerAuth:!0}})}retrieve(e,n,r){const{eval_id:i}=n;return this._client.get(O`/evals/${i}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/evals/${e}/runs`,Fe,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){const{eval_id:i}=n;return this._client.delete(O`/evals/${i}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}cancel(e,n,r){const{eval_id:i}=n;return this._client.post(O`/evals/${i}/runs/${e}`,{...r,__security:{bearerAuth:!0}})}};bg.OutputItems=Bk;class xg extends F{constructor(){super(...arguments),this.runs=new bg(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(O`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(O`/evals/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/evals",Fe,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/evals/${e}`,{...n,__security:{bearerAuth:!0}})}}xg.Runs=bg;let Hk=class extends F{create(e,n){return this._client.post("/files",pr({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(O`/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/files",Fe,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/files/${e}`,{...n,__security:{bearerAuth:!0}})}content(e,n){return this._client.get(O`/files/${e}/content`,{...n,headers:Z([{Accept:"application/binary"},n==null?void 0:n.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=5e3,maxWait:r=30*60*1e3}={}){const i=new Set(["processed","error","deleted"]),s=Date.now();let a=await this.retrieve(e);for(;!a.status||!i.has(a.status);)if(await au(n),a=await this.retrieve(e),Date.now()-s>r)throw new ld({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return a}};class Zk extends F{}let Vk=class extends F{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n,__security:{bearerAuth:!0}})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n,__security:{bearerAuth:!0}})}};class kg extends F{constructor(){super(...arguments),this.graders=new Vk(this._client)}}kg.Graders=Vk;class Kk extends F{create(e,n,r){return this._client.getAPIList(O`/fine_tuning/checkpoints/${e}/permissions`,xi,{body:n,method:"post",...r,__security:{adminAPIKeyAuth:!0}})}retrieve(e,n={},r){return this._client.get(O`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/fine_tuning/checkpoints/${e}/permissions`,yt,{query:n,...r,__security:{adminAPIKeyAuth:!0}})}delete(e,n,r){const{fine_tuned_model_checkpoint:i}=n;return this._client.delete(O`/fine_tuning/checkpoints/${i}/permissions/${e}`,{...r,__security:{adminAPIKeyAuth:!0}})}}let Sg=class extends F{constructor(){super(...arguments),this.permissions=new Kk(this._client)}};Sg.Permissions=Kk;class qk extends F{list(e,n={},r){return this._client.getAPIList(O`/fine_tuning/jobs/${e}/checkpoints`,Fe,{query:n,...r,__security:{bearerAuth:!0}})}}class Ag extends F{constructor(){super(...arguments),this.checkpoints=new qk(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n,__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(O`/fine_tuning/jobs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",Fe,{query:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(O`/fine_tuning/jobs/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}listEvents(e,n={},r){return this._client.getAPIList(O`/fine_tuning/jobs/${e}/events`,Fe,{query:n,...r,__security:{bearerAuth:!0}})}pause(e,n){return this._client.post(O`/fine_tuning/jobs/${e}/pause`,{...n,__security:{bearerAuth:!0}})}resume(e,n){return this._client.post(O`/fine_tuning/jobs/${e}/resume`,{...n,__security:{bearerAuth:!0}})}}Ag.Checkpoints=qk;class ba extends F{constructor(){super(...arguments),this.methods=new Zk(this._client),this.jobs=new Ag(this._client),this.checkpoints=new Sg(this._client),this.alpha=new kg(this._client)}}ba.Methods=Zk;ba.Jobs=Ag;ba.Checkpoints=Sg;ba.Alpha=kg;class Wk extends F{}class Eg extends F{constructor(){super(...arguments),this.graderModels=new Wk(this._client)}}Eg.GraderModels=Wk;class Gk extends F{createVariation(e,n){return this._client.post("/images/variations",pr({body:e,...n,__security:{bearerAuth:!0}},this._client))}edit(e,n){return this._client.post("/images/edits",pr({body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})}}class Jk extends F{retrieve(e,n){return this._client.get(O`/models/${e}`,{...n,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList("/models",xi,{...e,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/models/${e}`,{...n,__security:{bearerAuth:!0}})}}class Xk extends F{create(e,n){return this._client.post("/moderations",{body:e,...n,__security:{bearerAuth:!0}})}}class Qk extends F{accept(e,n,r){return this._client.post(O`/realtime/calls/${e}/accept`,{body:n,...r,headers:Z([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}hangup(e,n){return this._client.post(O`/realtime/calls/${e}/hangup`,{...n,headers:Z([{Accept:"*/*"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}refer(e,n,r){return this._client.post(O`/realtime/calls/${e}/refer`,{body:n,...r,headers:Z([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}reject(e,n={},r){return this._client.post(O`/realtime/calls/${e}/reject`,{body:n,...r,headers:Z([{Accept:"*/*"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}class Yk extends F{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n,__security:{bearerAuth:!0}})}}class yd extends F{constructor(){super(...arguments),this.clientSecrets=new Yk(this._client),this.calls=new Qk(this._client)}}yd.ClientSecrets=Yk;yd.Calls=Qk;function pN(t,e){return!e||!gN(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(r=>({...r,parsed:null}))}:n)}:eS(t,e)}function eS(t,e){const n=t.output.map(i=>{if(i.type==="function_call")return{...i,parsed_arguments:vN(e,i)};if(i.type==="message"){const s=i.content.map(a=>a.type==="output_text"?{...a,parsed:mN(e,a.text)}:a);return{...i,content:s}}return i}),r=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||dp(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const i of r.output)if(i.type==="message"){for(const s of i.content)if(s.type==="output_text"&&s.parsed!==null)return s.parsed}return null}}),r}function mN(t,e){var n,r,i,s;return((r=(n=t.text)==null?void 0:n.format)==null?void 0:r.type)!=="json_schema"?null:"$parseRaw"in((i=t.text)==null?void 0:i.format)?((s=t.text)==null?void 0:s.format).$parseRaw(e):JSON.parse(e)}function gN(t){var e;return!!og((e=t.text)==null?void 0:e.format)}function yN(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function _N(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function vN(t,e){const n=_N(t.tools??[],e.name);return{...e,...e,parsed_arguments:yN(n)?n.$parseRaw(e.arguments):n!=null&&n.strict?JSON.parse(e.arguments):null}}function dp(t){const e=[];for(const n of t.output)if(n.type==="message")for(const r of n.content)r.type==="output_text"&&e.push(r.text);t.output_text=e.join("")}var ps,Du,Jr,Uu,lv,cv,dv,fv;class Tg extends lg{constructor(e){super(),ps.add(this),Du.set(this,void 0),Jr.set(this,void 0),Uu.set(this,void 0),ne(this,Du,e)}static createResponse(e,n,r){const i=new Tg(n);return i._run(()=>i._createOrRetrieveResponse(e,n,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createOrRetrieveResponse(e,n,r){var o;const i=r==null?void 0:r.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort())),P(this,ps,"m",lv).call(this);let s,a=null;"response_id"in n?(s=await e.responses.retrieve(n.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),a=n.starting_after??null):s=await e.responses.create({...n,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const u of s)P(this,ps,"m",cv).call(this,u,a);if((o=s.controller.signal)!=null&&o.aborted)throw new dn;return P(this,ps,"m",dv).call(this)}[(Du=new WeakMap,Jr=new WeakMap,Uu=new WeakMap,ps=new WeakSet,lv=function(){this.ended||ne(this,Jr,void 0)},cv=function(n,r){if(this.ended)return;const i=(a,o)=>{(r==null||o.sequence_number>r)&&this._emit(a,o)},s=P(this,ps,"m",fv).call(this,n);switch(i("event",n),n.type){case"response.output_text.delta":{const a=s.output[n.output_index];if(!a)throw new Y(`missing output at index ${n.output_index}`);if(a.type==="message"){const o=a.content[n.content_index];if(!o)throw new Y(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new Y(`expected content to be 'output_text', got ${o.type}`);i("response.output_text.delta",{...n,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const a=s.output[n.output_index];if(!a)throw new Y(`missing output at index ${n.output_index}`);a.type==="function_call"&&i("response.function_call_arguments.delta",{...n,snapshot:a.arguments});break}default:i(n.type,n);break}},dv=function(){if(this.ended)throw new Y("stream has ended, this shouldn't happen");const n=P(this,Jr,"f");if(!n)throw new Y("request ended without sending any events");ne(this,Jr,void 0);const r=wN(n,P(this,Du,"f"));return ne(this,Uu,r),r},fv=function(n){var i;let r=P(this,Jr,"f");if(!r){if(n.type!=="response.created")throw new Y(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return r=ne(this,Jr,n.response),r}switch(n.type){case"response.output_item.added":{r.output.push(n.item);break}case"response.content_part.added":{const s=r.output[n.output_index];if(!s)throw new Y(`missing output at index ${n.output_index}`);const a=s.type,o=n.part;a==="message"&&o.type!=="reasoning_text"?s.content.push(o):a==="reasoning"&&o.type==="reasoning_text"&&(s.content||(s.content=[]),s.content.push(o));break}case"response.output_text.delta":{const s=r.output[n.output_index];if(!s)throw new Y(`missing output at index ${n.output_index}`);if(s.type==="message"){const a=s.content[n.content_index];if(!a)throw new Y(`missing content at index ${n.content_index}`);if(a.type!=="output_text")throw new Y(`expected content to be 'output_text', got ${a.type}`);a.text+=n.delta}break}case"response.function_call_arguments.delta":{const s=r.output[n.output_index];if(!s)throw new Y(`missing output at index ${n.output_index}`);s.type==="function_call"&&(s.arguments+=n.delta);break}case"response.reasoning_text.delta":{const s=r.output[n.output_index];if(!s)throw new Y(`missing output at index ${n.output_index}`);if(s.type==="reasoning"){const a=(i=s.content)==null?void 0:i[n.content_index];if(!a)throw new Y(`missing content at index ${n.content_index}`);if(a.type!=="reasoning_text")throw new Y(`expected content to be 'reasoning_text', got ${a.type}`);a.text+=n.delta}break}case"response.completed":{ne(this,Jr,n.response);break}}return r},Symbol.asyncIterator)](){const e=[],n=[];let r=!1;return this.on("event",i=>{const s=n.shift();s?s.resolve(i):e.push(i)}),this.on("end",()=>{r=!0;for(const i of n)i.resolve(void 0);n.length=0}),this.on("abort",i=>{r=!0;for(const s of n)s.reject(i);n.length=0}),this.on("error",i=>{r=!0;for(const s of n)s.reject(i);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((s,a)=>n.push({resolve:s,reject:a})).then(s=>s?{value:s,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=P(this,Uu,"f");if(!e)throw new Y("stream ended without producing a ChatCompletion");return e}}function wN(t,e){return pN(t,e)}class tS extends F{list(e,n={},r){return this._client.getAPIList(O`/responses/${e}/input_items`,Fe,{query:n,...r,__security:{bearerAuth:!0}})}}class nS extends F{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n,__security:{bearerAuth:!0}})}}class _d extends F{constructor(){super(...arguments),this.inputItems=new tS(this._client),this.inputTokens=new nS(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(r=>("object"in r&&r.object==="response"&&dp(r),r))}retrieve(e,n={},r){return this._client.get(O`/responses/${e}`,{query:n,...r,stream:(n==null?void 0:n.stream)??!1,__security:{bearerAuth:!0}})._thenUnwrap(i=>("object"in i&&i.object==="response"&&dp(i),i))}delete(e,n){return this._client.delete(O`/responses/${e}`,{...n,headers:Z([{Accept:"*/*"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(r=>eS(r,e))}stream(e,n){return Tg.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(O`/responses/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}compact(e,n){return this._client.post("/responses/compact",{body:e,...n,__security:{bearerAuth:!0}})}}_d.InputItems=tS;_d.InputTokens=nS;let rS=class extends F{retrieve(e,n){return this._client.get(O`/skills/${e}/content`,{...n,headers:Z([{Accept:"application/binary"},n==null?void 0:n.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}};class iS extends F{retrieve(e,n,r){const{skill_id:i}=n;return this._client.get(O`/skills/${i}/versions/${e}/content`,{...r,headers:Z([{Accept:"application/binary"},r==null?void 0:r.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}let Ig=class extends F{constructor(){super(...arguments),this.content=new iS(this._client)}create(e,n={},r){return this._client.post(O`/skills/${e}/versions`,fd({body:n,...r,__security:{bearerAuth:!0}},this._client))}retrieve(e,n,r){const{skill_id:i}=n;return this._client.get(O`/skills/${i}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/skills/${e}/versions`,Fe,{query:n,...r,__security:{bearerAuth:!0}})}delete(e,n,r){const{skill_id:i}=n;return this._client.delete(O`/skills/${i}/versions/${e}`,{...r,__security:{bearerAuth:!0}})}};Ig.Content=iS;class vd extends F{constructor(){super(...arguments),this.content=new rS(this._client),this.versions=new Ig(this._client)}create(e={},n){return this._client.post("/skills",fd({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(O`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(O`/skills/${e}`,{body:n,...r,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/skills",Fe,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/skills/${e}`,{...n,__security:{bearerAuth:!0}})}}vd.Content=rS;vd.Versions=Ig;class sS extends F{create(e,n,r){return this._client.post(O`/uploads/${e}/parts`,pr({body:n,...r,__security:{bearerAuth:!0}},this._client))}}class Og extends F{constructor(){super(...arguments),this.parts=new sS(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n,__security:{bearerAuth:!0}})}cancel(e,n){return this._client.post(O`/uploads/${e}/cancel`,{...n,__security:{bearerAuth:!0}})}complete(e,n,r){return this._client.post(O`/uploads/${e}/complete`,{body:n,...r,__security:{bearerAuth:!0}})}}Og.Parts=sS;const bN=async t=>{const e=await Promise.allSettled(t),n=e.filter(i=>i.status==="rejected");if(n.length){for(const i of n)console.error(i.reason);throw new Error(`${n.length} promise(s) failed - see the above errors`)}const r=[];for(const i of e)i.status==="fulfilled"&&r.push(i.value);return r};class aS extends F{create(e,n,r){return this._client.post(O`/vector_stores/${e}/file_batches`,{body:n,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){const{vector_store_id:i}=n;return this._client.get(O`/vector_stores/${i}/file_batches/${e}`,{...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}cancel(e,n,r){const{vector_store_id:i}=n;return this._client.post(O`/vector_stores/${i}/file_batches/${e}/cancel`,{...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){const i=await this.create(e,n);return await this.poll(e,i.id,r)}listFiles(e,n,r){const{vector_store_id:i,...s}=n;return this._client.getAPIList(O`/vector_stores/${i}/file_batches/${e}/files`,Fe,{query:s,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async poll(e,n,r){var s;const i=Z([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((s=r==null?void 0:r.pollIntervalMs)==null?void 0:s.toString())??void 0}]);for(;;){const{data:a,response:o}=await this.retrieve(n,{vector_store_id:e},{...r,headers:i}).withResponse();switch(a.status){case"in_progress":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const l=o.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(u=c)}}await au(u);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:n,fileIds:r=[]},i){if(n==null||n.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const s=(i==null?void 0:i.maxConcurrency)??5,a=Math.min(s,n.length),o=this._client,u=n.values(),l=[...r];async function c(f){for(let h of f){const m=await o.files.create({file:h,purpose:"assistants"},i);l.push(m.id)}}const d=Array(a).fill(u).map(c);return await bN(d),await this.createAndPoll(e,{file_ids:l})}}class oS extends F{create(e,n,r){return this._client.post(O`/vector_stores/${e}/files`,{body:n,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}retrieve(e,n,r){const{vector_store_id:i}=n;return this._client.get(O`/vector_stores/${i}/files/${e}`,{...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}update(e,n,r){const{vector_store_id:i,...s}=n;return this._client.post(O`/vector_stores/${i}/files/${e}`,{body:s,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e,n={},r){return this._client.getAPIList(O`/vector_stores/${e}/files`,Fe,{query:n,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}delete(e,n,r){const{vector_store_id:i}=n;return this._client.delete(O`/vector_stores/${i}/files/${e}`,{...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,n,r){const i=await this.create(e,n,r);return await this.poll(e,i.id,r)}async poll(e,n,r){var s;const i=Z([r==null?void 0:r.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":((s=r==null?void 0:r.pollIntervalMs)==null?void 0:s.toString())??void 0}]);for(;;){const a=await this.retrieve(n,{vector_store_id:e},{...r,headers:i}).withResponse(),o=a.data;switch(o.status){case"in_progress":let u=5e3;if(r!=null&&r.pollIntervalMs)u=r.pollIntervalMs;else{const l=a.response.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(u=c)}}await au(u);break;case"failed":case"completed":return o}}}async upload(e,n,r){const i=await this._client.files.create({file:n,purpose:"assistants"},r);return this.create(e,{file_id:i.id},r)}async uploadAndPoll(e,n,r){const i=await this.upload(e,n,r);return await this.poll(e,i.id,r)}content(e,n,r){const{vector_store_id:i}=n;return this._client.getAPIList(O`/vector_stores/${i}/files/${e}/content`,xi,{...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}class wd extends F{constructor(){super(...arguments),this.files=new oS(this._client),this.fileBatches=new aS(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}retrieve(e,n){return this._client.get(O`/vector_stores/${e}`,{...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}update(e,n,r){return this._client.post(O`/vector_stores/${e}`,{body:n,...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/vector_stores",Fe,{query:e,...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/vector_stores/${e}`,{...n,headers:Z([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),__security:{bearerAuth:!0}})}search(e,n,r){return this._client.getAPIList(O`/vector_stores/${e}/search`,xi,{body:n,method:"post",...r,headers:Z([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),__security:{bearerAuth:!0}})}}wd.Files=oS;wd.FileBatches=aS;class uS extends F{create(e,n){return this._client.post("/videos",pr({body:e,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,n){return this._client.get(O`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}list(e={},n){return this._client.getAPIList("/videos",yt,{query:e,...n,__security:{bearerAuth:!0}})}delete(e,n){return this._client.delete(O`/videos/${e}`,{...n,__security:{bearerAuth:!0}})}createCharacter(e,n){return this._client.post("/videos/characters",pr({body:e,...n,__security:{bearerAuth:!0}},this._client))}downloadContent(e,n={},r){return this._client.get(O`/videos/${e}/content`,{query:n,...r,headers:Z([{Accept:"application/binary"},r==null?void 0:r.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,n){return this._client.post("/videos/edits",pr({body:e,...n,__security:{bearerAuth:!0}},this._client))}extend(e,n){return this._client.post("/videos/extensions",pr({body:e,...n,__security:{bearerAuth:!0}},this._client))}getCharacter(e,n){return this._client.get(O`/videos/characters/${e}`,{...n,__security:{bearerAuth:!0}})}remix(e,n,r){return this._client.post(O`/videos/${e}/remix`,fd({body:n,...r,__security:{bearerAuth:!0}},this._client))}}var ws,lS,Tl;class cS extends F{constructor(){super(...arguments),ws.add(this)}async unwrap(e,n,r=this._client.webhookSecret,i=300){return await this.verifySignature(e,n,r,i),JSON.parse(e)}async verifySignature(e,n,r=this._client.webhookSecret,i=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");P(this,ws,"m",lS).call(this,r);const s=Z([n]).values,a=P(this,ws,"m",Tl).call(this,s,"webhook-signature"),o=P(this,ws,"m",Tl).call(this,s,"webhook-timestamp"),u=P(this,ws,"m",Tl).call(this,s,"webhook-id"),l=parseInt(o,10);if(isNaN(l))throw new Ha("Invalid webhook timestamp format");const c=Math.floor(Date.now()/1e3);if(c-l>i)throw new Ha("Webhook timestamp is too old");if(l>c+i)throw new Ha("Webhook timestamp is too new");const d=a.split(" ").map(_=>_.startsWith("v1,")?_.substring(3):_),f=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),h=u?`${u}.${o}.${e}`:`${o}.${e}`,m=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const _ of d)try{const v=Buffer.from(_,"base64");if(await crypto.subtle.verify("HMAC",m,v,new TextEncoder().encode(h)))return}catch{continue}throw new Ha("The given webhook signature does not match the expected signature")}}ws=new WeakSet,lS=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},Tl=function(e,n){if(!e)throw new Error("Headers are required");const r=e.get(n);if(r==null)throw new Error(`Missing required header: ${n}`);return r};var fp,Cg,Il,dS;const xN="workload-identity-auth";class oe{constructor({baseURL:e=Gr("OPENAI_BASE_URL"),apiKey:n=Gr("OPENAI_API_KEY")??null,adminAPIKey:r=Gr("OPENAI_ADMIN_KEY")??null,organization:i=Gr("OPENAI_ORG_ID")??null,project:s=Gr("OPENAI_PROJECT_ID")??null,webhookSecret:a=Gr("OPENAI_WEBHOOK_SECRET")??null,workloadIdentity:o,...u}={}){fp.add(this),Il.set(this,void 0),this.completions=new zk(this),this.chat=new fg(this),this.embeddings=new Fk(this),this.files=new Hk(this),this.images=new Gk(this),this.audio=new uu(this),this.moderations=new Xk(this),this.models=new Jk(this),this.fineTuning=new ba(this),this.graders=new Eg(this),this.vectorStores=new wd(this),this.webhooks=new cS(this),this.beta=new wa(this),this.batches=new Ck(this),this.uploads=new Og(this),this.admin=new gg(this),this.responses=new _d(this),this.realtime=new yd(this),this.conversations=new wg(this),this.evals=new xg(this),this.containers=new vg(this),this.skills=new vd(this),this.videos=new uS(this);const l={apiKey:n,adminAPIKey:r,organization:i,project:s,webhookSecret:a,workloadIdentity:o,...u,baseURL:e||"https://api.openai.com/v1"};if(n&&o)throw new Y("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!n&&!r&&!o)throw new Y("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!l.dangerouslyAllowBrowser&&wP())throw new Y(`It looks like you're running in a browser-like environment. This is disabled by default, as it risks exposing your secret API credentials to attackers. If you understand the risks and have appropriate mitigations in place, you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g., new OpenAI({ apiKey, dangerouslyAllowBrowser: true }); https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety `);this.baseURL=l.baseURL,this.timeout=l.timeout??Cg.DEFAULT_TIMEOUT,this.logger=l.logger??console;const c="warn";this.logLevel=c,this.logLevel=J_(l.logLevel,"ClientOptions.logLevel",this)??J_(Gr("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??c,this.fetchOptions=l.fetchOptions,this.maxRetries=l.maxRetries??2,this.fetch=l.fetch??v1(),ne(this,Il,AP);const d=Gr("OPENAI_CUSTOM_HEADERS");if(d){const f={};for(const h of d.split(` `)){const m=h.indexOf(":");m>=0&&(f[h.substring(0,m).trim()]=h.substring(m+1).trim())}l.defaultHeaders=Z([f,l.defaultHeaders])}this._options=l,o&&(this._workloadIdentityAuth=new ZP(o,this.fetch)),this.apiKey=typeof n=="string"?n:null,this.adminAPIKey=r,this.organization=i,this.project=s,this.webhookSecret=a}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n},r={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get("authorization")||e.get("api-key"))&&!(n.has("authorization")||n.has("api-key"))&&!(this._workloadIdentityAuth&&r.bearerAuth))throw new Error('Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted')}async authHeaders(e,n={bearerAuth:!0,adminAPIKeyAuth:!0}){return Z([n.bearerAuth?await this.bearerAuth(e):null,n.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return Z([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return Z([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return Z([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return NP(e)}getUserAgent(){return`${this.constructor.name}/JS ${_s}`}defaultIdempotencyKey(){return`stainless-node-retry-${o1()}`}makeStatusError(e,n,r,i){return St.generate(e,n,r,i)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(r){throw r instanceof Y?r:new Y(`Failed to get token from 'apiKey' function: ${r.message}`,{cause:r})}if(typeof n!="string"||!n)throw new Y(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,r){const i=!P(this,fp,"m",dS).call(this)&&r||this.baseURL,s=gP(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(s.searchParams);return(!D_(a)||!D_(o))&&(n={...o,...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(s.search=this.stringifyQuery(n)),s.toString()}async prepareOptions(e){(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(i=>({method:e,path:n,...i})))}request(e,n=null){return new C1(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){var p,g,b,E;const i=await e,s=i.maxRetries??this.maxRetries;n==null&&(n=s),await this.prepareOptions(i);const{req:a,url:o,timeout:u}=await this.buildRequest(i,{retryCount:s-n});await this.prepareRequest(a,{url:o,options:i});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(ft(this).debug(`[${l}] sending request`,Di({retryOfRequestLogID:r,method:i.method,url:o,options:i,headers:a.headers})),(p=i.signal)!=null&&p.aborted)throw new dn;const f=i.__security??{bearerAuth:!0},h=new AbortController,m=await this.fetchWithAuth(o,a,u,h,f).catch(Yh),_=Date.now();if(m instanceof globalThis.Error){const T=`retrying, ${n} attempts remaining`;if((g=i.signal)!=null&&g.aborted)throw new dn;const I=Qh(m)||/timed? ?out/i.test(String(m)+("cause"in m?String(m.cause):""));if(n)return ft(this).info(`[${l}] connection ${I?"timed out":"failed"} - ${T}`),ft(this).debug(`[${l}] connection ${I?"timed out":"failed"} (${T})`,Di({retryOfRequestLogID:r,url:o,durationMs:_-d,message:m.message})),this.retryRequest(i,n,r??l);throw ft(this).info(`[${l}] connection ${I?"timed out":"failed"} - error; no more retries left`),ft(this).debug(`[${l}] connection ${I?"timed out":"failed"} (error; no more retries left)`,Di({retryOfRequestLogID:r,url:o,durationMs:_-d,message:m.message})),m instanceof _1||m instanceof pP?m:I?new ld:new ud({message:kN(m),cause:m})}const v=[...m.headers.entries()].filter(([T])=>T==="x-request-id").map(([T,I])=>", "+T+": "+JSON.stringify(I)).join(""),y=`[${l}${c}${v}] ${a.method} ${o} ${m.ok?"succeeded":"failed"} with status ${m.status} in ${_-d}ms`;if(!m.ok){if(m.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!((b=i.__metadata)!=null&&b.hasStreamingBody)&&!((E=i.__metadata)!=null&&E.workloadIdentityTokenRefreshed))return await H_(m.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...i,__metadata:{...i.__metadata,workloadIdentityTokenRefreshed:!0}},n,r??l);const T=await this.shouldRetry(m);if(n&&T){const ue=`retrying, ${n} attempts remaining`;return await H_(m.body),ft(this).info(`${y} - ${ue}`),ft(this).debug(`[${l}] response error (${ue})`,Di({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:_-d})),this.retryRequest(i,n,r??l,m.headers)}const I=T?"error; no more retries left":"error; not retryable";ft(this).info(`${y} - ${I}`);const k=await m.text().catch(ue=>Yh(ue).message),j=vP(k),N=j?void 0:k;throw ft(this).debug(`[${l}] response error (${I})`,Di({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,message:N,durationMs:Date.now()-d})),this.makeStatusError(m.status,j,N,m.headers)}return ft(this).info(y),ft(this).debug(`[${l}] response start`,Di({retryOfRequestLogID:r,url:m.url,status:m.status,headers:m.headers,durationMs:_-d})),{response:m,options:i,controller:h,requestLogID:l,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...r})}requestAPIList(e,n){const r=this.makeRequest(n,null,void 0);return new FP(this,r,e)}async fetchWithAuth(e,n,r,i,s={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&s.bearerAuth){const o=n.headers,u=o.get("Authorization");if(!u||u===`Bearer ${xN}`){const l=await this._workloadIdentityAuth.getToken();o.set("Authorization",`Bearer ${l}`)}}return await this.fetchWithTimeout(e,n,r,i)}async fetchWithTimeout(e,n,r,i){const{signal:s,method:a,...o}=n||{},u=this._makeAbort(i);s&&s.addEventListener("abort",u,{once:!0});const l=setTimeout(u,r),c=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:i.signal,...c?{duplex:"half"}:{},method:"GET",...o};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,i){let s;const a=i==null?void 0:i.get("retry-after-ms");if(a){const u=parseFloat(a);Number.isNaN(u)||(s=u)}const o=i==null?void 0:i.get("retry-after");if(o&&!s){const u=parseFloat(o);Number.isNaN(u)?s=Date.parse(o)-Date.now():s=u*1e3}if(s===void 0){const u=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(n,u)}return await au(s),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){const s=n-e,a=Math.min(.5*Math.pow(2,s),8),o=1-Math.random()*.25;return a*o*1e3}async buildRequest(e,{retryCount:n=0}={}){const r={...e},{method:i,path:s,query:a,defaultBaseURL:o}=r,u=this.buildURL(s,a,o);"timeout"in r&&_P("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:l,body:c,isStreamingBody:d}=this.buildBody({options:r});d&&(e.__metadata={...e.__metadata,hasStreamingBody:!0});const f=await this.buildHeaders({options:e,method:i,bodyHeaders:l,retryCount:n});return{req:{method:i,headers:f,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:i}){let s={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const a=Z([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...SP(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};const r=Z([n]),i=typeof globalThis.ReadableStream<"u"&&e instanceof globalThis.ReadableStream,s=!i&&(typeof e=="string"||e instanceof ArrayBuffer||ArrayBuffer.isView(e)||typeof globalThis.Blob<"u"&&e instanceof globalThis.Blob||e instanceof URLSearchParams||e instanceof FormData);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||i?{bodyHeaders:void 0,body:e,isStreamingBody:!s}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:b1(e),isStreamingBody:!0}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e),isStreamingBody:!1}:{...P(this,Il,"f").call(this,{body:e,headers:r}),isStreamingBody:!1}}}Cg=oe,Il=new WeakMap,fp=new WeakSet,dS=function(){return this.baseURL!=="https://api.openai.com/v1"};oe.OpenAI=Cg;oe.DEFAULT_TIMEOUT=6e5;oe.OpenAIError=Y;oe.APIError=St;oe.APIConnectionError=ud;oe.APIConnectionTimeoutError=ld;oe.APIUserAbortError=dn;oe.NotFoundError=d1;oe.ConflictError=f1;oe.RateLimitError=p1;oe.BadRequestError=u1;oe.AuthenticationError=l1;oe.InternalServerError=m1;oe.PermissionDeniedError=c1;oe.UnprocessableEntityError=h1;oe.InvalidWebhookSignatureError=Ha;oe.toFile=GP;oe.Completions=zk;oe.Chat=fg;oe.Embeddings=Fk;oe.Files=Hk;oe.Images=Gk;oe.Audio=uu;oe.Moderations=Xk;oe.Models=Jk;oe.FineTuning=ba;oe.Graders=Eg;oe.VectorStores=wd;oe.Webhooks=cS;oe.Beta=wa;oe.Batches=Ck;oe.Uploads=Og;oe.Admin=gg;oe.Responses=_d;oe.Realtime=yd;oe.Conversations=wg;oe.Evals=xg;oe.Containers=vg;oe.Skills=vd;oe.Videos=uS;function kN(t){if(SN(t))return"Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });"}function SN(t){let e=t;for(let n=0;n<8&&e&&typeof e=="object";n++){const r=e;if(r.code==="UND_ERR_INVALID_ARG"&&typeof r.message=="string"&&r.message.includes("invalid onRequestStart method"))return!0;e=r.cause}return!1}var hv=Object.defineProperty,AN=(t,e)=>{let n={};for(var r in t)hv(n,r,{get:t[r],enumerable:!0});return hv(n,Symbol.toStringTag,{value:"Module"}),n};function fS(t){const e=Symbol.for(t);return{brand(n,r){var a,o;const i=r?Symbol.for(`${t}.${r}`):e;class s extends(o=n,a=i,o){constructor(...c){super(...c);A(this,a,!0)}static isInstance(c){return typeof c=="object"&&c!==null&&i in c&&c[i]===!0}}return Object.defineProperty(s,"name",{value:n.name}),s},sub(n){return fS(`${t}.${n}`)},isInstance(n){return typeof n=="object"&&n!==null&&e in n&&n[e]===!0}}}const EN=fS("langchain");function hS(t,e){return t.lc_error_code=e,t.message=`${t.message} Troubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${e}/ `,t}const Pg=EN.sub("error");var pS=class extends Pg.brand(Error){constructor(e){super(e);A(this,"name","LangChainError");Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},pv=class extends Pg.brand(pS,"model-abort"){constructor(e,n){super(e);A(this,"name","ModelAbortError");A(this,"partialOutput");this.partialOutput=n}},TN=class mS extends Pg.brand(pS,"context-overflow"){constructor(n){super(n??"Input exceeded the model's context window.");A(this,"name","ContextOverflowError");A(this,"cause")}static fromError(n){const r=new mS(n.message);return r.cause=n,r}};function IN(t){return!!(String(t).includes("context_length_exceeded")||"message"in t&&typeof t.message=="string"&&(t.message.includes("Input tokens exceed the configured limit")||t.message.includes("exceeds the context window")||t.message.includes("maximum context length")))}function Fo(t){if(!t||typeof t!="object")return t;let e;return t.constructor.name===ld.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="TimeoutError"):t.constructor.name===dn.name&&"message"in t&&typeof t.message=="string"?(e=new Error(t.message),e.name="AbortError"):IN(t)?e=TN.fromError(t):"status"in t&&t.status===400&&"message"in t&&typeof t.message=="string"&&t.message.includes("tool_calls")?e=$u(t,"INVALID_TOOL_RESULTS"):"status"in t&&t.status===401?e=$u(t,"MODEL_AUTHENTICATION"):"status"in t&&t.status===429?e=$u(t,"MODEL_RATE_LIMIT"):"status"in t&&t.status===404?e=$u(t,"MODEL_NOT_FOUND"):e=t,e}function ki(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}function gS(t){return ki(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}function yS(t){return ki(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}function ON(t){return ki(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}function CN(t){if(ki(t)){if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url}};if(t.source_type==="base64"){if(!t.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${t.mime_type};base64,${t.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function mv(t){const e=t.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${t}" - does not match type/subtype format.`);const n=e[0].trim(),r=e[1].trim();if(n===""||r==="")throw new Error(`Invalid mime type: "${t}" - type or subtype is empty.`);const i={};for(const s of t.split(";").slice(1)){const a=s.split("=");if(a.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${t}".`);const o=a[0].trim(),u=a[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${t}".`);i[o]=u}return{type:n,subtype:r,parameters:i}}function _c({dataUrl:t,asTypedArray:e=!1}){const n=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(n){r=n[1].toLowerCase();const i=e?Uint8Array.from(atob(n[2]),s=>s.charCodeAt(0)):n[2];return{mime_type:r,data:i}}}function _S(t,e){if(t.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(t)}if(t.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(t)}if(t.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(t)}if(t.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(t)}throw new Error(`Unable to convert content block type '${t.type}' to provider-specific format: not recognized.`)}function PN(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}const NN=/([A-Z]+)([A-Z][a-z0-9]+)/g,$N=/([a-z0-9])([A-Z])/g,RN=/[-_\s]+/g;function jN(t){return t.replace(NN,"$1_$2").replace($N,"$1_$2").replace(RN,"_").toLowerCase()}function LN(t,e){return(e==null?void 0:e[t])||jN(t)}function MN(t,e,n){const r={};for(const i in t)Object.hasOwn(t,i)&&(r[e(i,n)]=t[i]);return r}const zN="__lc_escaped__";function DN(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}function UN(t){return{[zN]:t}}function FN(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}function BN(t){var n;let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[((n=t.constructor)==null?void 0:n.name)??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}function hp(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return BN(t);if(FN(t))return t;e.add(t);const n=t;if(DN(n))return e.delete(t),UN(n);const r={};for(const[i,s]of Object.entries(n))r[i]=hp(s,e);return e.delete(t),r}return Array.isArray(t)?t.map(n=>hp(n,e)):t}function gv(t){return Array.isArray(t)?[...t]:{...t}}function HN(t,e){const n=gv(t);for(const[r,i]of Object.entries(e)){const[s,...a]=r.split(".").reverse();let o=n;for(const u of a.reverse()){if(o[u]===void 0)break;o[u]=gv(o[u]),o=o[u]}o[s]!==void 0&&(o[s]={lc:1,type:"secret",id:[i]})}return n}function vS(t){const e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}var Bo=class wS{constructor(e,...n){A(this,"lc_serializable",!1);A(this,"lc_kwargs");this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>{var i;return(i=this.lc_serializable_keys)==null?void 0:i.includes(r)})):this.lc_kwargs=e??{}}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,vS(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof wS||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},n={},r=Object.keys(this.lc_kwargs).reduce((o,u)=>(o[u]=u in this?this[u]:this.lc_kwargs[u],o),{});for(let o=Object.getPrototypeOf(this);o;o=Object.getPrototypeOf(o))Object.assign(e,Reflect.get(o,"lc_aliases",this)),Object.assign(n,Reflect.get(o,"lc_secrets",this)),Object.assign(r,Reflect.get(o,"lc_attributes",this));Object.keys(n).forEach(o=>{let u=this,l=r;const[c,...d]=o.split(".").reverse();for(const f of d.reverse()){if(!(f in u)||u[f]===void 0)return;(!(f in l)||l[f]===void 0)&&(typeof u[f]=="object"&&u[f]!=null?l[f]={}:Array.isArray(u[f])&&(l[f]=[])),u=u[f],l=l[f]}c in u&&u[c]!==void 0&&(l[c]=l[c]||u[c])});const i={},s=new WeakSet;s.add(this);for(const[o,u]of Object.entries(r))i[o]=hp(u,s);const a=MN(Object.keys(n).length?HN(i,n):i,LN,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function G(t,e){return te(t)&&t.type===e}function te(t){return typeof t=="object"&&t!==null}function qt(t){return Array.isArray(t)}function D(t){return typeof t=="string"}function Zn(t){return typeof t=="number"}function Ng(t){return t instanceof Uint8Array}function yv(t){try{return JSON.parse(t)}catch{return}}const mi=t=>t();function ZN(t){if(t.type==="char_location"&&D(t.document_title)&&Zn(t.start_char_index)&&Zn(t.end_char_index)&&D(t.cited_text)){const{document_title:e,start_char_index:n,end_char_index:r,cited_text:i,...s}=t;return{...s,type:"citation",source:"char",title:e??void 0,startIndex:n,endIndex:r,citedText:i}}if(t.type==="page_location"&&D(t.document_title)&&Zn(t.start_page_number)&&Zn(t.end_page_number)&&D(t.cited_text)){const{document_title:e,start_page_number:n,end_page_number:r,cited_text:i,...s}=t;return{...s,type:"citation",source:"page",title:e??void 0,startIndex:n,endIndex:r,citedText:i}}if(t.type==="content_block_location"&&D(t.document_title)&&Zn(t.start_block_index)&&Zn(t.end_block_index)&&D(t.cited_text)){const{document_title:e,start_block_index:n,end_block_index:r,cited_text:i,...s}=t;return{...s,type:"citation",source:"block",title:e??void 0,startIndex:n,endIndex:r,citedText:i}}if(t.type==="web_search_result_location"&&D(t.url)&&D(t.title)&&D(t.encrypted_index)&&D(t.cited_text)){const{url:e,title:n,encrypted_index:r,cited_text:i,...s}=t;return{...s,type:"citation",source:"url",url:e,title:n,startIndex:Number(r),endIndex:Number(r),citedText:i}}if(t.type==="search_result_location"&&D(t.source)&&D(t.title)&&Zn(t.start_block_index)&&Zn(t.end_block_index)&&D(t.cited_text)){const{source:e,title:n,start_block_index:r,end_block_index:i,cited_text:s,...a}=t;return{...a,type:"citation",source:"search",url:e,title:n??void 0,startIndex:r,endIndex:i,citedText:s}}}function bS(t){if(G(t,"document")&&te(t.source)&&"type"in t.source){if(t.source.type==="base64"&&D(t.source.media_type)&&D(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&D(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&D(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&D(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(G(t,"image")&&te(t.source)&&"type"in t.source){if(t.source.type==="base64"&&D(t.source.media_type)&&D(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&D(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&D(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}function VN(t){function*e(){for(const n of t){const r=bS(n);r?yield r:yield n}}return Array.from(e())}function _v(t){function*e(){var r;const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const i of n){if(G(i,"text")&&D(i.text)){const{text:s,citations:a,...o}=i;if(qt(a)&&a.length){const u=a.reduce((l,c)=>{const d=ZN(c);return d?[...l,d]:l},[]);yield{...o,type:"text",text:s,annotations:u};continue}else{yield{...o,type:"text",text:s};continue}}else if(G(i,"thinking")&&D(i.thinking)){const{thinking:s,signature:a,...o}=i;yield{...o,type:"reasoning",reasoning:s,signature:a};continue}else if(G(i,"redacted_thinking")){yield{type:"non_standard",value:i};continue}else if(G(i,"tool_use")&&D(i.name)&&D(i.id)){yield{type:"tool_call",id:i.id,name:i.name,args:i.input};continue}else if(G(i,"input_json_delta")){if(qN(t)&&((r=t.tool_call_chunks)!=null&&r.length)){const s=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(G(i,"server_tool_use")&&D(i.name)&&D(i.id)){const{name:s,id:a}=i;if(s==="web_search"){yield{id:a,type:"server_tool_call",name:"web_search",args:{query:mi(()=>{if(typeof i.input=="string")return i.input;if(te(i.input)&&D(i.input.query))return i.input.query;if(D(i.partial_json)){const o=yv(i.partial_json);if(o!=null&&o.query)return o.query}return""})}};continue}else if(i.name==="code_execution"){yield{id:a,type:"server_tool_call",name:"code_execution",args:{code:mi(()=>{if(typeof i.input=="string")return i.input;if(te(i.input)&&D(i.input.code))return i.input.code;if(D(i.partial_json)){const o=yv(i.partial_json);if(o!=null&&o.code)return o.code}return""})}};continue}}else if(G(i,"web_search_tool_result")&&D(i.tool_use_id)&&qt(i.content)){const{content:s,tool_use_id:a}=i;yield{type:"server_tool_call_result",name:"web_search",toolCallId:a,status:"success",output:{urls:s.reduce((o,u)=>G(u,"web_search_result")?[...o,u.url]:o,[])}};continue}else if(G(i,"code_execution_tool_result")&&D(i.tool_use_id)&&te(i.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:i.tool_use_id,status:"success",output:i.content};continue}else if(G(i,"mcp_tool_use")){yield{id:i.id,type:"server_tool_call",name:"mcp_tool_use",args:i.input};continue}else if(G(i,"mcp_tool_result")&&D(i.tool_use_id)&&te(i.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:i.tool_use_id,status:"success",output:i.content};continue}else if(G(i,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:i.input};continue}else if(G(i,"search_result")){yield{id:i.id,type:"non_standard",value:i};continue}else if(G(i,"tool_result")){yield{id:i.id,type:"non_standard",value:i};continue}else{const s=bS(i);if(s){yield s;continue}}yield{type:"non_standard",value:i}}}return Array.from(e())}const KN={translateContent:_v,translateContentChunk:_v};function qN(t){return typeof(t==null?void 0:t._getType)=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}function WN(t){return gS(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:yS(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:ON(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}function GN(t){return t.map(WN)}function JN(t){return!!(G(t,"image_url")&&te(t.image_url)||G(t,"input_audio")&&te(t.input_audio)||G(t,"file")&&te(t.file))}function XN(t){if(G(t,"image_url")&&te(t.image_url)&&D(t.image_url.url)){const e=_c({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(G(t,"input_audio")&&te(t.input_audio)&&D(t.input_audio.data)&&D(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(G(t,"file")&&te(t.file)&&D(t.file.data)){const e=_c({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(D(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}function QN(t){const e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...$g(t.content));for(const n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function YN(t){const e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...$g(t.content));for(const n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}function $g(t){const e=[];for(const n of t)JN(n)?e.push(XN(n)):e.push(n);return e}function e2(t){if(t.type==="url_citation"){const{url:e,title:n,start_index:r,end_index:i}=t;return{type:"citation",url:e,title:n,startIndex:r,endIndex:i}}if(t.type==="file_citation"){const{file_id:e,filename:n,index:r}=t;return{type:"citation",title:n,startIndex:r,endIndex:r,fileId:e}}return t}function xS(t){function*e(){var r;te((r=t.additional_kwargs)==null?void 0:r.reasoning)&&qt(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((i,s)=>te(s)&&D(s.text)?`${i}${s.text}`:i,"")});const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const i of n)if(G(i,"text")){const{text:s,annotations:a,phase:o,extras:u,...l}=i,c=te(u)?{...u}:{};D(o)&&(c.phase=o);const d=Object.keys(c).length>0?{extras:c}:{};Array.isArray(a)?yield{...l,...d,type:"text",text:String(s),annotations:a.map(e2)}:yield{...l,...d,type:"text",text:String(s)}}for(const i of t.tool_calls??[])yield{type:"tool_call",id:i.id,name:i.name,args:i.args};if(te(t.additional_kwargs)&&qt(t.additional_kwargs.tool_outputs))for(const i of t.additional_kwargs.tool_outputs){if(G(i,"web_search_call")){const s={};if(te(i.action)&&D(i.action.query)&&(s.query=i.action.query),yield{id:i.id,type:"server_tool_call",name:"web_search",args:s},i.status==="completed"||i.status==="failed"){const a={};te(i.action)&&(a.action=i.action),yield{type:"server_tool_call_result",toolCallId:D(i.id)?i.id:"",status:i.status==="completed"?"success":"error",output:a}}continue}else if(G(i,"file_search_call")){yield{id:i.id,type:"server_tool_call",name:"file_search",args:{queries:qt(i.queries)?i.queries:[]}},(i.status==="completed"||i.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:D(i.id)?i.id:"",status:i.status==="completed"?"success":"error",output:qt(i.results)?{results:i.results}:{}});continue}else if(G(i,"computer_call")){yield{type:"non_standard",value:i};continue}else if(G(i,"code_interpreter_call")){if(D(i.code)&&(yield{id:i.id,type:"server_tool_call",name:"code_interpreter",args:{code:i.code}}),qt(i.outputs)){const s=mi(()=>{if(i.status!=="in_progress"){if(i.status==="completed")return 0;if(i.status==="incomplete")return 127;if(i.status!=="interpreting"&&i.status==="failed")return 1}});for(const a of i.outputs)if(G(a,"logs")){yield{type:"server_tool_call_result",toolCallId:i.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(a.logs),stdout:[0,void 0].includes(s)?String(a.logs):void 0}};continue}}continue}else if(G(i,"mcp_call")){yield{id:i.id,type:"server_tool_call",name:"mcp_call",args:i.input};continue}else if(G(i,"mcp_list_tools")){yield{id:i.id,type:"server_tool_call",name:"mcp_list_tools",args:i.input};continue}else if(G(i,"mcp_approval_request")){yield{type:"non_standard",value:i};continue}else if(G(i,"tool_search_call")){const s={};te(i.arguments)&&Object.assign(s,i.arguments);const a={};D(i.execution)&&(a.execution=i.execution),D(i.status)&&(a.status=i.status),D(i.call_id)&&(a.call_id=i.call_id),yield{id:D(i.id)?i.id:"",type:"server_tool_call",name:"tool_search",args:s,...Object.keys(a).length>0?{extras:a}:{}};continue}else if(G(i,"tool_search_output")){const s={name:"tool_search"};D(i.execution)&&(s.execution=i.execution),yield{type:"server_tool_call_result",toolCallId:D(i.id)?i.id:"",status:i.status==="completed"?"success":i.status==="failed"?"error":"success",output:{tools:qt(i.tools)?i.tools:[]},extras:s};continue}else if(G(i,"image_generation_call")){D(i.result)&&(yield{type:"image",mimeType:"image/png",data:i.result,id:D(i.id)?i.id:void 0,metadata:{status:D(i.status)?i.status:void 0}}),yield{type:"non_standard",value:i};continue}te(i)&&(yield{type:"non_standard",value:i})}}return Array.from(e())}function t2(t){function*e(){yield*xS(t);for(const n of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:n.id,name:n.name,args:n.args}}return Array.from(e())}const n2={translateContent:t=>typeof t.content=="string"?QN(t):xS(t),translateContentChunk:t=>typeof t.content=="string"?YN(t):t2(t)};function r2(t,e="pretty"){return e==="pretty"?i2(t):JSON.stringify(t)}function i2(t){const e=[],n=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,r=Math.floor((80-n.length)/2),i="=".repeat(r),s=n.length%2===0?i:`${i}=`;if(e.push(`${i}${n}${s}`),t.type==="ai"){const a=t;if(a.tool_calls&&a.tool_calls.length>0){e.push("Tool Calls:");for(const o of a.tool_calls){e.push(` ${o.name} (${o.id})`),e.push(` Call ID: ${o.id}`),e.push(" Args:");for(const[u,l]of Object.entries(o.args))e.push(` ${u}: ${typeof l=="object"?JSON.stringify(l):l}`)}}}if(t.type==="tool"){const a=t;a.name&&e.push(`Name: ${a.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(` `)}const Sf=Symbol.for("langchain.message");function vv(t){return Array.isArray(t)?t:typeof t=="string"?t===""?[]:[{type:"text",text:t}]:t==null?[]:[t]}function Si(t,e){if(typeof t=="string")return t===""?e:typeof e=="string"?t+e:Array.isArray(e)&&e.length===0?t:Array.isArray(e)&&e.some(n=>ki(n))?[{type:"text",source_type:"text",text:t},...e]:[{type:"text",text:t},...e];if(Array.isArray(e)){const n=vv(t);return Ho(n,e)??[...n,...e]}else return e===""?t:Array.isArray(t)&&t.some(n=>ki(n))?[...t,{type:"file",source_type:"text",text:e}]:[...vv(t),{type:"text",text:e}]}function s2(t,e){return t==="error"||e==="error"?"error":"success"}function a2(t,e){function n(r,i){if(typeof r!="object"||r===null||r===void 0)return r;if(i>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(a=>n(a,i+1));const s={};for(const a of Object.keys(r))s[a]=n(r[a],i+1);return s}return JSON.stringify(n(t,0),null,2)}var Bw,ls=class extends Bo{constructor(e){const n=typeof e=="string"||Array.isArray(e)?{content:e}:e;n.additional_kwargs||(n.additional_kwargs={}),n.response_metadata||(n.response_metadata={});super(n);A(this,"lc_namespace",["langchain_core","messages"]);A(this,"lc_serializable",!0);A(this,Bw,!0);A(this,"id");A(this,"name");A(this,"content");A(this,"additional_kwargs");A(this,"response_metadata");this.name=n.name,n.content===void 0&&n.contentBlocks!==void 0?(this.content=n.contentBlocks,this.response_metadata={output_version:"v1",...n.response_metadata}):n.content!==void 0?(this.content=n.content??[],this.response_metadata=n.response_metadata):(this.content=[],this.response_metadata=n.response_metadata),this.additional_kwargs=n.additional_kwargs,this.id=n.id}get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}_getType(){return this.type}getType(){return this._getType()}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(e=>typeof e=="string"?e:e.type==="text"?e.text:"").join(""):""}get contentBlocks(){const e=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[GN,$g,VN].reduce((n,r)=>r(n),e)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(e){return typeof e=="object"&&e!==null&&Sf in e&&e[Sf]===!0&&PN(e)}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[(Bw=Sf,Symbol.toStringTag)](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const n=a2(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${n}`}toFormattedString(e="pretty"){return r2(this,e)}};const o2=["index","created","timestamp"];function zt(t,e,n){const r=o2;if(t==null&&e==null)return;if(t==null||e==null)return t??e;const i={...t};for(const[s,a]of Object.entries(e))if(i[s]==null)i[s]=a;else{if(a==null)continue;if(typeof i[s]!=typeof a||Array.isArray(i[s])!==Array.isArray(a))throw new Error(`field[${s}] already exists in the message chunk, but with a different type.`);if(typeof i[s]=="string"){if(s==="type")continue;if(["id","name","output_version","model_provider"].includes(s))a&&(i[s]=a);else{if(r.includes(s))continue;i[s]+=a}}else if(typeof i[s]=="number"){if(r.includes(s))continue;i[s]=i[s]+a}else if(typeof i[s]=="object"&&!Array.isArray(i[s]))i[s]=zt(i[s],a);else if(Array.isArray(i[s]))i[s]=Ho(i[s],a);else{if(i[s]===a)continue;console.warn(`field[${s}] already exists in this message chunk and value has unsupported type.`)}}return i}function u2(t){return typeof t=="number"||typeof t=="string"}function wv(t){return typeof t!="object"||t===null||!("index"in t)?!1:u2(t.index)}function bv(t){if(typeof t!="object"||t===null||!("id"in t))return!1;const e=t.id;return e!=null&&e!==""}function xv(t){return t.endsWith("_delta")?t.slice(0,-6):t}function l2(t,e){return typeof t!="object"||t===null||typeof e!="object"||e===null||!("type"in t)||!("type"in e)?!1:typeof t.type=="string"&&typeof e.type=="string"&&xv(t.type)!==xv(e.type)}function c2(t,e){const n=wv(e),r=bv(e);return!n&&!r?-1:t.findIndex(i=>{const s=wv(i),a=bv(i);return n&&s?i.index!==e.index||l2(i,e)?!1:a&&r?i.id===e.id:!0:!n&&!s&&r&&a?i.id===e.id:!1})}function Ho(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t||e;{const r=[...t];for(const i of e){const s=c2(r,i);if(s!==-1)r[s]=zt(r[s],i);else{if(typeof i=="object"&&i!==null&&"text"in i&&i.text==="")continue;r.push(i)}}return r}}}function d2(t,e,n){if(!(t==null&&e==null)){if(t==null||e==null)return t??e;if(typeof t!=typeof e)throw new Error(`Cannot merge objects of different types. Left ${typeof t} Right ${typeof e}`);if(typeof t=="string"&&typeof e=="string")return t+e;if(Array.isArray(t)&&Array.isArray(e))return Ho(t,e);if(typeof t=="object"&&typeof e=="object")return zt(t,e);if(t===e)return t;throw new Error(`Can not merge objects of different types. Left ${t} Right ${e}`)}}var cs=class kS extends ls{static isInstance(e){if(!super.isInstance(e))return!1;let n=Object.getPrototypeOf(e);for(;n!==null;){if(n===kS.prototype)return!0;n=Object.getPrototypeOf(n)}return!1}};function f2(t){return typeof t.role=="string"}function Rg(t){return typeof(t==null?void 0:t._getType)=="function"}function h2(t){return cs.isInstance(t)}function p2(t,e){return zt(t,e)??{}}function SS(t,e){const n={};return((t==null?void 0:t.audio)!==void 0||(e==null?void 0:e.audio)!==void 0)&&(n.audio=((t==null?void 0:t.audio)??0)+((e==null?void 0:e.audio)??0)),((t==null?void 0:t.image)!==void 0||(e==null?void 0:e.image)!==void 0)&&(n.image=((t==null?void 0:t.image)??0)+((e==null?void 0:e.image)??0)),((t==null?void 0:t.video)!==void 0||(e==null?void 0:e.video)!==void 0)&&(n.video=((t==null?void 0:t.video)??0)+((e==null?void 0:e.video)??0)),((t==null?void 0:t.document)!==void 0||(e==null?void 0:e.document)!==void 0)&&(n.document=((t==null?void 0:t.document)??0)+((e==null?void 0:e.document)??0)),((t==null?void 0:t.text)!==void 0||(e==null?void 0:e.text)!==void 0)&&(n.text=((t==null?void 0:t.text)??0)+((e==null?void 0:e.text)??0)),n}function m2(t,e){const n={...SS(t,e)};return((t==null?void 0:t.cache_read)!==void 0||(e==null?void 0:e.cache_read)!==void 0)&&(n.cache_read=((t==null?void 0:t.cache_read)??0)+((e==null?void 0:e.cache_read)??0)),((t==null?void 0:t.cache_creation)!==void 0||(e==null?void 0:e.cache_creation)!==void 0)&&(n.cache_creation=((t==null?void 0:t.cache_creation)??0)+((e==null?void 0:e.cache_creation)??0)),n}function g2(t,e){const n={...SS(t,e)};return((t==null?void 0:t.reasoning)!==void 0||(e==null?void 0:e.reasoning)!==void 0)&&(n.reasoning=((t==null?void 0:t.reasoning)??0)+((e==null?void 0:e.reasoning)??0)),n}function AS(t,e){return{input_tokens:((t==null?void 0:t.input_tokens)??0)+((e==null?void 0:e.input_tokens)??0),output_tokens:((t==null?void 0:t.output_tokens)??0)+((e==null?void 0:e.output_tokens)??0),total_tokens:((t==null?void 0:t.total_tokens)??0)+((e==null?void 0:e.total_tokens)??0),input_token_details:m2(t==null?void 0:t.input_token_details,e==null?void 0:e.input_token_details),output_token_details:g2(t==null?void 0:t.output_token_details,e==null?void 0:e.output_token_details)}}var jg=class extends ls{constructor(e,n,r){const i=typeof e=="string"||Array.isArray(e)?{content:e,name:r,tool_call_id:n}:e;super(i);A(this,"lc_direct_tool_output",!0);A(this,"type","tool");A(this,"status");A(this,"tool_call_id");A(this,"metadata");A(this,"artifact");this.tool_call_id=i.tool_call_id,this.artifact=i.artifact,this.status=i.status,this.metadata=i.metadata}static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}static isInstance(e){return super.isInstance(e)&&e.type==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}},y2=class extends cs{constructor(e){super(e);A(this,"type","tool");A(this,"tool_call_id");A(this,"status");A(this,"artifact");this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}concat(e){const n=this.constructor;return new n({content:Si(this.content,e.content),additional_kwargs:zt(this.additional_kwargs,e.additional_kwargs),response_metadata:zt(this.response_metadata,e.response_metadata),artifact:d2(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:s2(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}};function _2(t){const e=[],n=[];for(const r of t)if(r.function){const i=r.function.name;try{const s=JSON.parse(r.function.arguments);e.push({name:i||"",args:s||{},id:r.id})}catch{n.push({name:i,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,n]}function Lg(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}function v2(t){if(te(t.document)&&te(t.document.source)){const e=Lg(te(t.document)&&D(t.document.format)?t.document.format:"");if(te(t.document.source)){if(te(t.document.source.s3Location)&&D(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(Ng(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(D(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(qt(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((n,r)=>te(r)&&D(r.text)?n+r.text:n,"")}}}return{type:"non_standard",value:t}}function w2(t){if(G(t,"image")&&te(t.image)){const e=Lg(te(t.image)&&D(t.image.format)?t.image.format:"");if(te(t.image.source)){if(te(t.image.source.s3Location)&&D(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(Ng(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}function b2(t){if(G(t,"video")&&te(t.video)){const e=Lg(te(t.video)&&D(t.video.format)?t.video.format:"");if(te(t.video.source)){if(te(t.video.source.s3Location)&&D(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(Ng(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}function kv(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(G(r,"cache_point")){yield{type:"non_standard",value:r};continue}else if(G(r,"citations_content")&&te(r.citationsContent)){yield{type:"text",text:qt(r.citationsContent.content)?r.citationsContent.content.reduce((i,s)=>te(s)&&D(s.text)?i+s.text:i,""):"",annotations:qt(r.citationsContent.citations)?r.citationsContent.citations.reduce((i,s)=>{if(te(s)){const a=qt(s.sourceContent)?s.sourceContent.reduce((u,l)=>te(l)&&D(l.text)?u+l.text:u,""):"",o=mi(()=>{if(te(s.location)){const u=s.location.documentChar||s.location.documentPage||s.location.documentChunk;if(te(u))return{source:Zn(u.documentIndex)?u.documentIndex.toString():void 0,startIndex:Zn(u.start)?u.start:void 0,endIndex:Zn(u.end)?u.end:void 0}}return{}});i.push({type:"citation",citedText:a,...o})}return i},[]):[]};continue}else if(G(r,"document")&&te(r.document)){yield v2(r);continue}else if(G(r,"guard_content")){yield{type:"non_standard",value:r};continue}else if(G(r,"image")&&te(r.image)){yield w2(r);continue}else if(G(r,"reasoning_content")&&D(r.reasoningText)){yield{type:"reasoning",reasoning:r.reasoningText};continue}else if(G(r,"text")&&D(r.text)){yield{type:"text",text:r.text};continue}else if(G(r,"tool_result")){yield{type:"non_standard",value:r};continue}else{if(G(r,"tool_call"))continue;if(G(r,"video")&&te(r.video)){yield b2(r);continue}}yield{type:"non_standard",value:r}}}return Array.from(e())}const x2={translateContent:kv,translateContentChunk:kv};function Sv(t){var r;const e=[],n=(r=t.additional_kwargs)==null?void 0:r.reasoning_content;if(D(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const i of t.content)typeof i=="object"&&"type"in i&&i.type==="text"&&"text"in i&&D(i.text)&&e.push({type:"text",text:i.text});for(const i of t.tool_calls??[])e.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return e}const k2={translateContent:Sv,translateContentChunk:Sv};function Av(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(G(r,"text")&&D(r.text)){yield{type:"text",text:r.text};continue}else if(G(r,"thinking")&&D(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(G(r,"inlineData")&&te(r.inlineData)&&D(r.inlineData.mimeType)&&D(r.inlineData.data)){yield{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data};continue}else if(G(r,"functionCall")&&te(r.functionCall)&&D(r.functionCall.name)&&te(r.functionCall.args)){yield{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args};continue}else if(G(r,"functionResponse")){yield{type:"non_standard",value:r};continue}else if(G(r,"fileData")&&te(r.fileData)&&D(r.fileData.mimeType)&&D(r.fileData.fileUri)){yield{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri};continue}else if(G(r,"executableCode")){yield{type:"non_standard",value:r};continue}else if(G(r,"codeExecutionResult")){yield{type:"non_standard",value:r};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const S2={translateContent:Av,translateContentChunk:Av};function Ev(t){function*e(){const n=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(const r of n){if(G(r,"reasoning")&&D(r.reasoning)){const i=mi(()=>{var a;const s=n.indexOf(r);if(qt((a=t.additional_kwargs)==null?void 0:a.signatures)&&s>=0)return t.additional_kwargs.signatures.at(s)});D(i)?yield{type:"reasoning",reasoning:r.reasoning,signature:i}:yield{type:"reasoning",reasoning:r.reasoning};continue}else if(G(r,"thinking")&&D(r.thinking)){yield{type:"reasoning",reasoning:r.thinking,...r.signature?{signature:r.signature}:{}};continue}else if(G(r,"text")&&D(r.text)){yield{type:"text",text:r.text};continue}else if(G(r,"image_url")){if(D(r.image_url))if(r.image_url.startsWith("data:")){const i=r.image_url.match(/^data:([^;]+);base64,(.+)$/);i?yield{type:"image",data:i[2],mimeType:i[1]}:yield{type:"image",url:r.image_url}}else yield{type:"image",url:r.image_url};continue}else if(G(r,"media")&&D(r.mimeType)&&D(r.data)){yield{type:"file",mimeType:r.mimeType,data:r.data};continue}yield{type:"non_standard",value:r}}}return Array.from(e())}const A2={translateContent:Ev,translateContentChunk:Ev};function Tv(t){var r;const e=[],n=(r=t.additional_kwargs)==null?void 0:r.reasoning;if(D(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string"){let i=t.content;const s=i.match(/<think>([\s\S]*?)<\/think>/);if(s){const a=s[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&e.push({type:"text",text:i})}else for(const i of t.content)if(typeof i=="object"&&"type"in i&&i.type==="text"&&"text"in i&&D(i.text)){let s=i.text;const a=s.match(/<think>([\s\S]*?)<\/think>/);if(a){const o=a[1].trim();o.length>0&&e.push({type:"reasoning",reasoning:o}),s=s.replace(/<think>[\s\S]*?<\/think>/,"").trim()}s.length>0&&e.push({type:"text",text:s})}for(const i of t.tool_calls??[])e.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return e}const E2={translateContent:Tv,translateContentChunk:Tv};function Iv(t){var r;const e=[],n=(r=t.additional_kwargs)==null?void 0:r.reasoning_content;if(D(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const i of t.content)typeof i=="object"&&"type"in i&&i.type==="text"&&"text"in i&&D(i.text)&&e.push({type:"text",text:i.text});for(const i of t.tool_calls??[])e.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return e}const T2={translateContent:Iv,translateContentChunk:Iv};function Ov(t){var i,s;const e=[],n=(i=t.additional_kwargs)==null?void 0:i.reasoning_details;let r=!1;if(Array.isArray(n)&&n.length>0)for(const a of n){if(a==null||typeof a!="object")continue;const o=a.type;if(o==="reasoning.summary"){const u=a.summary;D(u)&&u.length>0&&(e.push({type:"reasoning",reasoning:u}),r=!0)}else if(o==="reasoning.text"){const u=a.text;D(u)&&u.length>0&&(e.push({type:"reasoning",reasoning:u}),r=!0)}}if(!r){const a=(s=t.additional_kwargs)==null?void 0:s.reasoning_content;D(a)&&a.length>0&&e.push({type:"reasoning",reasoning:a})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const a of t.content)typeof a=="object"&&"type"in a&&a.type==="text"&&"text"in a&&D(a.text)&&e.push({type:"text",text:a.text});for(const a of t.tool_calls??[])e.push({type:"tool_call",id:a.id,name:a.name,args:a.args});return e}const I2={translateContent:Ov,translateContentChunk:Ov};function Cv(t){var r,i;const e=[];if(te((r=t.additional_kwargs)==null?void 0:r.reasoning)){const s=t.additional_kwargs.reasoning;if(qt(s.summary)){const a=s.summary.reduce((o,u)=>te(u)&&D(u.text)?`${o}${u.text}`:o,"");a.length>0&&e.push({type:"reasoning",reasoning:a})}}const n=(i=t.additional_kwargs)==null?void 0:i.reasoning_content;if(D(n)&&n.length>0&&e.push({type:"reasoning",reasoning:n}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(const s of t.content)typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&D(s.text)&&e.push({type:"text",text:s.text});for(const s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}const O2={translateContent:Cv,translateContentChunk:Cv};function Pv(t){function*e(){const n=mi(()=>{var r;if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{const i=(r=t.additional_kwargs)==null?void 0:r.originalTextContentBlock;if(i!=null&&i.thoughtSignature&&!t.content.some(s=>"thoughtSignature"in s)){const s=[...t.content];for(let a=s.length-1;a>=0;a--){const o=s[a];if(o.type==="text"&&!o.thought)return o.thoughtSignature=i.thoughtSignature,s}}return t.content}});for(const r of n){const i=mi(()=>G(r,"text")&&D(r.text)?{type:"text",text:r.text}:G(r,"inlineData")&&te(r.inlineData)&&D(r.inlineData.mimeType)&&D(r.inlineData.data)?{type:"file",mimeType:r.inlineData.mimeType,data:r.inlineData.data}:G(r,"functionCall")&&te(r.functionCall)&&D(r.functionCall.name)&&te(r.functionCall.args)?{type:"tool_call",id:t.id,name:r.functionCall.name,args:r.functionCall.args}:G(r,"functionResponse")?{type:"non_standard",value:r}:G(r,"fileData")&&te(r.fileData)&&D(r.fileData.mimeType)&&D(r.fileData.fileUri)?{type:"file",mimeType:r.fileData.mimeType,fileId:r.fileData.fileUri}:G(r,"executableCode")?{type:"non_standard",value:r}:G(r,"codeExecutionResult")?{type:"non_standard",value:r}:{type:"non_standard",value:r}),s=mi(()=>"thought"in r&&r.thought?{type:"reasoning",reasoning:i.type==="text"?i.text:"",reasoningContentBlock:i}:i),a={thought:r.thought,thoughtSignature:r.thoughtSignature,partMetadata:r.partMetadata,...s};for(const o in a)a[o]===void 0&&delete a[o];yield a}}return Array.from(e())}const C2={translateContent:Pv,translateContentChunk:Pv};globalThis.lc_block_translators_registry??(globalThis.lc_block_translators_registry=new Map([["anthropic",KN],["bedrock-converse",x2],["deepseek",k2],["google",C2],["google-genai",S2],["google-vertexai",A2],["groq",E2],["ollama",T2],["openai",n2],["openrouter",I2],["xai",O2]]));function ES(t){return globalThis.lc_block_translators_registry.get(t)}function TS(t){return!!(t&&typeof t=="object"&&"type"in t&&t.type==="tool_call")}var P2=class extends Error{constructor(e,n){super(e);A(this,"output");this.output=n}};function pp(t,e=Mg){t=t.trim();const n=t.indexOf("```");if(n===-1)return e(t);let r=t.substring(n+3);r.startsWith(`json `)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(` `)&&(r=r.substring(1));const i=r.indexOf("```");let s=r;return i!==-1&&(s=r.substring(0,i)),e(s.trim())}function N2(t){try{return JSON.parse(t)}catch{}const e=t.trim();if(e.length===0)throw new Error("Unexpected end of JSON input");let n=0;function r(){for(;n<e.length&&/\s/.test(e[n]);)n+=1}function i(){if(e[n]!=='"')throw new Error(`Expected '"' at position ${n}, got '${e[n]}'`);n+=1;let c="",d=!1;for(;n<e.length;){const f=e[n];if(d){if(f==="n")c+=` `;else if(f==="t")c+=" ";else if(f==="r")c+="\r";else if(f==="\\")c+="\\";else if(f==='"')c+='"';else if(f==="b")c+="\b";else if(f==="f")c+="\f";else if(f==="/")c+="/";else if(f==="u"){const h=e.substring(n+1,n+5);if(/^[0-9A-Fa-f]{0,4}$/.test(h))h.length===4?c+=String.fromCharCode(Number.parseInt(h,16)):c+=`u${h}`,n+=h.length;else throw new Error(`Invalid unicode escape sequence '\\u${h}' at position ${n}`)}else throw new Error(`Invalid escape sequence '\\${f}' at position ${n}`);d=!1}else if(f==="\\")d=!0;else{if(f==='"')return n+=1,c;c+=f}n+=1}return d&&(c+="\\"),c}function s(){const c=n;let d="";if(e[n]==="-"&&(d+="-",n+=1),n<e.length&&e[n]==="0"&&(d+="0",n+=1,e[n]>="0"&&e[n]<="9"))throw new Error(`Invalid number at position ${c}`);if(n<e.length&&e[n]>="1"&&e[n]<="9")for(;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&e[n]===".")for(d+=".",n+=1;n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(n<e.length&&(e[n]==="e"||e[n]==="E"))for(d+=e[n],n+=1,n<e.length&&(e[n]==="+"||e[n]==="-")&&(d+=e[n],n+=1);n<e.length&&e[n]>="0"&&e[n]<="9";)d+=e[n],n+=1;if(d==="-")return-0;const f=Number.parseFloat(d);if(Number.isNaN(f))throw n=c,new Error(`Invalid number '${d}' at position ${c}`);return f}function a(){if(r(),n>=e.length)throw new Error(`Unexpected end of input at position ${n}`);const c=e[n];if(c==="{")return u();if(c==="[")return o();if(c==='"')return i();if("null".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),null;if("true".startsWith(e.substring(n,n+4)))return n+=Math.min(4,e.length-n),!0;if("false".startsWith(e.substring(n,n+5)))return n+=Math.min(5,e.length-n),!1;if(c==="-"||c>="0"&&c<="9")return s();throw new Error(`Unexpected character '${c}' at position ${n}`)}function o(){if(e[n]!=="[")throw new Error(`Expected '[' at position ${n}, got '${e[n]}'`);const c=[];if(n+=1,r(),n>=e.length)return c;if(e[n]==="]")return n+=1,c;for(;n<e.length;){if(r(),n>=e.length||(c.push(a()),r(),n>=e.length))return c;if(e[n]==="]")return n+=1,c;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or ']' at position ${n}, got '${e[n]}'`)}return c}function u(){if(e[n]!=="{")throw new Error(`Expected '{' at position ${n}, got '${e[n]}'`);const c={};if(n+=1,r(),n>=e.length)return c;if(e[n]==="}")return n+=1,c;for(;n<e.length;){if(r(),n>=e.length)return c;const d=i();if(r(),n>=e.length)return c;if(e[n]!==":")throw new Error(`Expected ':' at position ${n}, got '${e[n]}'`);if(n+=1,r(),n>=e.length||(c[d]=a(),r(),n>=e.length))return c;if(e[n]==="}")return n+=1,c;if(e[n]===","){n+=1;continue}throw new Error(`Expected ',' or '}' at position ${n}, got '${e[n]}'`)}return c}const l=a();if(r(),n<e.length)throw new Error(`Unexpected character '${e[n]}' at position ${n}`);return l}function Mg(t){try{return typeof t>"u"?null:N2(t)}catch{return null}}var zg=class IS extends ls{constructor(n,r){(typeof n=="string"||Array.isArray(n))&&(n={content:n,role:r});super(n);A(this,"type","generic");A(this,"role");this.role=n.role}static lc_name(){return"ChatMessage"}static _chatMessageClass(){return IS}static isInstance(n){return super.isInstance(n)&&n.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},OS=class extends cs{constructor(e,n){(typeof e=="string"||Array.isArray(e))&&(e={content:e,role:n});super(e);A(this,"type","generic");A(this,"role");this.role=e.role}static lc_name(){return"ChatMessageChunk"}concat(e){const n=this.constructor;return new n({content:Si(this.content,e.content),additional_kwargs:zt(this.additional_kwargs,e.additional_kwargs),response_metadata:zt(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}},CS=class extends cs{constructor(){super(...arguments);A(this,"type","function")}static lc_name(){return"FunctionMessageChunk"}concat(e){const n=this.constructor;return new n({content:Si(this.content,e.content),additional_kwargs:zt(this.additional_kwargs,e.additional_kwargs),response_metadata:zt(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}},Zo=class extends ls{constructor(e){super(e);A(this,"type","human")}static lc_name(){return"HumanMessage"}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},PS=class extends cs{constructor(e){super(e);A(this,"type","human")}static lc_name(){return"HumanMessageChunk"}concat(e){const n=this.constructor;return new n({content:Si(this.content,e.content),additional_kwargs:zt(this.additional_kwargs,e.additional_kwargs),response_metadata:zt(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="human"}},$2=class extends ls{constructor(e){super({...e,content:[]});A(this,"type","remove");A(this,"id");this.id=e.id}get _printableFields(){return{...super._printableFields,id:this.id}}static isInstance(e){return super.isInstance(e)&&e.type==="remove"}},mp=class Ol extends ls{constructor(n){super(n);A(this,"type","system")}static lc_name(){return"SystemMessage"}concat(n){if(typeof n=="string")return new Ol({content:Si(this.content,n),additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata,id:this.id,name:this.name});if(Ol.isInstance(n))return new Ol({content:Si(this.content,n.content),additional_kwargs:{...this.additional_kwargs,...n.additional_kwargs},response_metadata:{...this.response_metadata,...n.response_metadata},id:this.id??n.id,name:this.name??n.name});throw new Error("Unexpected chunk type for system message")}static isInstance(n){return super.isInstance(n)&&n.type==="system"}},gp=class extends cs{constructor(e){super(e);A(this,"type","system")}static lc_name(){return"SystemMessageChunk"}concat(e){const n=this.constructor;return new n({content:Si(this.content,e.content),additional_kwargs:zt(this.additional_kwargs,e.additional_kwargs),response_metadata:zt(this.response_metadata,e.response_metadata),id:this.id??e.id})}static isInstance(e){return super.isInstance(e)&&e.type==="system"}};function R2(t){return t.isCustomTool===!0}const j2=t=>t();function L2(t){return TS(t)?t:typeof t.id=="string"&&t.type==="function"&&typeof t.function=="object"&&t.function!==null&&"arguments"in t.function&&typeof t.function.arguments=="string"&&"name"in t.function&&typeof t.function.name=="string"?{id:t.id,args:JSON.parse(t.function.arguments),name:t.function.name,type:"tool_call"}:t}function M2(t){return typeof t=="object"&&t!=null&&t.lc===1&&Array.isArray(t.id)&&t.kwargs!=null&&typeof t.kwargs=="object"}function Af(t){let e,n;if(M2(t)){const r=t.id.at(-1);r==="HumanMessage"||r==="HumanMessageChunk"?e="user":r==="AIMessage"||r==="AIMessageChunk"?e="assistant":r==="SystemMessage"||r==="SystemMessageChunk"?e="system":r==="FunctionMessage"||r==="FunctionMessageChunk"?e="function":r==="ToolMessage"||r==="ToolMessageChunk"?e="tool":e="unknown",n=t.kwargs}else{const{type:r,...i}=t;e=r,n=i}if(e==="human"||e==="user")return new Zo(n);if(e==="ai"||e==="assistant"){const{tool_calls:r,...i}=n;if(!Array.isArray(r))return new Cn(n);const s=r.map(L2);return new Cn({...i,tool_calls:s})}else{if(e==="system")return new mp(n);if(e==="developer")return new mp({...n,additional_kwargs:{...n.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in n)return new jg({...n,content:n.content,tool_call_id:n.tool_call_id,name:n.name});if(e==="remove"&&"id"in n&&typeof n.id=="string")return new $2({...n,id:n.id});throw hS(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported. Received: ${JSON.stringify(t,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Cl(t){if(typeof t=="string")return new Zo(t);if(Rg(t))return t;if(Array.isArray(t)){const[e,n]=t;return Af({type:e,content:n})}else if(f2(t)){const{role:e,...n}=t;return Af({...n,type:e})}else return Af(t)}function z2(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}function NS(t,e="Human",n="AI"){const r=[];for(const i of t){let s;if(i.type==="human")s=e;else if(i.type==="ai")s=n;else if(i.type==="system")s="System";else if(i.type==="tool")s="Tool";else if(i.type==="generic")s=i.role;else throw new Error(`Got unsupported message type: ${i.type}`);const a=i.name?`${i.name}, `:"",o=typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.map(z2).filter(Boolean).join(""):"";let u=`${s}: ${a}${o}`;if(i.type==="ai"){const l=i;l.tool_calls&&l.tool_calls.length>0?u+=JSON.stringify(l.tool_calls):l.additional_kwargs&&"function_call"in l.additional_kwargs&&(u+=JSON.stringify(l.additional_kwargs.function_call))}r.push(u)}return r.join(` `)}function D2(t){var n;const e=t._getType();if(e==="human")return new PS({...t});if(e==="ai"){let r={...t};return"tool_calls"in r&&(r={...r,tool_call_chunks:(n=r.tool_calls)==null?void 0:n.map(i=>({...i,type:"tool_call_chunk",index:void 0,args:JSON.stringify(i.args)}))}),new vr({...r})}else{if(e==="system")return new gp({...t});if(e==="function")return new CS({...t});if(zg.isInstance(t))return new OS({...t});throw new Error("Unknown message type.")}}function U2(t){var i,s,a;const e=t.reduce((o,u)=>{const l=o.findIndex(([c])=>"id"in u&&u.id&&"index"in u&&u.index!==void 0?u.id===c.id&&u.index===c.index:"id"in u&&u.id?u.id===c.id:"index"in u&&u.index!==void 0?u.index===c.index:!1);return l!==-1?o[l].push(u):o.push([u]),o},[]),n=[],r=[];for(const o of e){let u=null;const l=o.some(R2),c=((i=o[0])==null?void 0:i.name)??"",d=o.map(_=>_.args||"").join(""),f=l?d:d.trim(),h=f.length?f:"{}",m=((s=o.find(_=>_.id))==null?void 0:s.id)??((a=o[0])==null?void 0:a.id);if(l&&m){n.push({name:c,args:{input:f},id:m,type:"tool_call"});continue}try{if(u=Mg(h),!m||u===null||typeof u!="object"||Array.isArray(u))throw new Error("Malformed tool call chunk args.");n.push({name:c,args:u,id:m,type:"tool_call"})}catch{r.push({name:c,args:h,id:m,error:"Malformed args.",type:"invalid_tool_call"})}}return{tool_call_chunks:t,tool_calls:n,invalid_tool_calls:r}}var Cn=class extends ls{constructor(e){var r;let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{n=e;const i=(r=n.additional_kwargs)==null?void 0:r.tool_calls,s=n.tool_calls;i!=null&&i.length>0&&(s===void 0||s.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling. Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(i!=null&&s===void 0){const[a,o]=_2(i);n.tool_calls=a??[],n.invalid_tool_calls=o??[]}else n.tool_calls=n.tool_calls??[],n.invalid_tool_calls=n.invalid_tool_calls??[]}catch{n.tool_calls=[],n.invalid_tool_calls=[]}if(n.response_metadata!==void 0&&"output_version"in n.response_metadata&&n.response_metadata.output_version==="v1"&&n.content!==void 0&&(n.contentBlocks=n.content,n.content=void 0),n.contentBlocks!==void 0){if(n.tool_calls){const o=n.tool_calls.filter(u=>{var l;return!((l=n.contentBlocks)!=null&&l.some(c=>c.type==="tool_call"&&c.id===u.id&&c.name===u.name))});n.contentBlocks.push(...o.map(u=>({type:"tool_call",id:u.id,name:u.name,args:u.args})))}const a=n.contentBlocks.filter(o=>o.type==="tool_call").filter(o=>{var u;return!((u=n.tool_calls)!=null&&u.some(l=>l.id===o.id&&l.name===o.name))});a.length>0&&(n.tool_calls=[...n.tool_calls??[],...a.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args}))])}}super(n);A(this,"type","ai");A(this,"tool_calls",[]);A(this,"invalid_tool_calls",[]);A(this,"usage_metadata");typeof n!="string"&&(this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const n=ES(this.response_metadata.model_provider);if(n)return n.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls){const n=this.tool_calls.filter(r=>!e.some(i=>i.id===r.id&&i.name===r.name));e.push(...n.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}};function Dg(t){return t._getType()==="ai"}function Nv(t){return t._getType()==="ai"}var vr=class extends cs{constructor(e){let n;if(typeof e=="string"||Array.isArray(e))n={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0||e.tool_call_chunks.length===0)n={...e,tool_calls:e.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0};else{const r=U2(e.tool_call_chunks??[]);n={...e,tool_call_chunks:r.tool_call_chunks,tool_calls:r.tool_calls,invalid_tool_calls:r.invalid_tool_calls,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(n);A(this,"type","ai");A(this,"tool_calls",[]);A(this,"invalid_tool_calls",[]);A(this,"tool_call_chunks",[]);A(this,"usage_metadata");this.tool_call_chunks=n.tool_call_chunks??this.tool_call_chunks,this.tool_calls=n.tool_calls??this.tool_calls,this.invalid_tool_calls=n.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=n.usage_metadata}get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",tool_call_chunks:"tool_call_chunks",usage_metadata:"usage_metadata"}}static lc_name(){return"AIMessageChunk"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){const n=ES(this.response_metadata.model_provider);if(n)return n.translateContent(this)}const e=super.contentBlocks;if(this.tool_calls&&typeof this.content!="string"){const n=this.content.filter(r=>r.type==="tool_call").map(r=>r.id);for(const r of this.tool_calls)r.id&&!n.includes(r.id)&&e.push({...r,type:"tool_call",id:r.id,name:r.name,args:r.args})}return e}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,tool_call_chunks:this.tool_call_chunks,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}concat(e){const n={content:Si(this.content,e.content),additional_kwargs:zt(this.additional_kwargs,e.additional_kwargs),response_metadata:p2(this.response_metadata,e.response_metadata),tool_call_chunks:[],tool_calls:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const i=Ho(this.tool_call_chunks,e.tool_call_chunks);i!==void 0&&i.length>0&&(n.tool_call_chunks=i)}if(this.tool_calls!==void 0||e.tool_calls!==void 0){const i=Ho(this.tool_calls,e.tool_calls);i!==void 0&&i.length>0&&(n.tool_calls=i)}(this.usage_metadata!==void 0||e.usage_metadata!==void 0)&&(n.usage_metadata=AS(this.usage_metadata,e.usage_metadata));const r=this.constructor;return new r(n)}static isInstance(e){return super.isInstance(e)&&e.type==="ai"}},F2=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function B2(t){return typeof t=="string"&&F2.test(t)}const lt=[];for(let t=0;t<256;++t)lt.push((t+256).toString(16).slice(1));function $S(t,e=0){return(lt[t[e+0]]+lt[t[e+1]]+lt[t[e+2]]+lt[t[e+3]]+"-"+lt[t[e+4]]+lt[t[e+5]]+"-"+lt[t[e+6]]+lt[t[e+7]]+"-"+lt[t[e+8]]+lt[t[e+9]]+"-"+lt[t[e+10]]+lt[t[e+11]]+lt[t[e+12]]+lt[t[e+13]]+lt[t[e+14]]+lt[t[e+15]]).toLowerCase()}const H2=new Uint8Array(16);function yp(){return crypto.getRandomValues(H2)}function Z2(t,e,n){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():V2(t,e,n)}function V2(t,e,n){var i;t=t||{};const r=t.random??((i=t.rng)==null?void 0:i.call(t))??yp();if(r.length<16)throw new Error("Random bytes length must be >= 16");if(r[6]=r[6]&15|64,r[8]=r[8]&63|128,e){if(n=n||0,n<0||n+16>e.length)throw new RangeError(`UUID byte range ${n}:${n+15} is out of buffer bounds`);for(let s=0;s<16;++s)e[n+s]=r[s];return e}return $S(r)}const Ef={};function K2(t,e,n){var i;let r;if(t)r=$v(t.random??((i=t.rng)==null?void 0:i.call(t))??yp(),t.msecs,t.seq,e,n);else{const s=Date.now(),a=yp();q2(Ef,s,a),r=$v(a,Ef.msecs,Ef.seq,e,n)}return e??$S(r)}function q2(t,e,n){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function $v(t,e,n,r,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??(e=Date.now()),n??(n=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),r[i++]=e/1099511627776&255,r[i++]=e/4294967296&255,r[i++]=e/16777216&255,r[i++]=e/65536&255,r[i++]=e/256&255,r[i++]=e&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|t[10]&3,r[i++]=t[11],r[i++]=t[12],r[i++]=t[13],r[i++]=t[14],r[i++]=t[15],r}const W2=Z2,ei=K2,Pl=B2,RS=Symbol.for("ls:tracing_async_local_storage"),Nl=Symbol.for("lc:context_variables"),G2=t=>{globalThis[RS]=t},Vo=()=>globalThis[RS];var Tf={};const J2=()=>typeof window<"u"&&typeof window.document<"u",X2=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Q2=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),Ug=()=>typeof Deno<"u",Y2=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ug(),jS=()=>{let t;return J2()?t="browser":Y2()?t="node":X2()?t="webworker":Q2()?t="jsdom":Ug()?t="deno":t="other",t};let If;function e$(){return If===void 0&&(If={library:"langchain-js",runtime:jS()}),If}function Jn(t){try{return typeof process<"u"?Tf==null?void 0:Tf[t]:Ug()?Deno==null?void 0:Deno.env.get(t):void 0}catch{return}}var t$=class{};function n$(t){return"lc_prefer_streaming"in t&&t.lc_prefer_streaming}function r$(t){return"lc_prefer_chat_model_stream_events"in t&&t.lc_prefer_chat_model_stream_events}var bd=class extends t${constructor(e){super();A(this,"lc_serializable",!1);A(this,"lc_kwargs");A(this,"ignoreLLM",!1);A(this,"ignoreChain",!1);A(this,"ignoreAgent",!1);A(this,"ignoreRetriever",!1);A(this,"ignoreCustomEvent",!1);A(this,"raiseError",!1);A(this,"awaitHandlers",Jn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false");this.lc_kwargs=e||{},e&&(this.ignoreLLM=e.ignoreLLM??this.ignoreLLM,this.ignoreChain=e.ignoreChain??this.ignoreChain,this.ignoreAgent=e.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=e.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=e.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=e.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(e._awaitHandler??this.awaitHandlers))}get lc_namespace(){return["langchain_core","callbacks",this.name]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,vS(this.constructor)]}copy(){return new this.constructor(this)}toJSON(){return Bo.prototype.toJSON.call(this)}toJSONNotImplemented(){return Bo.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class n extends bd{constructor(){super();A(this,"name",ei());Object.assign(this,e)}}return new n}};const i$=t=>{const e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},s$=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function a$(t){return typeof t=="string"&&s$.test(t)}function Rv(t){if(!a$(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}const ct=[];for(let t=0;t<256;++t)ct.push((t+256).toString(16).slice(1));function Fg(t,e=0){return(ct[t[e+0]]+ct[t[e+1]]+ct[t[e+2]]+ct[t[e+3]]+"-"+ct[t[e+4]]+ct[t[e+5]]+"-"+ct[t[e+6]]+ct[t[e+7]]+"-"+ct[t[e+8]]+ct[t[e+9]]+"-"+ct[t[e+10]]+ct[t[e+11]]+ct[t[e+12]]+ct[t[e+13]]+ct[t[e+14]]+ct[t[e+15]]).toLowerCase()}const o$=new Uint8Array(16);function _p(){return crypto.getRandomValues(o$)}function ja(t,e,n){return crypto.randomUUID?crypto.randomUUID():u$(t)}function u$(t,e,n){var i;t=t||{};const r=t.random??((i=t.rng)==null?void 0:i.call(t))??_p();if(r.length<16)throw new Error("Random bytes length must be >= 16");return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Fg(r)}function l$(t,e,n,r){switch(t){case 0:return e&n^~e&r;case 1:return e^n^r;case 2:return e&n^e&r^n&r;case 3:return e^n^r}}function Of(t,e){return t<<e|t>>>32-e}function c$(t){const e=[1518500249,1859775393,2400959708,3395469782],n=[1732584193,4023233417,2562383102,271733878,3285377520],r=new Uint8Array(t.length+1);r.set(t),r[t.length]=128,t=r;const i=t.length/4+2,s=Math.ceil(i/16),a=new Array(s);for(let o=0;o<s;++o){const u=new Uint32Array(16);for(let l=0;l<16;++l)u[l]=t[o*64+l*4]<<24|t[o*64+l*4+1]<<16|t[o*64+l*4+2]<<8|t[o*64+l*4+3];a[o]=u}a[s-1][14]=(t.length-1)*8/2**32,a[s-1][14]=Math.floor(a[s-1][14]),a[s-1][15]=(t.length-1)*8&4294967295;for(let o=0;o<s;++o){const u=new Uint32Array(80);for(let m=0;m<16;++m)u[m]=a[o][m];for(let m=16;m<80;++m)u[m]=Of(u[m-3]^u[m-8]^u[m-14]^u[m-16],1);let l=n[0],c=n[1],d=n[2],f=n[3],h=n[4];for(let m=0;m<80;++m){const _=Math.floor(m/20),v=Of(l,5)+l$(_,c,d,f)+h+e[_]+u[m]>>>0;h=f,f=d,d=Of(c,30)>>>0,c=l,l=v}n[0]=n[0]+l>>>0,n[1]=n[1]+c>>>0,n[2]=n[2]+d>>>0,n[3]=n[3]+f>>>0,n[4]=n[4]+h>>>0}return Uint8Array.of(n[0]>>24,n[0]>>16,n[0]>>8,n[0],n[1]>>24,n[1]>>16,n[1]>>8,n[1],n[2]>>24,n[2]>>16,n[2]>>8,n[2],n[3]>>24,n[3]>>16,n[3]>>8,n[3],n[4]>>24,n[4]>>16,n[4]>>8,n[4])}function d$(t){t=unescape(encodeURIComponent(t));const e=new Uint8Array(t.length);for(let n=0;n<t.length;++n)e[n]=t.charCodeAt(n);return e}const f$="6ba7b810-9dad-11d1-80b4-00c04fd430c8",h$="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function p$(t,e,n,r,i,s){const a=typeof n=="string"?d$(n):n,o=typeof r=="string"?Rv(r):r;if(typeof r=="string"&&(r=Rv(r)),(r==null?void 0:r.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+a.length);if(u.set(o),u.set(a,o.length),u=e(u),u[6]=u[6]&15|t,u[8]=u[8]&63|128,i){if(s??(s=0),s<0||s+16>i.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let l=0;l<16;++l)i[s+l]=u[l];return i}return Fg(u)}function Bg(t,e,n,r){return p$(80,c$,t,e,n,r)}Bg.DNS=f$;Bg.URL=h$;const Cf={};function LS(t,e,n){var i;let r;if(t)r=jv(t.random??((i=t.rng)==null?void 0:i.call(t))??_p(),t.msecs,t.seq,e,n);else{const s=Date.now(),a=_p();m$(Cf,s,a),r=jv(a,Cf.msecs,Cf.seq,e,n)}return e??Fg(r)}function m$(t,e,n){return t.msecs??(t.msecs=-1/0),t.seq??(t.seq=0),e>t.msecs?(t.seq=n[6]<<23|n[7]<<16|n[8]<<8|n[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}function jv(t,e,n,r,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!r)r=new Uint8Array(16),i=0;else if(i<0||i+16>r.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??(e=Date.now()),n??(n=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9]),r[i++]=e/1099511627776&255,r[i++]=e/4294967296&255,r[i++]=e/16777216&255,r[i++]=e/65536&255,r[i++]=e/256&255,r[i++]=e&255,r[i++]=112|n>>>28&15,r[i++]=n>>>20&255,r[i++]=128|n>>>14&63,r[i++]=n>>>6&255,r[i++]=n<<2&255|t[10]&3,r[i++]=t[11],r[i++]=t[12],r[i++]=t[13],r[i++]=t[14],r[i++]=t[15],r}const g$="gen_ai.operation.name",y$="gen_ai.system",Lv="gen_ai.request.model",_$="gen_ai.response.model",Mv="gen_ai.usage.input_tokens",zv="gen_ai.usage.output_tokens",Dv="gen_ai.usage.total_tokens",v$="gen_ai.request.max_tokens",w$="gen_ai.request.temperature",b$="gen_ai.request.top_p",x$="gen_ai.request.frequency_penalty",k$="gen_ai.request.presence_penalty",S$="gen_ai.response.finish_reasons",A$="gen_ai.prompt",E$="gen_ai.completion",T$="gen_ai.request.extra_query",I$="gen_ai.request.extra_body",O$="gen_ai.serialized.name",C$="gen_ai.serialized.signature",P$="gen_ai.serialized.doc",N$="gen_ai.response.id",$$="gen_ai.response.service_tier",R$="gen_ai.response.system_fingerprint",j$="gen_ai.usage.input_token_details",L$="gen_ai.usage.output_token_details",M$="langsmith.trace.session_id",z$="langsmith.trace.session_name",D$="langsmith.span.kind",U$="langsmith.trace.name",F$="langsmith.metadata",Uv="langsmith.span.tags",B$="langsmith.request.streaming",H$="langsmith.request.headers",Fv="langsmith.usage_metadata",Z$=(...t)=>fetch(...t),MS=Symbol.for("ls:fetch_implementation"),V$=()=>globalThis[MS]===void 0,K$=t=>async(...e)=>{if(t||Xe("DEBUG")==="true"){const[r,i]=e;console.log(`→ ${(i==null?void 0:i.method)||"GET"} ${r}`)}const n=await(globalThis[MS]??Z$)(...e);return(t||Xe("DEBUG")==="true")&&console.log(`← ${n.status} ${n.statusText} ${n.url}`),n},zS=()=>Xe("PROJECT")??en("LANGCHAIN_SESSION")??"default",Bv={};function $l(t){Bv[t]||(console.warn(t),Bv[t]=!0)}const z=t=>BigInt(t),DS=z("0x9E3779B1"),US=z("0x85EBCA77"),q$=z("0xC2B2AE3D"),Ai=z("0x9E3779B185EBCA87"),is=z("0xC2B2AE3D27D4EB4F"),FS=z("0x165667B19E3779F9"),Hg=z("0x85EBCA77C2B2AE63"),W$=z("0x27D4EB2F165667C5"),G$=z("0x165667919E3779F9"),J$=z("0x9FB21C651E98DF25");function X$(t){const e=new Uint8Array(t.length/2);for(let n=0;n<t.length;n+=2)e[n/2]=parseInt(t.substring(n,n+2),16);return e}const cr=X$("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Gs=(z(1)<<z(128))-z(1),le=(z(1)<<z(64))-z(1),vc=(z(1)<<z(32))-z(1),Tr=64,BS=Tr/8,Q$=8,Fu=4;function Ie(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}function $e(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}function Ls(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}function Pf(t,e=0){return t[e]}const Y$=t=>(t&z(255))<<z(56)|(t&z(65280))<<z(40)|(t&z(16711680))<<z(24)|(t&z(4278190080))<<z(8)|(t&z(0xff00000000))>>z(8)|(t&z(0xff0000000000))>>z(24)|(t&z(0xff000000000000))>>z(40)|(t&z(0xff00000000000000))>>z(56),eR=t=>(t=(t&z(65535))<<z(16)|(t&z(4294901760))>>z(16),t=(t&z(16711935))<<z(8)|(t&z(4278255360))>>z(8),t),tR=(t,e)=>(t&vc)*(e&vc)&le,aa=t=>{if(!t)throw new Error("Assert failed")};function nR(t,e){return(t<<e|t>>z(32)-e)&vc}function HS(t,e,n){for(let r=0;r<BS;r++){const i=$e(e,r*8),s=i^$e(n,r*8);t[r^1]+=i,t[r]+=tR(s,s>>z(32))}return t}function Hv(t,e,n,r){for(let i=0;i<r;i++)HS(t,Ie(e,i*Tr),Ie(n,i*8));return t}function rR(t,e){for(let n=0;n<BS;n++){const r=$e(e,n*8);let i=t[n];i=vp(i,z(47)),i^=r,i*=DS,t[n]=i&le}return t}function Bu(t,e){return ZS(t[0]^$e(e,0),t[1]^$e(e,Q$))}function Zv(t,e,n){let r=n;return r+=Bu(t.slice(0),Ie(e,0*Fu)),r+=Bu(t.slice(2),Ie(e,4*Fu)),r+=Bu(t.slice(4),Ie(e,8*Fu)),r+=Bu(t.slice(6),Ie(e,12*Fu)),mr(r&le)}function iR(t,e,n,r,i){const s=Math.floor((n.byteLength-Tr)/8),a=Tr*s,o=Math.floor((e.byteLength-1)/a);for(let u=0;u<o;u++)t=Hv(t,Ie(e,u*a),n,s),t=i(t,Ie(n,n.byteLength-Tr));{const u=Math.floor((e.byteLength-1-a*o)/Tr);t=Hv(t,Ie(e,o*a),n,u),t=r(t,Ie(e,e.byteLength-Tr),Ie(n,n.byteLength-Tr-7))}return t}function sR(t,e,n){let r=new BigUint64Array([q$,Ai,is,FS,Hg,US,W$,DS]);aa(t.length>128),r=iR(r,t,e,HS,rR),aa(r.length*8==64);{const i=Zv(r,Ie(e,11),z(t.byteLength)*Ai&le);return Zv(r,Ie(e,e.byteLength-Tr-11),~(z(t.byteLength)*is)&le)<<z(64)|i}}function ZS(t,e){const n=t*e&Gs;return n&le^n>>z(64)}function Vv(t,e,n){return ZS(($e(t,0)^$e(e,0)+n)&le,($e(t,8)^$e(e,8)-n)&le)}function Rl(t,e,n,r,i){let s=t&le,a=t>>z(64)≤return s+=Vv(e,r,i),s^=$e(n,0)+$e(n,8),s&=le,a+=Vv(n,Ie(r,16),i),a^=$e(e,0)+$e(e,8),a&=le,a<<z(64)|s}function mr(t){return t^=t>>z(37),t*=G$,t&=le,t^=t>>z(32),t}function wc(t){return t^=t>>z(33),t*=is,t&=le,t^=t>>z(29),t*=FS,t&=le,t^=t>>z(32),t}function aR(t,e,n){const r=t.byteLength;aa(r>0&&r<=3);const i=z(Pf(t,r-1))|z(r<<8)|z(Pf(t,0)<<16)|z(Pf(t,r>>1)<<24),s=(z(Ls(e,0))^z(Ls(e,4)))+n,a=(i^s)&le,o=(z(Ls(e,8))^z(Ls(e,12)))-n,u=(nR(eR(i),z(13))^o)≤return(wc(u)&le)<<z(64)|wc(a)}function vp(t,e){return t^t>>e}function oR(t,e,n){const r=t.byteLength;aa(r>=4&&r<=8);{const i=Ls(t,0),s=Ls(t,r-4),a=z(i)|z(s)<<z(32),o=($e(e,16)^$e(e,24))+n≤let l=(a^o)*(Ai+(z(r)<<z(2)))&Gs;return l+=(l&le)<<z(65),l&=Gs,l^=l>>z(67),vp(vp(l&le,z(35))*J$&le,z(28))|mr(l>>z(64))<<z(64)}}function uR(t,e,n){const r=t.byteLength;aa(r>=9&&r<=16);{const i=($e(e,32)^$e(e,40))+n&le,s=($e(e,48)^$e(e,56))-n&le,a=$e(t);let o=$e(t,r-8),u=(a^o^i)*Ai;const l=(u&le)+(z(r-1)<<z(54));u=u&(Gs^le)|l,o^=s,u+=o+(o&vc)*(US-z(1))<<z(64),u&=Gs,u^=Y$(u>>z(64));let c=(u&le)*is;return c+=(u>>z(64))*is<<z(64),c&=Gs,mr(c&le)|mr(c>>z(64))<<z(64)}}function lR(t,e){const n=t.byteLength;return aa(n<=16),n>8?uR(t,cr,e):n>=4?oR(t,cr,e):n>0?aR(t,cr,e):wc(e^$e(cr,64)^$e(cr,72))|wc(e^$e(cr,80)^$e(cr,88))<<z(64)}function wp(t){return~t+z(1)&le}function cR(t,e,n){let r=z(t.byteLength)*Ai&le,i=z(t.byteLength-1)/z(32);for(;i>=0;){const o=Number(i);r=Rl(r,Ie(t,16*o),Ie(t,t.byteLength-16*(o+1)),Ie(e,32*o),n),i--}let s=r+(r>>z(64))≤s=mr(s);let a=(r&le)*Ai+(r>>z(64))*Hg+(z(t.byteLength)-n&le)*is;return a&=le,a=wp(mr(a)),s|a<<z(64)}function dR(t,e,n){let r=z(t.byteLength)*Ai≤for(let a=32;a<160;a+=32)r=Rl(r,Ie(t,a-32),Ie(t,a-16),Ie(e,a-32),n);r=mr(r&le)|mr(r>>z(64))<<z(64);for(let a=160;a<=t.byteLength;a+=32)r=Rl(r,Ie(t,a-32),Ie(t,a-16),Ie(e,3+a-160),n);r=Rl(r,Ie(t,t.byteLength-16),Ie(t,t.byteLength-32),Ie(e,103),wp(n));let i=r+(r>>z(64))≤i=mr(i);let s=(r&le)*Ai+(r>>z(64))*Hg+(z(t.byteLength)-n&le)*is;return s&=le,s=wp(mr(s)),i|s<<z(64)}function fR(t,e=z(0)){const n=t.byteLength;return n<=16?lR(t,e):n<=128?cR(t,cr,e):n<=240?dR(t,cr,e):sR(t,cr)}function hR(t){const e=new Uint8Array(16),n=new DataView(e.buffer),r=t&le,i=t>>z(64);return n.setBigUint64(0,i,!1),n.setBigUint64(8,r,!1),e}const VS=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ae(t,e){if(!VS.test(t)){const n=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(n)}return t}function pR(t){const e=typeof t=="string"?Date.parse(t):t;return LS({msecs:e,seq:0})}function mR(t){if(!VS.test(t))return null;const e=t[14];return parseInt(e,16)}function gR(t){const e=t.replace(/-/g,""),n=new Uint8Array(16);for(let r=0;r<16;r++)n[r]=parseInt(e.slice(r*2,r*2+2),16);return n}function yR(t){const e=Array.from(t).map(n=>n.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}const _R=new TextEncoder;function vR(t){const e=_R.encode(t),n=fR(e);return hR(n)}function Hu(t,e){const n=`${t}:${e}`,r=vR(n),i=new Uint8Array(16);if(mR(t)===7){const a=gR(t);i.set(a.slice(0,6),0)}else{const a=Date.now();i[0]=a/1099511627776&255,i[1]=a/4294967296&255,i[2]=a/16777216&255,i[3]=a/65536&255,i[4]=a/256&255,i[5]=a&255}return i[6]=112|r[0]&15,i[7]=r[1],i[8]=128|r[2]&63,i.set(r.slice(3,10),9),yR(i)}const wR=t=>!!["TRACING_V2","TRACING"].find(n=>Xe(n)==="true");let bR=class{getStore(){}run(e,n){return n()}};const Nf=Symbol.for("ls:tracing_async_local_storage"),xR=new bR;let kR=class{getInstance(){return globalThis[Nf]??xR}initializeGlobalInstance(e){globalThis[Nf]===void 0&&(globalThis[Nf]=e)}};const SR=new kR;function AR(t=!1){const e=SR.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree. Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function Zg(t){return typeof t=="function"&&"langsmith:traceable"in t}const ss={join:(...t)=>t.join("/"),dirname:t=>t.split("/").slice(0,-1).join("/")};async function KS(t){}async function Vg(t,e){}async function ER(t){return[]}async function TR(t){return{size:0}}function IR(t){return!1}function Kg(t){return""}async function OR(t){}async function bp(t){}function CR(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}class PR{constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){const e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,n){if(this.maxSize===0)return;const r=this.cache.get(e);if(!r){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...r,refreshFunc:n}),this._metrics.hits+=1,r.value}set(e,n,r){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){const s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}const i={value:n,createdAt:Date.now(),refreshFunc:r};this.cache.delete(e),this.cache.set(e,i)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){const n={};for(const[i,s]of this.cache.entries())n[i]=s.value;ss.dirname(e);const r=`${e}.tmp`;try{JSON.stringify({entries:n},null,2)}catch(i){throw i}}load(e){return 0}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){const e=[];for(const[n,r]of this.cache.entries())CR(r,this.ttlSeconds)&&e.push([n,r]);return e}async refreshStaleEntries(){const e=this.getStaleEntries();if(e.length!==0){for(const[n,r]of e)if(r.refreshFunc!==void 0)try{const i=await r.refreshFunc();this.set(n,i,r.refreshFunc),this._metrics.refreshes+=1}catch(i){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${n}:`,i)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??5*60}}const Kv=new PR,qS="0.7.10";var _o={};let sr;const NR=()=>typeof window<"u"&&typeof window.document<"u",$R=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",RR=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),WS=()=>typeof Deno<"u",jR=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!WS(),qg=()=>sr||(typeof Bun<"u"?sr="bun":NR()?sr="browser":jR()?sr="node":$R()?sr="webworker":RR()?sr="jsdom":WS()?sr="deno":sr="other",sr);let $f;function GS(){if($f===void 0){const t=qg(),e=MR();$f={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:qS,...e}}return $f}function JS(){const t=LR(),e={},n=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,i]of Object.entries(t))typeof i=="string"&&!n.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=i:e[r]=i);return e}function LR(){const t={};try{if(typeof process<"u"&&_o)for(const[e,n]of Object.entries(_o))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&n!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof n=="string"?t[e]=n.slice(0,2)+"*".repeat(n.length-4)+n.slice(-2):t[e]=n)}catch{}return t}function en(t){try{return typeof process<"u"?_o==null?void 0:_o[t]:void 0}catch{return}}function Xe(t){return en(`LANGSMITH_${t}`)||en(`LANGCHAIN_${t}`)}let Rf;function MR(){if(Rf!==void 0)return Rf;const t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(const n of t){const r=en(n);r!==void 0&&(e[n]=r)}return Rf=e,e}function qv(){return en("OTEL_ENABLED")==="true"||Xe("OTEL_ENABLED")==="true"}const Wv=new Set(["langsmith","otel"]);function XS(t){if(t!==void 0)return t;const e=Xe("TRACING_MODE");if(e!==void 0&&e!==""){const n=e.toLowerCase();if(!Wv.has(n))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...Wv].sort().join(", ")}`);return qv()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),n}return qv()?"otel":"langsmith"}class zR{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...n){!this.hasWarned&&XS()==="otel"&&(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(n.length===1&&typeof n[0]=="function"?r=n[0]:n.length===2&&typeof n[1]=="function"?r=n[1]:n.length===3&&typeof n[2]=="function"&&(r=n[2]),typeof r=="function")return r()}}class DR{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new zR})}getTracer(e,n){return this.mockTracer}getActiveSpan(){}setSpan(e,n){return e}getSpan(e){}setSpanContext(e,n){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class UR{active(){return{}}with(e,n){return n()}}const jf=Symbol.for("ls:otel_trace"),Lf=Symbol.for("ls:otel_context"),Gv=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),FR=new DR,BR=new UR;class HR{getTraceInstance(){return globalThis[jf]??FR}getContextInstance(){return globalThis[Lf]??BR}initializeGlobalInstances(e){globalThis[jf]===void 0&&(globalThis[jf]=e.trace),globalThis[Lf]===void 0&&(globalThis[Lf]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[Gv]=e}getDefaultOTLPTracerComponents(){return globalThis[Gv]??void 0}}const Wg=new HR;function QS(){return Wg.getTraceInstance()}function ZR(){return Wg.getContextInstance()}function VR(){return Wg.getDefaultOTLPTracerComponents()}const KR={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function qR(t){return KR[t]||t}function WR(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}class GR{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,n){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const i=this.createSpanForRun(r,r.run,n.get(r.id));i&&!r.run.end_time&&this.spans.set(r.id,i)}else this.updateSpanForRun(r,r.run)}catch(i){console.error(`Error processing operation ${r.id}:`,i)}}createSpanForRun(e,n,r){const i=r&&QS().getSpan(r);if(i)try{return this.finishSpanSetup(i,n,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);return}}finishSpanSetup(e,n,r){return this.setSpanAttributes(e,n,r),n.error?(e.setStatus({code:2}),e.recordException(new Error(n.error))):e.setStatus({code:1}),n.end_time&&e.end(new Date(n.end_time)),e}updateSpanForRun(e,n){try{const r=this.spans.get(e.id);if(!r){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(r,n,e),n.error?(r.setStatus({code:2}),r.recordException(new Error(n.error))):r.setStatus({code:1});const i=n.end_time;i&&(r.end(new Date(i)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){var n;if((n=e.extra)!=null&&n.metadata){const r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){const i=r.invocation_params;if(i.model)return i.model;if(i.model_name)return i.model_name}}}setSpanAttributes(e,n,r){var o,u,l;if("run_type"in n&&n.run_type){e.setAttribute(D$,n.run_type);const c=qR(n.run_type||"chain");e.setAttribute(g$,c)}"name"in n&&n.name&&e.setAttribute(U$,n.name),"session_id"in n&&n.session_id&&e.setAttribute(M$,n.session_id),"session_name"in n&&n.session_name&&e.setAttribute(z$,n.session_name),this.setGenAiSystem(e,n);const i=this.extractModelName(n);i&&e.setAttribute(Lv,i),(u=(o=n.extra)==null?void 0:o.metadata)!=null&&u.usage_metadata&&typeof n.extra.metadata.usage_metadata=="object"&&e.setAttribute(Fv,JSON.stringify(n.extra.metadata.usage_metadata)),"prompt_tokens"in n&&typeof n.prompt_tokens=="number"&&e.setAttribute(Mv,n.prompt_tokens),"completion_tokens"in n&&typeof n.completion_tokens=="number"&&e.setAttribute(zv,n.completion_tokens),"total_tokens"in n&&typeof n.total_tokens=="number"&&e.setAttribute(Dv,n.total_tokens),this.setInvocationParameters(e,n);const s=((l=n.extra)==null?void 0:l.metadata)||{};for(const[c,d]of Object.entries(s))d!=null&&e.setAttribute(`${F$}.${c}`,WR(d)?String(d):JSON.stringify(d));const a=n.tags;if(a&&Array.isArray(a)?e.setAttribute(Uv,a.join(", ")):a&&e.setAttribute(Uv,String(a)),"serialized"in n&&typeof n.serialized=="object"){const c=n.serialized;c.name&&e.setAttribute(O$,String(c.name)),c.signature&&e.setAttribute(C$,String(c.signature)),c.doc&&e.setAttribute(P$,String(c.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,n){let r="langchain";const i=this.extractModelName(n);if(i){const s=i.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?r="anthropic":s.includes("bedrock")?r="aws.bedrock":s.includes("azure")&&s.includes("openai")?r="az.ai.openai":s.includes("azure")&&s.includes("inference")?r="az.ai.inference":s.includes("cohere")?r="cohere":s.includes("deepseek")?r="deepseek":s.includes("gemini")?r="gemini":s.includes("groq")?r="groq":s.includes("watson")||s.includes("ibm")?r="ibm.watsonx.ai":s.includes("mistral")?r="mistral_ai":s.includes("gpt")||s.includes("openai")?r="openai":s.includes("perplexity")||s.includes("sonar")?r="perplexity":s.includes("vertex")?r="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(r="xai")}e.setAttribute(y$,r)}setInvocationParameters(e,n){var i,s;if(!((s=(i=n.extra)==null?void 0:i.metadata)!=null&&s.invocation_params))return;const r=n.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(v$,r.max_tokens),r.temperature!==void 0&&e.setAttribute(w$,r.temperature),r.top_p!==void 0&&e.setAttribute(b$,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(x$,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(k$,r.presence_penalty)}setIOAttributes(e,n){if(n.run.inputs)try{const r=n.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(Lv,r.model),r.stream!==void 0&&e.setAttribute(B$,r.stream),r.extra_headers&&e.setAttribute(H$,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(T$,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(I$,JSON.stringify(r.extra_body))),e.setAttribute(A$,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${n.id}`,r)}if(n.run.outputs)try{const r=n.run.outputs,i=this.getUnifiedRunTokens(r);if(i&&(e.setAttribute(Mv,i[0]),e.setAttribute(zv,i[1]),e.setAttribute(Dv,i[0]+i[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(_$,String(r.model)),r.id&&e.setAttribute(N$,r.id),r.choices&&Array.isArray(r.choices)){const s=r.choices.map(a=>a.finish_reason).filter(a=>a).map(String);s.length>0&&e.setAttribute(S$,s.join(", "))}if(r.service_tier&&e.setAttribute($$,r.service_tier),r.system_fingerprint&&e.setAttribute(R$,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const s=r.usage_metadata;e.setAttribute(Fv,JSON.stringify(s)),s.input_token_details&&e.setAttribute(j$,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(L$,JSON.stringify(s.output_token_details))}}e.setAttribute(E$,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${n.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let n=this.extractUnifiedRunTokens(e.usage_metadata);if(n)return n;const r=Object.keys(e);for(const a of r){const o=e[a];if(!(!o||typeof o!="object")&&(n=this.extractUnifiedRunTokens(o.usage_metadata),n||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(n=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),n)))return n}const i=e.generations||[];if(!Array.isArray(i))return null;const s=Array.isArray(i[0])?i.flat():i;for(const a of s)if(typeof a=="object"&&a.message&&typeof a.message=="object"&&a.message.kwargs&&typeof a.message.kwargs=="object"&&(n=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),n))return n;return null}extractUnifiedRunTokens(e){return!e||typeof e!="object"||typeof e.input_tokens!="number"||typeof e.output_tokens!="number"?null:[e.input_tokens,e.output_tokens]}}const JR=Object.prototype.toString,XR=t=>JR.call(t)==="[object Error]",QR=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function YR(t){if(!(t&&XR(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:n,stack:r}=t;return n==="Load failed"?r===void 0||"__sentry_captured__"in t:n.startsWith("error sending request for url")?!0:QR.has(n)}function ej(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Zu(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be ≥ ${n}.`)}}let tj=class extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function nj(t,e){const n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1;let i=Math.round(r*e.minTimeout*e.factor**(n-1));return i=Math.min(i,e.maxTimeout),i}function Jv(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function rj({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:i}){var h,m,_;const s=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(s instanceof tj)throw s.originalError;const a=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,o=i.maxRetryTime??Number.POSITIVE_INFINITY,u=Object.freeze({error:s,attemptNumber:e,retriesLeft:a,retriesConsumed:n});if(await i.onFailedAttempt(u),Jv(r,o)<=0)throw s;const l=await i.shouldConsumeRetry(u),c=Jv(r,o);if(c<=0||a<=0)throw s;if(s instanceof TypeError&&!YR(s)){if(l)throw s;return(h=i.signal)==null||h.throwIfAborted(),!1}if(!await i.shouldRetry(u))throw s;if(!l)return(m=i.signal)==null||m.throwIfAborted(),!1;const d=nj(n,i),f=Math.min(d,c);return f>0&&await new Promise((v,y)=>{var b,E;const p=()=>{var T;clearTimeout(g),(T=i.signal)==null||T.removeEventListener("abort",p),y(i.signal.reason)},g=setTimeout(()=>{var T;(T=i.signal)==null||T.removeEventListener("abort",p),v()},f);i.unref&&((b=g.unref)==null||b.call(g)),(E=i.signal)==null||E.addEventListener("abort",p,{once:!0})}),(_=i.signal)==null||_.throwIfAborted(),!0}async function ij(t,e={}){var s,a,o;if(e={...e},ej(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),Zu("factor",e.factor,{min:0,allowInfinity:!1}),Zu("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Zu("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Zu("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(s=e.signal)==null||s.throwIfAborted();let n=0,r=0;const i=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{(a=e.signal)==null||a.throwIfAborted();const u=await t(n);return(o=e.signal)==null||o.throwIfAborted(),u}catch(u){await rj({error:u,attemptNumber:n,retriesConsumed:r,startTime:i,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}var YS={},eA={exports:{}};(function(t){var e=Object.prototype.hasOwnProperty,n="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(n=!1));function i(u,l,c){this.fn=u,this.context=l,this.once=c||!1}function s(u,l,c,d,f){if(typeof c!="function")throw new TypeError("The listener must be a function");var h=new i(c,d||u,f),m=n?n+l:l;return u._events[m]?u._events[m].fn?u._events[m]=[u._events[m],h]:u._events[m].push(h):(u._events[m]=h,u._eventsCount++),u}function a(u,l){--u._eventsCount===0?u._events=new r:delete u._events[l]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var l=[],c,d;if(this._eventsCount===0)return l;for(d in c=this._events)e.call(c,d)&&l.push(n?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},o.prototype.listeners=function(l){var c=n?n+l:l,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var f=0,h=d.length,m=new Array(h);f<h;f++)m[f]=d[f].fn;return m},o.prototype.listenerCount=function(l){var c=n?n+l:l,d=this._events[c];return d?d.fn?1:d.length:0},o.prototype.emit=function(l,c,d,f,h,m){var _=n?n+l:l;if(!this._events[_])return!1;var v=this._events[_],y=arguments.length,p,g;if(v.fn){switch(v.once&&this.removeListener(l,v.fn,void 0,!0),y){case 1:return v.fn.call(v.context),!0;case 2:return v.fn.call(v.context,c),!0;case 3:return v.fn.call(v.context,c,d),!0;case 4:return v.fn.call(v.context,c,d,f),!0;case 5:return v.fn.call(v.context,c,d,f,h),!0;case 6:return v.fn.call(v.context,c,d,f,h,m),!0}for(g=1,p=new Array(y-1);g<y;g++)p[g-1]=arguments[g];v.fn.apply(v.context,p)}else{var b=v.length,E;for(g=0;g<b;g++)switch(v[g].once&&this.removeListener(l,v[g].fn,void 0,!0),y){case 1:v[g].fn.call(v[g].context);break;case 2:v[g].fn.call(v[g].context,c);break;case 3:v[g].fn.call(v[g].context,c,d);break;case 4:v[g].fn.call(v[g].context,c,d,f);break;default:if(!p)for(E=1,p=new Array(y-1);E<y;E++)p[E-1]=arguments[E];v[g].fn.apply(v[g].context,p)}}return!0},o.prototype.on=function(l,c,d){return s(this,l,c,d,!1)},o.prototype.once=function(l,c,d){return s(this,l,c,d,!0)},o.prototype.removeListener=function(l,c,d,f){var h=n?n+l:l;if(!this._events[h])return this;if(!c)return a(this,h),this;var m=this._events[h];if(m.fn)m.fn===c&&(!f||m.once)&&(!d||m.context===d)&&a(this,h);else{for(var _=0,v=[],y=m.length;_<y;_++)(m[_].fn!==c||f&&!m[_].once||d&&m[_].context!==d)&&v.push(m[_]);v.length?this._events[h]=v.length===1?v[0]:v:a(this,h)}return this},o.prototype.removeAllListeners=function(l){var c;return l?(c=n?n+l:l,this._events[c]&&a(this,c)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=n,o.EventEmitter=o,t.exports=o})(eA);var sj=eA.exports,xd={exports:{}},aj=(t,e)=>(e=e||(()=>{}),t.then(n=>new Promise(r=>{r(e())}).then(()=>n),n=>new Promise(r=>{r(e())}).then(()=>{throw n})));const oj=aj;class tA extends Error{constructor(e){super(e),this.name="TimeoutError"}}const nA=(t,e,n)=>new Promise((r,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){r(t);return}const s=setTimeout(()=>{if(typeof n=="function"){try{r(n())}catch(u){i(u)}return}const a=typeof n=="string"?n:`Promise timed out after ${e} milliseconds`,o=n instanceof Error?n:new tA(a);typeof t.cancel=="function"&&t.cancel(),i(o)},e);oj(t.then(r,i),()=>{clearTimeout(s)})});xd.exports=nA;xd.exports.default=nA;xd.exports.TimeoutError=tA;var uj=xd.exports,Gg={},Jg={};Object.defineProperty(Jg,"__esModule",{value:!0});function lj(t,e,n){let r=0,i=t.length;for(;i>0;){const s=i/2|0;let a=r+s;n(t[a],e)<=0?(r=++a,i-=s+1):i=s}return r}Jg.default=lj;Object.defineProperty(Gg,"__esModule",{value:!0});const cj=Jg;class dj{constructor(){this._queue=[]}enqueue(e,n){n=Object.assign({priority:0},n);const r={priority:n.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=n.priority){this._queue.push(r);return}const i=cj.default(this._queue,r,(s,a)=>a.priority-s.priority);this._queue.splice(i,0,r)}dequeue(){const e=this._queue.shift();return e==null?void 0:e.run}filter(e){return this._queue.filter(n=>n.priority===e.priority).map(n=>n.run)}get size(){return this._queue.length}}Gg.default=dj;Object.defineProperty(YS,"__esModule",{value:!0});const fj=sj,rA=uj,hj=Gg,Vu=()=>{},pj=new rA.TimeoutError;let mj=class extends fj{constructor(e){var n,r,i,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Vu,this._resolveIdle=Vu,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:hj.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(r=(n=e.intervalCap)===null||n===void 0?void 0:n.toString())!==null&&r!==void 0?r:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=Vu,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=Vu,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const e=Date.now();if(this._intervalId===void 0){const n=this._intervalEnd-e;if(n<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},n)),!0}return!1}_tryToStartAnother(){if(this._queue.size===0)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const n=this._queue.dequeue();return n?(this.emit("active"),n(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,n={}){return new Promise((r,i)=>{const s=async()=>{this._pendingCount++,this._intervalCount++;try{const a=this._timeout===void 0&&n.timeout===void 0?e():rA.default(Promise.resolve(e()),n.timeout===void 0?this._timeout:n.timeout,()=>{(n.throwOnTimeout===void 0?this._throwOnTimeout:n.throwOnTimeout)&&i(pj)});r(await a)}catch(a){i(a)}this._next()};this._queue.enqueue(s,n),this._tryToStartAnother(),this.emit("add")})}async addAll(e,n){return Promise.all(e.map(async r=>this.add(r,n)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{const n=this._resolveEmpty;this._resolveEmpty=()=>{n(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{const n=this._resolveIdle;this._resolveIdle=()=>{n(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};var $r=YS.default=mj;const gj="default"in $r?$r.default:$r,yj=[408,425,429,500,502,503,504];let Xv=class{constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new gj({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e==null?void 0:e.onFailedResponseHook}call(e,...n){return this.callWithOptions({},e,...n)}callWithOptions(e,n,...r){const i=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&i>0&&this.queueSizeBytes+i>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${i} bytes.`));i>0&&(this.queueSizeBytes+=i);const s=this.onFailedResponseHook;let a=this.queue.add(()=>ij(()=>n(...r).catch(o=>{throw o instanceof Error?o:new Error(o)}),{async onFailedAttempt({error:o}){if(typeof o!="object"||o==null)throw o;const u="message"in o&&typeof o.message=="string"?o.message:void 0;if(u!=null&&u.startsWith("Cancel")||u!=null&&u.startsWith("TimeoutError")||u!=null&&u.startsWith("AbortError")||"name"in o&&o.name==="TimeoutError"||"code"in o&&o.code==="ECONNABORTED")throw o;const l="response"in o?o.response:void 0;if(s&&await s(l))return;const c=(l==null?void 0:l.status)??("status"in o?o.status:void 0);if(c!=null&&(typeof c=="number"||typeof c=="string")&&!yj.includes(+c))throw o},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(a=a.finally(()=>{this.queueSizeBytes-=i})),e.signal?Promise.race([a,new Promise((o,u)=>{var l;(l=e.signal)==null||l.addEventListener("abort",()=>{u(new Error("AbortError"))})})]):a}};function Qv(t){return typeof(t==null?void 0:t._getType)=="function"}function Yv(t){const e={type:t._getType(),data:{content:t.content}};return t!=null&&t.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}let iA=function(){const{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return iA=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^n()&15>>+r/4).toString(16))};function _j(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const xp=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class oa extends Error{}class Dt extends oa{constructor(e,n,r,i){super(`${Dt.makeMessage(e,n,r)}`),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.status=e,this.headers=i,this.error=n}static makeMessage(e,n,r){const i=n!=null&&n.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):r;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,n,r,i){if(!e||!i)return new kd({message:r,cause:xp(n)});const s=n;return e===400?new aA(e,s,r,i):e===401?new oA(e,s,r,i):e===403?new uA(e,s,r,i):e===404?new lA(e,s,r,i):e===409?new cA(e,s,r,i):e===422?new dA(e,s,r,i):e===429?new fA(e,s,r,i):e>=500?new hA(e,s,r,i):new Dt(e,s,r,i)}}class kp extends Dt{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class kd extends Dt{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class sA extends kd{constructor({message:e}={}){super({message:e??"Request timed out."})}}class aA extends Dt{}class oA extends Dt{}class uA extends Dt{}class lA extends Dt{}class cA extends Dt{}class dA extends Dt{}class fA extends Dt{}class hA extends Dt{}const vj=/^[a-z][a-z0-9+.-]*:/i,wj=t=>vj.test(t);let Vt=t=>(Vt=Array.isArray,Vt(t)),e0=Vt;function lu(t){return typeof t!="object"?{}:t??{}}function t0(t){if(!t)return!0;for(const e in t)return!1;return!0}function bj(t,e){return Object.prototype.hasOwnProperty.call(t,e)}const xj=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new oa(`${t} must be an integer`);if(e<0)throw new oa(`${t} must be a positive integer`);return e},kj=t=>{try{return JSON.parse(t)}catch{return}},Sj=t=>new Promise(e=>setTimeout(e,t)),bs="0.0.1";function Aj(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const Ej=()=>{var n;const t=Aj();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bs,"X-Stainless-OS":r0(Deno.build.os),"X-Stainless-Arch":n0(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:((n=Deno.version)==null?void 0:n.deno)??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bs,"X-Stainless-OS":r0(globalThis.process.platform??"unknown"),"X-Stainless-Arch":n0(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=Tj();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":bs,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Tj(){if(typeof navigator>"u"||!navigator)return null;const t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:n}of t){const r=n.exec(navigator.userAgent);if(r){const i=r[1]||0,s=r[2]||0,a=r[3]||0;return{browser:e,version:`${i}.${s}.${a}`}}}return null}const n0=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",r0=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Ij;const Oj=()=>Ij??(Ij=Ej());function Cj(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Langsmith({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Pj(...t){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function pA(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Pj({start(){},async pull(n){const{done:r,value:i}=await e.next();r?n.close():n.enqueue(i)},async cancel(){var n;await((n=e.return)==null?void 0:n.call(e))}})}async function Nj(t){var r,i;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((i=(r=t[Symbol.asyncIterator]()).return)==null?void 0:i.call(r));return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const $j=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),mA="RFC3986",gA=t=>String(t),i0={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:gA},Rj="RFC1738";let Sp=(t,e)=>(Sp=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Sp(t,e));const ar=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),Mf=1024,jj=(t,e,n,r,i)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),n==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let a="";for(let o=0;o<s.length;o+=Mf){const u=s.length>=Mf?s.slice(o,o+Mf):s,l=[];for(let c=0;c<u.length;++c){let d=u.charCodeAt(c);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||i===Rj&&(d===40||d===41)){l[l.length]=u.charAt(c);continue}if(d<128){l[l.length]=ar[d];continue}if(d<2048){l[l.length]=ar[192|d>>6]+ar[128|d&63];continue}if(d<55296||d>=57344){l[l.length]=ar[224|d>>12]+ar[128|d>>6&63]+ar[128|d&63];continue}c+=1,d=65536+((d&1023)<<10|u.charCodeAt(c)&1023),l[l.length]=ar[240|d>>18]+ar[128|d>>12&63]+ar[128|d>>6&63]+ar[128|d&63]}a+=l.join("")}return a};function Lj(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function s0(t,e){if(Vt(t)){const n=[];for(let r=0;r<t.length;r+=1)n.push(e(t[r]));return n}return e(t)}const yA={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},_A=function(t,e){Array.prototype.push.apply(t,Vt(e)?e:[e])};let Mj;const tt={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:jj,encodeValuesOnly:!1,format:mA,formatter:gA,indices:!1,serializeDate(t){return(Mj??(Mj=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function zj(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const zf={};function vA(t,e,n,r,i,s,a,o,u,l,c,d,f,h,m,_,v,y){let p=t,g=y,b=0,E=!1;for(;(g=g.get(zf))!==void 0&&!E;){const N=g.get(t);if(b+=1,typeof N<"u"){if(N===b)throw new RangeError("Cyclic object value");E=!0}typeof g.get(zf)>"u"&&(b=0)}if(typeof l=="function"?p=l(e,p):p instanceof Date?p=f==null?void 0:f(p):n==="comma"&&Vt(p)&&(p=s0(p,function(N){return N instanceof Date?f==null?void 0:f(N):N})),p===null){if(s)return u&&!_?u(e,tt.encoder,v,"key",h):e;p=""}if(zj(p)||Lj(p)){if(u){const N=_?e:u(e,tt.encoder,v,"key",h);return[(m==null?void 0:m(N))+"="+(m==null?void 0:m(u(p,tt.encoder,v,"value",h)))]}return[(m==null?void 0:m(e))+"="+(m==null?void 0:m(String(p)))]}const T=[];if(typeof p>"u")return T;let I;if(n==="comma"&&Vt(p))_&&u&&(p=s0(p,u)),I=[{value:p.length>0?p.join(",")||null:void 0}];else if(Vt(l))I=l;else{const N=Object.keys(p);I=c?N.sort(c):N}const k=o?String(e).replace(/\./g,"%2E"):String(e),j=r&&Vt(p)&&p.length===1?k+"[]":k;if(i&&Vt(p)&&p.length===0)return j+"[]";for(let N=0;N<I.length;++N){const L=I[N],ue=typeof L=="object"&&typeof L.value<"u"?L.value:p[L];if(a&&ue===null)continue;const Ee=d&&o?L.replace(/\./g,"%2E"):L,Et=Vt(p)?typeof n=="function"?n(j,Ee):j:j+(d?"."+Ee:"["+Ee+"]");y.set(t,b);const tr=new WeakMap;tr.set(zf,y),_A(T,vA(ue,Et,n,r,i,s,a,o,n==="comma"&&_&&Vt(p)?null:u,l,c,d,f,h,m,_,v,tr))}return T}function Dj(t=tt){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||tt.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=mA;if(typeof t.format<"u"){if(!Sp(i0,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const r=i0[n];let i=tt.filter;(typeof t.filter=="function"||Vt(t.filter))&&(i=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in yA?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=tt.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:tt.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:tt.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:tt.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:tt.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?tt.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:tt.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:tt.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:tt.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:tt.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:tt.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:tt.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:tt.strictNullHandling}}function Uj(t,e={}){let n=t;const r=Dj(e);let i,s;typeof r.filter=="function"?(s=r.filter,n=s("",n)):Vt(r.filter)&&(s=r.filter,i=s);const a=[];if(typeof n!="object"||n===null)return"";const o=yA[r.arrayFormat],u=o==="comma"&&r.commaRoundTrip;i||(i=Object.keys(n)),r.sort&&i.sort(r.sort);const l=new WeakMap;for(let f=0;f<i.length;++f){const h=i[f];r.skipNulls&&n[h]===null||_A(a,vA(n[h],h,o,u,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}const c=a.join(r.delimiter);let d=r.addQueryPrefix===!0?"?":"";return r.charsetSentinel&&(r.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),c.length>0?d+c:""}function Fj(t){return Uj(t,{arrayFormat:"comma"})}const bc={off:0,error:200,warn:300,info:400,debug:500},a0=(t,e,n)=>{if(t){if(bj(bc,t))return t;un(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(bc))}`)}};function Qa(){}function Ku(t,e,n){return!e||bc[t]>bc[n]?Qa:e[t].bind(e)}const Bj={error:Qa,warn:Qa,info:Qa,debug:Qa};let o0=new WeakMap;function un(t){const e=t.logger,n=t.logLevel??"off";if(!e)return Bj;const r=o0.get(e);if(r&&r[0]===n)return r[1];const i={error:Ku("error",e,n),warn:Ku("warn",e,n),info:Ku("info",e,n),debug:Ku("debug",e,n)};return o0.set(e,[n,i]),i}const Ui=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"||e.toLowerCase()==="x-tenant-id"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);async function wA(t,e){const{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:s}=e,a=await(async()=>{var d;if(n.status===204)return null;if(e.options.__binaryResponse)return n;const o=n.headers.get("content-type"),u=(d=o==null?void 0:o.split(";")[0])==null?void 0:d.trim();return(u==null?void 0:u.includes("application/json"))||(u==null?void 0:u.endsWith("+json"))?n.headers.get("content-length")==="0"?void 0:await n.json():await n.text()})();return un(t).debug(`[${r}] response parsed`,Ui({retryOfRequestLogID:i,url:n.url,status:n.status,body:a,durationMs:Date.now()-s})),a}var Hj=function(t,e,n,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(t,n):i?i.value=n:e.set(t,n),n},u0=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},Ya;class Sd extends Promise{constructor(e,n,r=wA){super(i=>{i(null)}),Object.defineProperty(this,"responsePromise",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"parseResponse",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"parsedPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ya.set(this,void 0),Hj(this,Ya,e,"f")}_thenUnwrap(e){return new Sd(u0(this,Ya,"f"),this.responsePromise,async(n,r)=>e(await this.parseResponse(n,r),r))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(u0(this,Ya,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Ya=new WeakMap;var Zj=function(t,e,n,r,i){if(r==="m")throw new TypeError("Private method is not writable");if(r==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return r==="a"?i.call(t,n):i?i.value=n:e.set(t,n),n},Vj=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},qu;class cu{constructor(e,n,r,i){qu.set(this,void 0),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Zj(this,qu,e,"f"),this.options=i,this.response=n,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new oa("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Vj(this,qu,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(qu=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class Kj extends Sd{constructor(e,n,r){super(e,n,async(i,s)=>new r(i,s.response,await wA(i,s),s.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class wr extends cu{constructor(e,n,r,i){super(e,n,r,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=r||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){const e=this.options.query.offset??0,n=this.getPaginatedItems().length,r=e+n;return{...this.options,query:{...lu(this.options.query),offset:r}}}}class qj extends cu{constructor(e,n,r,i){super(e,n,r,i),Object.defineProperty(this,"repos",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"total",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.repos=r.repos||[],this.total=r.total||0}getPaginatedItems(){return this.repos??[]}nextPageRequestOptions(){const e=this.options.query.offset??0,n=this.getPaginatedItems().length,r=e+n;return{...this.options,query:{...lu(this.options.query),offset:r}}}}class Wj extends cu{constructor(e,n,r,i){super(e,n,r,i),Object.defineProperty(this,"commits",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"total",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.commits=r.commits||[],this.total=r.total||0}getPaginatedItems(){return this.commits??[]}nextPageRequestOptions(){const e=this.options.query.offset??0,n=this.getPaginatedItems().length,r=e+n;return{...this.options,query:{...lu(this.options.query),offset:r}}}}class Gj extends cu{constructor(e,n,r,i){super(e,n,r,i),Object.defineProperty(this,"evaluators",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"total",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.evaluators=r.evaluators||[],this.total=r.total||0}getPaginatedItems(){return this.evaluators??[]}nextPageRequestOptions(){const e=this.options.query.offset??0,n=this.getPaginatedItems().length,r=e+n;return{...this.options,query:{...lu(this.options.query),offset:r}}}}class Jj extends cu{constructor(e,n,r,i){super(e,n,r,i),Object.defineProperty(this,"clustering_jobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.clustering_jobs=r.clustering_jobs||[]}getPaginatedItems(){return this.clustering_jobs??[]}nextPageRequestOptions(){const e=this.options.query.offset??0,n=this.getPaginatedItems().length,r=e+n;return{...this.options,query:{...lu(this.options.query),offset:r}}}}const bA=()=>{var t;if(typeof File>"u"){const{process:e}=globalThis,n=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(n?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function vo(t,e,n){return bA(),new File(t,e??"unknown_file",n)}function jl(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const xA=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",kA=async(t,e)=>({...t,body:await Qj(t.body,e)}),l0=new WeakMap;function Xj(t){const e=typeof t=="function"?t:t.fetch,n=l0.get(e);if(n)return n;const r=(async()=>{try{const i="Response"in e?e.Response:(await e("data:,")).constructor,s=new FormData;return s.toString()!==await new i(s).text()}catch{return!0}})();return l0.set(e,r),r}const Qj=async(t,e)=>{if(!await Xj(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([r,i])=>Ap(n,r,i))),n},Yj=t=>t instanceof Blob&&"name"in t,Ap=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,vo([await n.blob()],jl(n)));else if(xA(n))t.append(e,vo([await new Response(pA(n)).blob()],jl(n)));else if(Yj(n))t.append(e,n,jl(n));else if(Array.isArray(n))await Promise.all(n.map(r=>Ap(t,e+"[]",r)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([r,i])=>Ap(t,`${e}[${r}]`,i)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},SA=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",e4=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&SA(t),t4=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function n4(t,e,n){if(bA(),t=await t,e4(t))return t instanceof File?t:vo([await t.arrayBuffer()],t.name);if(t4(t)){const i=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),vo(await Ep(i),e,n)}const r=await Ep(t);if(e||(e=jl(t)),!(n!=null&&n.type)){const i=r.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(n={...n,type:i})}return vo(r,e,n)}async function Ep(t){var n;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(SA(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(xA(t))for await(const r of t)e.push(...await Ep(r));else{const r=(n=t==null?void 0:t.constructor)==null?void 0:n.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${r4(t)}`)}return e}function r4(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class pe{constructor(e){Object.defineProperty(this,"_client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._client=e}}function AA(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const c0=Object.freeze(Object.create(null)),i4=(t=AA)=>function(n,...r){if(n.length===1)return n[0];let i=!1;const s=[],a=n.reduce((c,d,f)=>{var _;/[?#]/.test(d)&&(i=!0);const h=r[f];let m=(i?encodeURIComponent:t)(""+h);return f!==r.length&&(h==null||typeof h=="object"&&h.toString===((_=Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??c0)??c0))==null?void 0:_.toString))&&(m=h+"",s.push({start:c.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),c+d+(f===r.length?"":m)},""),o=a.split(/[?#]/,1)[0],u=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let l;for(;(l=u.exec(o))!==null;)s.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(s.sort((c,d)=>c.start-d.start),s.length>0){let c=0;const d=s.reduce((f,h)=>{const m=" ".repeat(h.start-c),_="^".repeat(h.length);return c=h.start+h.length,f+m+_},"");throw new oa(`Path parameters result in path with invalid segments: ${s.map(f=>f.error).join(` `)} ${a} ${d}`)}return a},H=i4(AA);let EA=class extends pe{create(e,n,r){const{body:i}=n;return this._client.post(H`/api/v1/annotation-queues/${e}/runs`,{body:i,...r})}update(e,n,r){const{queue_id:i,...s}=n;return this._client.patch(H`/api/v1/annotation-queues/${i}/runs/${e}`,{body:s,...r})}list(e,n={},r){return this._client.get(H`/api/v1/annotation-queues/${e}/runs`,{query:n,...r})}deleteAll(e,n,r){return this._client.post(H`/api/v1/annotation-queues/${e}/runs/delete`,{body:n,...r})}deleteQueue(e,n,r){const{queue_id:i}=n;return this._client.delete(H`/api/v1/annotation-queues/${i}/runs/${e}`,r)}};class Xg extends pe{constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new EA(this._client)})}retrieve(e,n){return this._client.get(H`/api/v1/annotation-queues/${e}`,n)}update(e,n,r){return this._client.patch(H`/api/v1/annotation-queues/${e}`,{body:n,...r})}delete(e,n){return this._client.delete(H`/api/v1/annotation-queues/${e}`,n)}annotationQueues(e,n){return this._client.post("/api/v1/annotation-queues",{body:e,...n})}createRunStatus(e,n,r){return this._client.post(H`/api/v1/annotation-queues/status/${e}`,{body:n,...r})}export(e,n,r){return this._client.post(H`/api/v1/annotation-queues/${e}/export`,{body:n,...r})}populate(e,n){return this._client.post("/api/v1/annotation-queues/populate",{body:e,...n})}retrieveAnnotationQueues(e={},n){return this._client.getAPIList("/api/v1/annotation-queues",wr,{query:e,...n})}retrieveQueues(e,n){return this._client.get(H`/api/v1/annotation-queues/${e}/queues`,n)}retrieveRun(e,n,r){const{queue_id:i,...s}=n;return this._client.get(H`/api/v1/annotation-queues/${i}/run/${e}`,{query:s,...r})}retrieveSize(e,n={},r){return this._client.get(H`/api/v1/annotation-queues/${e}/size`,{query:n,...r})}retrieveTotalArchived(e,n={},r){return this._client.get(H`/api/v1/annotation-queues/${e}/total_archived`,{query:n,...r})}retrieveTotalSize(e,n){return this._client.get(H`/api/v1/annotation-queues/${e}/total_size`,n)}}Xg.Runs=EA;class TA extends pe{create(e,n,r){const{owner:i,...s}=n;return this._client.post(H`/commits/${i}/${e}`,{body:s,...r})}retrieve(e,n,r){const{owner:i,repo:s,...a}=n;return this._client.get(H`/commits/${i}/${s}/${e}`,{query:a,...r})}list(e,n,r){const{owner:i,...s}=n;return this._client.getAPIList(H`/commits/${i}/${e}`,Wj,{query:s,...r})}}class IA extends pe{create(e,n){return this._client.post("/api/v1/datasets/comparative",{body:e,...n})}delete(e,n){return this._client.delete(H`/api/v1/datasets/comparative/${e}`,n)}}class OA extends pe{grouped(e,n,r){return this._client.post(H`/api/v1/datasets/${e}/experiments/grouped`,{body:n,...r})}}class CA extends pe{runs(e,n,r){return this._client.post(H`/api/v1/datasets/${e}/group/runs`,{body:n,...r})}}let PA=class extends pe{create(e,n,r){const{format:i,...s}=n;return this._client.post(H`/api/v1/datasets/${e}/runs`,{query:{format:i},body:s,...r})}delta(e,n,r){return this._client.post(H`/api/v1/datasets/${e}/runs/delta`,{body:n,...r})}};class NA extends pe{create(e,n={},r){const{share_projects:i}=n??{};return this._client.put(H`/api/v1/datasets/${e}/share`,{query:{share_projects:i},...r})}retrieve(e,n){return this._client.get(H`/api/v1/datasets/${e}/share`,n)}deleteAll(e,n){return this._client.delete(H`/api/v1/datasets/${e}/share`,n)}}class $A extends pe{create(e,n,r){return this._client.put(H`/api/v1/datasets/${e}/splits`,{body:n,...r})}retrieve(e,n={},r){return this._client.get(H`/api/v1/datasets/${e}/splits`,{query:n,...r})}}class RA extends pe{list(e,n={},r){return this._client.getAPIList(H`/api/v1/datasets/${e}/versions`,wr,{query:n,...r})}retrieveDiff(e,n,r){return this._client.get(H`/api/v1/datasets/${e}/versions/diff`,{query:n,...r})}}let Vr=class extends pe{constructor(){super(...arguments),Object.defineProperty(this,"versions",{enumerable:!0,configurable:!0,writable:!0,value:new RA(this._client)}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new PA(this._client)}),Object.defineProperty(this,"group",{enumerable:!0,configurable:!0,writable:!0,value:new CA(this._client)}),Object.defineProperty(this,"experiments",{enumerable:!0,configurable:!0,writable:!0,value:new OA(this._client)}),Object.defineProperty(this,"share",{enumerable:!0,configurable:!0,writable:!0,value:new NA(this._client)}),Object.defineProperty(this,"comparative",{enumerable:!0,configurable:!0,writable:!0,value:new IA(this._client)}),Object.defineProperty(this,"splits",{enumerable:!0,configurable:!0,writable:!0,value:new $A(this._client)})}create(e,n){return this._client.post("/api/v1/datasets",{body:e,...n})}retrieve(e,n){return this._client.get(H`/api/v1/datasets/${e}`,n)}update(e,n,r){return this._client.patch(H`/api/v1/datasets/${e}`,{body:n,...r})}list(e={},n){const{datatype:r,...i}=e??{};return this._client.getAPIList("/api/v1/datasets",wr,{query:{data_type:r,...i},...n})}delete(e,n){return this._client.delete(H`/api/v1/datasets/${e}`,n)}clone(e,n){return this._client.post("/api/v1/datasets/clone",{body:e,...n})}retrieveCsv(e,n={},r){return this._client.get(H`/api/v1/datasets/${e}/csv`,{query:n,...r})}retrieveJSONL(e,n={},r){return this._client.get(H`/api/v1/datasets/${e}/jsonl`,{query:n,...r})}retrieveOpenAI(e,n={},r){return this._client.get(H`/api/v1/datasets/${e}/openai`,{query:n,...r})}retrieveOpenAIFt(e,n={},r){return this._client.get(H`/api/v1/datasets/${e}/openai_ft`,{query:n,...r})}retrieveVersion(e,n={},r){return this._client.get(H`/api/v1/datasets/${e}/version`,{query:n,...r})}updateTags(e,n,r){return this._client.put(H`/api/v1/datasets/${e}/tags`,{body:n,...r})}upload(e,n){return this._client.post("/api/v1/datasets/upload",kA({body:e,...n},this._client))}};Vr.Versions=RA;Vr.Runs=PA;Vr.Group=CA;Vr.Experiments=OA;Vr.Share=NA;Vr.Comparative=IA;Vr.Splits=$A;class jA extends pe{list(e={},n){return this._client.get("/api/v1/runs/rules",{query:e,...n})}}class LA extends pe{create(e,n){const{body:r}=e;return this._client.post("/api/v1/examples/bulk",{body:r,...n})}patchAll(e,n){const{body:r}=e;return this._client.patch("/api/v1/examples/bulk",{body:r,...n})}}class MA extends pe{create(e){return this._client.post("/api/v1/examples/validate",e)}bulk(e){return this._client.post("/api/v1/examples/validate/bulk",e)}}class Ad extends pe{constructor(){super(...arguments),Object.defineProperty(this,"bulk",{enumerable:!0,configurable:!0,writable:!0,value:new LA(this._client)}),Object.defineProperty(this,"validate",{enumerable:!0,configurable:!0,writable:!0,value:new MA(this._client)})}create(e,n){return this._client.post("/api/v1/examples",{body:e,...n})}retrieve(e,n={},r){return this._client.get(H`/api/v1/examples/${e}`,{query:n,...r})}update(e,n,r){return this._client.patch(H`/api/v1/examples/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/api/v1/examples",wr,{query:e,...n})}delete(e,n){return this._client.delete(H`/api/v1/examples/${e}`,n)}deleteAll(e,n){const{example_ids:r}=e;return this._client.delete("/api/v1/examples",{query:{example_ids:r},...n})}retrieveCount(e={},n){return this._client.get("/api/v1/examples/count",{query:e,...n})}uploadFromCsv(e,n,r){return this._client.post(H`/api/v1/examples/upload/${e}`,kA({body:n,...r},this._client))}}Ad.Bulk=LA;Ad.Validate=MA;const zA=Symbol("brand.privateNullableHeaders");function*s4(t){if(!t)return;if(zA in t){const{values:r,nulls:i}=t;yield*r.entries();for(const s of i)yield[s,null];return}let e=!1,n;t instanceof Headers?n=t.entries():e0(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let r of n){const i=r[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");const s=e0(r[1])?r[1]:[r[1]];let a=!1;for(const o of s)o!==void 0&&(e&&!a&&(a=!0,yield[i,null]),yield[i,o])}}const jt=t=>{const e=new Headers,n=new Set;for(const r of t){const i=new Set;for(const[s,a]of s4(r)){const o=s.toLowerCase();i.has(o)||(e.delete(s),i.add(o)),a===null?(e.delete(s),n.add(o)):(e.append(s,a),n.delete(o))}}return{[zA]:!0,values:e,nulls:n}};class DA extends pe{delete(e,n){const{feedback_key:r}=e;return this._client.delete("/api/v1/feedback-configs",{query:{feedback_key:r},...n,headers:jt([{Accept:"*/*"},n==null?void 0:n.headers])})}}class UA extends pe{create(e,n){const r="body"in e?e.body:e;return this._client.post("/api/v1/feedback/tokens",{body:r,...n})}retrieve(e,n={},r){return this._client.get(H`/api/v1/feedback/tokens/${e}`,{query:n,...r})}update(e,n,r){return this._client.post(H`/api/v1/feedback/tokens/${e}`,{body:n,...r})}list(e,n){return this._client.get("/api/v1/feedback/tokens",{query:e,...n})}}class Ed extends pe{constructor(){super(...arguments),Object.defineProperty(this,"tokens",{enumerable:!0,configurable:!0,writable:!0,value:new UA(this._client)}),Object.defineProperty(this,"configs",{enumerable:!0,configurable:!0,writable:!0,value:new DA(this._client)})}create(e,n){return this._client.post("/api/v1/feedback",{body:e,...n})}retrieve(e,n={},r){return this._client.get(H`/api/v1/feedback/${e}`,{query:n,...r})}update(e,n,r){return this._client.patch(H`/api/v1/feedback/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/api/v1/feedback",wr,{query:e,...n})}delete(e,n){return this._client.delete(H`/api/v1/feedback/${e}`,n)}}Ed.Tokens=UA;Ed.Configs=DA;class FA extends pe{list(e){return this._client.get("/api/v1/info",e)}}class BA extends pe{create(e,n){return this._client.post("/v1/platform/evaluators",{body:e,...n})}retrieve(e,n){return this._client.get(H`/v1/platform/evaluators/${e}`,n)}update(e,n,r){return this._client.patch(H`/v1/platform/evaluators/${e}`,{body:n,...r})}list(e={},n){return this._client.getAPIList("/v1/platform/evaluators",Gj,{query:e,...n})}delete(e,n={},r){const{delete_run_rules:i}=n??{};return this._client.delete(H`/v1/platform/evaluators/${e}`,{query:{delete_run_rules:i},...r,headers:jt([{Accept:"*/*"},r==null?void 0:r.headers])})}bulkDelete(e,n){const{evaluator_ids:r,delete_run_rules:i}=e;return this._client.delete("/v1/platform/evaluators",{query:{evaluator_ids:r,delete_run_rules:i},...n})}spend(e,n){return this._client.get("/v1/platform/evaluators/spend",{query:e,...n})}}class HA extends pe{list(e,n={},r){return this._client.get(H`/api/v1/public/${e}/datasets`,{query:n,...r})}listComparative(e,n={},r){return this._client.getAPIList(H`/api/v1/public/${e}/datasets/comparative`,wr,{query:n,...r})}listFeedback(e,n={},r){return this._client.getAPIList(H`/api/v1/public/${e}/datasets/feedback`,wr,{query:n,...r})}listSessions(e,n={},r){const{accept:i,...s}=n??{};return this._client.getAPIList(H`/api/v1/public/${e}/datasets/sessions`,wr,{query:s,...r,headers:jt([{...i!=null?{accept:i}:void 0},r==null?void 0:r.headers])})}retrieveSessionsBulk(e,n){return this._client.get("/api/v1/public/datasets/sessions-bulk",{query:e,...n})}}class Qg extends pe{constructor(){super(...arguments),Object.defineProperty(this,"datasets",{enumerable:!0,configurable:!0,writable:!0,value:new HA(this._client)})}retrieveFeedbacks(e,n={},r){return this._client.getAPIList(H`/api/v1/public/${e}/feedbacks`,wr,{query:n,...r})}}Qg.Datasets=HA;class ZA extends pe{list(e,n,r){const{owner:i,...s}=n;return this._client.get(H`/v1/platform/hub/repos/${i}/${e}/directories`,{query:s,...r})}delete(e,n,r){const{owner:i}=n;return this._client.delete(H`/v1/platform/hub/repos/${i}/${e}/directories`,{...r,headers:jt([{Accept:"*/*"},r==null?void 0:r.headers])})}commit(e,n,r){const{owner:i,...s}=n;return this._client.post(H`/v1/platform/hub/repos/${i}/${e}/directories/commits`,{body:s,...r})}}class Yg extends pe{constructor(){super(...arguments),Object.defineProperty(this,"directories",{enumerable:!0,configurable:!0,writable:!0,value:new ZA(this._client)})}create(e,n){return this._client.post("/api/v1/repos",{body:e,...n})}retrieve(e,n,r){const{owner:i}=n;return this._client.get(H`/api/v1/repos/${i}/${e}`,r)}update(e,n,r){const{owner:i,...s}=n;return this._client.patch(H`/api/v1/repos/${i}/${e}`,{body:s,...r})}list(e={},n){const{single_repo_type:r,...i}=e??{};return this._client.getAPIList("/api/v1/repos",qj,{query:{repo_type:r,...i},...n})}delete(e,n,r){const{owner:i}=n;return this._client.delete(H`/api/v1/repos/${i}/${e}`,r)}}Yg.Directories=ZA;class VA extends pe{}class ey extends pe{constructor(){super(...arguments),Object.defineProperty(this,"rules",{enumerable:!0,configurable:!0,writable:!0,value:new VA(this._client)})}create(e,n){return this._client.post("/runs",{body:e,...n})}retrieve(e,n={},r){return this._client.get(H`/api/v1/runs/${e}`,{query:n,...r})}update(e,n,r){return this._client.patch(H`/runs/${e}`,{body:n,...r})}ingestBatch(e,n){return this._client.post("/runs/batch",{body:e,...n})}query(e,n){return this._client.post("/api/v1/runs/query",{body:e,...n})}stats(e,n){return this._client.post("/api/v1/runs/stats",{body:e,...n})}update2(e,n){return this._client.patch(H`/api/v1/runs/${e}`,n)}}ey.Rules=VA;class KA extends pe{create(e,n){return this._client.post("/v2/sandboxes/boxes",{body:e,...n})}retrieve(e,n){return this._client.get(H`/v2/sandboxes/boxes/${e}`,n)}update(e,n,r){return this._client.patch(H`/v2/sandboxes/boxes/${e}`,{body:n,...r})}list(e={},n){return this._client.get("/v2/sandboxes/boxes",{query:e,...n})}delete(e,n){return this._client.delete(H`/v2/sandboxes/boxes/${e}`,{...n,headers:jt([{Accept:"*/*"},n==null?void 0:n.headers])})}createSnapshot(e,n,r){return this._client.post(H`/v2/sandboxes/boxes/${e}/snapshot`,{body:n,...r})}generateServiceURL(e,n,r){return this._client.post(H`/v2/sandboxes/boxes/${e}/service-url`,{body:n,...r})}getStatus(e,n){return this._client.get(H`/v2/sandboxes/boxes/${e}/status`,n)}start(e,n){return this._client.post(H`/v2/sandboxes/boxes/${e}/start`,n)}stop(e,n){return this._client.post(H`/v2/sandboxes/boxes/${e}/stop`,{...n,headers:jt([{Accept:"*/*"},n==null?void 0:n.headers])})}}class qA extends pe{create(e,n){return this._client.post("/v2/sandboxes/snapshots",{body:e,...n})}retrieve(e,n){return this._client.get(H`/v2/sandboxes/snapshots/${e}`,n)}list(e={},n){return this._client.get("/v2/sandboxes/snapshots",{query:e,...n})}delete(e,n){return this._client.delete(H`/v2/sandboxes/snapshots/${e}`,{...n,headers:jt([{Accept:"*/*"},n==null?void 0:n.headers])})}}class Td extends pe{constructor(){super(...arguments),Object.defineProperty(this,"boxes",{enumerable:!0,configurable:!0,writable:!0,value:new KA(this._client)}),Object.defineProperty(this,"snapshots",{enumerable:!0,configurable:!0,writable:!0,value:new qA(this._client)})}}Td.Boxes=KA;Td.Snapshots=qA;class WA extends pe{create(e,n,r){return this._client.post(H`/api/v1/sessions/${e}/insights`,{body:n,...r})}update(e,n,r){const{session_id:i,...s}=n;return this._client.patch(H`/api/v1/sessions/${i}/insights/${e}`,{body:s,...r})}list(e,n={},r){return this._client.getAPIList(H`/api/v1/sessions/${e}/insights`,Jj,{query:n,...r})}delete(e,n,r){const{session_id:i}=n;return this._client.delete(H`/api/v1/sessions/${i}/insights/${e}`,r)}retrieveJob(e,n,r){const{session_id:i}=n;return this._client.get(H`/api/v1/sessions/${i}/insights/${e}`,r)}retrieveRuns(e,n,r){const{session_id:i,...s}=n;return this._client.get(H`/api/v1/sessions/${i}/insights/${e}/runs`,{query:s,...r})}}class ty extends pe{constructor(){super(...arguments),Object.defineProperty(this,"insights",{enumerable:!0,configurable:!0,writable:!0,value:new WA(this._client)})}create(e,n){const{upsert:r,...i}=e;return this._client.post("/api/v1/sessions",{query:{upsert:r},body:i,...n})}retrieve(e,n={},r){const{accept:i,...s}=n??{};return this._client.get(H`/api/v1/sessions/${e}`,{query:s,...r,headers:jt([{...i!=null?{accept:i}:void 0},r==null?void 0:r.headers])})}update(e,n,r){return this._client.patch(H`/api/v1/sessions/${e}`,{body:n,...r})}list(e={},n){const{accept:r,...i}=e??{};return this._client.getAPIList("/api/v1/sessions",wr,{query:i,...n,headers:jt([{...r!=null?{accept:r}:void 0},n==null?void 0:n.headers])})}delete(e,n){return this._client.delete(H`/api/v1/sessions/${e}`,n)}dashboard(e,n,r){const{accept:i,...s}=n;return this._client.post(H`/api/v1/sessions/${e}/dashboard`,{body:s,...r,headers:jt([{...i!=null?{accept:i}:void 0},r==null?void 0:r.headers])})}}ty.Insights=WA;class GA extends pe{list(e){return this._client.get("/api/v1/settings",e)}}class JA extends pe{create(e,n){return this._client.post("/api/v1/workspaces",{body:e,...n})}update(e,n,r){return this._client.patch(H`/api/v1/workspaces/${e}`,{body:n,...r})}list(e={},n){return this._client.get("/api/v1/workspaces",{query:e,...n})}delete(e,n){return this._client.delete(H`/api/v1/workspaces/${e}`,n)}}var Df={};const La=t=>{var e,n,r,i;if(typeof globalThis.process<"u")return((e=Df==null?void 0:Df[t])==null?void 0:e.trim())||void 0;if(typeof globalThis.Deno<"u")return((i=(r=(n=globalThis.Deno.env)==null?void 0:n.get)==null?void 0:r.call(n,t))==null?void 0:i.trim())||void 0};var a4=function(t,e,n,r,i){if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n},d0=function(t,e,n,r){if(n==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!r:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?r:n==="a"?r.call(t):r?r.value:e.get(t)},Tp,ny,Ll,XA;class me{constructor({baseURL:e=La("LANGCHAIN_BASE_URL"),apiKey:n=La("LANGSMITH_API_KEY")??null,tenantID:r=La("LANGSMITH_TENANT_ID")??null,...i}={}){Tp.add(this),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tenantID",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"baseURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logLevel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ll.set(this,void 0),Object.defineProperty(this,"idempotencyHeader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sessions",{enumerable:!0,configurable:!0,writable:!0,value:new ty(this)}),Object.defineProperty(this,"examples",{enumerable:!0,configurable:!0,writable:!0,value:new Ad(this)}),Object.defineProperty(this,"datasets",{enumerable:!0,configurable:!0,writable:!0,value:new Vr(this)}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new ey(this)}),Object.defineProperty(this,"evaluators",{enumerable:!0,configurable:!0,writable:!0,value:new jA(this)}),Object.defineProperty(this,"onlineEvaluators",{enumerable:!0,configurable:!0,writable:!0,value:new BA(this)}),Object.defineProperty(this,"feedback",{enumerable:!0,configurable:!0,writable:!0,value:new Ed(this)}),Object.defineProperty(this,"public",{enumerable:!0,configurable:!0,writable:!0,value:new Qg(this)}),Object.defineProperty(this,"annotationQueues",{enumerable:!0,configurable:!0,writable:!0,value:new Xg(this)}),Object.defineProperty(this,"info",{enumerable:!0,configurable:!0,writable:!0,value:new FA(this)}),Object.defineProperty(this,"workspaces",{enumerable:!0,configurable:!0,writable:!0,value:new JA(this)}),Object.defineProperty(this,"repos",{enumerable:!0,configurable:!0,writable:!0,value:new Yg(this)}),Object.defineProperty(this,"commits",{enumerable:!0,configurable:!0,writable:!0,value:new TA(this)}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:new GA(this)}),Object.defineProperty(this,"sandboxes",{enumerable:!0,configurable:!0,writable:!0,value:new Td(this)});const s={apiKey:n,tenantID:r,...i,baseURL:e||"https://api.smith.langchain.com/"};this.baseURL=s.baseURL,this.timeout=s.timeout??ny.DEFAULT_TIMEOUT,this.logger=s.logger??console;const a="warn";this.logLevel=a,this.logLevel=a0(s.logLevel,"ClientOptions.logLevel",this)??a0(La("LANGCHAIN_LOG"),"process.env['LANGCHAIN_LOG']",this)??a,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??Cj(),a4(this,Ll,$j);const o=La("LANGCHAIN_CUSTOM_HEADERS");if(o){const u={};for(const l of o.split(` `)){const c=l.indexOf(":");c>=0&&(u[l.substring(0,c).trim()]=l.substring(c+1).trim())}s.defaultHeaders={...u,...s.defaultHeaders}}this._options=s,this.apiKey=n,this.tenantID=r}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,tenantID:this.tenantID,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:n}){if(!(this.apiKey&&e.get("x-api-key"))&&!n.has("x-api-key")&&!(this.tenantID&&e.get("x-tenant-id"))&&!n.has("x-tenant-id"))throw new Error('Could not resolve authentication method. Expected either apiKey or tenantID to be set. Or for one of the "X-API-Key" or "X-Tenant-Id" headers to be explicitly omitted')}async authHeaders(e){return jt([await this.apiKeyAuth(e),await this.tenantIDAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return jt([{"X-API-Key":this.apiKey}])}async tenantIDAuth(e){if(this.tenantID!=null)return jt([{"X-Tenant-Id":this.tenantID}])}stringifyQuery(e){return Fj(e)}getUserAgent(){return`${this.constructor.name}/JS ${bs}`}defaultIdempotencyKey(){return`stainless-node-retry-${iA()}`}makeStatusError(e,n,r,i){return Dt.generate(e,n,r,i)}buildURL(e,n,r){const i=!d0(this,Tp,"m",XA).call(this)&&r||this.baseURL,s=wj(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(s.searchParams);return(!t0(a)||!t0(o))&&(n={...o,...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(s.search=this.stringifyQuery(n)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:n,options:r}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,r){return this.request(Promise.resolve(r).then(i=>({method:e,path:n,...i})))}request(e,n=null){return new Sd(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,r){var v,y;const i=await e,s=i.maxRetries??this.maxRetries;n==null&&(n=s),await this.prepareOptions(i);const{req:a,url:o,timeout:u}=await this.buildRequest(i,{retryCount:s-n});await this.prepareRequest(a,{url:o,options:i});const l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),c=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(un(this).debug(`[${l}] sending request`,Ui({retryOfRequestLogID:r,method:i.method,url:o,options:i,headers:a.headers})),(v=i.signal)!=null&&v.aborted)throw new kp;const f=new AbortController,h=await this.fetchWithTimeout(o,a,u,f).catch(xp),m=Date.now();if(h instanceof globalThis.Error){const p=`retrying, ${n} attempts remaining`;if((y=i.signal)!=null&&y.aborted)throw new kp;const g=_j(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return un(this).info(`[${l}] connection ${g?"timed out":"failed"} - ${p}`),un(this).debug(`[${l}] connection ${g?"timed out":"failed"} (${p})`,Ui({retryOfRequestLogID:r,url:o,durationMs:m-d,message:h.message})),this.retryRequest(i,n,r??l);throw un(this).info(`[${l}] connection ${g?"timed out":"failed"} - error; no more retries left`),un(this).debug(`[${l}] connection ${g?"timed out":"failed"} (error; no more retries left)`,Ui({retryOfRequestLogID:r,url:o,durationMs:m-d,message:h.message})),g?new sA:new kd({cause:h})}const _=`[${l}${c}] ${a.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${m-d}ms`;if(!h.ok){const p=await this.shouldRetry(h);if(n&&p){const k=`retrying, ${n} attempts remaining`;return await Nj(h.body),un(this).info(`${_} - ${k}`),un(this).debug(`[${l}] response error (${k})`,Ui({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),this.retryRequest(i,n,r??l,h.headers)}const g=p?"error; no more retries left":"error; not retryable";un(this).info(`${_} - ${g}`);const b=await h.text().catch(k=>xp(k).message),E=kj(b),T=E?void 0:b;throw un(this).debug(`[${l}] response error (${g})`,Ui({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,message:T,durationMs:Date.now()-d})),this.makeStatusError(h.status,E,T,h.headers)}return un(this).info(_),un(this).debug(`[${l}] response start`,Ui({retryOfRequestLogID:r,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),{response:h,options:i,controller:f,requestLogID:l,retryOfRequestLogID:r,startTime:d}}getAPIList(e,n,r){return this.requestAPIList(n,r&&"then"in r?r.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...r})}requestAPIList(e,n){const r=this.makeRequest(n,null,void 0);return new Kj(this,r,e)}async fetchWithTimeout(e,n,r,i){const{signal:s,method:a,...o}=n||{},u=this._makeAbort(i);s&&s.addEventListener("abort",u,{once:!0});const l=setTimeout(u,r),c=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:i.signal,...c?{duplex:"half"}:{},method:"GET",...o};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,r,i){let s;const a=i==null?void 0:i.get("retry-after-ms");if(a){const u=parseFloat(a);Number.isNaN(u)||(s=u)}const o=i==null?void 0:i.get("retry-after");if(o&&!s){const u=parseFloat(o);Number.isNaN(u)?s=Date.parse(o)-Date.now():s=u*1e3}if(s===void 0){const u=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(n,u)}return await Sj(s),this.makeRequest(e,n-1,r)}calculateDefaultRetryTimeoutMillis(e,n){const s=n-e,a=Math.min(.5*Math.pow(2,s),16),o=1-Math.random()*.25;return a*o*1e3}async buildRequest(e,{retryCount:n=0}={}){const r={...e},{method:i,path:s,query:a,defaultBaseURL:o}=r,u=this.buildURL(s,a,o);"timeout"in r&&xj("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:l,body:c}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:i,bodyHeaders:l,retryCount:n});return{req:{method:i,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&c instanceof globalThis.ReadableStream&&{duplex:"half"},...c&&{body:c},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:r,retryCount:i}){let s={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);const a=jt([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Oj()},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(a),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=jt([n]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:pA(e)}:typeof e=="object"&&r.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:d0(this,Ll,"f").call(this,{body:e,headers:r})}}ny=me,Ll=new WeakMap,Tp=new WeakSet,XA=function(){return this.baseURL!=="https://api.smith.langchain.com/"};Object.defineProperty(me,"Langsmith",{enumerable:!0,configurable:!0,writable:!0,value:ny});Object.defineProperty(me,"DEFAULT_TIMEOUT",{enumerable:!0,configurable:!0,writable:!0,value:9e4});Object.defineProperty(me,"LangsmithError",{enumerable:!0,configurable:!0,writable:!0,value:oa});Object.defineProperty(me,"APIError",{enumerable:!0,configurable:!0,writable:!0,value:Dt});Object.defineProperty(me,"APIConnectionError",{enumerable:!0,configurable:!0,writable:!0,value:kd});Object.defineProperty(me,"APIConnectionTimeoutError",{enumerable:!0,configurable:!0,writable:!0,value:sA});Object.defineProperty(me,"APIUserAbortError",{enumerable:!0,configurable:!0,writable:!0,value:kp});Object.defineProperty(me,"NotFoundError",{enumerable:!0,configurable:!0,writable:!0,value:lA});Object.defineProperty(me,"ConflictError",{enumerable:!0,configurable:!0,writable:!0,value:cA});Object.defineProperty(me,"RateLimitError",{enumerable:!0,configurable:!0,writable:!0,value:fA});Object.defineProperty(me,"BadRequestError",{enumerable:!0,configurable:!0,writable:!0,value:aA});Object.defineProperty(me,"AuthenticationError",{enumerable:!0,configurable:!0,writable:!0,value:oA});Object.defineProperty(me,"InternalServerError",{enumerable:!0,configurable:!0,writable:!0,value:hA});Object.defineProperty(me,"PermissionDeniedError",{enumerable:!0,configurable:!0,writable:!0,value:uA});Object.defineProperty(me,"UnprocessableEntityError",{enumerable:!0,configurable:!0,writable:!0,value:dA});Object.defineProperty(me,"toFile",{enumerable:!0,configurable:!0,writable:!0,value:n4});me.Sessions=ty;me.Examples=Ad;me.Datasets=Vr;me.Runs=ey;me.Evaluators=jA;me.OnlineEvaluators=BA;me.Feedback=Ed;me.Public=Qg;me.AnnotationQueues=Xg;me.Info=FA;me.Workspaces=JA;me.Repos=Yg;me.Commits=TA;me.Settings=GA;me.Sandboxes=Td;function Uf(t){return`Invalid prompt identifier format: "${t}". Expected one of: - "prompt-name" (for private prompts) - "owner/prompt-name" (for prompts with explicit owner) - "prompt-name:commit-hash" (with commit reference) - "owner/prompt-name:commit-hash" (with owner and commit)`}class o4 extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}}class u4 extends Error{constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}}function Ff(t){return t!=null&&typeof t=="object"&&"name"in t&&(t==null?void 0:t.name)==="LangSmithNotFoundError"}function l4(t){return t!=null&&typeof t=="object"&&"name"in t&&(t==null?void 0:t.name)==="LangSmithConflictError"}async function q(t,e,n){let r;if(t.ok){n&&(r=await t.text());return}if(t.status===403)try{const a=await t.json();(a==null?void 0:a.error)==="org_scoped_key_requires_workspace"&&(r="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{const o=new Error(`${t.status} ${t.statusText}`);throw o.status=t==null?void 0:t.status,o}if(r===void 0)try{r=await t.text()}catch{r=""}const i=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${r}`;if(t.status===404)throw new u4(i);if(t.status===409)throw new o4(i);const s=new Error(i);throw s.status=t.status,s}const QA="ERR_CONFLICTING_ENDPOINTS";class c4 extends Error{constructor(){super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT and LANGSMITH_RUNS_ENDPOINTS."),Object.defineProperty(this,"code",{enumerable:!0,configurable:!0,writable:!0,value:QA}),this.name="ConflictingEndpointsError"}}function d4(t){return typeof t=="object"&&t!==null&&t.code===QA}function Ct(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(Uf(t));const[e,n]=t.split(":"),r=n||"latest";if(e.includes("/")){const[i,s]=e.split("/",2);if(!i||!s)throw new Error(Uf(t));return[i,s,r]}else{if(!e)throw new Error(Uf(t));return["-",e,r]}}const f4=10,h4=1e4,YA="created_at";function p4(t){return new Promise(e=>setTimeout(e,t))}function m4(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}function eE(t){try{return Kg(ss.join(t,YA)).split(` `)}catch{return}}function g4(t){const e=eE(t);if(e&&e[0]&&e[0].trim()){const n=Date.parse(e[0].trim());if(!Number.isNaN(n))return n}return void 0}function y4(t){const e=eE(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}async function _4(t){const e=g4(t);return e===void 0||Date.now()-e<=h4?!1:(await bp(),!0)}async function v4(t,e){const n=`${t}.oauth.lock.lock`;ss.dirname(n)&&await KS();const i=globalThis.crypto.randomUUID();for(;;){try{await OR(n)}catch(s){if(!m4(s))throw s;if(!await _4(n)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await p4(Math.min(f4,Math.max(0,e-Date.now())))}continue}try{await Vg(ss.join(n,YA),`${new Date().toISOString()} ${i} `)}catch(s){throw await bp(),s}break}return{async release(){y4(n)===i&&await bp()}}}const Ip="https://api.smith.langchain.com",w4="langsmith-cli",b4=6e4,x4=1e4;function k4(){const t=qg();return t==="browser"||t==="webworker"}function S4(){const t=en("LANGSMITH_CONFIG_FILE");if(t)return t;const e=en("HOME")??en("USERPROFILE");if(e)return ss.join(e,".langsmith","config.json")}function A4(t){var n;const e=en("LANGSMITH_PROFILE");if(e)return e;if(t.current_profile)return t.current_profile;if((n=t.profiles)!=null&&n.default)return"default"}function E4(){var e;if(k4())return;const t=S4();if(!(!t||!IR()))try{const n=JSON.parse(Kg(t)),r=A4(n),i=r?(e=n.profiles)==null?void 0:e[r]:void 0;return!r||!i?void 0:{configPath:t,config:n,profileName:r,profile:i}}catch{return}}function jn(t){return t!=null&&t.trim()!==""}function gi(t){return t==null?void 0:t.trim().replace(/^["']|["']$/g,"")}function f0(t){const e=t.oauth;if(!(e!=null&&e.refresh_token))return!1;if(!e.access_token)return!0;if(!e.expires_at)return!1;const n=Date.parse(e.expires_at);return Number.isNaN(n)?!1:n<=Date.now()+b4}function T4(t){let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);const n="/api/v1";return e.endsWith(n)?e.slice(0,-n.length):e}function I4(t,e){t.oauth??(t.oauth={}),e.access_token&&(t.oauth.access_token=e.access_token),e.refresh_token&&(t.oauth.refresh_token=e.refresh_token),typeof e.expires_in=="number"&&e.expires_in>0&&(t.oauth.expires_at=new Date(Date.now()+e.expires_in*1e3).toISOString())}function h0(t){return t.reason??new Error("The operation was aborted.")}async function O4(t,e){if(!e)return t;if(e.aborted)throw h0(e);let n;const r=new Promise((i,s)=>{const a=()=>{s(h0(e))};e.addEventListener("abort",a,{once:!0}),n=()=>{e.removeEventListener("abort",a)}});try{return await Promise.race([t,r])}finally{n==null||n()}}function C4(){var s,a;const t=E4(),e=t==null?void 0:t.profile;if(!t||!e)return{};const n=gi(e.api_key),r=gi((s=e.oauth)==null?void 0:s.access_token),i=gi((a=e.oauth)==null?void 0:a.refresh_token);return{apiUrl:e.api_url,apiKey:n,workspaceId:e.workspace_id,oauthAccessToken:r,oauthRefreshToken:i,profileAuth:n||r||i?new P4(t):void 0}}class P4{constructor(e){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"refreshPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedAuthorizationValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.rememberProfileAuthHeader(this.currentAuthHeader())}currentAuthHeader(){const e=N4(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,n){f0(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await O4(this.refreshPromise,n));const r=tE(this.state.profile);return this.rememberProfileAuthHeader(r),r}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}reloadProfile(){var e;try{const n=JSON.parse(Kg(this.state.configPath)),r=(e=n.profiles)==null?void 0:e[this.state.profileName];return r?(this.state.config=n,this.state.profile=r,r):void 0}catch{return}}async refreshOAuthToken(e){var a,o,u;const n=(a=this.state.profile.oauth)==null?void 0:a.refresh_token;if(!n)return;const r=gi(this.state.profile.api_url)??Ip,i=Date.now()+x4;let s;try{if(s=await v4(this.state.configPath,i),this.reloadProfile()&&!f0(this.state.profile))return;const c=new URLSearchParams({grant_type:"refresh_token",client_id:w4,refresh_token:((o=this.state.profile.oauth)==null?void 0:o.refresh_token)??n}),d=await e(`${T4(r)}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c.toString(),signal:AbortSignal.timeout(Math.max(0,i-Date.now()))});if(!d.ok)return;const f=await d.json();if(!f.access_token)return;I4(this.state.profile,f),(u=this.state.config).profiles??(u.profiles={}),this.state.config.profiles[this.state.profileName]=this.state.profile,await Vg(this.state.configPath,`${JSON.stringify(this.state.config,null,2)} `)}catch{return}finally{await(s==null?void 0:s.release())}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=(e==null?void 0:e.name)==="Authorization"?e.value:void 0}}function N4(t){var n,r;const e=gi((n=t.oauth)==null?void 0:n.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!gi((r=t.oauth)==null?void 0:r.refresh_token))return tE(t)}function tE(t){var r;const e=gi((r=t.oauth)==null?void 0:r.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};const n=gi(t.api_key);if(n)return{name:"x-api-key",value:n}}var p0="[...]",$4={result:"[Circular]"},xc=[],Ms=[];const R4=new TextEncoder;function j4(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Wu(t){return R4.encode(t)}function nE(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}function L4(t){return function(e,n){return nE(n)}}function M4(t){try{let l=function(_){const v=u(_);return v>o&&(o=v),v+2},c=function(_){return _===0?2:2+_*4},d=function(_){return _===void 0||typeof _=="function"||typeof _=="symbol"},f=function(_){return _===void 0||typeof _=="function"||typeof _=="symbol"?4:h(_)},h=function(_){if(_===null)return 4;if(_===void 0)return 0;const v=typeof _;if(v==="boolean")return 5;if(v==="number")return Number.isFinite(_)?_.toString().length:4;if(v==="bigint")return _.toString().length+2;if(v==="string")return l(_);if(v==="function"||v==="symbol")return 0;const y=_;if(y instanceof Date)return 26;if(y instanceof RegExp)return u(y.toString())+2;if(y instanceof Error){const g=y.name??"",b=y.message??"";return 22+u(g)+u(b)}if(typeof Buffer<"u"&&y instanceof Buffer)return 28+c(y.byteLength);if(ArrayBuffer.isView(y)){if(y instanceof DataView)return 2;const g=y.length??0,E=y instanceof Float32Array||y instanceof Float64Array?30:12;return 2+g*E}if(y instanceof ArrayBuffer)return 2;if(a.has(y))return 24;if(typeof y.toJSON=="function"){let g;try{g=y.toJSON("")}catch{return 16}a.add(y);const b=h(g);return a.delete(y),b}a.add(y);let p;if(Array.isArray(y)){p=2;const g=y.length;for(let b=0;b<g;b++)p+=f(y[b]),b<g-1&&(p+=1)}else if(y instanceof Map){p=2;let g=0;for(const[b,E]of y){if(d(E))continue;g>0&&(p+=1);const T=typeof b=="string"?b:String(b);p+=u(T)+3,p+=h(E),g++}}else if(y instanceof Set){p=2;let g=0;for(const b of y)g>0&&(p+=1),p+=f(b),g++}else{p=2;let g=0;const b=Object.keys(y);for(let E=0;E<b.length;E++){const T=b[E],I=y[T];d(I)||(g>0&&(p+=1),p+=u(T)+3,p+=h(I),g++)}}return a.delete(y),p};var e=l,n=c,r=d,i=f,s=h;const a=new Set;let o=0;const u=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?_=>Buffer.byteLength(_,"utf8"):_=>_.length;return{size:h(t),maxStringLen:o}}catch{return{size:Pt(t).length,maxStringLen:0}}}function Pt(t,e,n,r,i){var s;try{const a=JSON.stringify(t,L4(n),r);return Wu(a)}catch(a){if(!((s=a.message)!=null&&s.includes("Converting circular structure to JSON")))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?` Context: ${e}`:""}`),Wu("[Unserializable]");Xe("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?` Context: ${e}`:""}`),typeof i>"u"&&(i=j4()),Op(t,"",0,[],void 0,0,i);let o;try{Ms.length===0?o=JSON.stringify(t,n,r):o=JSON.stringify(t,z4(n),r)}catch{return Wu("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;xc.length!==0;){const u=xc.pop();u.length===4?Object.defineProperty(u[0],u[1],u[3]):u[0][u[1]]=u[2]}}return Wu(o)}}function Bf(t,e,n,r){var i=Object.getOwnPropertyDescriptor(r,n);i.get!==void 0?i.configurable?(Object.defineProperty(r,n,{value:t}),xc.push([r,n,e,i])):Ms.push([e,n,t]):(r[n]=t,xc.push([r,n,e]))}function Op(t,e,n,r,i,s,a){s+=1;var o;if(typeof t=="object"&&t!==null){for(o=0;o<r.length;o++)if(r[o]===t){Bf($4,t,e,i);return}if(typeof a.depthLimit<"u"&&s>a.depthLimit){Bf(p0,t,e,i);return}if(typeof a.edgesLimit<"u"&&n+1>a.edgesLimit){Bf(p0,t,e,i);return}if(r.push(t),Array.isArray(t))for(o=0;o<t.length;o++)Op(t[o],o,o,r,t,s,a);else{t=nE(t);var u=Object.keys(t);for(o=0;o<u.length;o++){var l=u[o];Op(t[l],l,o,r,t,s,a)}}r.pop()}}function z4(t){return t=typeof t<"u"?t:function(e,n){return n},function(e,n){if(Ms.length>0)for(var r=0;r<Ms.length;r++){var i=Ms[r];if(i[1]===e&&i[0]===n){n=i[2],Ms.splice(r,1);break}}return t.call(this,e,n)}}class D4{constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(this.worker!==null)return!0;if(this.startPromise!==null)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){return this.disabled=!0,!1}async serialize(e){if(!await this.ensureStarted())return null;const r=this.nextId++;return new Promise((i,s)=>{this.pending.set(r,{resolve:i,reject:s});try{this.worker.postMessage({id:r,op:"serialize",payload:e})}catch(a){this.pending.delete(r),s(a)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(const[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}}let Hf=null;function U4(){return Hf===null&&(Hf=new D4),Hf}const F4=64*1024,B4=2048;function H4(t,e=F4,n=B4){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;const r=[t],i=new Set;let s=0;for(;r.length>0;){if(s++>=n)return!1;const a=r.pop();if(a==null)continue;const o=typeof a;if(o==="string"){if(a.length>=e)return!0;continue}if(o!=="object")continue;const u=a;if(i.has(u)||(i.add(u),u instanceof Date||u instanceof RegExp||u instanceof Error||u instanceof ArrayBuffer||ArrayBuffer.isView(u)))continue;if(Array.isArray(u)){for(let c=u.length-1;c>=0;c--)r.push(u[c]);continue}if(u instanceof Map){for(const[,c]of u)r.push(c);continue}if(u instanceof Set){for(const c of u)r.push(c);continue}const l=Object.keys(u);for(let c=l.length-1;c>=0;c--)r.push(u[l[c]])}return!1}function Z4(t,e){const[n]=Ct(t);if(n!=="-"&&!e)throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}function m0(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}function ms(t){return{...t,start_time:m0(t.start_time),end_time:m0(t.end_time)}}function g0(t,e,n){if(n)return t;const r=GS(),i=e??JS(),s=t.extra??{},a=s.metadata;return t.extra={...s,runtime:{...r,...s==null?void 0:s.runtime},metadata:{...i,...i.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??i.revision_id}:{},...a}},t}const V4=t=>{const e=(t==null?void 0:t.toString())??Xe("TRACING_SAMPLING_RATE");if(e===void 0)return;const n=parseFloat(e);if(n<0||n>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${n}`);return n},K4=t=>{const n=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return n==="localhost"||n==="127.0.0.1"||n==="::1"};async function q4(t){const e=[];for await(const n of t)e.push(n);return e}function Gu(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const W4=async t=>{if((t==null?void 0:t.status)===429){const e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(n=>setTimeout(n,e)),!0}return!1};function y0(t){return typeof t=="number"?Number(t.toFixed(4)):t}const G4=24*1024*1024,rE=1024*1024*1024,J4=1e4,X4=100;class Q4{constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??rE}peek(){return this.items[0]}push(e){let n;const r=new Promise(s=>{n=s}),i=M4(e.item).size;return this.sizeBytes+i>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${i} bytes.`),n(),r):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:n,itemPromise:r,size:i}),this.sizeBytes+=i,r)}pop({upToSizeBytes:e,upToSize:n}){var s;if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let i=0;for(;i+(((s=this.peek())==null?void 0:s.size)??0)<e&&this.items.length>0&&r.length<n;){const a=this.items.shift();a&&(r.push(a),i+=a.size,this.sizeBytes-=a.size)}if(r.length===0&&this.items.length>0){const a=this.items.shift();r.push(a),i+=a.size,this.sizeBytes-=a.size}return[r.map(a=>({action:a.action,item:a.payload,otelContext:a.otelContext,apiKey:a.apiKey,apiUrl:a.apiUrl,size:a.size})),()=>r.forEach(a=>a.itemPromiseResolve())]}}class Ir{get tracingMode(){return this._tracingMode}get _fetch(){const e=this.fetchImplementation||K$(this.debug);return async(n,r)=>{var a;let i;const s=this.getProfileManagedAuthorizationHeader(r);return this.apiKey!==void 0?i={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(r,s)||(i=await((a=this.profileAuth)==null?void 0:a.getAuthHeader(e,r==null?void 0:r.signal))),e(n,this.applyCurrentAuthHeaders(r,i,s))}}getProfileManagedAuthorizationHeader(e){if(!(e!=null&&e.headers)||!this.profileAuth)return;const n=new Headers(e.headers).get("Authorization");if(jn(n))return this.profileAuth.isProfileAuthorizationHeader(n??"")?n??void 0:void 0}isProfileManagedAuthorizationHeader(e,n){var r;return e===n||((r=this.profileAuth)==null?void 0:r.isProfileAuthorizationHeader(e))===!0}hasExplicitAuthHeader(e,n){if(!(e!=null&&e.headers))return!1;const r=new Headers(e.headers);if(jn(r.get("x-api-key")))return!0;const i=r.get("Authorization");return jn(i)?!this.isProfileManagedAuthorizationHeader(i??"",n):!1}applyCurrentAuthHeaders(e,n,r){if(!n)return e;const i=d=>{if(this.apiKey!==void 0&&n.name==="x-api-key")return d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",n.value),d;if(n.name==="Authorization"){if(jn(d.get("x-api-key")))return d;const h=d.get("Authorization");return jn(h)&&!this.isProfileManagedAuthorizationHeader(h??"",r)||d.set("Authorization",n.value),d}const f=d.get("Authorization");return jn(f)&&!this.isProfileManagedAuthorizationHeader(f??"",r)||(jn(f)&&d.delete("Authorization"),d.has("x-api-key")||d.set("x-api-key",n.value)),d};if(!e)return{headers:{[n.name]:n.value}};if(e.headers instanceof Headers)return{...e,headers:i(new Headers(e.headers))};if(Array.isArray(e.headers))return{...e,headers:i(new Headers(e.headers))};const s={...e.headers??{}},a=d=>Object.keys(s).find(f=>f.toLowerCase()===d),o=d=>{const f=a(d);return f?s[f]:void 0},u=jn(o("x-api-key")),l=o("authorization"),c=jn(l)&&!this.isProfileManagedAuthorizationHeader(l??"",r);if(this.apiKey!==void 0&&n.name==="x-api-key"){const d=a("authorization");return d&&delete s[d],u||(s["x-api-key"]=n.value),{...e,headers:s}}if(n.name==="Authorization"){if(!u&&!c){const d=a("authorization");d&&d!=="Authorization"&&delete s[d],s.Authorization=n.value}return{...e,headers:s}}if(!c){const d=a("authorization");d&&delete s[d],u||(s["x-api-key"]=n.value)}return{...e,headers:s}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,n){if(this.manualFlushMode||!H4(e)||(this._serializeWorker===void 0&&(this._serializeWorker=U4()),this._serializeWorker===null))return Pt(e,n);try{const r=await this._serializeWorker.serialize(e);return r===null?(this._serializeWorker=null,Pt(e,n)):r}catch{return Pt(e,n)}}constructor(e={}){var a;Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"webUrl",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"workspaceId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchIngestCaller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout_ms",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tenantId",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"hideInputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideOutputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"openAPIClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:en("LANGSMITH_TRACING_BACKGROUND")==="false"}),Object.defineProperty(this,"traceBatchConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:5}),Object.defineProperty(this,"_serverInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_getServerInfoPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"profileAuth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Xe("DISABLE_MULTIPART_STREAMING")==="true"}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Xe("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:en("LANGSMITH_DEBUG")==="true"});const n=Ir.getDefaultClientConfig();this.tracingSampleRate=V4(e.tracingSamplingRate),this.apiUrl=Gu(e.apiUrl??n.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));const r=Gu(e.apiKey??n.apiKey);if(this.apiKey=jn(r)?r:void 0,this.profileAuth=this.apiKey!==void 0?void 0:n.profileAuth,this.webUrl=Gu(e.webUrl??n.webUrl),(a=this.webUrl)!=null&&a.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Gu(e.workspaceId??n.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Xv({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=Xe("FAILED_TRACES_DIR")||void 0;const i=Xe("FAILED_TRACES_MAX_MB");if(i){const o=parseInt(i,10);Number.isFinite(o)&&o>0&&(this.failedTracesMaxBytes=o*1024*1024)}const s=e.maxIngestMemoryBytes??rE;this.batchIngestCaller=new Xv({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:W4,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??n.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??n.hideOutputs,this.hideMetadata=e.hideMetadata??n.hideMetadata,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Q4(s),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.openAPIClient=this._newOpenAPIClient(),this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=XS(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new GR),this.cachedLSEnvVarsForMetadata=JS(),e.cache!==void 0&&e.disablePromptCache&&$l("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?($l("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=Kv:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=Kv),this._customHeaders=e.headers??{}}static getDefaultClientConfig(){const e=C4(),n=Xe("API_KEY"),r=Xe("ENDPOINT"),i=Xe("WORKSPACE_ID"),s=jn(n),a=r??e.apiUrl??Ip,o=i??e.workspaceId,u=Xe("HIDE_INPUTS")==="true",l=Xe("HIDE_OUTPUTS")==="true",c=Xe("HIDE_METADATA")==="true";return{apiUrl:a,apiKey:n,webUrl:void 0,hideInputs:u,hideOutputs:l,hideMetadata:c,workspaceId:o,oauthAccessToken:s?void 0:e.oauthAccessToken,oauthRefreshToken:s?void 0:e.oauthRefreshToken,profileAuth:s?void 0:e.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:K4(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("apac")?(this.webUrl="https://apac.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get _mergedHeaders(){var n;const e={"User-Agent":`langsmith-js/${qS}`,...this._customHeaders};if(this.apiKey!==void 0)e["x-api-key"]=`${this.apiKey}`;else{const r=(n=this.profileAuth)==null?void 0:n.currentAuthHeader();r&&(e[r.name]=r.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get headers(){return this._customHeaders}set headers(e){this._customHeaders=e??{}}_getOpenAPIBaseUrl(){return this.apiUrl.endsWith("/v1")?this.apiUrl.slice(0,-3):this.apiUrl}_newOpenAPIClient(){const e=this.apiKey===void 0&&this.workspaceId===void 0?{"X-API-Key":null}:void 0,{method:n,headers:r,body:i,signal:s,...a}=this.fetchOptions;return new me({apiKey:this.apiKey,tenantID:this.workspaceId,baseURL:this._getOpenAPIBaseUrl(),timeout:this.timeout_ms,fetch:this._fetch,fetchOptions:a,defaultHeaders:e})}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}get onlineEvaluators(){return this.openAPIClient.onlineEvaluators}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async processMetadata(e){return this.hideMetadata===!1?e:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(e):e}_filterNewTokenEvents(e){return!e||e.length===0?e:e.map(n=>{if(n.name==="new_token"){const{kwargs:r,...i}=n;return i}return n})}async prepareRunCreateOrUpdateInputs(e){const n={...e};return n.inputs!==void 0&&(n.inputs=await this.processInputs(n.inputs)),n.outputs!==void 0&&(n.outputs=await this.processOutputs(n.outputs)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events!==void 0&&(n.events=this._filterNewTokenEvents(n.events)),n}async _getResponse(e,n){const r=(n==null?void 0:n.toString())??"",i=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const a=await this._fetch(i,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(a,`fetch ${e}`),a})}async _get(e,n){return(await this._getResponse(e,n)).json()}async*_getPaginated(e,n=new URLSearchParams,r){let i=Number(n.get("offset"))||0;const s=Number(n.get("limit"))||100;for(;;){n.set("offset",String(i)),n.set("limit",String(s));const a=`${this.apiUrl}${e}?${n}`,o=await this.caller.call(async()=>{const l=await this._fetch(a,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(l,`fetch ${e}`),l}),u=r?r(await o.json()):await o.json();if(u.length===0||(yield u,u.length<s))break;i+=u.length}}async*_getCursorPaginatedList(e,n=null,r="POST",i="runs"){const s=n?{...n}:{};for(;;){const a=JSON.stringify(s),u=await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await q(c,`fetch ${e}`),c})).json();if(!u||!u[i])break;yield u[i];const l=u.cursors;if(!l||!l.next)break;s.cursor=l.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,n=!1){if(this.tracingSampleRate===void 0)return e;if(n){const r=[];for(const i of e)this.filteredPostUuids.has(i.trace_id)?i.id===i.trace_id&&this.filteredPostUuids.delete(i.trace_id):r.push(i);return r}else{const r=[];for(const i of e){const s=i.trace_id??i.id;this.filteredPostUuids.has(s)||(i.id===s?this._shouldSample()?r.push(i):this.filteredPostUuids.add(s):r.push(i))}return r}}async _getBatchSizeLimitBytes(){var n;const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??((n=e==null?void 0:e.batch_ingest_config)==null?void 0:n.size_limit_bytes)??G4}async _getBatchSizeLimit(){var n;const e=await this._ensureServerInfo();return this.batchSizeLimit??((n=e==null?void 0:e.batch_ingest_config)==null?void 0:n.size_limit)??X4}async _getDatasetExamplesMultiPartSupport(){var n;return((n=(await this._ensureServerInfo()).instance_flags)==null?void 0:n.dataset_examples_multipart_enabled)??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[i,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:n});if(!i.length){s();break}const a=i.reduce((l,c)=>{const d=c.apiUrl??this.apiUrl,f=c.apiKey??this.apiKey,m=c.apiKey===this.apiKey&&c.apiUrl===this.apiUrl?"default":`${d}|${f}`;return l[m]||(l[m]=[]),l[m].push(c),l},{}),o=[];for(const[l,c]of Object.entries(a)){const d=this._processBatch(c,{apiUrl:l==="default"?void 0:l.split("|")[0],apiKey:l==="default"?void 0:l.split("|")[1]});o.push(d)}const u=Promise.all(o).finally(s);r.push(u)}return Promise.all(r)}static async _writeTraceToFallbackDir(e,n,r,i,s){try{const a=typeof n=="string"?Buffer.from(n,"utf8"):Buffer.from(n),o=JSON.stringify({version:1,endpoint:i,headers:r,body_base64:a.toString("base64")}),u=`trace_${Date.now()}_${ja().slice(0,8)}.json`,l=ss.join(e,u);if(Ir._fallbackDirsCreated.has(e)||(await KS(e),Ir._fallbackDirsCreated.add(e)),s!==void 0&&s>0)try{const d=(await ER(e)).filter(h=>h.startsWith("trace_")&&h.endsWith(".json"));let f=0;for(const h of d){const{size:m}=await TR(ss.join(e,h));f+=m}if(f>=s){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${f} bytes >= ${s} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await Vg(l,o),console.warn(`LangSmith trace upload failed; data saved to ${l} for later replay.`)}catch(a){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,a)}}async _processBatch(e,n){var i,s;if(!e.length)return;const r=e.reduce((a,o)=>a+(o.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const a={runCreates:e.filter(l=>l.action==="create").map(l=>l.item),runUpdates:e.filter(l=>l.action==="update").map(l=>l.item)},o=await this._ensureServerInfo();if(!this._multipartDisabled&&(((i=o==null?void 0:o.batch_ingest_config)==null?void 0:i.use_multipart_endpoint)??!0)){const l=!this._runCompressionDisabled&&((s=o==null?void 0:o.instance_flags)==null?void 0:s.gzip_body_enabled);try{await this.multipartIngestRuns(a,{...n,useGzip:l,sizeBytes:r})}catch(c){if(Ff(c))this._multipartDisabled=!0,await this.batchIngestRuns(a,{...n,sizeBytes:r});else throw c}}else await this.batchIngestRuns(a,{...n,sizeBytes:r})}}catch(a){console.error("Error exporting batch:",a)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const n=new Map,r=[];for(const i of e)i.item.id&&i.otelContext&&(n.set(i.item.id,i.otelContext),i.action==="create"?r.push({operation:"post",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}):r.push({operation:"patch",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}));this.langSmithToOTELTranslator.exportBatch(r,n)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=g0(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);const n=this.autoBatchQueue.push(e);if(this.manualFlushMode)return n;const r=await this._getBatchSizeLimitBytes(),i=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>i)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:i})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:i}))},this.autoBatchAggregationDelayMs)),n}async _getServerInfo(){const n=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(J4),...this.fetchOptions});return await q(r,"get server info"),r})).json();return this.debug&&console.log(` === LangSmith Server Configuration === `+JSON.stringify(n,null,2)+` `),n}async _ensureServerInfo(){return this._getServerInfoPromise===void 0&&(this._getServerInfoPromise=(async()=>{if(this._serverInfo===void 0)try{this._serverInfo=await this._getServerInfo()}catch(e){console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status??"Unspecified status code"} ${e.message}`)}return this._serverInfo??{}})()),this._getServerInfoPromise.then(e=>(this._serverInfo===void 0&&(this._getServerInfoPromise=void 0),e))}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){const e=await this._getBatchSizeLimitBytes(),n=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:n})}_cloneCurrentOTELContext(){const e=QS(),n=ZR();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(n.active(),r)}}async createRun(e,n){if(!this._filterForSampling([e]).length)return;const r={...this._mergedHeaders,"Content-Type":"application/json"},i=e.project_name;delete e.project_name;const s=await this.prepareRunCreateOrUpdateInputs({session_name:i,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:u,apiKey:n==null?void 0:n.apiKey,apiUrl:n==null?void 0:n.apiUrl}).catch(console.error);return}const a=g0(s,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);(n==null?void 0:n.apiKey)!==void 0&&(r["x-api-key"]=n.apiKey),(n==null?void 0:n.workspaceId)!==void 0&&(r["x-tenant-id"]=n.workspaceId);const o=Pt(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{const u=await this._fetch(`${(n==null?void 0:n.apiUrl)??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await q(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;let i=await Promise.all((e==null?void 0:e.map(u=>this.prepareRunCreateOrUpdateInputs(u)))??[]),s=await Promise.all((n==null?void 0:n.map(u=>this.prepareRunCreateOrUpdateInputs(u)))??[]);if(i.length>0&&s.length>0){const u=i.reduce((c,d)=>(d.id&&(c[d.id]=d),c),{}),l=[];for(const c of s)c.id!==void 0&&u[c.id]?u[c.id]={...u[c.id],...c}:l.push(c);i=Object.values(u),s=l}const a={post:i,patch:s};if(!a.post.length&&!a.patch.length)return;const o={post:[],patch:[]};for(const u of["post","patch"]){const l=u,c=a[l].reverse();let d=c.pop();for(;d!==void 0;)o[l].push(d),d=c.pop()}if(o.post.length>0||o.patch.length>0){const u=o.post.map(l=>l.id).concat(o.patch.map(l=>l.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(o,`Ingesting runs with ids: ${u}`),r)}}async _postBatchIngestRuns(e,n){const r={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};(n==null?void 0:n.apiKey)!==void 0&&(r["x-api-key"]=n.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:n==null?void 0:n.sizeBytes},async()=>{const i=await this._fetch(`${(n==null?void 0:n.apiUrl)??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await q(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:e,runUpdates:n},r){if(e===void 0&&n===void 0)return;const i={};let s=[];for(const d of e??[]){const f=await this.prepareRunCreateOrUpdateInputs(d);f.id!==void 0&&f.attachments!==void 0&&(i[f.id]=f.attachments),delete f.attachments,s.push(f)}let a=[];for(const d of n??[])a.push(await this.prepareRunCreateOrUpdateInputs(d));if(s.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(d=>d.trace_id===void 0||d.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&a.length>0){const d=s.reduce((h,m)=>(m.id&&(h[m.id]=m),h),{}),f=[];for(const h of a)h.id!==void 0&&d[h.id]?d[h.id]={...d[h.id],...h}:f.push(h);s=Object.values(d),a=f}if(s.length===0&&a.length===0)return;const l=[],c=[];for(const[d,f]of[["post",s],["patch",a]])for(const h of f){const{inputs:m,outputs:_,events:v,extra:y,error:p,serialized:g,attachments:b,...E}=h,T={inputs:m,outputs:_,events:v,extra:y,error:p,serialized:g},I=await this._serializeBody(E,`Serializing for multipart ingestion of run with id: ${E.id}`);c.push({name:`${d}.${E.id}`,payload:new Blob([I],{type:`application/json; length=${I.length}`})});for(const[k,j]of Object.entries(T)){if(j===void 0)continue;const N=await this._serializeBody(j,`Serializing ${k} for multipart ingestion of run with id: ${E.id}`);c.push({name:`${d}.${E.id}.${k}`,payload:new Blob([N],{type:`application/json; length=${N.length}`})})}if(E.id!==void 0){const k=i[E.id];if(k){delete i[E.id];for(const[j,N]of Object.entries(k)){let L,ue;if(Array.isArray(N)?[L,ue]=N:(L=N.mimeType,ue=N.data),j.includes(".")){console.warn(`Skipping attachment '${j}' for run ${E.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}c.push({name:`attachment.${E.id}.${j}`,payload:new Blob([ue],{type:`${L}; length=${ue.byteLength}`})})}}}l.push(`trace=${E.trace_id},id=${E.id}`)}await this._sendMultipartRequest(c,l.join("; "),r)}async _createNodeFetchBody(e,n){const r=[];for(const a of e)r.push(new Blob([`--${n}\r `])),r.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r `,`Content-Type: ${a.payload.type}\r \r `])),r.push(a.payload),r.push(new Blob([`\r `]));return r.push(new Blob([`--${n}--\r `])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,n){const r=new TextEncoder;return new ReadableStream({async start(s){const a=async o=>{typeof o=="string"?s.enqueue(r.encode(o)):s.enqueue(o)};for(const o of e){await a(`--${n}\r `),await a(`Content-Disposition: form-data; name="${o.name}"\r `),await a(`Content-Type: ${o.payload.type}\r \r `);const l=o.payload.stream().getReader();try{let c;for(;!(c=await l.read()).done;)s.enqueue(c.value)}finally{l.releaseLock()}await a(`\r `)}await a(`--${n}--\r `),s.close()}})}async _sendMultipartRequest(e,n,r){const i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=()=>this._createNodeFetchBody(e,i),a=()=>this._createMultipartStream(e,i),o=async u=>this.batchIngestCaller.callWithOptions({sizeBytes:r==null?void 0:r.sizeBytes},async()=>{const l=await u(),c={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${i}`};(r==null?void 0:r.apiKey)!==void 0&&(c["x-api-key"]=r.apiKey);let d=l;r!=null&&r.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(d=l.pipeThrough(new CompressionStream("gzip")),c["Content-Encoding"]="gzip");const f=await this._fetch(`${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/multipart`,{method:"POST",headers:c,body:d,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(f,"Failed to send multipart request",!0),f});try{let u,l=!1;V$()&&!this.multipartStreamingDisabled&&qg()!=="bun"?(l=!0,u=await o(a)):u=await o(s),(!this.multipartStreamingDisabled||l)&&u.status===422&&((r==null?void 0:r.apiUrl)??this.apiUrl)!==Ip&&(console.warn(`Streaming multipart upload to ${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${n}".`),this.multipartStreamingDisabled=!0,u=await o(s))}catch(u){if(Ff(u))throw u;if(console.warn(`${u.message.trim()} Context: ${n}`),this.failedTracesDir){const l=await this._createNodeFetchBody(e,i).catch(()=>null);l&&await Ir._writeTraceToFallbackDir(this.failedTracesDir,l,{"Content-Type":`multipart/form-data; boundary=${i}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,n,r){ae(e),n.inputs&&(n.inputs=await this.processInputs(n.inputs)),n.outputs&&(n.outputs=await this.processOutputs(n.outputs)),n.extra!=null&&"metadata"in n.extra&&(n.extra={...n.extra,metadata:await this.processMetadata(n.extra.metadata)}),n.events&&(n.events=this._filterNewTokenEvents(n.events));const i={...n,id:e};if(!this._filterForSampling([i],!0).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(n.end_time!==void 0&&i.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:i,otelContext:o,apiKey:r==null?void 0:r.apiKey,apiUrl:r==null?void 0:r.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:o,apiKey:r==null?void 0:r.apiKey,apiUrl:r==null?void 0:r.apiUrl}).catch(console.error);return}const s={...this._mergedHeaders,"Content-Type":"application/json"};(r==null?void 0:r.apiKey)!==void 0&&(s["x-api-key"]=r.apiKey),(r==null?void 0:r.workspaceId)!==void 0&&(s["x-tenant-id"]=r.workspaceId);const a=Pt(n,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${(r==null?void 0:r.apiUrl)??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await q(o,"update run",!0),o})}async readRun(e,{loadChildRuns:n}={loadChildRuns:!1}){ae(e);let r=ms(await this._get(`/runs/${e}`));return n&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:n,projectOpts:r}){if(n!==void 0){let i;n.session_id?i=n.session_id:r!=null&&r.projectName?i=(await this.readProject({projectName:r==null?void 0:r.projectName})).id:r!=null&&r.projectId?i=r==null?void 0:r.projectId:i=(await this.readProject({projectName:Xe("PROJECT")||"default"})).id;const s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${i}/r/${n.id}?poll=true`}else if(e!==void 0){const i=await this.readRun(e);if(!i.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){var s;const n=await q4(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},i={};n.sort((a,o)=>((a==null?void 0:a.dotted_order)??"").localeCompare((o==null?void 0:o.dotted_order)??""));for(const a of n){if(a.parent_run_id===null||a.parent_run_id===void 0)throw new Error(`Child run ${a.id} has no parent`);(s=a.dotted_order)!=null&&s.startsWith(e.dotted_order??"")&&a.id!==e.id&&(a.parent_run_id in r||(r[a.parent_run_id]=[]),r[a.parent_run_id].push(a),i[a.id]=a)}e.child_runs=r[e.id]||[];for(const a in r)a!==e.id&&(i[a].child_runs=r[a]);return e}async*listRuns(e){const{projectId:n,projectName:r,parentRunId:i,traceId:s,referenceExampleId:a,startTime:o,executionOrder:u,isRoot:l,runType:c,error:d,id:f,query:h,filter:m,traceFilter:_,treeFilter:v,limit:y,select:p,order:g}=e;let b=[];if(n&&(b=Array.isArray(n)?n:[n]),r){const k=Array.isArray(r)?r:[r],j=await Promise.all(k.map(N=>this.readProject({projectName:N}).then(L=>L.id)));b.push(...j)}const E=["app_path","completion_cost","completion_tokens","dotted_order","end_time","error","events","extra","feedback_stats","first_token_time","id","inputs","name","outputs","parent_run_id","parent_run_ids","prompt_cost","prompt_tokens","reference_example_id","run_type","session_id","start_time","status","tags","total_cost","total_tokens","trace_id"],T={session:b.length?b:null,run_type:c,reference_example:a,query:h,filter:m,trace_filter:_,tree_filter:v,execution_order:u,parent_run:i,start_time:o?o.toISOString():null,error:d,id:f,limit:y,trace:s,select:p||E,is_root:l,order:g};T.select.includes("child_run_ids")&&$l("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let I=0;for await(const k of this._getCursorPaginatedList("/runs/query",T)){const j=k.map(ms);if(y){if(I>=y)break;if(j.length+I>y){yield*j.slice(0,y-I);break}I+=j.length,yield*j}else yield*j}}async*listGroupRuns(e){const{projectId:n,projectName:r,groupBy:i,filter:s,startTime:a,endTime:o,limit:u,offset:l}=e,d={session_id:n||(await this.readProject({projectName:r})).id,group_by:i,filter:s,start_time:a?a.toISOString():null,end_time:o?o.toISOString():null,limit:Number(u)||100};let f=Number(l)||0;const h="/runs/group",m=`${this.apiUrl}${h}`;for(;;){const _={...d,offset:f},v=Object.fromEntries(Object.entries(_).filter(([T,I])=>I!==void 0)),y=JSON.stringify(v),g=await(await this.caller.call(async()=>{const T=await this._fetch(m,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await q(T,`Failed to fetch ${h}`),T})).json(),{groups:b,total:E}=g;if(b.length===0)break;for(const T of b)yield T;if(f+=b.length,f>=E)break}}async*readThread(e){const{threadId:n,projectId:r,projectName:i,isRoot:s=!0,limit:a,filter:o,order:u="asc"}=e;if(!r&&!i)throw new Error("threadId requires projectId or projectName");const l=`eq(thread_id, ${JSON.stringify(n)})`,c=o?`and(${l}, ${o})`:l;yield*this.listRuns({projectId:r??void 0,projectName:i??void 0,isRoot:s,limit:a,filter:c,order:u})}async listThreads(e){const{projectId:n,projectName:r,limit:i,offset:s=0,filter:a,startTime:o,isRoot:u=!0}=e;if(!n&&!r)throw new Error("Either projectId or projectName must be provided");if(n&&r)throw new Error("Provide exactly one of projectId or projectName");const l=n??(await this.readProject({projectName:r})).id,c=o??new Date(Date.now()-1*24*60*60*1e3),f={session:[l],is_root:u,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:c.toISOString()};a!=null&&(f.filter=a);const h=new Map;for await(const y of this._getCursorPaginatedList("/runs/query",f))for(const p of y){const g=ms(p),b=g.thread_id;if(b){const E=h.get(b)??[];E.push(g),h.set(b,E)}}const m=[];for(const[y,p]of h.entries()){p.sort((I,k)=>{const j=I,N=k,L=j.start_time??"",ue=N.start_time??"";if(L!==ue)return L.localeCompare(ue);const Ee=j.dotted_order??"",Et=N.dotted_order??"";return Ee.localeCompare(Et)});const b=[...p.map(I=>I.start_time).filter(Boolean)].sort(),E=b.length?b[0]:"",T=b.length?b[b.length-1]:"";m.push({thread_id:y,runs:p,count:p.length,filter:"",total_tokens:0,total_cost:null,min_start_time:E,max_start_time:T,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}m.sort((y,p)=>{const g=y.max_start_time??"";return(p.max_start_time??"").localeCompare(g)});const _=s>0?m.slice(s):m;return i!==void 0?_.slice(0,i):_}async getRunStats({id:e,trace:n,parentRun:r,runType:i,projectNames:s,projectIds:a,referenceExampleIds:o,startTime:u,endTime:l,error:c,query:d,filter:f,traceFilter:h,treeFilter:m,isRoot:_,dataSourceType:v}){let y=a||[];s&&(y=[...a||[],...await Promise.all(s.map(I=>this.readProject({projectName:I}).then(k=>k.id)))]);const g=Object.fromEntries(Object.entries({id:e,trace:n,parent_run:r,run_type:i,session:y,reference_example:o,start_time:u,end_time:l,error:c,query:d,filter:f,trace_filter:h,tree_filter:m,is_root:_,data_source_type:v}).filter(([I,k])=>k!==void 0)),b=JSON.stringify(g);return await(await this.caller.call(async()=>{const I=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:b});return await q(I,"get run stats"),I})).json()}async shareRun(e,{shareId:n}={}){const r={run_id:e,share_token:n||ja()};ae(e);const i=JSON.stringify(r),a=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await q(o,"share run"),o})).json();if(a===null||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){ae(e),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(n,"unshare run",!0),n})}async readRunSharedLink(e){ae(e);const r=await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(i,"read run shared link"),i})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:n}={}){const r=new URLSearchParams({share_token:e});if(n!==void 0)for(const a of n)r.append("id",a);return ae(e),(await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(a,"list shared runs"),a})).json()).map(ms)}async readDatasetSharedSchema(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id),ae(e);const i=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(s,"read dataset shared schema"),s})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(e,n){if(!e&&!n)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:n})).id);const r={dataset_id:e};ae(e);const i=JSON.stringify(r),a=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await q(o,"share dataset"),o})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(e){ae(e),await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(n,"unshare dataset",!0),n})}async readSharedDataset(e){return ae(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(i,"read shared dataset"),i})).json()}async listSharedExamples(e,n){const r={};n!=null&&n.exampleIds&&(r.id=n.exampleIds);const i=new URLSearchParams;Object.entries(r).forEach(([o,u])=>{Array.isArray(u)?u.forEach(l=>i.append(o,l)):i.append(o,u)});const s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${i.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(o,"list shared examples"),o}),a=await s.json();if(!s.ok)throw"detail"in a?new Error(`Failed to list shared examples. Status: ${s.status} Message: ${Array.isArray(a.detail)?a.detail.join(` `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return a.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:n=null,metadata:r=null,upsert:i=!1,projectExtra:s=null,referenceDatasetId:a=null,numExamples:o=null,numRepetitions:u=null,evaluatorKeys:l=null}){const c=i?"?upsert=true":"",d=`${this.apiUrl}/sessions${c}`,f=s||{};r&&(f.metadata=r);const h={name:e,extra:f,description:n};a!==null&&(h.reference_dataset_id=a),o!=null&&(h.num_examples=o),u!=null&&(h.num_repetitions=u),l!=null&&l.length>0&&(h.evaluator_keys=l);const m=JSON.stringify(h);return await(await this.caller.call(async()=>{const y=await this._fetch(d,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:m});return await q(y,"create project"),y})).json()}async updateProject(e,{name:n=null,description:r=null,metadata:i=null,projectExtra:s=null,endTime:a=null}){const o=`${this.apiUrl}/sessions/${e}`;let u=s;i&&(u={...u||{},metadata:i});const l=JSON.stringify({name:n,extra:u,description:r,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{const f=await this._fetch(o,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await q(f,"update project"),f})).json()}async hasProject({projectId:e,projectName:n}){let r="/sessions";const i=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)ae(e),r+=`/${e}`;else if(n!==void 0)i.append("name",n);else throw new Error("Must provide projectName or projectId");const s=await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}?${i}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(a,"has project"),a});try{const a=await s.json();return s.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:n,includeStats:r}){let i="/sessions";const s=new URLSearchParams;if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)ae(e),i+=`/${e}`;else if(n!==void 0)s.append("name",n);else throw new Error("Must provide projectName or projectId");r!==void 0&&s.append("include_stats",r.toString());const a=await this._get(i,s);let o;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${n}] not found`);o=a[0]}else o=a;return o}async getProjectUrl({projectId:e,projectName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:n}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:n}){if(e===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:n}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const n of this._getPaginated("/sessions",e))return this._tenantId=n[0].tenant_id,n[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:n,nameContains:r,referenceDatasetId:i,referenceDatasetName:s,includeStats:a,datasetVersion:o,referenceFree:u,metadata:l}={}){const c=new URLSearchParams;if(e!==void 0)for(const d of e)c.append("id",d);if(n!==void 0&&c.append("name",n),r!==void 0&&c.append("name_contains",r),i!==void 0)c.append("reference_dataset",i);else if(s!==void 0){const d=await this.readDataset({datasetName:s});c.append("reference_dataset",d.id)}a!==void 0&&c.append("include_stats",a.toString()),o!==void 0&&c.append("dataset_version",o),u!==void 0&&c.append("reference_free",u.toString()),l!==void 0&&c.append("metadata",JSON.stringify(l));for await(const d of this._getPaginated("/sessions",c))yield*d}async deleteProject({projectId:e,projectName:n}){let r;if(e===void 0&&n===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&n!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:n})).id:r=e,ae(r),await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(i,`delete session ${r} (${n})`,!0),i})}async uploadCsv({csvFile:e,fileName:n,inputKeys:r,outputKeys:i,description:s,dataType:a,name:o}){const u=`${this.apiUrl}/datasets/upload`,l=new FormData,c=new Blob([e],{type:"text/csv"});return l.append("file",c,n),r.forEach(h=>{l.append("input_keys",h)}),i.forEach(h=>{l.append("output_keys",h)}),s&&l.append("description",s),a&&l.append("data_type",a),o&&l.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(u,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await q(h,"upload CSV"),h})).json()}async createDataset(e,{description:n,dataType:r,inputsSchema:i,outputsSchema:s,metadata:a}={}){const o={name:e,description:n,extra:{source:"sdk",...a?{metadata:a}:{}}};r&&(o.data_type=r),i&&(o.inputs_schema_definition=i),s&&(o.outputs_schema_definition=s);const u=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await q(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:n}){let r="/datasets";const i=new URLSearchParams({limit:"1"});if(e&&n)throw new Error("Must provide either datasetName or datasetId, not both");if(e)ae(e),r+=`/${e}`;else if(n)i.append("name",n);else throw new Error("Must provide datasetName or datasetId");const s=await this._get(r,i);let a;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${n}] not found`);a=s[0]}else a=s;return a}async hasDataset({datasetId:e,datasetName:n}){try{return await this.readDataset({datasetId:e,datasetName:n}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:n,fromVersion:r,toVersion:i}){let s=e;if(s===void 0&&n===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:n})).id);const a=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof i=="string"?i:i.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:n}){const r="/datasets";if(e===void 0)if(n!==void 0)e=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(` `).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:n=0,datasetIds:r,datasetName:i,datasetNameContains:s,metadata:a}={}){const o="/datasets",u=new URLSearchParams({limit:e.toString(),offset:n.toString()});if(r!==void 0)for(const l of r)u.append("id",l);i!==void 0&&u.append("name",i),s!==void 0&&u.append("name_contains",s),a!==void 0&&u.append("metadata",JSON.stringify(a));for await(const l of this._getPaginated(o,u))yield*l}async updateDataset(e){const{datasetId:n,datasetName:r,...i}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const s=n??(await this.readDataset({datasetName:r})).id;ae(s);const a=JSON.stringify(i);return await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await q(u,"update dataset"),u})).json()}async updateDatasetTag(e){const{datasetId:n,datasetName:r,asOf:i,tag:s}=e;if(!n&&!r)throw new Error("Must provide either datasetName or datasetId");const a=n??(await this.readDataset({datasetName:r})).id;ae(a);const o=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:s});await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await q(u,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:n}){let r="/datasets",i=e;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(n!==void 0&&(i=(await this.readDataset({datasetName:n})).id),i!==void 0)ae(i),r+=`/${i}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const s=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(s,`delete ${r}`,!0),s})}async createExample(e,n,r){var c;if(_0(e)&&(n!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=n?r==null?void 0:r.datasetId:e.dataset_id;const s=n?r==null?void 0:r.datasetName:e.dataset_name;if(i===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:s})).id);const a=(n?r==null?void 0:r.createdAt:e.created_at)||new Date;let o;_0(e)?o=e:o={inputs:e,outputs:n,created_at:a==null?void 0:a.toISOString(),id:r==null?void 0:r.exampleId,metadata:r==null?void 0:r.metadata,split:r==null?void 0:r.split,source_run_id:r==null?void 0:r.sourceRunId,use_source_run_io:r==null?void 0:r.useSourceRunIO,use_source_run_attachments:r==null?void 0:r.useSourceRunAttachments,attachments:r==null?void 0:r.attachments};const u=await this._uploadExamplesMultipart(i,[o]);return await this.readExample(((c=u.example_ids)==null?void 0:c[0])??ja())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const p=e;let g=p[0].dataset_id;const b=p[0].dataset_name;if(g===void 0&&b===void 0)throw new Error("Must provide either datasetName or datasetId");if(g!==void 0&&b!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");g===void 0&&(g=(await this.readDataset({datasetName:b})).id);const E=await this._uploadExamplesMultipart(g,p);return await Promise.all(E.example_ids.map(I=>this.readExample(I)))}const{inputs:n,outputs:r,metadata:i,splits:s,sourceRunIds:a,useSourceRunIOs:o,useSourceRunAttachments:u,attachments:l,exampleIds:c,datasetId:d,datasetName:f}=e;if(n===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=d;const m=f;if(h===void 0&&m===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&m!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:m})).id);const _=n.map((p,g)=>({dataset_id:h,inputs:p,outputs:r==null?void 0:r[g],metadata:i==null?void 0:i[g],split:s==null?void 0:s[g],id:c==null?void 0:c[g],attachments:l==null?void 0:l[g],source_run_id:a==null?void 0:a[g],use_source_run_io:o==null?void 0:o[g],use_source_run_attachments:u==null?void 0:u[g]})),v=await this._uploadExamplesMultipart(h,_);return await Promise.all(v.example_ids.map(p=>this.readExample(p)))}async createLLMExample(e,n,r){return this.createExample({input:e},{output:n},r)}async createChatExample(e,n,r){const i=e.map(a=>Qv(a)?Yv(a):a),s=Qv(n)?Yv(n):n;return this.createExample({input:i},{output:s},r)}async readExample(e){ae(e);const n=`/examples/${e}`,r=await this._get(n),{attachment_urls:i,...s}=r,a=s;return i&&(a.attachments=Object.entries(i).reduce((o,[u,l])=>(o[u.slice(11)]={presigned_url:l.presigned_url,mime_type:l.mime_type},o),{})),a}async*listExamples({datasetId:e,datasetName:n,exampleIds:r,asOf:i,splits:s,inlineS3Urls:a,metadata:o,limit:u,offset:l,filter:c,includeAttachments:d}={}){let f;if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)f=e;else if(n!==void 0)f=(await this.readDataset({datasetName:n})).id;else throw new Error("Must provide a datasetName or datasetId");const h=new URLSearchParams({dataset:f}),m=i?typeof i=="string"?i:i==null?void 0:i.toISOString():void 0;m&&h.append("as_of",m);const _=a??!0;if(h.append("inline_s3_urls",_.toString()),r!==void 0)for(const y of r)h.append("id",y);if(s!==void 0)for(const y of s)h.append("splits",y);if(o!==void 0){const y=JSON.stringify(o);h.append("metadata",y)}u!==void 0&&h.append("limit",u.toString()),l!==void 0&&h.append("offset",l.toString()),c!==void 0&&h.append("filter",c),d===!0&&["attachment_urls","outputs","metadata"].forEach(y=>h.append("select",y));let v=0;for await(const y of this._getPaginated("/examples",h)){for(const p of y){const{attachment_urls:g,...b}=p,E=b;g&&(E.attachments=Object.entries(g).reduce((T,[I,k])=>(T[I.slice(11)]={presigned_url:k.presigned_url,mime_type:k.mime_type||void 0},T),{})),yield E,v++}if(u!==void 0&&v>=u)break}}async deleteExample(e){ae(e);const n=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(r,`delete ${n}`,!0),r})}async deleteExamples(e,n){if(e.forEach(r=>ae(r)),n!=null&&n.hardDelete){const r=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(i,"hard delete examples",!0),i})}else{const r=new URLSearchParams;e.forEach(i=>r.append("example_ids",i)),await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/examples?${r.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(i,"delete examples",!0),i})}}async updateExample(e,n){let r;n?r=e:r=e.id,ae(r);let i;n?i={id:r,...n}:i=e;let s;return i.dataset_id!==void 0?s=i.dataset_id:s=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(s,[i])}async updateExamples(e){let n;return e[0].dataset_id===void 0?n=(await this.readExample(e[0].id)).dataset_id:n=e[0].dataset_id,this._updateExamplesMultipart(n,e)}async readDatasetVersion({datasetId:e,datasetName:n,asOf:r,tag:i}){let s;if(e?s=e:s=(await this.readDataset({datasetName:n})).id,ae(s),r&&i||!r&&!i)throw new Error("Exactly one of asOf and tag must be specified.");const a=new URLSearchParams;return r!==void 0&&a.append("as_of",typeof r=="string"?r:r.toISOString()),i!==void 0&&a.append("tag",i),await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${a.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(u,"read dataset version"),u})).json()}async listDatasetSplits({datasetId:e,datasetName:n,asOf:r}){let i;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:n})).id:i=e,ae(i);const s=new URLSearchParams,a=r?typeof r=="string"?r:r==null?void 0:r.toISOString():void 0;return a&&s.append("as_of",a),await this._get(`/datasets/${i}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:n,splitName:r,exampleIds:i,remove:s=!1}){let a;if(e===void 0&&n===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&n!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:n})).id:a=e,ae(a);const o={split_name:r,examples:i.map(l=>(ae(l),l)),remove:s},u=JSON.stringify(o);await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await q(l,"update dataset splits",!0),l})}async createFeedback(e,n,{score:r,value:i,correction:s,comment:a,sourceInfo:o,feedbackSourceType:u="api",sourceRunId:l,feedbackId:c,feedbackConfig:d,projectId:f,comparativeExperimentId:h,sessionId:m,startTime:_}){var b;if(!e&&!f)throw new Error("One of runId or projectId must be provided");if(e&&f)throw new Error("Only one of runId or projectId can be provided");const v={type:u??"api",metadata:o??{}};l!==void 0&&(v==null?void 0:v.metadata)!==void 0&&!v.metadata.__run&&(v.metadata.__run={run_id:l}),(v==null?void 0:v.metadata)!==void 0&&((b=v.metadata.__run)==null?void 0:b.run_id)!==void 0&&ae(v.metadata.__run.run_id);const y={id:c??LS(),run_id:e,key:n,score:y0(r),value:i,correction:s,comment:a,feedback_source:v,comparative_experiment_id:h,feedbackConfig:d,session_id:m??f,start_time:_},p=JSON.stringify(y),g=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const E=await this._fetch(g,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:p});return await q(E,"create feedback",!0),E}),y}async updateFeedback(e,{score:n,value:r,correction:i,comment:s}){const a={};n!=null&&(a.score=y0(n)),r!=null&&(a.value=r),i!=null&&(a.correction=i),s!=null&&(a.comment=s),ae(e);const o=JSON.stringify(a);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await q(u,"update feedback",!0),u})}async readFeedback(e){ae(e);const n=`/feedback/${e}`;return await this._get(n)}async deleteFeedback(e){ae(e);const n=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(r,`delete ${n}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:n,feedbackSourceTypes:r}={}){const i=new URLSearchParams;if(e)for(const s of e)ae(s),i.append("run",s);if(n)for(const s of n)i.append("key",s);if(r)for(const s of r)i.append("source",s);for await(const s of this._getPaginated("/feedback",i))yield*s}async createPresignedFeedbackToken(e,n,{expiration:r,feedbackConfig:i}={}){const s={run_id:e,feedback_key:n,feedback_config:i};r?typeof r=="string"?s.expires_at=r:(r!=null&&r.hours||r!=null&&r.minutes||r!=null&&r.days)&&(s.expires_in=r):s.expires_in={hours:3};const a=JSON.stringify(s);return await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await q(u,"create presigned feedback token"),u})).json()}async createComparativeExperiment({name:e,experimentIds:n,referenceDatasetId:r,createdAt:i,description:s,metadata:a,id:o}){var d;if(n.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:n[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const u={id:o,name:e,experiment_ids:n,reference_dataset_id:r,description:s,created_at:(d=i??new Date)==null?void 0:d.toISOString(),extra:{}};a&&(u.extra.metadata=a);const l=JSON.stringify(u);return(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await q(f,"create comparative experiment"),f})).json()}async*listPresignedFeedbackTokens(e){ae(e);const n=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",n))yield*r}_selectEvalResults(e){let n;return"results"in e?n=e.results:Array.isArray(e)?n=e:n=[e],n}async _logEvaluationFeedback(e,n,r){const i=this._selectEvalResults(e),s=[];for(const a of i){let o=r||{};a.evaluatorInfo&&(o={...a.evaluatorInfo,...o});let u=null;a.targetRunId?u=a.targetRunId:n&&(u=n.id),s.push(await this.createFeedback(u,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:o,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model",sessionId:n==null?void 0:n.session_id,startTime:n==null?void 0:n.start_time}))}return[i,s]}async logEvaluationFeedback(e,n,r){const[i]=await this._logEvaluationFeedback(e,n,r);return i}async createFeedbackConfig(e){const{feedbackKey:n,feedbackConfig:r,isLowerScoreBetter:i=!1}=e,s={feedback_key:n,feedback_config:r,is_lower_score_better:i};return(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await q(o,"create feedback config"),o})).json()}async*listFeedbackConfigs(e={}){const{feedbackKeys:n,nameContains:r,limit:i}=e,s=new URLSearchParams;n&&n.forEach(o=>{s.append("key",o)}),r&&s.append("name_contains",r),s.append("limit",(i!==void 0?Math.min(i,100):100).toString());let a=0;for await(const o of this._getPaginated("/feedback-configs",s))if(yield*o,a+=o.length,i!==void 0&&a>=i)break}async updateFeedbackConfig(e,n={}){const{feedbackConfig:r,isLowerScoreBetter:i}=n,s={feedback_key:e};return r!==void 0&&(s.feedback_config=r),i!==void 0&&(s.is_lower_score_better=i),(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await q(o,"update feedback config"),o})).json()}async deleteFeedbackConfig(e){const n=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/feedback-configs?${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(r,"delete feedback config",!0),r})}async*listAnnotationQueues(e={}){const{queueIds:n,name:r,nameContains:i,limit:s}=e,a=new URLSearchParams;n&&n.forEach((u,l)=>{ae(u,`queueIds[${l}]`),a.append("ids",u)}),r&&a.append("name",r),i&&a.append("name_contains",i),a.append("limit",(s!==void 0?Math.min(s,100):100).toString());let o=0;for await(const u of this._getPaginated("/annotation-queues",a))if(yield*u,o++,s!==void 0&&o>=s)break}async createAnnotationQueue(e){const{name:n,description:r,queueId:i,rubricInstructions:s,rubricItems:a}=e,o={name:n,description:r,id:i||ja(),rubric_instructions:s,rubric_items:a},u=JSON.stringify(Object.fromEntries(Object.entries(o).filter(([c,d])=>d!==void 0)));return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await q(c,"create annotation queue"),c})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${ae(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,n){const{name:r,description:i,rubricInstructions:s,rubricItems:a}=n,o={};r!==void 0&&(o.name=r),i!==void 0&&(o.description=i),s!==void 0&&(o.rubric_instructions=s),a!==void 0&&(o.rubric_items=a);const u=JSON.stringify(o);await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}/annotation-queues/${ae(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await q(l,"update annotation queue",!0),l})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const n=await this._fetch(`${this.apiUrl}/annotation-queues/${ae(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(n,"delete annotation queue",!0),n})}async addRunsToAnnotationQueue(e,n){const r=JSON.stringify(n.map((i,s)=>ae(i,`runIds[${s}]`).toString()));await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/annotation-queues/${ae(e,"queueId")}/runs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await q(i,"add runs to annotation queue",!0),i})}async getRunFromAnnotationQueue(e,n){const r=`/annotation-queues/${ae(e,"queueId")}/run`,s=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(a,"get run from annotation queue"),a})).json();return ms(s)}async*listRunsFromAnnotationQueue(e,n={}){const{status:r,limit:i}=n,s=new URLSearchParams,a=i!==void 0&&Number.isFinite(i)?Math.min(i,100):100;r&&s.append("status",r),s.append("limit",a.toString());let o=0;const u=`/annotation-queues/${ae(e,"queueId")}/runs`;for await(const l of this._getPaginated(u,s))for(const c of l)if(yield ms(c),o++,o>=a)return}async deleteRunFromAnnotationQueue(e,n){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${ae(e,"queueId")}/runs/${ae(n,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(r,"delete run from annotation queue",!0),r})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${ae(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const n=await this._getSettings();return e=="-"||n.tenant_handle===e}async _ownerConflictError(e,n){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant. Current tenant: ${r.tenant_handle} Requested tenant: ${n}`)}async _getLatestCommitHash(e){const r=await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(i,"get latest commit hash"),i})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _createCommitTags(e,n,r){const i=typeof r=="string"?[r]:r;await Promise.all(i.map(async s=>this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/repos/${e}/tags`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify({tag_name:s,commit_id:n})});return await q(a,"create commit tag"),a})))}async _likeOrUnlikePrompt(e,n){const[r,i,s]=Ct(e),a=JSON.stringify({like:n});return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/likes/${r}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await q(u,`${n?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){const[n,r,i]=Ct(e);if(await this._currentTenantIsOwner(n)){const s=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${r}/${i.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${s.id}`}else return i!=="latest"?`${this.getHostUrl()}/hub/${n}/${r}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${n}/${r}`}async promptExists(e){return!!await this.getPrompt(e)}async likePrompt(e){return this._likeOrUnlikePrompt(e,!0)}async unlikePrompt(e){return this._likeOrUnlikePrompt(e,!1)}async*listCommits(e){const[n,r,i]=Ct(e);for await(const s of this._getPaginated(`/commits/${n}/${r}/`,new URLSearchParams,a=>a.commits))yield*s}async*listPrompts(e){const n=new URLSearchParams;n.append("sort_field",(e==null?void 0:e.sortField)??"updated_at"),n.append("sort_direction","desc"),n.append("is_archived",(!!(e!=null&&e.isArchived)).toString()),(e==null?void 0:e.isPublic)!==void 0&&n.append("is_public",e.isPublic.toString()),e!=null&&e.query&&n.append("query",e.query);for await(const r of this._getPaginated("/repos",n,i=>i.repos))yield*r}async getPrompt(e){const[n,r,i]=Ct(e),s=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return(o==null?void 0:o.status)===404?null:(await q(o,"get prompt"),o)}),a=await(s==null?void 0:s.json());return a!=null&&a.repo?a.repo:null}async createPrompt(e,n){const r=await this._getSettings();if(n!=null&&n.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first creating a LangChain Hub handle. You can add a handle by creating a public prompt at: https://smith.langchain.com/prompts`);const[i,s,a]=Ct(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);const o={repo_handle:s,...(n==null?void 0:n.description)&&{description:n.description},...(n==null?void 0:n.readme)&&{readme:n.readme},...(n==null?void 0:n.tags)&&{tags:n.tags},is_public:!!(n!=null&&n.isPublic)},u=JSON.stringify(o),l=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await q(d,"create prompt"),d}),{repo:c}=await l.json();return c}async createCommit(e,n,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[i,s,a]=Ct(e),o=(r==null?void 0:r.parentCommitHash)==="latest"||!(r!=null&&r.parentCommitHash)?await this._getLatestCommitHash(`${i}/${s}`):r==null?void 0:r.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(n)),parent_commit:o,...(r==null?void 0:r.description)!==void 0&&{description:r.description}},l=JSON.stringify(u),d=await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/commits/${i}/${s}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await q(h,"create commit"),h})).json(),f=d.commit??d;return r!=null&&r.tags&&await this._createCommitTags(`${i}/${s}`,f.id,r.tags),this._getPromptUrl(`${i}/${s}${f.commit_hash?`:${f.commit_hash}`:""}`)}async updateExamplesMultipart(e,n=[]){return this._updateExamplesMultipart(e,n)}async _updateExamplesMultipart(e,n=[]){var a;if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const o of n){const u=o.id,l={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},c=Pt(l,`Serializing body for example with id: ${u}`),d=new Blob([c],{type:"application/json"});if(r.append(u,d),o.inputs){const f=Pt(o.inputs,`Serializing inputs for example with id: ${u}`),h=new Blob([f],{type:"application/json"});r.append(`${u}.inputs`,h)}if(o.outputs){const f=Pt(o.outputs,`Serializing outputs whle updating example with id: ${u}`),h=new Blob([f],{type:"application/json"});r.append(`${u}.outputs`,h)}if(o.attachments)for(const[f,h]of Object.entries(o.attachments)){let m,_;Array.isArray(h)?[m,_]=h:(m=h.mimeType,_=h.data);const v=new Blob([_],{type:`${m}; length=${_.byteLength}`});r.append(`${u}.attachment.${f}`,v)}if(o.attachments_operations){const f=Pt(o.attachments_operations,`Serializing attachments while updating example with id: ${u}`),h=new Blob([f],{type:"application/json"});r.append(`${u}.attachments_operations`,h)}}const i=e??((a=n[0])==null?void 0:a.dataset_id);return(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${i}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await q(o,"update examples"),o})).json()}async uploadExamplesMultipart(e,n=[]){return this._uploadExamplesMultipart(e,n)}async _uploadExamplesMultipart(e,n=[]){if(!await this._getDatasetExamplesMultiPartSupport())throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version.");const r=new FormData;for(const s of n){const a=(s.id??ja()).toString(),o={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},u=Pt(o,`Serializing body for uploaded example with id: ${a}`),l=new Blob([u],{type:"application/json"});if(r.append(a,l),s.inputs){const c=Pt(s.inputs,`Serializing inputs for uploaded example with id: ${a}`),d=new Blob([c],{type:"application/json"});r.append(`${a}.inputs`,d)}if(s.outputs){const c=Pt(s.outputs,`Serializing outputs for uploaded example with id: ${a}`),d=new Blob([c],{type:"application/json"});r.append(`${a}.outputs`,d)}if(s.attachments)for(const[c,d]of Object.entries(s.attachments)){let f,h;Array.isArray(d)?[f,h]=d:(f=d.mimeType,h=d.data);const m=new Blob([h],{type:`${f}; length=${h.byteLength}`});r.append(`${a}.attachment.${c}`,m)}}return(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await q(s,"upload examples"),s})).json()}async updatePrompt(e,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,i]=Ct(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const s={};if((n==null?void 0:n.description)!==void 0&&(s.description=n.description),(n==null?void 0:n.readme)!==void 0&&(s.readme=n.readme),(n==null?void 0:n.tags)!==void 0&&(s.tags=n.tags),(n==null?void 0:n.isPublic)!==void 0&&(s.is_public=n.isPublic),(n==null?void 0:n.isArchived)!==void 0&&(s.is_archived=n.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");const a=JSON.stringify(s);return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/repos/${r}/${i}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await q(u,"update prompt"),u})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[n,r,i]=Ct(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete a prompt",n);return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/repos/${n}/${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(a,"delete prompt"),a})).json()}_getPromptCacheKey(e,n){return`${e}${n?":with_model":""}`}async _fetchPromptFromApi(e,n){const[r,i,s]=Ct(e),o=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/commits/${r}/${i}/${s}${n!=null&&n.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(u,"pull prompt commit"),u})).json();return{owner:r,repo:i,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples,hub_model_config:o.model_config,hub_model_provider:o.model_provider}}async pullPromptCommit(e,n){Z4(e,n==null?void 0:n.dangerouslyPullPublicPrompt);const r=this._fetchPromptFromApi.bind(this,e,n);if(!(n!=null&&n.skipCache)&&this._promptCache){const i=this._getPromptCacheKey(e,n==null?void 0:n.includeModel),s=this._promptCache.get(i,r);if(s)return s;const a=await r();return this._promptCache.set(i,a,r),a}return this._fetchPromptFromApi(e,n)}async _pullPrompt(e,n){const r=await this.pullPromptCommit(e,{includeModel:n==null?void 0:n.includeModel,skipCache:n==null?void 0:n.skipCache,dangerouslyPullPublicPrompt:n==null?void 0:n.dangerouslyPullPublicPrompt});return JSON.stringify(r.manifest)}async pushPrompt(e,n){return await this.promptExists(e)?n&&["description","readme","tags","isPublic"].some(i=>n[i]!==void 0)&&await this.updatePrompt(e,{description:n==null?void 0:n.description,readme:n==null?void 0:n.readme,tags:n==null?void 0:n.tags,isPublic:n==null?void 0:n.isPublic}):await this.createPrompt(e,{description:n==null?void 0:n.description,readme:n==null?void 0:n.readme,tags:n==null?void 0:n.tags,isPublic:n==null?void 0:n.isPublic}),n!=null&&n.object?await this.createCommit(e,n==null?void 0:n.object,{parentCommitHash:n==null?void 0:n.parentCommitHash,tags:n==null?void 0:n.commitTags,description:n==null?void 0:n.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){const[n,r]=Ct(e);return this._repoExists(n,r)}async skillExists(e){const[n,r]=Ct(e);return this._repoExists(n,r)}async pullAgent(e,n){return await this._pullDirectory(e,"agent",n==null?void 0:n.version)}async pullSkill(e,n){return await this._pullDirectory(e,"skill",n==null?void 0:n.version)}async pushAgent(e,n){return this._pushDirectory(e,"agent",n)}async pushSkill(e,n){return this._pushDirectory(e,"skill",n)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,n){const r=new URLSearchParams;r.append("repo_type",e),r.append("is_archived",(!!(n!=null&&n.isArchived)).toString()),(n==null?void 0:n.isPublic)!==void 0&&r.append("is_public",n.isPublic.toString()),n!=null&&n.query&&r.append("query",n.query);for await(const i of this._getPaginated("/repos",r,s=>s.repos))yield*i}async _pullDirectory(e,n,r){const[i,s,a]=Ct(e),o=r??(a!=="latest"?a:void 0),u=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${s}/directories`)}`);return u.searchParams.set("repo_type",n),o&&u.searchParams.set("commit",o),await(await this.caller.call(async()=>{const c=await this._fetch(u.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(c,"pull directory"),c})).json()}async _pushDirectory(e,n,r){if(r.parentCommit!==void 0&&(r.parentCommit.length<8||r.parentCommit.length>64))throw new Error("parent_commit must be 8-64 characters");const[i,s]=Ct(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError(`push ${n}`,i);if(await this._repoExists(i,s))(r.description!==void 0||r.readme!==void 0||r.tags!==void 0||r.isPublic!==void 0)&&await this._updateRepoMetadata(i,s,r);else{const f=/^[a-z][a-z0-9-_]*$/;if(!f.test(s))throw new Error(`Invalid repo_handle ${JSON.stringify(s)}: must match ${f}`);await this._createRepo(s,n,r)}const a={files:r.files};r.parentCommit&&(a.parent_commit=r.parentCommit);const l=(await(await this.caller.call(async()=>{const f=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${s}/directories/commits`)}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(a)});return await q(f,`push ${n}`),f})).json()).commit.commit_hash,c=await this._getSettings(),d=new URLSearchParams({organizationId:c.id});return`${this.getHostUrl()}/context/${s}/${l.slice(0,8)}?${d.toString()}`}async _deleteDirectory(e){const[n,r]=Ct(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("delete",n);await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${n}/${r}/directories`)}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(i,"delete directory"),i})}async _repoExists(e,n){try{return await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/repos/${e}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await q(r,"check repo exists"),r}),!0}catch(r){if(Ff(r))return!1;throw r}}async _createRepo(e,n,r){const i={repo_handle:e,repo_type:n,is_public:!!r.isPublic};r.description!==void 0&&(i.description=r.description),r.readme!==void 0&&(i.readme=r.readme),r.tags!==void 0&&(i.tags=r.tags);try{await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await q(s,`create ${n}`),s})}catch(s){if(l4(s))return;throw s}}async _updateRepoMetadata(e,n,r){const i={};r.description!==void 0&&(i.description=r.description),r.readme!==void 0&&(i.readme=r.readme),r.tags!==void 0&&(i.tags=r.tags),r.isPublic!==void 0&&(i.is_public=r.isPublic),Object.keys(i).length!==0&&await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/repos/${e}/${n}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await q(s,"update repo metadata"),s})}async clonePublicDataset(e,n={}){const{sourceApiUrl:r=this.apiUrl,datasetName:i}=n,[s,a]=this.parseTokenOrUrl(e,r),o=new Ir({apiUrl:s,apiKey:"placeholder"}),u=await o.readSharedDataset(a),l=i||u.name;try{if(await this.hasDataset({datasetId:l})){console.log(`Dataset ${l} already exists in your tenant. Skipping.`);return}}catch{}const c=await o.listSharedExamples(a),d=await this.createDataset(l,{description:u.description,dataType:u.data_type||"kv",inputsSchema:u.inputs_schema_definition??void 0,outputsSchema:u.outputs_schema_definition??void 0});try{await this.createExamples({inputs:c.map(f=>f.inputs),outputs:c.flatMap(f=>f.outputs?[f.outputs]:[]),datasetId:d.id})}catch(f){throw console.error(`An error occurred while creating dataset ${l}. You should delete it manually.`),f}}parseTokenOrUrl(e,n,r=2,i="dataset"){try{return ae(e),[n,e]}catch{}try{const a=new URL(e).pathname.split("/").filter(o=>o!=="");if(a.length>=r){const o=a[a.length-r];return[n,o]}else throw new Error(`Invalid public ${i} URL: ${e}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){var e,n;if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(r=>setTimeout(r,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:r})=>r),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await((n=(e=VR())==null?void 0:e.DEFAULT_LANGSMITH_SPAN_PROCESSOR)==null?void 0:n.forceFlush())}toString(){const e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}}Object.defineProperty(Ir,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function _0(t){return"dataset_id"in t||"dataset_name"in t}const yi=Symbol.for("lc:context_variables"),Zf=Symbol.for("langsmith:replica_trace_roots");function v0(t,e){if(yi in t)return t[yi][e]}function Y4(t,e,n){const r=yi in t?t[yi]:{};r[e]=n,t[yi]=r}const Ma=36,eL="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function w0(t){const n=Object.keys(t).sort().map(r=>`${r}:${t[r]??""}`).join("|");return Bg(n,eL)}function tL(t){return t.replace(/[-:.]/g,"")}function iE(t,e=1){const n=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${n}Z`}function sE(t,e,n=1){const r=iE(t,n);return{dottedOrder:tL(r)+e,microsecondPrecisionDatestring:r}}const nL=new Set(["projectName","updates","reroot"]);function rL(t){const e={};for(const n of Object.keys(t))nL.has(n)&&(e[n]=t[n]);return e}class kc{constructor(e,n,r,i){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=n,this.project_name=r,this.replicas=i}static fromHeader(e){const n=e.split(",");let r={},i=[],s,a;for(const o of n){const[u,l]=o.split("="),c=decodeURIComponent(l);u==="langsmith-metadata"?r=JSON.parse(c):u==="langsmith-tags"?i=c.split(","):u==="langsmith-project"?s=c:u==="langsmith-replicas"&&(a=JSON.parse(c).map(f=>Array.isArray(f)?f:rL(f)))}return new kc(r,i,s,a)}toHeader(){const e=[];return this.metadata&&Object.keys(this.metadata).length>0&&e.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`),this.tags&&this.tags.length>0&&e.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`),this.project_name&&e.push(`langsmith-project=${encodeURIComponent(this.project_name)}`),e.join(",")}}class Ht{constructor(e){var o;if(Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"run_type",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"parent_run_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_runs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"end_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"extra",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"serialized",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"inputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"outputs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reference_example_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"events",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"trace_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"dotted_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"child_execution_order",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"attachments",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),iL(e)){Object.assign(this,{...e});return}const n=Ht.getDefaultConfig(),{metadata:r,...i}=e,s=i.client??Ht.getSharedClient(),a={...r,...(o=i==null?void 0:i.extra)==null?void 0:o.metadata};if(i.extra={...i.extra,metadata:a},"id"in i&&i.id==null&&delete i.id,Object.assign(this,{...n,...i,client:s}),this.execution_order??(this.execution_order=1),this.child_execution_order??(this.child_execution_order=1),this.dotted_order||(this._serialized_start_time=iE(this.start_time,this.execution_order)),this.id||(this.id=pR(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=uL(this.replicas),!this.dotted_order){const{dottedOrder:u}=sE(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+u:this.dotted_order=u}}set metadata(e){var n;this.extra={...this.extra,metadata:{...(n=this.extra)==null?void 0:n.metadata,...e}}}get metadata(){var e;return(e=this.extra)==null?void 0:e.metadata}static getDefaultConfig(){const e=Date.now();return{run_type:"chain",project_name:zS(),child_runs:[],api_url:en("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:en("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return Ht.sharedClient||(Ht.sharedClient=new Ir),Ht.sharedClient}createChild(e){var f,h,m,_,v,y,p,g,b;const n=this.child_execution_order+1,r=(f=this.replicas)==null?void 0:f.map(E=>{const{reroot:T,...I}=E;return I}),i=e.replicas??r,s=new Ht({...e,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:n,child_execution_order:n}),a=((h=this.extra)==null?void 0:h.metadata)??{},o=((m=s.extra)==null?void 0:m.metadata)??{};Object.keys(a).length>0&&(s.extra={...s.extra,metadata:{...a,...o}}),yi in this&&(s[yi]=this[yi]);const u=Symbol.for("lc:child_config"),l=((_=e.extra)==null?void 0:_[u])??this.extra[u];if(aL(l)){const E={...l},T=sL(E.callbacks)?(y=(v=E.callbacks).copy)==null?void 0:y.call(v):void 0;T&&(Object.assign(T,{_parentRunId:s.id}),(b=(g=(p=T.handlers)==null?void 0:p.find(aE))==null?void 0:g.updateFromRunTree)==null||b.call(g,s),E.callbacks=T),s.extra[u]=E}const c=new Set;let d=this;for(;d!=null&&!c.has(d.id);)c.add(d.id),d.child_execution_order=Math.max(d.child_execution_order,n),d=d.parent_run;return this.child_runs.push(s),s}async end(e,n,r=Date.now(),i){this.outputs=this.outputs??e,this.error=this.error??n,this.end_time=this.end_time??r,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(e,n,r=!0){var o,u;const i=e.extra??{};if(((o=i==null?void 0:i.runtime)==null?void 0:o.library)===void 0&&(i.runtime||(i.runtime={}),n))for(const[l,c]of Object.entries(n))i.runtime[l]||(i.runtime[l]=c);const s=((u=e.parent_run)==null?void 0:u.id)??e.parent_run_id;let a;return r?a=[]:a=e.child_runs.map(l=>this._convertToCreate(l,n,r)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:i,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:s,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,n){if(n.dotted_order){const r=n.dotted_order.split(".");let i=null;for(let s=0;s<r.length;s++)if(r[s].slice(-Ma)===e){i=s;break}if(i!==null){const s=r.slice(i+1);n.dotted_order=s.join("."),s.length>0?n.trace_id=s[0].slice(-Ma):n.trace_id=n.id}}n.parent_run_id===e&&(n.parent_run_id=void 0)}_setReplicaTraceRoot(e,n){const r=v0(this,Zf)??{};r[e]=n,Y4(this,Zf,r);for(const i of this.child_runs)i._setReplicaTraceRoot(e,n)}_remapForProject(e){const{projectName:n,runtimeEnv:r,excludeChildRuns:i=!0,reroot:s=!1,distributedParentId:a,apiUrl:o,apiKey:u,workspaceId:l}=e,c=this._convertToCreate(this,r,i);if(n===this.project_name)return{...c,session_name:n};if(s){if(a)this._sliceParentId(a,c);else if(c.parent_run_id=void 0,c.dotted_order){const p=c.dotted_order.split(".");p.length>0&&(c.dotted_order=p[p.length-1],c.trace_id=c.id)}const y=w0({projectName:n,apiUrl:o,apiKey:u,workspaceId:l});this._setReplicaTraceRoot(y,c.id)}let d;if(!s){const y=v0(this,Zf)??{},p=w0({projectName:n,apiUrl:o,apiKey:u,workspaceId:l});if(d=y[p],d&&(c.trace_id=d,c.dotted_order)){const g=c.dotted_order.split(".");let b=null;for(let E=0;E<g.length;E++)if(g[E].slice(-Ma)===d){b=E;break}if(b!==null){const E=g.slice(b);c.dotted_order=E.join(".")}}}const f=c.id,h=Hu(f,n);let m;c.trace_id?m=Hu(c.trace_id,n):m=h;let _;c.parent_run_id&&(_=Hu(c.parent_run_id,n));let v;return c.dotted_order&&(v=c.dotted_order.split(".").map(g=>{const b=g.slice(-Ma),E=Hu(b,n);return g.slice(0,-Ma)+E}).join(".")),{...c,id:h,trace_id:m,parent_run_id:_,dotted_order:v,session_name:n}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{const n=GS();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:i,apiUrl:s,workspaceId:a,reroot:o,client:u}of this.replicas){const l=this._remapForProject({projectName:r??this.project_name,runtimeEnv:n,excludeChildRuns:!0,reroot:o,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:i,workspaceId:a});await(u??this.client).createRun(l,{apiKey:i,apiUrl:s,workspaceId:a})}else{const r=this._convertToCreate(this,n,e);await this.client.createRun(r)}if(!e){$l("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(const r of this.child_runs)await r.postRun(!1)}this.child_runs=[]}catch(n){console.error(`Error in postRun for run ${this.id}:`,n)}}async patchRun(e){var n;if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:i,apiUrl:s,workspaceId:a,updates:o,reroot:u,client:l}of this.replicas){const c=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:u,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:i,workspaceId:a}),d={id:c.id,name:c.name,run_type:c.run_type,start_time:c.start_time,outputs:c.outputs,error:c.error,parent_run_id:c.parent_run_id,session_name:c.session_name,reference_example_id:c.reference_example_id,end_time:c.end_time,dotted_order:c.dotted_order,trace_id:c.trace_id,events:c.events,tags:c.tags,extra:c.extra,attachments:this.attachments,...o};e!=null&&e.excludeInputs||(d.inputs=c.inputs),await(l??this.client).updateRun(c.id,d,{apiKey:i,apiUrl:s,workspaceId:a})}else try{const r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:((n=this.parent_run)==null?void 0:n.id)??this.parent_run_id,reference_example_id:this.reference_example_id,extra:this.extra,events:this.events,dotted_order:this.dotted_order,trace_id:this.trace_id,tags:this.tags,attachments:this.attachments,session_name:this.project_name};e!=null&&e.excludeInputs||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,n){var l,c,d,f;const r=e==null?void 0:e.callbacks;let i,s,a,o=wR();if(r){const h=((l=r==null?void 0:r.getParentRunId)==null?void 0:l.call(r))??"",m=(c=r==null?void 0:r.handlers)==null?void 0:c.find(_=>(_==null?void 0:_.name)=="langchain_tracer");i=(d=m==null?void 0:m.getRun)==null?void 0:d.call(m,h),s=m==null?void 0:m.projectName,a=m==null?void 0:m.client,o=o||!!m}return i?new Ht({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:a,tracingEnabled:o,project_name:s,tags:[...new Set(((i==null?void 0:i.tags)??[]).concat((e==null?void 0:e.tags)??[]))],extra:{metadata:{...(f=i==null?void 0:i.extra)==null?void 0:f.metadata,...e==null?void 0:e.metadata}}}).createChild(n):new Ht({...n,client:a,tracingEnabled:o,project_name:s})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,n){var c;const r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,i=r["langsmith-trace"];if(!i||typeof i!="string")return;const s=i.trim(),a=s.split(".").map(d=>{const[f,h]=d.split("Z");return{strTime:f,time:Date.parse(f+"Z"),uuid:h}}),o=a[0].uuid,u={...n,name:(n==null?void 0:n.name)??"parent",run_type:(n==null?void 0:n.run_type)??"chain",start_time:(n==null?void 0:n.start_time)??Date.now(),id:(c=a.at(-1))==null?void 0:c.uuid,trace_id:o,dotted_order:s};if(r.baggage&&typeof r.baggage=="string"){const d=kc.fromHeader(r.baggage);u.metadata=d.metadata,u.tags=d.tags,u.project_name=d.project_name,u.replicas=d.replicas}const l=new Ht(u);return l.distributedParentId=l.id,l}toHeaders(e){var r;const n={"langsmith-trace":this.dotted_order,baggage:new kc((r=this.extra)==null?void 0:r.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[i,s]of Object.entries(n))e.set(i,s);return n}}Object.defineProperty(Ht,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function iL(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}function aE(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}function b0(t){return Array.isArray(t)&&t.some(e=>aE(e))}function sL(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}function aL(t){const e=t==null?void 0:t.callbacks;return t!=null&&typeof e=="object"&&(b0(e==null?void 0:e.handlers)||b0(e))}function oL(){const t=en("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{const e=JSON.parse(t);if(Array.isArray(e)){const n=[];for(const r of e){if(typeof r!="object"||r===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof r}`);continue}if(typeof r.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_url}`);continue}if(typeof r.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof r.api_key}`);continue}n.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return n}else if(typeof e=="object"&&e!==null){lL(e);const n=[];for(const[r,i]of Object.entries(e)){const s=r.replace(/\/$/,"");if(typeof i=="string")n.push({apiUrl:s,apiKey:i});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof i}`);continue}}return n}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof e}`),[]}catch(e){if(d4(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}function uL(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):oL()}function lL(t){if(Object.keys(t).length>0&&Xe("ENDPOINT"))throw new c4}const cL=t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t};function Cp(t,e){if(t)return new Ht({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Cp(e),child_runs:t.child_runs.map(n=>Cp(n)).filter(n=>n!==void 0),extra:{...t.extra,runtime:e$()},tracingEnabled:!1})}function Vf(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}function za(t){return typeof t._addRunToRunMap=="function"}var du=class extends bd{constructor(e){super(...arguments);A(this,"runMap",new Map);A(this,"runTreeMap",new Map);A(this,"usesRunTreeMap",!1)}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?cL(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e!=null&&e.stack?` ${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,n){e.child_runs.push(n)}_addRunToRunMap(e){const{dottedOrder:n,microsecondPrecisionDatestring:r}=sE(new Date(e.start_time).getTime(),e.id,e.execution_order),i={...e},s=this.getRunById(i.parent_run_id);if(i.parent_run_id!==void 0?s?(this._addChildRun(s,i),s.child_execution_order=Math.max(s.child_execution_order,i.child_execution_order),i.trace_id=s.trace_id,s.dotted_order!==void 0&&(i.dotted_order=[s.dotted_order,n].join("."),i._serialized_start_time=r)):i.parent_run_id=void 0:(i.trace_id=i.id,i.dotted_order=n,i._serialized_start_time=r),this.usesRunTreeMap){const a=Cp(i,s);a!==void 0&&this.runTreeMap.set(i.id,a)}else this.runMap.set(i.id,i);return i}async _endTrace(e){var r;const n=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);n?n.child_execution_order=Math.max(n.child_execution_order,e.child_execution_order):await this.persistRun(e),await((r=this.onRunUpdate)==null?void 0:r.call(this,e)),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const n=e!==void 0&&this.getRunById(e);return n?n.child_execution_order+1:1}_createRunForLLMStart(e,n,r,i,s,a,o,u){const l=this._getExecutionOrder(i),c=Date.now(),d=o?{...s,metadata:o}:s,f={id:r,name:u??e.id[e.id.length-1],parent_run_id:i,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{prompts:n},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleLLMStart(e,n,r,i,s,a,o,u){var c,d;const l=this.getRunById(r)??this._createRunForLLMStart(e,n,r,i,s,a,o,u);return await((c=this.onRunCreate)==null?void 0:c.call(this,l)),await((d=this.onLLMStart)==null?void 0:d.call(this,l)),l}_createRunForChatModelStart(e,n,r,i,s,a,o,u){const l=this._getExecutionOrder(i),c=Date.now(),d=o?{...s,metadata:o}:s,f={id:r,name:u??e.id[e.id.length-1],parent_run_id:i,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{messages:n},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:a||[]};return this._addRunToRunMap(f)}async handleChatModelStart(e,n,r,i,s,a,o,u){var c,d;const l=this.getRunById(r)??this._createRunForChatModelStart(e,n,r,i,s,a,o,u);return await((c=this.onRunCreate)==null?void 0:c.call(this,l)),await((d=this.onLLMStart)==null?void 0:d.call(this,l)),l}async handleLLMEnd(e,n,r,i,s){var o;const a=this.getRunById(n);if(!a||(a==null?void 0:a.run_type)!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.outputs=e,a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await((o=this.onLLMEnd)==null?void 0:o.call(this,a)),await this._endTrace(a),a}async handleLLMError(e,n,r,i,s){var o;const a=this.getRunById(n);if(!a||(a==null?void 0:a.run_type)!=="llm")throw new Error("No LLM run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),a.extra={...a.extra,...s},await((o=this.onLLMError)==null?void 0:o.call(this,a)),await this._endTrace(a),a}_createRunForChainStart(e,n,r,i,s,a,o,u,l){const c=this._getExecutionOrder(i),d=Date.now(),f={id:r,name:u??e.id[e.id.length-1],parent_run_id:i,start_time:d,serialized:e,events:[{name:"start",time:new Date(d).toISOString()}],inputs:n,execution_order:c,child_execution_order:c,run_type:o??"chain",child_runs:[],extra:a?{...l,metadata:a}:{...l},tags:s||[]};return this._addRunToRunMap(f)}async handleChainStart(e,n,r,i,s,a,o,u){var c,d;const l=this.getRunById(r)??this._createRunForChainStart(e,n,r,i,s,a,o,u);return await((c=this.onRunCreate)==null?void 0:c.call(this,l)),await((d=this.onChainStart)==null?void 0:d.call(this,l)),l}async handleChainEnd(e,n,r,i,s){var o;const a=this.getRunById(n);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.outputs=Vf(e,"output"),a.events.push({name:"end",time:new Date(a.end_time).toISOString()}),(s==null?void 0:s.inputs)!==void 0&&(a.inputs=Vf(s.inputs,"input")),await((o=this.onChainEnd)==null?void 0:o.call(this,a)),await this._endTrace(a),a}async handleChainError(e,n,r,i,s){var o;const a=this.getRunById(n);if(!a)throw new Error("No chain run to end.");return a.end_time=Date.now(),a.error=this.stringifyError(e),a.events.push({name:"error",time:new Date(a.end_time).toISOString()}),(s==null?void 0:s.inputs)!==void 0&&(a.inputs=Vf(s.inputs,"input")),await((o=this.onChainError)==null?void 0:o.call(this,a)),await this._endTrace(a),a}_createRunForToolStart(e,n,r,i,s,a,o){const u=this._getExecutionOrder(i),l=Date.now(),c={id:r,name:o??e.id[e.id.length-1],parent_run_id:i,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:n},execution_order:u,child_execution_order:u,run_type:"tool",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(c)}async handleToolStart(e,n,r,i,s,a,o){var l,c;const u=this.getRunById(r)??this._createRunForToolStart(e,n,r,i,s,a,o);return await((l=this.onRunCreate)==null?void 0:l.call(this,u)),await((c=this.onToolStart)==null?void 0:c.call(this,u)),u}async handleToolEnd(e,n){var i;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await((i=this.onToolEnd)==null?void 0:i.call(this,r)),await this._endTrace(r),r}async handleToolError(e,n){var i;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await((i=this.onToolError)==null?void 0:i.call(this,r)),await this._endTrace(r),r}async handleAgentAction(e,n){var s;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="chain")return;const i=r;i.actions=i.actions||[],i.actions.push(e),i.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await((s=this.onAgentAction)==null?void 0:s.call(this,r))}async handleAgentEnd(e,n){var i;const r=this.getRunById(n);!r||(r==null?void 0:r.run_type)!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await((i=this.onAgentEnd)==null?void 0:i.call(this,r)))}_createRunForRetrieverStart(e,n,r,i,s,a,o){const u=this._getExecutionOrder(i),l=Date.now(),c={id:r,name:o??e.id[e.id.length-1],parent_run_id:i,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:n},execution_order:u,child_execution_order:u,run_type:"retriever",child_runs:[],extra:a?{metadata:a}:{},tags:s||[]};return this._addRunToRunMap(c)}async handleRetrieverStart(e,n,r,i,s,a,o){var l,c;const u=this.getRunById(r)??this._createRunForRetrieverStart(e,n,r,i,s,a,o);return await((l=this.onRunCreate)==null?void 0:l.call(this,u)),await((c=this.onRetrieverStart)==null?void 0:c.call(this,u)),u}async handleRetrieverEnd(e,n){var i;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:e},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await((i=this.onRetrieverEnd)==null?void 0:i.call(this,r)),await this._endTrace(r),r}async handleRetrieverError(e,n){var i;const r=this.getRunById(n);if(!r||(r==null?void 0:r.run_type)!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(e),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await((i=this.onRetrieverError)==null?void 0:i.call(this,r)),await this._endTrace(r),r}async handleText(e,n){var i;const r=this.getRunById(n);!r||(r==null?void 0:r.run_type)!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await((i=this.onText)==null?void 0:i.call(this,r)))}async handleLLMNewToken(e,n,r,i,s,a){var u;const o=this.getRunById(r);if(!o||(o==null?void 0:o.run_type)!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return o.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:e,idx:n,chunk:a==null?void 0:a.chunk}}),await((u=this.onLLMNewToken)==null?void 0:u.call(this,o,e,{chunk:a==null?void 0:a.chunk})),o}};const oE={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};function It(t,e){return`${t.open}${e}${t.close}`}function bn(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}function x0(t){return typeof t=="string"?t.trim():t==null?t:bn(t,t.toString())}function Xr(t){if(!t.end_time)return"";const e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:Bt}=oE;var k0=class extends du{constructor(){super(...arguments);A(this,"name","console_callback_handler")}persistRun(e){return Promise.resolve()}getParents(e){const n=[];let r=e;for(;r.parent_run_id;){const i=this.runMap.get(r.parent_run_id);if(i)n.push(i),r=i;else break}return n}getBreadcrumbs(e){const n=[...this.getParents(e).reverse(),e].map((r,i,s)=>{const a=`${r.execution_order}:${r.run_type}:${r.name}`;return i===s.length-1?It(oE.bold,a):a}).join(" > ");return It(Bt.grey,n)}onChainStart(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.green,"[chain/start]")} [${n}] Entering Chain run with input: ${bn(e.inputs,"[inputs]")}`)}onChainEnd(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.cyan,"[chain/end]")} [${n}] [${Xr(e)}] Exiting Chain run with output: ${bn(e.outputs,"[outputs]")}`)}onChainError(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.red,"[chain/error]")} [${n}] [${Xr(e)}] Chain run errored with error: ${bn(e.error,"[error]")}`)}onLLMStart(e){const n=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(i=>i.trim())}:e.inputs;console.log(`${It(Bt.green,"[llm/start]")} [${n}] Entering LLM run with input: ${bn(r,"[inputs]")}`)}onLLMEnd(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.cyan,"[llm/end]")} [${n}] [${Xr(e)}] Exiting LLM run with output: ${bn(e.outputs,"[response]")}`)}onLLMError(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.red,"[llm/error]")} [${n}] [${Xr(e)}] LLM run errored with error: ${bn(e.error,"[error]")}`)}onToolStart(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.green,"[tool/start]")} [${n}] Entering Tool run with input: "${x0(e.inputs.input)}"`)}onToolEnd(e){var r;const n=this.getBreadcrumbs(e);console.log(`${It(Bt.cyan,"[tool/end]")} [${n}] [${Xr(e)}] Exiting Tool run with output: "${x0((r=e.outputs)==null?void 0:r.output)}"`)}onToolError(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.red,"[tool/error]")} [${n}] [${Xr(e)}] Tool run errored with error: ${bn(e.error,"[error]")}`)}onRetrieverStart(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.green,"[retriever/start]")} [${n}] Entering Retriever run with input: ${bn(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.cyan,"[retriever/end]")} [${n}] [${Xr(e)}] Exiting Retriever run with output: ${bn(e.outputs,"[outputs]")}`)}onRetrieverError(e){const n=this.getBreadcrumbs(e);console.log(`${It(Bt.red,"[retriever/error]")} [${n}] [${Xr(e)}] Retriever run errored with error: ${bn(e.error,"[error]")}`)}onAgentAction(e){const n=e,r=this.getBreadcrumbs(e);console.log(`${It(Bt.blue,"[agent/action]")} [${r}] Agent selected action: ${bn(n.actions[n.actions.length-1],"[action]")}`)}};let Kf;const dL=()=>(Kf===void 0&&(Kf=new Ir(Jn("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Kf),uE=new Set(["ls_agent_type"]);function fL(t){let e;for(const n of t)for(const r of n)Cn.isInstance(r.message)&&r.message.usage_metadata!==void 0&&(e=AS(e,r.message.usage_metadata));return e}var Ju=class Pp extends du{constructor(n={}){super(n);A(this,"name","langchain_tracer");A(this,"projectName");A(this,"exampleId");A(this,"client");A(this,"replicas");A(this,"usesRunTreeMap",!0);A(this,"tracingMetadata");A(this,"tracingTags",[]);this.fields=n;const{exampleId:r,projectName:i,client:s,replicas:a,metadata:o,tags:u}=n;this.projectName=i??zS(),this.replicas=a,this.exampleId=r,this.client=s??dL(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=u??[];const l=Pp.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(n){}async onRunCreate(n){var r,i;S0(this,n),(r=n.extra)!=null&&r.lc_defers_inputs||await((i=this.getRunTreeWithTracingConfig(n.id))==null?void 0:i.postRun())}async onRunUpdate(n){var i;S0(this,n);const r=this.getRunTreeWithTracingConfig(n.id);(i=n.extra)!=null&&i.lc_defers_inputs?await(r==null?void 0:r.postRun()):await(r==null?void 0:r.patchRun())}onLLMEnd(n){const r=n.outputs;if(r!=null&&r.generations){const i=fL(r.generations);if(i!==void 0){n.extra=n.extra??{};const s=n.extra.metadata??{};s.usage_metadata=i,n.extra.metadata=s}}}copyWithTracingConfig({metadata:n,tags:r}){let i;if(n===void 0)i=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)i={...n};else{i={...this.tracingMetadata};for(const[o,u]of Object.entries(n))(!Object.prototype.hasOwnProperty.call(i,o)||uE.has(o))&&(i[o]=u)}const s=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],a=new Pp({...this.fields,metadata:i,tags:s});return a.runMap=this.runMap,a.runTreeMap=this.runTreeMap,a}getRun(n){return this.runTreeMap.get(n)}updateFromRunTree(n){this.runTreeMap.set(n.id,n);let r=n;const i=new Set;for(;r.parent_run&&!(i.has(r.id)||(i.add(r.id),!r.parent_run));)r=r.parent_run;i.clear();const s=[r];for(;s.length>0;){const a=s.shift();!a||i.has(a.id)||(i.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&s.push(...a.child_runs))}this.client=n.client??this.client,this.replicas=n.replicas??this.replicas,this.projectName=n.project_name??this.projectName,this.exampleId=n.reference_example_id??this.exampleId,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(n){const r=this.runTreeMap.get(n);if(r)return new Ht({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return AR(!0)}catch{return}}static[Symbol.hasInstance](n){if(typeof n!="object"||n===null)return!1;const r=n;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function S0(t,e){if(t.tracingMetadata){e.extra??(e.extra={});const n=e.extra.metadata??{};let r=!1;for(const[i,s]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(n,i)||uE.has(i))&&n[i]!==s&&(n[i]=s,r=!0);r&&(e.extra.metadata=n)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}let wo;function hL(){return new("default"in $r?$r.default:$r)({autoStart:!0,concurrency:1})}function pL(){return typeof wo>"u"&&(wo=hL()),wo}async function Ge(t,e){if(e===!0){const n=Vo();n!==void 0?await n.run(void 0,async()=>t()):await t()}else wo=pL(),wo.add(async()=>{const n=Vo();n!==void 0?await n.run(void 0,async()=>t()):await t()})}const mL=t=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Jn(e)==="true");function lE(t){var n,r;const e=Vo();if(e!==void 0)return(r=(n=e.getStore())==null?void 0:n[Nl])==null?void 0:r[t]}const gL=Symbol("lc:configure_hooks"),yL=()=>lE(gL)||[];var _L=class{setHandler(t){return this.setHandlers([t])}},Id=class{constructor(t,e,n,r,i,s,a,o){this.runId=t,this.handlers=e,this.inheritableHandlers=n,this.tags=r,this.inheritableTags=i,this.metadata=s,this.inheritableMetadata=a,this._parentRunId=o}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>Ge(async()=>{var n;try{await((n=e.handleText)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,n,r,i){await Promise.all(this.handlers.map(s=>Ge(async()=>{var a;try{await((a=s.handleCustomEvent)==null?void 0:a.call(s,t,e,this.runId,this.tags,this.metadata))}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},vL=class extends Id{getChild(t){const e=new Rr(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>Ge(async()=>{var n;if(!e.ignoreRetriever)try{await((n=e.handleRetrieverEnd)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>Ge(async()=>{var n;if(!e.ignoreRetriever)try{await((n=e.handleRetrieverError)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},A0=class extends Id{async handleLLMNewToken(t,e,n,r,i,s){await Promise.all(this.handlers.map(a=>Ge(async()=>{var o;if(!a.ignoreLLM)try{await((o=a.handleLLMNewToken)==null?void 0:o.call(a,t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s))}catch(u){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMNewToken: ${u}`),a.raiseError)throw u}},a.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>Ge(async()=>{var n;if(!e.ignoreLLM)try{await((n=e.handleChatModelStreamEvent)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleLLMError(t,e,n,r,i){await Promise.all(this.handlers.map(s=>Ge(async()=>{var a;if(!s.ignoreLLM)try{await((a=s.handleLLMError)==null?void 0:a.call(s,t,this.runId,this._parentRunId,this.tags,i))}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleLLMEnd(t,e,n,r,i){await Promise.all(this.handlers.map(s=>Ge(async()=>{var a;if(!s.ignoreLLM)try{await((a=s.handleLLMEnd)==null?void 0:a.call(s,t,this.runId,this._parentRunId,this.tags,i))}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},wL=class extends Id{getChild(t){const e=new Rr(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,n,r,i){await Promise.all(this.handlers.map(s=>Ge(async()=>{var a;if(!s.ignoreChain)try{await((a=s.handleChainError)==null?void 0:a.call(s,t,this.runId,this._parentRunId,this.tags,i))}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleChainEnd(t,e,n,r,i){await Promise.all(this.handlers.map(s=>Ge(async()=>{var a;if(!s.ignoreChain)try{await((a=s.handleChainEnd)==null?void 0:a.call(s,t,this.runId,this._parentRunId,this.tags,i))}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>Ge(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleAgentAction)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>Ge(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleAgentEnd)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},bL=class extends Id{getChild(t){const e=new Rr(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>Ge(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleToolError)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>Ge(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleToolEvent)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>Ge(async()=>{var n;if(!e.ignoreAgent)try{await((n=e.handleToolEnd)==null?void 0:n.call(e,t,this.runId,this._parentRunId,this.tags))}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Rr=class eo extends _L{constructor(n,r){super();A(this,"handlers",[]);A(this,"inheritableHandlers",[]);A(this,"tags",[]);A(this,"inheritableTags",[]);A(this,"metadata",{});A(this,"inheritableMetadata",{});A(this,"name","callback_manager");A(this,"_parentRunId");this.handlers=(r==null?void 0:r.handlers)??this.handlers,this.inheritableHandlers=(r==null?void 0:r.inheritableHandlers)??this.inheritableHandlers,this.tags=(r==null?void 0:r.tags)??this.tags,this.inheritableTags=(r==null?void 0:r.inheritableTags)??this.inheritableTags,this.metadata=(r==null?void 0:r.metadata)??this.metadata,this.inheritableMetadata=(r==null?void 0:r.inheritableMetadata)??this.inheritableMetadata,this._parentRunId=n}getParentRunId(){return this._parentRunId}async handleLLMStart(n,r,i=void 0,s=void 0,a=void 0,o=void 0,u=void 0,l=void 0){return Promise.all(r.map(async(c,d)=>{const f=d===0&&i?i:ei();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return za(h)&&h._createRunForLLMStart(n,[c],f,this._parentRunId,a,this.tags,this.metadata,l),Ge(async()=>{var m;try{await((m=h.handleLLMStart)==null?void 0:m.call(h,n,[c],f,this._parentRunId,a,this.tags,this.metadata,l))}catch(_){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${_}`),h.raiseError)throw _}},h.awaitHandlers)})),new A0(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(n,r,i=void 0,s=void 0,a=void 0,o=void 0,u=void 0,l=void 0){return Promise.all(r.map(async(c,d)=>{const f=d===0&&i?i:ei();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return za(h)&&h._createRunForChatModelStart(n,[c],f,this._parentRunId,a,this.tags,this.metadata,l),Ge(async()=>{var m,_;try{if(h.handleChatModelStart)await((m=h.handleChatModelStart)==null?void 0:m.call(h,n,[c],f,this._parentRunId,a,this.tags,this.metadata,l));else if(h.handleLLMStart){const v=NS(c);await((_=h.handleLLMStart)==null?void 0:_.call(h,n,[v],f,this._parentRunId,a,this.tags,this.metadata,l))}}catch(v){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${v}`),h.raiseError)throw v}},h.awaitHandlers)})),new A0(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(n,r,i=ei(),s=void 0,a=void 0,o=void 0,u=void 0,l=void 0,c=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return za(d)&&d._createRunForChainStart(n,r,i,this._parentRunId,this.tags,this.metadata,s,u,c),Ge(async()=>{var f;try{await((f=d.handleChainStart)==null?void 0:f.call(d,n,r,i,this._parentRunId,this.tags,this.metadata,s,u,c))}catch(h){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${h}`),d.raiseError)throw h}},d.awaitHandlers)})),new wL(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(n,r,i=ei(),s=void 0,a=void 0,o=void 0,u=void 0,l=void 0){return await Promise.all(this.handlers.map(c=>{if(!c.ignoreAgent)return za(c)&&c._createRunForToolStart(n,r,i,this._parentRunId,this.tags,this.metadata,u),Ge(async()=>{var d;try{await((d=c.handleToolStart)==null?void 0:d.call(c,n,r,i,this._parentRunId,this.tags,this.metadata,u,l))}catch(f){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleToolStart: ${f}`),c.raiseError)throw f}},c.awaitHandlers)})),new bL(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(n,r,i=ei(),s=void 0,a=void 0,o=void 0,u=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreRetriever)return za(l)&&l._createRunForRetrieverStart(n,r,i,this._parentRunId,this.tags,this.metadata,u),Ge(async()=>{var c;try{await((c=l.handleRetrieverStart)==null?void 0:c.call(l,n,r,i,this._parentRunId,this.tags,this.metadata,u))}catch(d){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleRetrieverStart: ${d}`),l.raiseError)throw d}},l.awaitHandlers)})),new vL(i,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(n,r,i,s,a){await Promise.all(this.handlers.map(o=>Ge(async()=>{var u;if(!o.ignoreCustomEvent)try{await((u=o.handleCustomEvent)==null?void 0:u.call(o,n,r,i,this.tags,this.metadata))}catch(l){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${l}`),o.raiseError)throw l}},o.awaitHandlers)))}addHandler(n,r=!0){this.handlers.push(n),r&&this.inheritableHandlers.push(n)}removeHandler(n){this.handlers=this.handlers.filter(r=>r!==n),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==n)}setHandlers(n,r=!0){this.handlers=[],this.inheritableHandlers=[];for(const i of n)this.addHandler(i,r)}addTags(n,r=!0){this.removeTags(n),this.tags.push(...n),r&&this.inheritableTags.push(...n)}removeTags(n){this.tags=this.tags.filter(r=>!n.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!n.includes(r))}addMetadata(n,r=!0){this.metadata={...this.metadata,...n},r&&(this.inheritableMetadata={...this.inheritableMetadata,...n})}removeMetadata(n){for(const r of Object.keys(n))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(n=[],r=!0){const i=new eo(this._parentRunId);for(const s of this.handlers){const a=this.inheritableHandlers.includes(s);i.addHandler(s,a)}for(const s of this.tags){const a=this.inheritableTags.includes(s);i.addTags([s],a)}for(const s of Object.keys(this.metadata)){const a=Object.keys(this.inheritableMetadata).includes(s);i.addMetadata({[s]:this.metadata[s]},a)}for(const s of n)i.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===s.name)||i.addHandler(s,r);return i}static fromHandlers(n){class r extends bd{constructor(){super();A(this,"name",ei());Object.assign(this,n)}}const i=new this;return i.addHandler(new r),i}static configure(n,r,i,s,a,o,u){return this._configureSync(n,r,i,s,a,o,u)}static _configureSync(n,r,i,s,a,o,u){var v;let l;(n||r)&&(Array.isArray(n)||!n?(l=new eo,l.setHandlers((n==null?void 0:n.map(Sc))??[],!0)):l=n,l=l.copy(Array.isArray(r)?r.map(Sc):r==null?void 0:r.handlers,!1));const c=Jn("LANGCHAIN_VERBOSE")==="true"||(u==null?void 0:u.verbose),d=Ju.getTraceableRunTree(),f=(d==null?void 0:d.tracingEnabled)??mL();if((d==null?void 0:d.tracingEnabled)===!1&&l){const y=l.handlers.filter(p=>p.name==="langchain_tracer");for(const p of y)l.removeHandler(p)}const h=f||(Jn("LANGCHAIN_TRACING")??!1);if(c||h){if(l||(l=new eo),c&&!l.handlers.some(y=>y.name===k0.prototype.name)){const y=new k0;l.addHandler(y,!0)}if(h&&!l.handlers.some(y=>y.name==="langchain_tracer")&&f){const y=new Ju;l.addHandler(y,!0)}f&&d&&l._parentRunId===void 0&&(l._parentRunId=d.id,(v=l.handlers.find(y=>y.name==="langchain_tracer"))==null||v.updateFromRunTree(d))}for(const{contextVar:y,inheritable:p=!0,handlerClass:g,envVar:b}of yL()){const E=b&&Jn(b)==="true"&&g;let T;const I=y!==void 0?lE(y):void 0;I&&i$(I)?T=I:E&&(T=new g({})),T!==void 0&&(l||(l=new eo),l.handlers.some(k=>k.name===T.name)||l.addHandler(T,p))}(i||s)&&l&&(l.addTags(i??[]),l.addTags(s??[],!1)),(a||o)&&l&&(l.addMetadata(a??{}),l.addMetadata(o??{},!1));const m=u==null?void 0:u.tracerInheritableMetadata,_=u==null?void 0:u.tracerInheritableTags;return l&&(m||_)&&(l.handlers=l.handlers.map(y=>y instanceof Ju?y.copyWithTracingConfig({metadata:m,tags:_}):y),l.inheritableHandlers=l.inheritableHandlers.map(y=>y instanceof Ju?y.copyWithTracingConfig({metadata:m,tags:_}):y)),l}};function Sc(t){return"name"in t?t:bd.fromMethods(t)}var xL=class{getStore(){}run(t,e){return e()}enterWith(t){}};const kL=new xL,E0=Symbol.for("lc:child_config");var SL=class{getInstance(){return Vo()??kL}getRunnableConfig(){var t,e;return(e=(t=this.getInstance().getStore())==null?void 0:t.extra)==null?void 0:e[E0]}runWithConfig(t,e,n){var l;const r=Rr._configureSync(t==null?void 0:t.callbacks,void 0,t==null?void 0:t.tags,void 0,t==null?void 0:t.metadata),i=this.getInstance(),s=i.getStore(),a=r==null?void 0:r.getParentRunId(),o=(l=r==null?void 0:r.handlers)==null?void 0:l.find(c=>(c==null?void 0:c.name)==="langchain_tracer");let u;return o&&a?u=o.getRunTreeWithTracingConfig(a):n||(u=new Ht({name:"<runnable_lambda>",tracingEnabled:!1})),u&&(u.extra={...u.extra,[E0]:t}),s!==void 0&&s[Nl]!==void 0&&(u===void 0&&(u={}),u[Nl]=s[Nl]),i.run(u,e)}initializeGlobalInstance(t){Vo()===void 0&&G2(t)}};const Ei=new SL,AL=new Set(["api_key"]),EL=new Set(["string","number","boolean"]);function TL(t){const e=t.configurable??{},n=t.metadata??{},r={};for(const[i,s]of Object.entries(e))!i.startsWith("__")&&!Object.prototype.hasOwnProperty.call(n,i)&&!AL.has(i)&&EL.has(typeof s)&&(r[i]=s);return Object.keys(r).length>0?r:void 0}async function Xn(t){return Rr._configureSync(t==null?void 0:t.callbacks,void 0,t==null?void 0:t.tags,void 0,t==null?void 0:t.metadata,void 0,{tracerInheritableMetadata:t?TL(t):void 0})}function T0(...t){const e={};for(const n of t.filter(r=>!!r))for(const r of Object.keys(n))if(r==="metadata")e[r]={...e[r],...n[r]};else if(r==="tags"){const i=e[r]??[];e[r]=[...new Set(i.concat(n[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...n[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=n.timeout:n.timeout!==void 0&&(e.timeout=Math.min(e.timeout,n.timeout));else if(r==="signal")e.signal===void 0?e.signal=n.signal:n.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,n.signal]):e.signal=n.signal);else if(r==="callbacks"){const i=e.callbacks,s=n.callbacks;if(Array.isArray(s))if(!i)e.callbacks=s;else if(Array.isArray(i))e.callbacks=i.concat(s);else{const a=i.copy();for(const o of s)a.addHandler(Sc(o),!0);e.callbacks=a}else if(s)if(!i)e.callbacks=s;else if(Array.isArray(i)){const a=s.copy();for(const o of i)a.addHandler(Sc(o),!0);e.callbacks=a}else e.callbacks=new Rr(s._parentRunId,{handlers:i.handlers.concat(s.handlers),inheritableHandlers:i.inheritableHandlers.concat(s.inheritableHandlers),tags:Array.from(new Set(i.tags.concat(s.tags))),inheritableTags:Array.from(new Set(i.inheritableTags.concat(s.inheritableTags))),metadata:{...i.metadata,...s.metadata}})}else{const i=r;e[i]=n[i]??e[i]}return e}function xe(t){var r;const e=Ei.getRunnableConfig();let n={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:i,runName:s,...a}=e;n=Object.entries(a).reduce((o,[u,l])=>(l!==void 0&&(o[u]=l),o),n)}if(t&&(n=Object.entries(t).reduce((i,[s,a])=>(a!==void 0&&(i[s]=a),i),n)),n!=null&&n.configurable&&typeof n.configurable.model=="string"&&((r=n.metadata)==null?void 0:r.model)===void 0&&(n.metadata||(n.metadata={}),n.metadata.model=n.configurable.model),n.timeout!==void 0){if(n.timeout<=0)throw new Error("Timeout must be a positive number");const i=n.timeout,s=AbortSignal.timeout(i);n.metadata||(n.metadata={}),n.metadata.timeoutMs===void 0&&(n.metadata.timeoutMs=i),n.signal!==void 0?"any"in AbortSignal&&(n.signal=AbortSignal.any([n.signal,s])):n.signal=s,delete n.timeout}return n}function Lt(t={},{callbacks:e,maxConcurrency:n,recursionLimit:r,runName:i,configurable:s,runId:a}={}){const o=xe(t);return e!==void 0&&(delete o.runName,o.callbacks=e),r!==void 0&&(o.recursionLimit=r),n!==void 0&&(o.maxConcurrency=n),i!==void 0&&(o.runName=i),s!==void 0&&(o.configurable={...o.configurable,...s}),a!==void 0&&delete o.runId,o}function ua(t){if(t)return{configurable:t.configurable,recursionLimit:t.recursionLimit,callbacks:t.callbacks,tags:t.tags,metadata:t.metadata,maxConcurrency:t.maxConcurrency,timeout:t.timeout,signal:t.signal,store:t.store}}async function Dr(t,e){if(e===void 0)return t;let n;return Promise.race([t.catch(r=>{if(!(e!=null&&e.aborted))throw r}),new Promise((r,i)=>{n=()=>{i(Ac(e))},e.addEventListener("abort",n,{once:!0}),e.aborted&&i(Ac(e))})]).finally(()=>e.removeEventListener("abort",n))}function Ac(t){return(t==null?void 0:t.reason)instanceof Error?t.reason:typeof(t==null?void 0:t.reason)=="string"?new Error(t.reason):new Error("Aborted")}var br=class Np extends ReadableStream{constructor(){super(...arguments);A(this,"reader")}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const n=await this.reader.read();return n.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:n.value}}catch(n){throw this.reader.releaseLock(),n}}async return(){if(this.ensureReader(),this.locked){const n=this.reader.cancel();this.reader.releaseLock(),await n}return{done:!0,value:void 0}}async throw(n){if(this.ensureReader(),this.locked){const r=this.reader.cancel();this.reader.releaseLock(),await r}throw n}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(n){const r=n.getReader();return new Np({start(i){return s();function s(){return r.read().then(({done:a,value:o})=>{if(a){i.close();return}return i.enqueue(o),s()})}},cancel(){r.releaseLock()}})}static fromAsyncGenerator(n){return new Np({async pull(r){const{value:i,done:s}=await n.next();s&&r.close(),r.enqueue(i)},async cancel(r){await n.return(r)}})}};function cE(t,e=2){const n=Array.from({length:e},()=>[]);return n.map(async function*(i){for(;;)if(i.length===0){const s=await t.next();for(const a of n)a.push(s)}else{if(i[0].done)return;yield i.shift().value}})}function Od(t,e){if(Array.isArray(t)&&Array.isArray(e))return t.concat(e);if(typeof t=="string"&&typeof e=="string")return t+e;if(typeof t=="number"&&typeof e=="number")return t+e;if("concat"in t&&typeof t.concat=="function")return t.concat(e);if(typeof t=="object"&&typeof e=="object"){const n={...t};for(const[r,i]of Object.entries(e))r in n&&!Array.isArray(n[r])?n[r]=Od(n[r],i):n[r]=i;return n}else throw new Error(`Cannot concat ${typeof t} and ${typeof e}`)}var xa=class{constructor(t){A(this,"generator");A(this,"setup");A(this,"config");A(this,"signal");A(this,"firstResult");A(this,"firstResultUsed",!1);var e;this.generator=t.generator,this.config=t.config,this.signal=t.signal??((e=this.config)==null?void 0:e.signal),this.setup=new Promise((n,r)=>{Ei.runWithConfig(ua(t.config),async()=>{this.firstResult=this.signal?Dr(t.generator.next(),this.signal):t.generator.next(),t.startSetup?this.firstResult.then(t.startSetup).then(n,r):this.firstResult.then(i=>n(void 0),r)},!0)})}async next(...t){var e;return(e=this.signal)==null||e.throwIfAborted(),this.firstResultUsed?Ei.runWithConfig(ua(this.config),this.signal?async()=>Dr(this.generator.next(...t),this.signal):async()=>this.generator.next(...t),!0):(this.firstResultUsed=!0,this.firstResult)}async return(t){return this.generator.return(t)}async throw(t){return this.generator.throw(t)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}};async function IL(t,e,n,r,...i){const s=new xa({generator:e,startSetup:n,signal:r}),a=await s.setup;return{output:t(s,a,...i),setup:a}}/*! * https://github.com/Starcounter-Jack/JSON-Patch * (c) 2017-2022 Joachim Wester * MIT licensed */const OL=Object.prototype.hasOwnProperty;function $p(t,e){return OL.call(t,e)}function Rp(t){if(Array.isArray(t)){const n=new Array(t.length);for(let r=0;r<n.length;r++)n[r]=""+r;return n}if(Object.keys)return Object.keys(t);let e=[];for(let n in t)$p(t,n)&&e.push(n);return e}function qn(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}function jp(t){let e=0;const n=t.length;let r;for(;e<n;){if(r=t.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function gs(t){return t.indexOf("/")===-1&&t.indexOf("~")===-1?t:t.replace(/~/g,"~0").replace(/\//g,"~1")}function CL(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}function Lp(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let n=0,r=t.length;n<r;n++)if(Lp(t[n]))return!0}else if(typeof t=="object"){const n=Rp(t),r=n.length;for(var e=0;e<r;e++)if(Lp(t[n[e]]))return!0}}return!1}function I0(t,e){const n=[t];for(const r in e){const i=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof i<"u"&&n.push(`${r}: ${i}`)}return n.join(` `)}var PL=class extends Error{constructor(t,e,n,r,i){super(I0(t,{name:e,index:n,operation:r,tree:i})),this.name=e,this.index=n,this.operation=r,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=I0(t,{name:e,index:n,operation:r,tree:i})}},NL=AN({JsonPatchError:()=>He,_areEquals:()=>qo,applyOperation:()=>Qi,applyPatch:()=>Ko,applyReducer:()=>jL,deepClone:()=>$L,getValueByPointer:()=>Ec,validate:()=>dE,validator:()=>Tc});const He=PL,$L=qn,zs={add:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:n}},remove:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return delete t[e],{newDocument:n,removed:r}},replace:function(t,e,n){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:function(t,e,n){let r=Ec(n,this.path);r&&(r=qn(r));const i=Qi(n,{op:"remove",path:this.from}).removed;return Qi(n,{op:"add",path:this.path,value:i}),{newDocument:n,removed:r}},copy:function(t,e,n){const r=Ec(n,this.from);return Qi(n,{op:"add",path:this.path,value:qn(r)}),{newDocument:n}},test:function(t,e,n){return{newDocument:n,test:qo(t[e],this.value)}},_get:function(t,e,n){return this.value=t[e],{newDocument:n}}};var RL={add:function(t,e,n){return jp(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:n,index:e}},remove:function(t,e,n){return{newDocument:n,removed:t.splice(e,1)[0]}},replace:function(t,e,n){var r=t[e];return t[e]=this.value,{newDocument:n,removed:r}},move:zs.move,copy:zs.copy,test:zs.test,_get:zs._get};function Ec(t,e){if(e=="")return t;var n={op:"_get",path:e};return Qi(t,n),n.value}function Qi(t,e,n=!1,r=!0,i=!0,s=0){if(n&&(typeof n=="function"?n(e,0,t,e.path):Tc(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Ec(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=qo(t,e.value),a.test===!1)throw new He("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(n)throw new He("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return a}}else{r||(t=qn(t));const a=(e.path||"").split("/");let o=t,u=1,l=a.length,c,d,f;for(typeof n=="function"?f=n:f=Tc;;){if(d=a[u],d&&d.indexOf("~")!=-1&&(d=CL(d)),i&&(d=="__proto__"||d=="prototype"&&u>0&&a[u-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(n&&c===void 0&&(o[d]===void 0?c=a.slice(0,u).join("/"):u==l-1&&(c=e.path),c!==void 0&&f(e,0,t,c)),u++,Array.isArray(o)){if(d==="-")d=o.length;else{if(n&&!jp(d))throw new He("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);jp(d)&&(d=~~d)}if(u>=l){if(n&&e.op==="add"&&d>o.length)throw new He("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);const h=RL[e.op].call(e,o,d,t);if(h.test===!1)throw new He("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return h}}else if(u>=l){const h=zs[e.op].call(e,o,d,t);if(h.test===!1)throw new He("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return h}if(o=o[d],n&&u<l&&(!o||typeof o!="object"))throw new He("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}function Ko(t,e,n,r=!0,i=!0){if(n&&!Array.isArray(e))throw new He("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(t=qn(t));const s=new Array(e.length);for(let a=0,o=e.length;a<o;a++)s[a]=Qi(t,e[a],n,!0,i,a),t=s[a].newDocument;return s.newDocument=t,s}function jL(t,e,n){const r=Qi(t,e);if(r.test===!1)throw new He("Test operation failed","TEST_OPERATION_FAILED",n,e,t);return r.newDocument}function Tc(t,e,n,r){if(typeof t!="object"||t===null||Array.isArray(t))throw new He("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,n);if(zs[t.op]){if(typeof t.path!="string")throw new He("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,n);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new He('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,n);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new He("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new He("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,n);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Lp(t.value))throw new He("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,n);if(n){if(t.op=="add"){var i=t.path.split("/").length,s=r.split("/").length;if(i!==s+1&&i!==s)throw new He("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,n)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==r)throw new He("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,n)}else if(t.op==="move"||t.op==="copy"){var a=dE([{op:"_get",path:t.from,value:void 0}],n);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new He("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,n)}}}else throw new He("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,n)}function dE(t,e,n){try{if(!Array.isArray(t))throw new He("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Ko(qn(e),qn(t),n||!0);else{n=n||Tc;for(var r=0;r<t.length;r++)n(t[r],r,e,void 0)}}catch(i){if(i instanceof He)return i;throw i}}function qo(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var n=Array.isArray(t),r=Array.isArray(e),i,s,a;if(n&&r){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!qo(t[i],e[i]))return!1;return!0}if(n!=r)return!1;var o=Object.keys(t);if(s=o.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(o[i]))return!1;for(i=s;i--!==0;)if(a=o[i],!qo(t[a],e[a]))return!1;return!0}return t!==t&&e!==e}/*! * https://github.com/Starcounter-Jack/JSON-Patch * (c) 2013-2021 Joachim Wester * MIT license */function fE(t,e,n,r,i){if(e!==t){typeof e.toJSON=="function"&&(e=e.toJSON());for(var s=Rp(e),a=Rp(t),o=!1,u=a.length-1;u>=0;u--){var l=a[u],c=t[l];if($p(e,l)&&!(e[l]===void 0&&c!==void 0&&Array.isArray(e)===!1)){var d=e[l];typeof c=="object"&&c!=null&&typeof d=="object"&&d!=null&&Array.isArray(c)===Array.isArray(d)?fE(c,d,n,r+"/"+gs(l),i):c!==d&&(i&&n.push({op:"test",path:r+"/"+gs(l),value:qn(c)}),n.push({op:"replace",path:r+"/"+gs(l),value:qn(d)}))}else Array.isArray(t)===Array.isArray(e)?(i&&n.push({op:"test",path:r+"/"+gs(l),value:qn(c)}),n.push({op:"remove",path:r+"/"+gs(l)}),o=!0):(i&&n.push({op:"test",path:r,value:t}),n.push({op:"replace",path:r,value:e}))}if(!(!o&&s.length==a.length))for(var u=0;u<s.length;u++){var l=s[u];!$p(t,l)&&e[l]!==void 0&&n.push({op:"add",path:r+"/"+gs(l),value:qn(e[l])})}}}function LL(t,e,n=!1){var r=[];return fE(t,e,r,"",n),r}({...NL});var ti=class{constructor(t){A(this,"ops");this.ops=t.ops??[]}concat(t){const e=this.ops.concat(t.ops),n=Ko({},e);return new hE({ops:e,state:n[n.length-1].newDocument})}},hE=class Mp extends ti{constructor(n){super(n);A(this,"state");this.state=n.state}concat(n){const r=this.ops.concat(n.ops),i=Ko(this.state,n.ops);return new Mp({ops:r,state:i[i.length-1].newDocument})}static fromRunLogPatch(n){const r=Ko({},n.ops);return new Mp({ops:n.ops,state:r[r.length-1].newDocument})}};const ML=t=>t.name==="log_stream_tracer";async function O0(t,e){if(e==="original")throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events.");const{inputs:n}=t;if(["retriever","llm","prompt"].includes(t.run_type))return n;if(!(Object.keys(n).length===1&&(n==null?void 0:n.input)===""))return n.input}async function C0(t,e){const{outputs:n}=t;return e==="original"||["retriever","llm","prompt"].includes(t.run_type)?n:n!==void 0&&Object.keys(n).length===1&&(n==null?void 0:n.output)!==void 0?n.output:n}function zL(t){return t!==void 0&&t.message!==void 0}var P0=class extends du{constructor(e){super({_awaitHandler:!0,...e});A(this,"autoClose",!0);A(this,"includeNames");A(this,"includeTypes");A(this,"includeTags");A(this,"excludeNames");A(this,"excludeTypes");A(this,"excludeTags");A(this,"_schemaFormat","original");A(this,"rootId");A(this,"keyMapByRunId",{});A(this,"counterMapByRunName",{});A(this,"transformStream");A(this,"writer");A(this,"receiveStream");A(this,"name","log_stream_tracer");A(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this._schemaFormat=(e==null?void 0:e._schemaFormat)??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=br.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const n=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.run_type)),this.includeTags!==void 0&&(r=r||n.find(i=>{var s;return(s=this.includeTags)==null?void 0:s.includes(i)})!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.run_type)),this.excludeTags!==void 0&&(r=r&&n.every(i=>{var s;return!((s=this.excludeTags)!=null&&s.includes(i))})),r}async*tapOutputIterable(e,n){for await(const r of n){if(e!==this.rootId){const i=this.keyMapByRunId[e];i&&await this.writer.write(new ti({ops:[{op:"add",path:`/logs/${i}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){var i;if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new ti({ops:[{op:"replace",path:"",value:{id:e.id,name:e.name,type:e.run_type,streamed_output:[],final_output:void 0,logs:{}}}]}))),!this._includeRun(e))return;this.counterMapByRunName[e.name]===void 0&&(this.counterMapByRunName[e.name]=0),this.counterMapByRunName[e.name]+=1;const n=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=n===1?e.name:`${e.name}:${n}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{},start_time:new Date(e.start_time).toISOString(),streamed_output:[],streamed_output_str:[],final_output:void 0,end_time:void 0};this._schemaFormat==="streaming_events"&&(r.inputs=await O0(e,this._schemaFormat)),await this.writer.write(new ti({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const n=this.keyMapByRunId[e.id];if(n===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${n}/inputs`,value:await O0(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${n}/final_output`,value:await C0(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${n}/end_time`,value:new Date(e.end_time).toISOString()});const i=new ti({ops:r});await this.writer.write(i)}finally{if(e.id===this.rootId){const n=new ti({ops:[{op:"replace",path:"/final_output",value:await C0(e,this._schemaFormat)}]});await this.writer.write(n),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,n,r){const i=this.keyMapByRunId[e.id];if(i===void 0)return;const s=e.inputs.messages!==void 0;let a;s?zL(r==null?void 0:r.chunk)?a=r==null?void 0:r.chunk:a=new vr({id:`run-${e.id}`,content:n}):a=n;const o=new ti({ops:[{op:"add",path:`/logs/${i}/streamed_output_str/-`,value:n},{op:"add",path:`/logs/${i}/streamed_output/-`,value:a}]});await this.writer.write(o)}};const N0="__run";var Ic=class pE{constructor(e){A(this,"text");A(this,"generationInfo");this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new pE({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}},Wo=class mE extends Ic{constructor(n){super(n);A(this,"message");this.message=n.message}concat(n){return new mE({text:this.text+n.text,generationInfo:{...this.generationInfo,...n.generationInfo},message:this.message.concat(n.message)})}};function Xu({name:t,serialized:e}){return t!==void 0?t:(e==null?void 0:e.name)!==void 0?e.name:(e==null?void 0:e.id)!==void 0&&Array.isArray(e==null?void 0:e.id)?e.id[e.id.length-1]:"Unnamed"}const DL=t=>t.name==="event_stream_tracer";var UL=class extends du{constructor(e){super({_awaitHandler:!0,...e});A(this,"autoClose",!0);A(this,"includeNames");A(this,"includeTypes");A(this,"includeTags");A(this,"excludeNames");A(this,"excludeTypes");A(this,"excludeTags");A(this,"runInfoMap",new Map);A(this,"tappedPromises",new Map);A(this,"transformStream");A(this,"writer");A(this,"receiveStream");A(this,"readableStreamClosed",!1);A(this,"name","event_stream_tracer");A(this,"lc_prefer_streaming",!0);this.autoClose=(e==null?void 0:e.autoClose)??!0,this.includeNames=e==null?void 0:e.includeNames,this.includeTypes=e==null?void 0:e.includeTypes,this.includeTags=e==null?void 0:e.includeTags,this.excludeNames=e==null?void 0:e.excludeNames,this.excludeTypes=e==null?void 0:e.excludeTypes,this.excludeTags=e==null?void 0:e.excludeTags,this.transformStream=new TransformStream({flush:()=>{this.readableStreamClosed=!0}}),this.writer=this.transformStream.writable.getWriter(),this.receiveStream=br.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const n=e.tags??[];let r=this.includeNames===void 0&&this.includeTags===void 0&&this.includeTypes===void 0;return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(e.runType)),this.includeTags!==void 0&&(r=r||n.find(i=>{var s;return(s=this.includeTags)==null?void 0:s.includes(i)})!==void 0),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(e.runType)),this.excludeTags!==void 0&&(r=r&&n.every(i=>{var s;return!((s=this.excludeTags)!=null&&s.includes(i))})),r}async*tapOutputIterable(e,n){const r=await n.next();if(r.done)return;const i=this.runInfoMap.get(e);if(i===void 0){yield r.value;return}function s(o,u){return o==="llm"&&typeof u=="string"?new Ic({text:u}):u}let a=this.tappedPromises.get(e);if(a===void 0){let o;a=new Promise(u=>{o=u}),this.tappedPromises.set(e,a);try{const u={event:`on_${i.runType}_stream`,run_id:e,name:i.name,tags:i.tags,metadata:i.metadata,data:{}};await this.send({...u,data:{chunk:s(i.runType,r.value)}},i),yield r.value;for await(const l of n)i.runType!=="tool"&&i.runType!=="retriever"&&await this.send({...u,data:{chunk:s(i.runType,l)}},i),yield l}finally{o==null||o()}}else{yield r.value;for await(const o of n)yield o}}async send(e,n){this.readableStreamClosed||this._includeRun(n)&&await this.writer.write(e)}async sendEndEvent(e,n){const r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,n)}):await this.send(e,n)}async onLLMStart(e){var a,o;const n=Xu(e),r=e.inputs.messages!==void 0?"chat_model":"llm",i={tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},name:n,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,i);const s=`on_${r}_start`;await this.send({event:s,data:{input:e.inputs},name:n,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},i)}async onLLMNewToken(e,n,r){const i=this.runInfoMap.get(e.id);let s,a;if(i===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(i.runType==="chat_model")a="on_chat_model_stream",(r==null?void 0:r.chunk)===void 0?s=new vr({content:n,id:`run-${e.id}`}):s=r.chunk.message;else if(i.runType==="llm")a="on_llm_stream",(r==null?void 0:r.chunk)===void 0?s=new Ic({text:n}):s=r.chunk;else throw new Error(`Unexpected run type ${i.runType}`);await this.send({event:a,data:{chunk:s},run_id:e.id,name:i.name,tags:i.tags,metadata:i.metadata},i)}}async onLLMEnd(e){var a,o,u;const n=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(n===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const i=(a=e.outputs)==null?void 0:a.generations;let s;if(n.runType==="chat_model"){for(const l of i??[]){if(s!==void 0)break;s=(o=l[0])==null?void 0:o.message}r="on_chat_model_end"}else if(n.runType==="llm")s={generations:i==null?void 0:i.map(l=>l.map(c=>({text:c.text,generationInfo:c.generationInfo}))),llmOutput:((u=e.outputs)==null?void 0:u.llmOutput)??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${n.runType}`);await this.sendEndEvent({event:r,data:{output:s,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onChainStart(e){var a,o;const n=Xu(e),r=e.run_type??"chain",i={tags:e.tags??[],metadata:((a=e.extra)==null?void 0:a.metadata)??{},name:n,runType:e.run_type};let s={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(s={},i.inputs={}):e.inputs.input!==void 0?(s.input=e.inputs.input,i.inputs=e.inputs.input):(s.input=e.inputs,i.inputs=e.inputs),this.runInfoMap.set(e.id,i),await this.send({event:`on_${r}_start`,data:s,name:n,tags:e.tags??[],run_id:e.id,metadata:((o=e.extra)==null?void 0:o.metadata)??{}},i)}async onChainEnd(e){var a;const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,i=e.inputs??n.inputs??{},s={output:((a=e.outputs)==null?void 0:a.output)??e.outputs,input:i};i.input&&Object.keys(i).length===1&&(s.input=i.input,n.inputs=i.input),await this.sendEndEvent({event:r,data:s,run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata??{}},n)}async onToolStart(e){var i,s;const n=Xu(e),r={tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{},name:n,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:n,run_id:e.id,tags:e.tags??[],metadata:((s=e.extra)==null?void 0:s.metadata)??{}},r)}async onToolEnd(e){var i;const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=((i=e.outputs)==null?void 0:i.output)===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onToolError(e){const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(n.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);await this.sendEndEvent({event:"on_tool_error",data:{input:n.inputs,error:e.error},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async onRetrieverStart(e){var i,s;const n=Xu(e),r={tags:e.tags??[],metadata:((i=e.extra)==null?void 0:i.metadata)??{},name:n,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,r),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:n,tags:e.tags??[],run_id:e.id,metadata:((s=e.extra)==null?void 0:s.metadata)??{}},r)}async onRetrieverEnd(e){var r;const n=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),n===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:((r=e.outputs)==null?void 0:r.documents)??e.outputs,input:n.inputs},run_id:e.id,name:n.name,tags:n.tags,metadata:n.metadata},n)}async handleCustomEvent(e,n,r){const i=this.runInfoMap.get(r);if(i===void 0)throw new Error(`handleCustomEvent: Run ID ${r} not found in run map.`);await this.send({event:"on_custom_event",run_id:r,name:e,tags:i.tags,metadata:i.metadata,data:n},i)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}};const FL=Object.prototype.toString,BL=t=>FL.call(t)==="[object Error]",HL=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function ZL(t){if(!(t&&BL(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;const{message:e,stack:n}=t;return e==="Load failed"?n===void 0||"__sentry_captured__"in t:e.startsWith("error sending request for url")?!0:HL.has(e)}function VL(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}function Qu(t,e,{min:n=0,allowInfinity:r=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${r?" or Infinity":""}.`);if(!r&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<n)throw new TypeError(`Expected \`${t}\` to be ≥ ${n}.`)}}var KL=class extends Error{constructor(t){super(),t instanceof Error?(this.originalError=t,{message:t}=t):(this.originalError=new Error(t),this.originalError.stack=this.stack),this.name="AbortError",this.message=t}};function qL(t,e){const n=Math.max(1,t+1),r=e.randomize?Math.random()+1:1;let i=Math.round(r*e.minTimeout*e.factor**(n-1));return i=Math.min(i,e.maxTimeout),i}function $0(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}async function WL({error:t,attemptNumber:e,retriesConsumed:n,startTime:r,options:i}){var m,_,v;const s=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(s instanceof KL)throw s.originalError;const a=Number.isFinite(i.retries)?Math.max(0,i.retries-n):i.retries,o=i.maxRetryTime??Number.POSITIVE_INFINITY,u=Object.freeze({error:s,attemptNumber:e,retriesLeft:a,retriesConsumed:n});if(await i.onFailedAttempt(u),$0(r,o)<=0)throw s;const l=await i.shouldConsumeRetry(u),c=$0(r,o);if(c<=0||a<=0)throw s;if(s instanceof TypeError&&!ZL(s)){if(l)throw s;return(m=i.signal)==null||m.throwIfAborted(),!1}if(!await i.shouldRetry(u))throw s;if(!l)return(_=i.signal)==null||_.throwIfAborted(),!1;let d=qL(n,i);const f=typeof s.retryAfterMs=="number"&&s.retryAfterMs>=0?s.retryAfterMs:void 0;f!==void 0&&(d=Math.max(d,f));const h=Math.min(d,c);return h>0&&await new Promise((y,p)=>{var E,T;const g=()=>{var I;clearTimeout(b),(I=i.signal)==null||I.removeEventListener("abort",g),p(i.signal.reason)},b=setTimeout(()=>{var I;(I=i.signal)==null||I.removeEventListener("abort",g),y()},h);i.unref&&((E=b.unref)==null||E.call(b)),(T=i.signal)==null||T.addEventListener("abort",g,{once:!0})}),(v=i.signal)==null||v.throwIfAborted(),!0}async function zp(t,e={}){var s,a,o;if(e={...e},VL(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??(e.retries=10),e.factor??(e.factor=2),e.minTimeout??(e.minTimeout=1e3),e.maxTimeout??(e.maxTimeout=Number.POSITIVE_INFINITY),e.maxRetryTime??(e.maxRetryTime=Number.POSITIVE_INFINITY),e.randomize??(e.randomize=!1),e.onFailedAttempt??(e.onFailedAttempt=()=>{}),e.shouldRetry??(e.shouldRetry=()=>!0),e.shouldConsumeRetry??(e.shouldConsumeRetry=()=>!0),Qu("factor",e.factor,{min:0,allowInfinity:!1}),Qu("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),Qu("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),Qu("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),(s=e.signal)==null||s.throwIfAborted();let n=0,r=0;const i=performance.now();for(;!Number.isFinite(e.retries)||r<=e.retries;){n++;try{(a=e.signal)==null||a.throwIfAborted();const u=await t(n);return(o=e.signal)==null||o.throwIfAborted(),u}catch(u){await WL({error:u,attemptNumber:n,retriesConsumed:r,startTime:i,options:e})&&r++}}throw new Error("Retry attempts exhausted without throwing an error.")}const GL=[400,401,402,403,404,405,406,407,409],JL=6e4,XL=[/insufficient[_ -]?quota/i,/exceeded (?:your|the current|the available).+quota/i,/usage quota/i,/quota (?:has been )?exhausted/i,/billing/i,/credit balance/i,/out of credits/i,/will reset at/i],QL=/(?:try again in|retry after)\s+(\d+(?:\.\d+)?)\s*(milliseconds?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h)\b/i;function gE(t){return typeof t=="object"&&t!==null&&"response"in t&&typeof t.response=="object"&&t.response!==null&&"status"in t.response&&typeof t.response.status=="number"?t.response.status:void 0}function yE(t){if(!(typeof t!="object"||t===null)){if("status"in t&&typeof t.status=="number")return t.status;if("statusCode"in t&&typeof t.statusCode=="number")return t.statusCode}}function Dp(t){return typeof t=="object"&&t!==null&&"message"in t&&typeof t.message=="string"?t.message:void 0}function _E(t){if(!(typeof t!="object"||t===null))return"code"in t&&typeof t.code=="string"?t.code:"error"in t&&typeof t.error=="object"&&t.error!==null&&"code"in t.error&&typeof t.error.code=="string"?t.error.code:void 0}function YL(t){var e;if(t!=null&&t.headers)return typeof t.headers.get=="function"?t.headers.get("retry-after"):t.headers["retry-after"]??t.headers["Retry-After"];if((e=t==null?void 0:t.response)!=null&&e.headers)return typeof t.response.headers.get=="function"?t.response.headers.get("retry-after"):t.response.headers["retry-after"]??t.response.headers["Retry-After"]}function eM(t){var i;if(t==null)return;const e=QL.exec(t);if(!e)return;const n=Number(e[1]),r=(i=e[2])==null?void 0:i.toLowerCase();if(!(Number.isNaN(n)||!r))return r==="ms"||r.startsWith("millisecond")?n:r==="m"||r.startsWith("min")?n*6e4:r==="h"||r.startsWith("hr")||r.startsWith("hour")?n*36e5:n*1e3}function R0(t,e){if(t instanceof Error)return t;const n=new Error(e);return typeof t=="object"&&t!==null&&Object.assign(n,t),n}function qf(t,e){if(typeof t!="object"||t===null)return;const n=t;n.rateLimitType=e.action,n.rateLimitReason=e.reason,e.retryAfterMs!==void 0&&(n.retryAfterMs=e.retryAfterMs)}function tM(t){if(t==null)return;const e=t.trim();if(!e)return;const n=Number(e);if(!Number.isNaN(n)&&n>=0)return n*1e3;const r=Date.parse(e);if(!Number.isNaN(r)){const i=r-Date.now();return i>0?i:0}}function nM(t){if((gE(t)??yE(t))!==429)return;if(_E(t)==="insufficient_quota")return{action:"stop",reason:"insufficient_quota"};const e=Dp(t);if(e&&XL.some(r=>r.test(e)))return{action:"stop",reason:"quota_message"};const n=tM(YL(t))??eM(e);return n!==void 0?n<=JL?{action:"wait",retryAfterMs:n,reason:"retry_after_hint"}:{action:"capacity",retryAfterMs:n,reason:"retry_after_too_large"}:{action:"capacity",reason:"headerless_429"}}const rM=t=>{if(typeof t!="object"||t===null)return;if("message"in t&&typeof t.message=="string"&&(t.message.startsWith("Cancel")||t.message.startsWith("AbortError"))||"name"in t&&typeof t.name=="string"&&t.name==="AbortError"||"code"in t&&typeof t.code=="string"&&t.code==="ECONNABORTED")throw t;const e=gE(t)??yE(t);if(e&&GL.includes(+e))throw t;if(_E(t)==="insufficient_quota"){const r=R0(t,Dp(t)??"Insufficient quota");throw r.name="InsufficientQuotaError",qf(r,{action:"stop",reason:"insufficient_quota"}),r}const n=nM(t);if(n){if(n.action==="wait"){qf(t,n);return}const r=R0(t,Dp(t)??"Rate limit exceeded");throw r.name==="Error"&&(r.name=n.action==="stop"?"RateLimitQuotaExhaustedError":"RateLimitCapacityError"),qf(r,n),r}};var Cd=class{constructor(t){A(this,"maxConcurrency");A(this,"maxRetries");A(this,"onFailedAttempt");A(this,"queue");this.maxConcurrency=t.maxConcurrency??1/0,this.maxRetries=t.maxRetries??6,this.onFailedAttempt=t.onFailedAttempt??rM;const e="default"in $r?$r.default:$r;this.queue=new e({concurrency:this.maxConcurrency})}async call(t,...e){return this.queue.add(()=>zp(()=>t(...e).catch(n=>{throw n instanceof Error?n:new Error(n)}),{onFailedAttempt:({error:n})=>{var r;return(r=this.onFailedAttempt)==null?void 0:r.call(this,n)},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(t,e,...n){if(t.signal){let r;return Promise.race([this.call(e,...n),new Promise((i,s)=>{var a;r=()=>{s(Ac(t.signal))},(a=t.signal)==null||a.addEventListener("abort",r,{once:!0})})]).finally(()=>{t.signal&&r&&t.signal.removeEventListener("abort",r)})}return this.call(e,...n)}fetch(...t){return this.call(()=>fetch(...t).then(e=>e.ok?e:Promise.reject(e)))}},vE=class extends du{constructor({config:e,onStart:n,onEnd:r,onError:i}){super({_awaitHandler:!0});A(this,"name","RootListenersTracer");A(this,"rootId");A(this,"config");A(this,"argOnStart");A(this,"argOnEnd");A(this,"argOnError");this.config=e,this.argOnStart=n,this.argOnEnd=r,this.argOnError=i}persistRun(e){return Promise.resolve()}async onRunCreate(e){this.rootId||(this.rootId=e.id,this.argOnStart&&await this.argOnStart(e,this.config))}async onRunUpdate(e){e.id===this.rootId&&(e.error?this.argOnError&&await this.argOnError(e,this.config):this.argOnEnd&&await this.argOnEnd(e,this.config))}};function ry(t){return t?t.lc_runnable:!1}var iM=class{constructor(t){A(this,"includeNames");A(this,"includeTypes");A(this,"includeTags");A(this,"excludeNames");A(this,"excludeTypes");A(this,"excludeTags");this.includeNames=t.includeNames,this.includeTypes=t.includeTypes,this.includeTags=t.includeTags,this.excludeNames=t.excludeNames,this.excludeTypes=t.excludeTypes,this.excludeTags=t.excludeTags}includeEvent(t,e){let n=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const r=t.tags??[];return this.includeNames!==void 0&&(n=n||this.includeNames.includes(t.name)),this.includeTypes!==void 0&&(n=n||this.includeTypes.includes(e)),this.includeTags!==void 0&&(n=n||r.some(i=>{var s;return(s=this.includeTags)==null?void 0:s.includes(i)})),this.excludeNames!==void 0&&(n=n&&!this.excludeNames.includes(t.name)),this.excludeTypes!==void 0&&(n=n&&!this.excludeTypes.includes(e)),this.excludeTags!==void 0&&(n=n&&r.every(i=>{var s;return!((s=this.excludeTags)!=null&&s.includes(i))})),n}};const sM=t=>btoa(t).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");var j0;function R(t,e,n){function r(o,u){if(o._zod||Object.defineProperty(o,"_zod",{value:{def:u,constr:a,traits:new Set},enumerable:!1}),o._zod.traits.has(t))return;o._zod.traits.add(t),e(o,u);const l=a.prototype,c=Object.keys(l);for(let d=0;d<c.length;d++){const f=c[d];f in o||(o[f]=l[f].bind(o))}}const i=(n==null?void 0:n.Parent)??Object;class s extends i{}Object.defineProperty(s,"name",{value:t});function a(o){var u;const l=n!=null&&n.Parent?new s:this;r(l,o),(u=l._zod).deferred??(u.deferred=[]);for(const c of l._zod.deferred)c();return l}return Object.defineProperty(a,"init",{value:r}),Object.defineProperty(a,Symbol.hasInstance,{value:o=>{var u,l;return n!=null&&n.Parent&&o instanceof n.Parent?!0:(l=(u=o==null?void 0:o._zod)==null?void 0:u.traits)==null?void 0:l.has(t)}}),Object.defineProperty(a,"name",{value:t}),a}class Js extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class wE extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name="ZodEncodeError"}}(j0=globalThis).__zod_globalConfig??(j0.__zod_globalConfig={});const iy=globalThis.__zod_globalConfig;function Ur(t){return iy}function bE(t){const e=Object.values(t).filter(r=>typeof r=="number");return Object.entries(t).filter(([r,i])=>e.indexOf(+r)===-1).map(([r,i])=>i)}function Up(t,e){return typeof e=="bigint"?e.toString():e}function sy(t){return{get value(){{const e=t();return Object.defineProperty(this,"value",{value:e}),e}}}}function ay(t){return t==null}function oy(t){const e=t.startsWith("^")?1:0,n=t.endsWith("$")?t.length-1:t.length;return t.slice(e,n)}function aM(t,e){const n=t/e,r=Math.round(n),i=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}const L0=Symbol("evaluating");function Te(t,e,n){let r;Object.defineProperty(t,e,{get(){if(r!==L0)return r===void 0&&(r=L0,r=n()),r},set(i){Object.defineProperty(t,e,{value:i})},configurable:!0})}function ds(t,e,n){Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Ni(...t){const e={};for(const n of t){const r=Object.getOwnPropertyDescriptors(n);Object.assign(e,r)}return Object.defineProperties({},e)}function M0(t){return JSON.stringify(t)}function oM(t){return t.toLowerCase().trim().replace(/[^\w\s-]/g,"").replace(/[\s_-]+/g,"-").replace(/^-+|-+$/g,"")}const xE="captureStackTrace"in Error?Error.captureStackTrace:(...t)=>{};function Oc(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}const uM=sy(()=>{var t;if(iy.jitless||typeof navigator<"u"&&((t=navigator==null?void 0:navigator.userAgent)!=null&&t.includes("Cloudflare")))return!1;try{const e=Function;return new e(""),!0}catch{return!1}});function la(t){if(Oc(t)===!1)return!1;const e=t.constructor;if(e===void 0||typeof e!="function")return!0;const n=e.prototype;return!(Oc(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function kE(t){return la(t)?{...t}:Array.isArray(t)?[...t]:t instanceof Map?new Map(t):t instanceof Set?new Set(t):t}const lM=new Set(["string","number","symbol"]);function ca(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Jt(t,e,n){const r=new t._zod.constr(e??t._zod.def);return(!e||n!=null&&n.parent)&&(r._zod.parent=t),r}function ee(t){const e=t;if(!e)return{};if(typeof e=="string")return{error:()=>e};if((e==null?void 0:e.message)!==void 0){if((e==null?void 0:e.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");e.error=e.message}return delete e.message,typeof e.error=="string"?{...e,error:()=>e.error}:e}function cM(t){return Object.keys(t).filter(e=>t[e]._zod.optin==="optional"&&t[e]._zod.optout==="optional")}const dM={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function fM(t,e){const n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const s=Ni(t._zod.def,{get shape(){const a={};for(const o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&(a[o]=n.shape[o])}return ds(this,"shape",a),a},checks:[]});return Jt(t,s)}function hM(t,e){const n=t._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const s=Ni(t._zod.def,{get shape(){const a={...t._zod.def.shape};for(const o in e){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);e[o]&&delete a[o]}return ds(this,"shape",a),a},checks:[]});return Jt(t,s)}function pM(t,e){if(!la(e))throw new Error("Invalid input to extend: expected a plain object");const n=t._zod.def.checks;if(n&&n.length>0){const s=t._zod.def.shape;for(const a in e)if(Object.getOwnPropertyDescriptor(s,a)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const i=Ni(t._zod.def,{get shape(){const s={...t._zod.def.shape,...e};return ds(this,"shape",s),s}});return Jt(t,i)}function mM(t,e){if(!la(e))throw new Error("Invalid input to safeExtend: expected a plain object");const n=Ni(t._zod.def,{get shape(){const r={...t._zod.def.shape,...e};return ds(this,"shape",r),r}});return Jt(t,n)}function gM(t,e){var r;if((r=t._zod.def.checks)!=null&&r.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=Ni(t._zod.def,{get shape(){const i={...t._zod.def.shape,...e._zod.def.shape};return ds(this,"shape",i),i},get catchall(){return e._zod.def.catchall},checks:e._zod.def.checks??[]});return Jt(t,n)}function yM(t,e,n){const i=e._zod.def.checks;if(i&&i.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const a=Ni(e._zod.def,{get shape(){const o=e._zod.def.shape,u={...o};if(n)for(const l in n){if(!(l in o))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(u[l]=t?new t({type:"optional",innerType:o[l]}):o[l])}else for(const l in o)u[l]=t?new t({type:"optional",innerType:o[l]}):o[l];return ds(this,"shape",u),u},checks:[]});return Jt(e,a)}function _M(t,e,n){const r=Ni(e._zod.def,{get shape(){const i=e._zod.def.shape,s={...i};if(n)for(const a in n){if(!(a in s))throw new Error(`Unrecognized key: "${a}"`);n[a]&&(s[a]=new t({type:"nonoptional",innerType:i[a]}))}else for(const a in i)s[a]=new t({type:"nonoptional",innerType:i[a]});return ds(this,"shape",s),s}});return Jt(e,r)}function Ds(t,e=0){var n;if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(((n=t.issues[r])==null?void 0:n.continue)!==!0)return!0;return!1}function vM(t,e=0){var n;if(t.aborted===!0)return!0;for(let r=e;r<t.issues.length;r++)if(((n=t.issues[r])==null?void 0:n.continue)===!1)return!0;return!1}function Us(t,e){return e.map(n=>{var r;return(r=n).path??(r.path=[]),n.path.unshift(t),n})}function Yu(t){return typeof t=="string"?t:t==null?void 0:t.message}function Fr(t,e,n){var u,l,c,d,f,h;const r=t.message?t.message:Yu((c=(l=(u=t.inst)==null?void 0:u._zod.def)==null?void 0:l.error)==null?void 0:c.call(l,t))??Yu((d=e==null?void 0:e.error)==null?void 0:d.call(e,t))??Yu((f=n.customError)==null?void 0:f.call(n,t))??Yu((h=n.localeError)==null?void 0:h.call(n,t))??"Invalid input",{inst:i,continue:s,input:a,...o}=t;return o.path??(o.path=[]),o.message=r,e!=null&&e.reportInput&&(o.input=a),o}function uy(t){return Array.isArray(t)?"array":typeof t=="string"?"string":"unknown"}function Go(...t){const[e,n,r]=t;return typeof e=="string"?{message:e,code:"custom",input:n,inst:r}:{...e}}const SE=(t,e)=>{t.name="$ZodError",Object.defineProperty(t,"_zod",{value:t._zod,enumerable:!1}),Object.defineProperty(t,"issues",{value:e,enumerable:!1}),t.message=JSON.stringify(e,Up,2),Object.defineProperty(t,"toString",{value:()=>t.message,enumerable:!1})},AE=R("$ZodError",SE),Pd=R("$ZodError",SE,{Parent:Error});function wM(t,e=n=>n.message){const n={},r=[];for(const i of t.issues)i.path.length>0?(n[i.path[0]]=n[i.path[0]]||[],n[i.path[0]].push(e(i))):r.push(e(i));return{formErrors:r,fieldErrors:n}}function bM(t,e=n=>n.message){const n={_errors:[]},r=(i,s=[])=>{for(const a of i.issues)if(a.code==="invalid_union"&&a.errors.length)a.errors.map(o=>r({issues:o},[...s,...a.path]));else if(a.code==="invalid_key")r({issues:a.issues},[...s,...a.path]);else if(a.code==="invalid_element")r({issues:a.issues},[...s,...a.path]);else{const o=[...s,...a.path];if(o.length===0)n._errors.push(e(a));else{let u=n,l=0;for(;l<o.length;){const c=o[l];l===o.length-1?(u[c]=u[c]||{_errors:[]},u[c]._errors.push(e(a))):u[c]=u[c]||{_errors:[]},u=u[c],l++}}}};return r(t),n}const Nd=t=>(e,n,r,i)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:n,issues:[]},s);if(a instanceof Promise)throw new Js;if(a.issues.length){const o=new((i==null?void 0:i.Err)??t)(a.issues.map(u=>Fr(u,s,Ur())));throw xE(o,i==null?void 0:i.callee),o}return a.value},xM=Nd(Pd),$d=t=>async(e,n,r,i)=>{const s=r?{...r,async:!0}:{async:!0};let a=e._zod.run({value:n,issues:[]},s);if(a instanceof Promise&&(a=await a),a.issues.length){const o=new((i==null?void 0:i.Err)??t)(a.issues.map(u=>Fr(u,s,Ur())));throw xE(o,i==null?void 0:i.callee),o}return a.value},EE=$d(Pd),Rd=t=>(e,n,r)=>{const i=r?{...r,async:!1}:{async:!1},s=e._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw new Js;return s.issues.length?{success:!1,error:new(t??AE)(s.issues.map(a=>Fr(a,i,Ur())))}:{success:!0,data:s.value}},kM=Rd(Pd),jd=t=>async(e,n,r)=>{const i=r?{...r,async:!0}:{async:!0};let s=e._zod.run({value:n,issues:[]},i);return s instanceof Promise&&(s=await s),s.issues.length?{success:!1,error:new t(s.issues.map(a=>Fr(a,i,Ur())))}:{success:!0,data:s.value}},SM=jd(Pd),AM=t=>(e,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Nd(t)(e,n,i)},EM=t=>(e,n,r)=>Nd(t)(e,n,r),TM=t=>async(e,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return $d(t)(e,n,i)},IM=t=>async(e,n,r)=>$d(t)(e,n,r),OM=t=>(e,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return Rd(t)(e,n,i)},CM=t=>(e,n,r)=>Rd(t)(e,n,r),PM=t=>async(e,n,r)=>{const i=r?{...r,direction:"backward"}:{direction:"backward"};return jd(t)(e,n,i)},NM=t=>async(e,n,r)=>jd(t)(e,n,r),$M=/^[cC][0-9a-z]{6,}$/,RM=/^[0-9a-z]+$/,jM=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,LM=/^[0-9a-vA-V]{20}$/,MM=/^[A-Za-z0-9]{27}$/,zM=/^[a-zA-Z0-9_-]{21}$/,DM=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,UM=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,z0=t=>t?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${t}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,FM=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,BM="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function HM(){return new RegExp(BM,"u")}const ZM=/^(?:(?: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])$/,VM=/^(([0-9a-fA-F]{1,4}:){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}|:))$/,KM=/^((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])\/([0-9]|[1-2][0-9]|3[0-2])$/,qM=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,WM=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,TE=/^[A-Za-z0-9_-]*$/,GM=/^https?$/,JM=/^\+[1-9]\d{6,14}$/,IE="(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))",XM=new RegExp(`^${IE}$`);function OE(t){const e="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof t.precision=="number"?t.precision===-1?`${e}`:t.precision===0?`${e}:[0-5]\\d`:`${e}:[0-5]\\d\\.\\d{${t.precision}}`:`${e}(?::[0-5]\\d(?:\\.\\d+)?)?`}function QM(t){return new RegExp(`^${OE(t)}$`)}function YM(t){const e=OE({precision:t.precision}),n=["Z"];t.local&&n.push(""),t.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${e}(?:${n.join("|")})`;return new RegExp(`^${IE}T(?:${r})$`)}const ez=t=>{const e=t?`[\\s\\S]{${(t==null?void 0:t.minimum)??0},${(t==null?void 0:t.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${e}$`)},tz=/^-?\d+$/,CE=/^-?\d+(?:\.\d+)?$/,nz=/^[^A-Z]*$/,rz=/^[^a-z]*$/,nn=R("$ZodCheck",(t,e)=>{var n;t._zod??(t._zod={}),t._zod.def=e,(n=t._zod).onattach??(n.onattach=[])}),PE={number:"number",bigint:"bigint",object:"date"},NE=R("$ZodCheckLessThan",(t,e)=>{nn.init(t,e);const n=PE[typeof e.value];t._zod.onattach.push(r=>{const i=r._zod.bag,s=(e.inclusive?i.maximum:i.exclusiveMaximum)??Number.POSITIVE_INFINITY;e.value<s&&(e.inclusive?i.maximum=e.value:i.exclusiveMaximum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value<=e.value:r.value<e.value)||r.issues.push({origin:n,code:"too_big",maximum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),$E=R("$ZodCheckGreaterThan",(t,e)=>{nn.init(t,e);const n=PE[typeof e.value];t._zod.onattach.push(r=>{const i=r._zod.bag,s=(e.inclusive?i.minimum:i.exclusiveMinimum)??Number.NEGATIVE_INFINITY;e.value>s&&(e.inclusive?i.minimum=e.value:i.exclusiveMinimum=e.value)}),t._zod.check=r=>{(e.inclusive?r.value>=e.value:r.value>e.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof e.value=="object"?e.value.getTime():e.value,input:r.value,inclusive:e.inclusive,inst:t,continue:!e.abort})}}),iz=R("$ZodCheckMultipleOf",(t,e)=>{nn.init(t,e),t._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=e.value)}),t._zod.check=n=>{if(typeof n.value!=typeof e.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%e.value===BigInt(0):aM(n.value,e.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:e.value,input:n.value,inst:t,continue:!e.abort})}}),sz=R("$ZodCheckNumberFormat",(t,e)=>{var a;nn.init(t,e),e.format=e.format||"float64";const n=(a=e.format)==null?void 0:a.includes("int"),r=n?"int":"number",[i,s]=dM[e.format];t._zod.onattach.push(o=>{const u=o._zod.bag;u.format=e.format,u.minimum=i,u.maximum=s,n&&(u.pattern=tz)}),t._zod.check=o=>{const u=o.value;if(n){if(!Number.isInteger(u)){o.issues.push({expected:r,format:e.format,code:"invalid_type",continue:!1,input:u,inst:t});return}if(!Number.isSafeInteger(u)){u>0?o.issues.push({input:u,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort}):o.issues.push({input:u,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:t,origin:r,inclusive:!0,continue:!e.abort});return}}u<i&&o.issues.push({origin:"number",input:u,code:"too_small",minimum:i,inclusive:!0,inst:t,continue:!e.abort}),u>s&&o.issues.push({origin:"number",input:u,code:"too_big",maximum:s,inclusive:!0,inst:t,continue:!e.abort})}}),az=R("$ZodCheckMaxLength",(t,e)=>{var n;nn.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!ay(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag.maximum??Number.POSITIVE_INFINITY;e.maximum<i&&(r._zod.bag.maximum=e.maximum)}),t._zod.check=r=>{const i=r.value;if(i.length<=e.maximum)return;const a=uy(i);r.issues.push({origin:a,code:"too_big",maximum:e.maximum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),oz=R("$ZodCheckMinLength",(t,e)=>{var n;nn.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!ay(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;e.minimum>i&&(r._zod.bag.minimum=e.minimum)}),t._zod.check=r=>{const i=r.value;if(i.length>=e.minimum)return;const a=uy(i);r.issues.push({origin:a,code:"too_small",minimum:e.minimum,inclusive:!0,input:i,inst:t,continue:!e.abort})}}),uz=R("$ZodCheckLengthEquals",(t,e)=>{var n;nn.init(t,e),(n=t._zod.def).when??(n.when=r=>{const i=r.value;return!ay(i)&&i.length!==void 0}),t._zod.onattach.push(r=>{const i=r._zod.bag;i.minimum=e.length,i.maximum=e.length,i.length=e.length}),t._zod.check=r=>{const i=r.value,s=i.length;if(s===e.length)return;const a=uy(i),o=s>e.length;r.issues.push({origin:a,...o?{code:"too_big",maximum:e.length}:{code:"too_small",minimum:e.length},inclusive:!0,exact:!0,input:r.value,inst:t,continue:!e.abort})}}),Ld=R("$ZodCheckStringFormat",(t,e)=>{var n,r;nn.init(t,e),t._zod.onattach.push(i=>{const s=i._zod.bag;s.format=e.format,e.pattern&&(s.patterns??(s.patterns=new Set),s.patterns.add(e.pattern))}),e.pattern?(n=t._zod).check??(n.check=i=>{e.pattern.lastIndex=0,!e.pattern.test(i.value)&&i.issues.push({origin:"string",code:"invalid_format",format:e.format,input:i.value,...e.pattern?{pattern:e.pattern.toString()}:{},inst:t,continue:!e.abort})}):(r=t._zod).check??(r.check=()=>{})}),lz=R("$ZodCheckRegex",(t,e)=>{Ld.init(t,e),t._zod.check=n=>{e.pattern.lastIndex=0,!e.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:e.pattern.toString(),inst:t,continue:!e.abort})}}),cz=R("$ZodCheckLowerCase",(t,e)=>{e.pattern??(e.pattern=nz),Ld.init(t,e)}),dz=R("$ZodCheckUpperCase",(t,e)=>{e.pattern??(e.pattern=rz),Ld.init(t,e)}),fz=R("$ZodCheckIncludes",(t,e)=>{nn.init(t,e);const n=ca(e.includes),r=new RegExp(typeof e.position=="number"?`^.{${e.position}}${n}`:n);e.pattern=r,t._zod.onattach.push(i=>{const s=i._zod.bag;s.patterns??(s.patterns=new Set),s.patterns.add(r)}),t._zod.check=i=>{i.value.includes(e.includes,e.position)||i.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:e.includes,input:i.value,inst:t,continue:!e.abort})}}),hz=R("$ZodCheckStartsWith",(t,e)=>{nn.init(t,e);const n=new RegExp(`^${ca(e.prefix)}.*`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=r=>{r.value.startsWith(e.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:e.prefix,input:r.value,inst:t,continue:!e.abort})}}),pz=R("$ZodCheckEndsWith",(t,e)=>{nn.init(t,e);const n=new RegExp(`.*${ca(e.suffix)}$`);e.pattern??(e.pattern=n),t._zod.onattach.push(r=>{const i=r._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(n)}),t._zod.check=r=>{r.value.endsWith(e.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:e.suffix,input:r.value,inst:t,continue:!e.abort})}}),mz=R("$ZodCheckOverwrite",(t,e)=>{nn.init(t,e),t._zod.check=n=>{n.value=e.tx(n.value)}});class gz{constructor(e=[]){this.content=[],this.indent=0,this&&(this.args=e)}indented(e){this.indent+=1,e(this),this.indent-=1}write(e){if(typeof e=="function"){e(this,{execution:"sync"}),e(this,{execution:"async"});return}const r=e.split(` `).filter(a=>a),i=Math.min(...r.map(a=>a.length-a.trimStart().length)),s=r.map(a=>a.slice(i)).map(a=>" ".repeat(this.indent*2)+a);for(const a of s)this.content.push(a)}compile(){const e=Function,n=this==null?void 0:this.args,i=[...((this==null?void 0:this.content)??[""]).map(s=>` ${s}`)];return new e(...n,i.join(` `))}}const yz={major:4,minor:4,patch:3},Ve=R("$ZodType",(t,e)=>{var i;var n;t??(t={}),t._zod.def=e,t._zod.bag=t._zod.bag||{},t._zod.version=yz;const r=[...t._zod.def.checks??[]];t._zod.traits.has("$ZodCheck")&&r.unshift(t);for(const s of r)for(const a of s._zod.onattach)a(t);if(r.length===0)(n=t._zod).deferred??(n.deferred=[]),(i=t._zod.deferred)==null||i.push(()=>{t._zod.run=t._zod.parse});else{const s=(o,u,l)=>{let c=Ds(o),d;for(const f of u){if(f._zod.def.when){if(vM(o)||!f._zod.def.when(o))continue}else if(c)continue;const h=o.issues.length,m=f._zod.check(o);if(m instanceof Promise&&(l==null?void 0:l.async)===!1)throw new Js;if(d||m instanceof Promise)d=(d??Promise.resolve()).then(async()=>{await m,o.issues.length!==h&&(c||(c=Ds(o,h)))});else{if(o.issues.length===h)continue;c||(c=Ds(o,h))}}return d?d.then(()=>o):o},a=(o,u,l)=>{if(Ds(o))return o.aborted=!0,o;const c=s(u,r,l);if(c instanceof Promise){if(l.async===!1)throw new Js;return c.then(d=>t._zod.parse(d,l))}return t._zod.parse(c,l)};t._zod.run=(o,u)=>{if(u.skipChecks)return t._zod.parse(o,u);if(u.direction==="backward"){const c=t._zod.parse({value:o.value,issues:[]},{...u,skipChecks:!0});return c instanceof Promise?c.then(d=>a(d,o,u)):a(c,o,u)}const l=t._zod.parse(o,u);if(l instanceof Promise){if(u.async===!1)throw new Js;return l.then(c=>s(c,r,u))}return s(l,r,u)}}Te(t,"~standard",()=>({validate:s=>{var a;try{const o=kM(t,s);return o.success?{value:o.data}:{issues:(a=o.error)==null?void 0:a.issues}}catch{return SM(t,s).then(u=>{var l;return u.success?{value:u.data}:{issues:(l=u.error)==null?void 0:l.issues}})}},vendor:"zod",version:1}))}),ly=R("$ZodString",(t,e)=>{var n;Ve.init(t,e),t._zod.pattern=[...((n=t==null?void 0:t._zod.bag)==null?void 0:n.patterns)??[]].pop()??ez(t._zod.bag),t._zod.parse=(r,i)=>{if(e.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:t}),r}}),Me=R("$ZodStringFormat",(t,e)=>{Ld.init(t,e),ly.init(t,e)}),_z=R("$ZodGUID",(t,e)=>{e.pattern??(e.pattern=UM),Me.init(t,e)}),vz=R("$ZodUUID",(t,e)=>{if(e.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[e.version];if(r===void 0)throw new Error(`Invalid UUID version: "${e.version}"`);e.pattern??(e.pattern=z0(r))}else e.pattern??(e.pattern=z0());Me.init(t,e)}),wz=R("$ZodEmail",(t,e)=>{e.pattern??(e.pattern=FM),Me.init(t,e)}),bz=R("$ZodURL",(t,e)=>{Me.init(t,e),t._zod.check=n=>{var r;try{const i=n.value.trim();if(!e.normalize&&((r=e.protocol)==null?void 0:r.source)===GM.source&&!/^https?:\/\//i.test(i)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:t,continue:!e.abort});return}const s=new URL(i);e.hostname&&(e.hostname.lastIndex=0,e.hostname.test(s.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:e.hostname.source,input:n.value,inst:t,continue:!e.abort})),e.protocol&&(e.protocol.lastIndex=0,e.protocol.test(s.protocol.endsWith(":")?s.protocol.slice(0,-1):s.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:e.protocol.source,input:n.value,inst:t,continue:!e.abort})),e.normalize?n.value=s.href:n.value=i;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:t,continue:!e.abort})}}}),xz=R("$ZodEmoji",(t,e)=>{e.pattern??(e.pattern=HM()),Me.init(t,e)}),kz=R("$ZodNanoID",(t,e)=>{e.pattern??(e.pattern=zM),Me.init(t,e)}),Sz=R("$ZodCUID",(t,e)=>{e.pattern??(e.pattern=$M),Me.init(t,e)}),Az=R("$ZodCUID2",(t,e)=>{e.pattern??(e.pattern=RM),Me.init(t,e)}),Ez=R("$ZodULID",(t,e)=>{e.pattern??(e.pattern=jM),Me.init(t,e)}),Tz=R("$ZodXID",(t,e)=>{e.pattern??(e.pattern=LM),Me.init(t,e)}),Iz=R("$ZodKSUID",(t,e)=>{e.pattern??(e.pattern=MM),Me.init(t,e)}),Oz=R("$ZodISODateTime",(t,e)=>{e.pattern??(e.pattern=YM(e)),Me.init(t,e)}),Cz=R("$ZodISODate",(t,e)=>{e.pattern??(e.pattern=XM),Me.init(t,e)}),Pz=R("$ZodISOTime",(t,e)=>{e.pattern??(e.pattern=QM(e)),Me.init(t,e)}),Nz=R("$ZodISODuration",(t,e)=>{e.pattern??(e.pattern=DM),Me.init(t,e)}),$z=R("$ZodIPv4",(t,e)=>{e.pattern??(e.pattern=ZM),Me.init(t,e),t._zod.bag.format="ipv4"}),Rz=R("$ZodIPv6",(t,e)=>{e.pattern??(e.pattern=VM),Me.init(t,e),t._zod.bag.format="ipv6",t._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:t,continue:!e.abort})}}}),jz=R("$ZodCIDRv4",(t,e)=>{e.pattern??(e.pattern=KM),Me.init(t,e)}),Lz=R("$ZodCIDRv6",(t,e)=>{e.pattern??(e.pattern=qM),Me.init(t,e),t._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[i,s]=r;if(!s)throw new Error;const a=Number(s);if(`${a}`!==s)throw new Error;if(a<0||a>128)throw new Error;new URL(`http://[${i}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:t,continue:!e.abort})}}});function RE(t){if(t==="")return!0;if(/\s/.test(t)||t.length%4!==0)return!1;try{return atob(t),!0}catch{return!1}}const Mz=R("$ZodBase64",(t,e)=>{e.pattern??(e.pattern=WM),Me.init(t,e),t._zod.bag.contentEncoding="base64",t._zod.check=n=>{RE(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:t,continue:!e.abort})}});function zz(t){if(!TE.test(t))return!1;const e=t.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=e.padEnd(Math.ceil(e.length/4)*4,"=");return RE(n)}const Dz=R("$ZodBase64URL",(t,e)=>{e.pattern??(e.pattern=TE),Me.init(t,e),t._zod.bag.contentEncoding="base64url",t._zod.check=n=>{zz(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:t,continue:!e.abort})}}),Uz=R("$ZodE164",(t,e)=>{e.pattern??(e.pattern=JM),Me.init(t,e)});function Fz(t,e=null){try{const n=t.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const i=JSON.parse(atob(r));return!("typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||e&&(!("alg"in i)||i.alg!==e))}catch{return!1}}const Bz=R("$ZodJWT",(t,e)=>{Me.init(t,e),t._zod.check=n=>{Fz(n.value,e.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:t,continue:!e.abort})}}),jE=R("$ZodNumber",(t,e)=>{Ve.init(t,e),t._zod.pattern=t._zod.bag.pattern??CE,t._zod.parse=(n,r)=>{if(e.coerce)try{n.value=Number(n.value)}catch{}const i=n.value;if(typeof i=="number"&&!Number.isNaN(i)&&Number.isFinite(i))return n;const s=typeof i=="number"?Number.isNaN(i)?"NaN":Number.isFinite(i)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:i,inst:t,...s?{received:s}:{}}),n}}),Hz=R("$ZodNumberFormat",(t,e)=>{sz.init(t,e),jE.init(t,e)}),Zz=R("$ZodUnknown",(t,e)=>{Ve.init(t,e),t._zod.parse=n=>n}),LE=R("$ZodNever",(t,e)=>{Ve.init(t,e),t._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:t}),n)});function D0(t,e,n){t.issues.length&&e.issues.push(...Us(n,t.issues)),e.value[n]=t.value}const Vz=R("$ZodArray",(t,e)=>{Ve.init(t,e),t._zod.parse=(n,r)=>{const i=n.value;if(!Array.isArray(i))return n.issues.push({expected:"array",code:"invalid_type",input:i,inst:t}),n;n.value=Array(i.length);const s=[];for(let a=0;a<i.length;a++){const o=i[a],u=e.element._zod.run({value:o,issues:[]},r);u instanceof Promise?s.push(u.then(l=>D0(l,n,a))):D0(u,n,a)}return s.length?Promise.all(s).then(()=>n):n}});function Cc(t,e,n,r,i,s){const a=n in r;if(t.issues.length){if(i&&s&&!a)return;e.issues.push(...Us(n,t.issues))}if(!a&&!i){t.issues.length||e.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}t.value===void 0?a&&(e.value[n]=void 0):e.value[n]=t.value}function ME(t){var r,i,s,a;const e=Object.keys(t.shape);for(const o of e)if(!((a=(s=(i=(r=t.shape)==null?void 0:r[o])==null?void 0:i._zod)==null?void 0:s.traits)!=null&&a.has("$ZodType")))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const n=cM(t.shape);return{...t,keys:e,keySet:new Set(e),numKeys:e.length,optionalKeys:new Set(n)}}function zE(t,e,n,r,i,s){const a=[],o=i.keySet,u=i.catchall._zod,l=u.def.type,c=u.optin==="optional",d=u.optout==="optional";for(const f in e){if(f==="__proto__"||o.has(f))continue;if(l==="never"){a.push(f);continue}const h=u.run({value:e[f],issues:[]},r);h instanceof Promise?t.push(h.then(m=>Cc(m,n,f,e,c,d))):Cc(h,n,f,e,c,d)}return a.length&&n.issues.push({code:"unrecognized_keys",keys:a,input:e,inst:s}),t.length?Promise.all(t).then(()=>n):n}const Kz=R("$ZodObject",(t,e)=>{Ve.init(t,e);const n=Object.getOwnPropertyDescriptor(e,"shape");if(!(n!=null&&n.get)){const o=e.shape;Object.defineProperty(e,"shape",{get:()=>{const u={...o};return Object.defineProperty(e,"shape",{value:u}),u}})}const r=sy(()=>ME(e));Te(t._zod,"propValues",()=>{const o=e.shape,u={};for(const l in o){const c=o[l]._zod;if(c.values){u[l]??(u[l]=new Set);for(const d of c.values)u[l].add(d)}}return u});const i=Oc,s=e.catchall;let a;t._zod.parse=(o,u)=>{a??(a=r.value);const l=o.value;if(!i(l))return o.issues.push({expected:"object",code:"invalid_type",input:l,inst:t}),o;o.value={};const c=[],d=a.shape;for(const f of a.keys){const h=d[f],m=h._zod.optin==="optional",_=h._zod.optout==="optional",v=h._zod.run({value:l[f],issues:[]},u);v instanceof Promise?c.push(v.then(y=>Cc(y,o,f,l,m,_))):Cc(v,o,f,l,m,_)}return s?zE(c,l,o,u,r.value,t):c.length?Promise.all(c).then(()=>o):o}}),qz=R("$ZodObjectJIT",(t,e)=>{Kz.init(t,e);const n=t._zod.parse,r=sy(()=>ME(e)),i=f=>{var g,b;const h=new gz(["shape","payload","ctx"]),m=r.value,_=E=>{const T=M0(E);return`shape[${T}]._zod.run({ value: input[${T}], issues: [] }, ctx)`};h.write("const input = payload.value;");const v=Object.create(null);let y=0;for(const E of m.keys)v[E]=`key_${y++}`;h.write("const newResult = {};");for(const E of m.keys){const T=v[E],I=M0(E),k=f[E],j=((g=k==null?void 0:k._zod)==null?void 0:g.optin)==="optional",N=((b=k==null?void 0:k._zod)==null?void 0:b.optout)==="optional";h.write(`const ${T} = ${_(E)};`),j&&N?h.write(` if (${T}.issues.length) { if (${I} in input) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ ...iss, path: iss.path ? [${I}, ...iss.path] : [${I}] }))); } } if (${T}.value === undefined) { if (${I} in input) { newResult[${I}] = undefined; } } else { newResult[${I}] = ${T}.value; } `):j?h.write(` if (${T}.issues.length) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ ...iss, path: iss.path ? [${I}, ...iss.path] : [${I}] }))); } if (${T}.value === undefined) { if (${I} in input) { newResult[${I}] = undefined; } } else { newResult[${I}] = ${T}.value; } `):h.write(` const ${T}_present = ${I} in input; if (${T}.issues.length) { payload.issues = payload.issues.concat(${T}.issues.map(iss => ({ ...iss, path: iss.path ? [${I}, ...iss.path] : [${I}] }))); } if (!${T}_present && !${T}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${I}] }); } if (${T}_present) { if (${T}.value === undefined) { newResult[${I}] = undefined; } else { newResult[${I}] = ${T}.value; } } `)}h.write("payload.value = newResult;"),h.write("return payload;");const p=h.compile();return(E,T)=>p(f,E,T)};let s;const a=Oc,o=!iy.jitless,l=o&&uM.value,c=e.catchall;let d;t._zod.parse=(f,h)=>{d??(d=r.value);const m=f.value;return a(m)?o&&l&&(h==null?void 0:h.async)===!1&&h.jitless!==!0?(s||(s=i(e.shape)),f=s(f,h),c?zE([],m,f,h,d,t):f):n(f,h):(f.issues.push({expected:"object",code:"invalid_type",input:m,inst:t}),f)}});function U0(t,e,n,r){for(const s of t)if(s.issues.length===0)return e.value=s.value,e;const i=t.filter(s=>!Ds(s));return i.length===1?(e.value=i[0].value,i[0]):(e.issues.push({code:"invalid_union",input:e.value,inst:n,errors:t.map(s=>s.issues.map(a=>Fr(a,r,Ur())))}),e)}const Wz=R("$ZodUnion",(t,e)=>{Ve.init(t,e),Te(t._zod,"optin",()=>e.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Te(t._zod,"optout",()=>e.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Te(t._zod,"values",()=>{if(e.options.every(r=>r._zod.values))return new Set(e.options.flatMap(r=>Array.from(r._zod.values)))}),Te(t._zod,"pattern",()=>{if(e.options.every(r=>r._zod.pattern)){const r=e.options.map(i=>i._zod.pattern);return new RegExp(`^(${r.map(i=>oy(i.source)).join("|")})$`)}});const n=e.options.length===1?e.options[0]._zod.run:null;t._zod.parse=(r,i)=>{if(n)return n(r,i);let s=!1;const a=[];for(const o of e.options){const u=o._zod.run({value:r.value,issues:[]},i);if(u instanceof Promise)a.push(u),s=!0;else{if(u.issues.length===0)return u;a.push(u)}}return s?Promise.all(a).then(o=>U0(o,r,t,i)):U0(a,r,t,i)}}),Gz=R("$ZodIntersection",(t,e)=>{Ve.init(t,e),t._zod.parse=(n,r)=>{const i=n.value,s=e.left._zod.run({value:i,issues:[]},r),a=e.right._zod.run({value:i,issues:[]},r);return s instanceof Promise||a instanceof Promise?Promise.all([s,a]).then(([u,l])=>F0(n,u,l)):F0(n,s,a)}});function Fp(t,e){if(t===e)return{valid:!0,data:t};if(t instanceof Date&&e instanceof Date&&+t==+e)return{valid:!0,data:t};if(la(t)&&la(e)){const n=Object.keys(e),r=Object.keys(t).filter(s=>n.indexOf(s)!==-1),i={...t,...e};for(const s of r){const a=Fp(t[s],e[s]);if(!a.valid)return{valid:!1,mergeErrorPath:[s,...a.mergeErrorPath]};i[s]=a.data}return{valid:!0,data:i}}if(Array.isArray(t)&&Array.isArray(e)){if(t.length!==e.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;r<t.length;r++){const i=t[r],s=e[r],a=Fp(i,s);if(!a.valid)return{valid:!1,mergeErrorPath:[r,...a.mergeErrorPath]};n.push(a.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function F0(t,e,n){const r=new Map;let i;for(const o of e.issues)if(o.code==="unrecognized_keys"){i??(i=o);for(const u of o.keys)r.has(u)||r.set(u,{}),r.get(u).l=!0}else t.issues.push(o);for(const o of n.issues)if(o.code==="unrecognized_keys")for(const u of o.keys)r.has(u)||r.set(u,{}),r.get(u).r=!0;else t.issues.push(o);const s=[...r].filter(([,o])=>o.l&&o.r).map(([o])=>o);if(s.length&&i&&t.issues.push({...i,keys:s}),Ds(t))return t;const a=Fp(e.value,n.value);if(!a.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(a.mergeErrorPath)}`);return t.value=a.data,t}const Jz=R("$ZodRecord",(t,e)=>{Ve.init(t,e),t._zod.parse=(n,r)=>{const i=n.value;if(!la(i))return n.issues.push({expected:"record",code:"invalid_type",input:i,inst:t}),n;const s=[],a=e.keyType._zod.values;if(a){n.value={};const o=new Set;for(const l of a)if(typeof l=="string"||typeof l=="number"||typeof l=="symbol"){o.add(typeof l=="number"?l.toString():l);const c=e.keyType._zod.run({value:l,issues:[]},r);if(c instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(c.issues.length){n.issues.push({code:"invalid_key",origin:"record",issues:c.issues.map(h=>Fr(h,r,Ur())),input:l,path:[l],inst:t});continue}const d=c.value,f=e.valueType._zod.run({value:i[l],issues:[]},r);f instanceof Promise?s.push(f.then(h=>{h.issues.length&&n.issues.push(...Us(l,h.issues)),n.value[d]=h.value})):(f.issues.length&&n.issues.push(...Us(l,f.issues)),n.value[d]=f.value)}let u;for(const l in i)o.has(l)||(u=u??[],u.push(l));u&&u.length>0&&n.issues.push({code:"unrecognized_keys",input:i,inst:t,keys:u})}else{n.value={};for(const o of Reflect.ownKeys(i)){if(o==="__proto__"||!Object.prototype.propertyIsEnumerable.call(i,o))continue;let u=e.keyType._zod.run({value:o,issues:[]},r);if(u instanceof Promise)throw new Error("Async schemas not supported in object keys currently");if(typeof o=="string"&&CE.test(o)&&u.issues.length){const d=e.keyType._zod.run({value:Number(o),issues:[]},r);if(d instanceof Promise)throw new Error("Async schemas not supported in object keys currently");d.issues.length===0&&(u=d)}if(u.issues.length){e.mode==="loose"?n.value[o]=i[o]:n.issues.push({code:"invalid_key",origin:"record",issues:u.issues.map(d=>Fr(d,r,Ur())),input:o,path:[o],inst:t});continue}const c=e.valueType._zod.run({value:i[o],issues:[]},r);c instanceof Promise?s.push(c.then(d=>{d.issues.length&&n.issues.push(...Us(o,d.issues)),n.value[u.value]=d.value})):(c.issues.length&&n.issues.push(...Us(o,c.issues)),n.value[u.value]=c.value)}}return s.length?Promise.all(s).then(()=>n):n}}),Xz=R("$ZodEnum",(t,e)=>{Ve.init(t,e);const n=bE(e.entries),r=new Set(n);t._zod.values=r,t._zod.pattern=new RegExp(`^(${n.filter(i=>lM.has(typeof i)).map(i=>typeof i=="string"?ca(i):i.toString()).join("|")})$`),t._zod.parse=(i,s)=>{const a=i.value;return r.has(a)||i.issues.push({code:"invalid_value",values:n,input:a,inst:t}),i}}),Qz=R("$ZodLiteral",(t,e)=>{if(Ve.init(t,e),e.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(e.values);t._zod.values=n,t._zod.pattern=new RegExp(`^(${e.values.map(r=>typeof r=="string"?ca(r):r?ca(r.toString()):String(r)).join("|")})$`),t._zod.parse=(r,i)=>{const s=r.value;return n.has(s)||r.issues.push({code:"invalid_value",values:e.values,input:s,inst:t}),r}}),Yz=R("$ZodTransform",(t,e)=>{Ve.init(t,e),t._zod.optin="optional",t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new wE(t.constructor.name);const i=e.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(a=>(n.value=a,n.fallback=!0,n));if(i instanceof Promise)throw new Js;return n.value=i,n.fallback=!0,n}});function B0(t,e){return e===void 0&&(t.issues.length||t.fallback)?{issues:[],value:void 0}:t}const DE=R("$ZodOptional",(t,e)=>{Ve.init(t,e),t._zod.optin="optional",t._zod.optout="optional",Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,void 0]):void 0),Te(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${oy(n.source)})?$`):void 0}),t._zod.parse=(n,r)=>{if(e.innerType._zod.optin==="optional"){const i=n.value,s=e.innerType._zod.run(n,r);return s instanceof Promise?s.then(a=>B0(a,i)):B0(s,i)}return n.value===void 0?n:e.innerType._zod.run(n,r)}}),e3=R("$ZodExactOptional",(t,e)=>{DE.init(t,e),Te(t._zod,"values",()=>e.innerType._zod.values),Te(t._zod,"pattern",()=>e.innerType._zod.pattern),t._zod.parse=(n,r)=>e.innerType._zod.run(n,r)}),t3=R("$ZodNullable",(t,e)=>{Ve.init(t,e),Te(t._zod,"optin",()=>e.innerType._zod.optin),Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"pattern",()=>{const n=e.innerType._zod.pattern;return n?new RegExp(`^(${oy(n.source)}|null)$`):void 0}),Te(t._zod,"values",()=>e.innerType._zod.values?new Set([...e.innerType._zod.values,null]):void 0),t._zod.parse=(n,r)=>n.value===null?n:e.innerType._zod.run(n,r)}),n3=R("$ZodDefault",(t,e)=>{Ve.init(t,e),t._zod.optin="optional",Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);if(n.value===void 0)return n.value=e.defaultValue,n;const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>H0(s,e)):H0(i,e)}});function H0(t,e){return t.value===void 0&&(t.value=e.defaultValue),t}const r3=R("$ZodPrefault",(t,e)=>{Ve.init(t,e),t._zod.optin="optional",Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=e.defaultValue),e.innerType._zod.run(n,r))}),i3=R("$ZodNonOptional",(t,e)=>{Ve.init(t,e),Te(t._zod,"values",()=>{const n=e.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),t._zod.parse=(n,r)=>{const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>Z0(s,t)):Z0(i,t)}});function Z0(t,e){return!t.issues.length&&t.value===void 0&&t.issues.push({code:"invalid_type",expected:"nonoptional",input:t.value,inst:e}),t}const s3=R("$ZodCatch",(t,e)=>{Ve.init(t,e),t._zod.optin="optional",Te(t._zod,"optout",()=>e.innerType._zod.optout),Te(t._zod,"values",()=>e.innerType._zod.values),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(s=>(n.value=s.value,s.issues.length&&(n.value=e.catchValue({...n,error:{issues:s.issues.map(a=>Fr(a,r,Ur()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=i.value,i.issues.length&&(n.value=e.catchValue({...n,error:{issues:i.issues.map(s=>Fr(s,r,Ur()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),a3=R("$ZodPipe",(t,e)=>{Ve.init(t,e),Te(t._zod,"values",()=>e.in._zod.values),Te(t._zod,"optin",()=>e.in._zod.optin),Te(t._zod,"optout",()=>e.out._zod.optout),Te(t._zod,"propValues",()=>e.in._zod.propValues),t._zod.parse=(n,r)=>{if(r.direction==="backward"){const s=e.out._zod.run(n,r);return s instanceof Promise?s.then(a=>el(a,e.in,r)):el(s,e.in,r)}const i=e.in._zod.run(n,r);return i instanceof Promise?i.then(s=>el(s,e.out,r)):el(i,e.out,r)}});function el(t,e,n){return t.issues.length?(t.aborted=!0,t):e._zod.run({value:t.value,issues:t.issues,fallback:t.fallback},n)}const o3=R("$ZodReadonly",(t,e)=>{Ve.init(t,e),Te(t._zod,"propValues",()=>e.innerType._zod.propValues),Te(t._zod,"values",()=>e.innerType._zod.values),Te(t._zod,"optin",()=>{var n,r;return(r=(n=e.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),Te(t._zod,"optout",()=>{var n,r;return(r=(n=e.innerType)==null?void 0:n._zod)==null?void 0:r.optout}),t._zod.parse=(n,r)=>{if(r.direction==="backward")return e.innerType._zod.run(n,r);const i=e.innerType._zod.run(n,r);return i instanceof Promise?i.then(V0):V0(i)}});function V0(t){return t.value=Object.freeze(t.value),t}const u3=R("$ZodCustom",(t,e)=>{nn.init(t,e),Ve.init(t,e),t._zod.parse=(n,r)=>n,t._zod.check=n=>{const r=n.value,i=e.fn(r);if(i instanceof Promise)return i.then(s=>K0(s,n,r,t));K0(i,n,r,t)}});function K0(t,e,n,r){if(!t){const i={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(i.params=r._zod.def.params),e.issues.push(Go(i))}}var q0;class l3{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...n){const r=n[0];return this._map.set(e,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){const n=this._map.get(e);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(e),this}get(e){const n=e._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const i={...r,...this._map.get(e)};return Object.keys(i).length?i:void 0}return this._map.get(e)}has(e){return this._map.has(e)}}function c3(){return new l3}(q0=globalThis).__zod_globalRegistry??(q0.__zod_globalRegistry=c3());const En=globalThis.__zod_globalRegistry;function d3(t,e){return new t({type:"string",...ee(e)})}function f3(t,e){return new t({type:"string",format:"email",check:"string_format",abort:!1,...ee(e)})}function W0(t,e){return new t({type:"string",format:"guid",check:"string_format",abort:!1,...ee(e)})}function h3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,...ee(e)})}function p3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ee(e)})}function m3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ee(e)})}function g3(t,e){return new t({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ee(e)})}function y3(t,e){return new t({type:"string",format:"url",check:"string_format",abort:!1,...ee(e)})}function _3(t,e){return new t({type:"string",format:"emoji",check:"string_format",abort:!1,...ee(e)})}function v3(t,e){return new t({type:"string",format:"nanoid",check:"string_format",abort:!1,...ee(e)})}function w3(t,e){return new t({type:"string",format:"cuid",check:"string_format",abort:!1,...ee(e)})}function b3(t,e){return new t({type:"string",format:"cuid2",check:"string_format",abort:!1,...ee(e)})}function x3(t,e){return new t({type:"string",format:"ulid",check:"string_format",abort:!1,...ee(e)})}function k3(t,e){return new t({type:"string",format:"xid",check:"string_format",abort:!1,...ee(e)})}function S3(t,e){return new t({type:"string",format:"ksuid",check:"string_format",abort:!1,...ee(e)})}function A3(t,e){return new t({type:"string",format:"ipv4",check:"string_format",abort:!1,...ee(e)})}function E3(t,e){return new t({type:"string",format:"ipv6",check:"string_format",abort:!1,...ee(e)})}function T3(t,e){return new t({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ee(e)})}function I3(t,e){return new t({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ee(e)})}function O3(t,e){return new t({type:"string",format:"base64",check:"string_format",abort:!1,...ee(e)})}function C3(t,e){return new t({type:"string",format:"base64url",check:"string_format",abort:!1,...ee(e)})}function P3(t,e){return new t({type:"string",format:"e164",check:"string_format",abort:!1,...ee(e)})}function N3(t,e){return new t({type:"string",format:"jwt",check:"string_format",abort:!1,...ee(e)})}function $3(t,e){return new t({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ee(e)})}function R3(t,e){return new t({type:"string",format:"date",check:"string_format",...ee(e)})}function j3(t,e){return new t({type:"string",format:"time",check:"string_format",precision:null,...ee(e)})}function L3(t,e){return new t({type:"string",format:"duration",check:"string_format",...ee(e)})}function M3(t,e){return new t({type:"number",checks:[],...ee(e)})}function z3(t,e){return new t({type:"number",check:"number_format",abort:!1,format:"safeint",...ee(e)})}function D3(t){return new t({type:"unknown"})}function UE(t,e){return new t({type:"never",...ee(e)})}function G0(t,e){return new NE({check:"less_than",...ee(e),value:t,inclusive:!1})}function Wf(t,e){return new NE({check:"less_than",...ee(e),value:t,inclusive:!0})}function J0(t,e){return new $E({check:"greater_than",...ee(e),value:t,inclusive:!1})}function Gf(t,e){return new $E({check:"greater_than",...ee(e),value:t,inclusive:!0})}function X0(t,e){return new iz({check:"multiple_of",...ee(e),value:t})}function FE(t,e){return new az({check:"max_length",...ee(e),maximum:t})}function Pc(t,e){return new oz({check:"min_length",...ee(e),minimum:t})}function BE(t,e){return new uz({check:"length_equals",...ee(e),length:t})}function U3(t,e){return new lz({check:"string_format",format:"regex",...ee(e),pattern:t})}function F3(t){return new cz({check:"string_format",format:"lowercase",...ee(t)})}function B3(t){return new dz({check:"string_format",format:"uppercase",...ee(t)})}function H3(t,e){return new fz({check:"string_format",format:"includes",...ee(e),includes:t})}function Z3(t,e){return new hz({check:"string_format",format:"starts_with",...ee(e),prefix:t})}function V3(t,e){return new pz({check:"string_format",format:"ends_with",...ee(e),suffix:t})}function ka(t){return new mz({check:"overwrite",tx:t})}function K3(t){return ka(e=>e.normalize(t))}function q3(){return ka(t=>t.trim())}function W3(){return ka(t=>t.toLowerCase())}function G3(){return ka(t=>t.toUpperCase())}function J3(){return ka(t=>oM(t))}function X3(t,e,n){return new t({type:"array",element:e,...ee(n)})}function Q3(t,e,n){return new t({type:"custom",check:"custom",fn:e,...ee(n)})}function Y3(t,e){const n=e6(r=>(r.addIssue=i=>{if(typeof i=="string")r.issues.push(Go(i,r.value,n._zod.def));else{const s=i;s.fatal&&(s.continue=!1),s.code??(s.code="custom"),s.input??(s.input=r.value),s.inst??(s.inst=n),s.continue??(s.continue=!n._zod.def.abort),r.issues.push(Go(s))}},t(r.value,r)),e);return n}function e6(t,e){const n=new nn({check:"custom",...ee(e)});return n._zod.check=t,n}function Nc(t){let e=(t==null?void 0:t.target)??"draft-2020-12";return e==="draft-4"&&(e="draft-04"),e==="draft-7"&&(e="draft-07"),{processors:t.processors??{},metadataRegistry:(t==null?void 0:t.metadata)??En,target:e,unrepresentable:(t==null?void 0:t.unrepresentable)??"throw",override:(t==null?void 0:t.override)??(()=>{}),io:(t==null?void 0:t.io)??"output",counter:0,seen:new Map,cycles:(t==null?void 0:t.cycles)??"ref",reused:(t==null?void 0:t.reused)??"inline",external:(t==null?void 0:t.external)??void 0}}function Ce(t,e,n={path:[],schemaPath:[]}){var c,d;var r;const i=t._zod.def,s=e.seen.get(t);if(s)return s.count++,n.schemaPath.includes(t)&&(s.cycle=n.path),s.schema;const a={schema:{},count:1,cycle:void 0,path:n.path};e.seen.set(t,a);const o=(d=(c=t._zod).toJSONSchema)==null?void 0:d.call(c);if(o)a.schema=o;else{const f={...n,schemaPath:[...n.schemaPath,t],path:n.path};if(t._zod.processJSONSchema)t._zod.processJSONSchema(e,a.schema,f);else{const m=a.schema,_=e.processors[i.type];if(!_)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);_(t,e,m,f)}const h=t._zod.parent;h&&(a.ref||(a.ref=h),Ce(h,e,f),e.seen.get(h).isParent=!0)}const u=e.metadataRegistry.get(t);return u&&Object.assign(a.schema,u),e.io==="input"&&Nt(t)&&(delete a.schema.examples,delete a.schema.default),e.io==="input"&&"_prefault"in a.schema&&((r=a.schema).default??(r.default=a.schema._prefault)),delete a.schema._prefault,e.seen.get(t).schema}function $c(t,e){var a,o,u,l;const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const c of t.seen.entries()){const d=(a=t.metadataRegistry.get(c[0]))==null?void 0:a.id;if(d){const f=r.get(d);if(f&&f!==c[0])throw new Error(`Duplicate schema id "${d}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(d,c[0])}}const i=c=>{var _;const d=t.target==="draft-2020-12"?"$defs":"definitions";if(t.external){const v=(_=t.external.registry.get(c[0]))==null?void 0:_.id,y=t.external.uri??(g=>g);if(v)return{ref:y(v)};const p=c[1].defId??c[1].schema.id??`schema${t.counter++}`;return c[1].defId=p,{defId:p,ref:`${y("__shared")}#/${d}/${p}`}}if(c[1]===n)return{ref:"#"};const h=`#/${d}/`,m=c[1].schema.id??`__schema${t.counter++}`;return{defId:m,ref:h+m}},s=c=>{if(c[1].schema.$ref)return;const d=c[1],{ref:f,defId:h}=i(c);d.def={...d.schema},h&&(d.defId=h);const m=d.schema;for(const _ in m)delete m[_];m.$ref=f};if(t.cycles==="throw")for(const c of t.seen.entries()){const d=c[1];if(d.cycle)throw new Error(`Cycle detected: #/${(o=d.cycle)==null?void 0:o.join("/")}/<root> Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const c of t.seen.entries()){const d=c[1];if(e===c[0]){s(c);continue}if(t.external){const h=(u=t.external.registry.get(c[0]))==null?void 0:u.id;if(e!==c[0]&&h){s(c);continue}}if((l=t.metadataRegistry.get(c[0]))==null?void 0:l.id){s(c);continue}if(d.cycle){s(c);continue}if(d.count>1&&t.reused==="ref"){s(c);continue}}}function Rc(t,e){var o,u,l,c;const n=t.seen.get(e);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=d=>{const f=t.seen.get(d);if(f.ref===null)return;const h=f.def??f.schema,m={...h},_=f.ref;if(f.ref=null,_){r(_);const y=t.seen.get(_),p=y.schema;if(p.$ref&&(t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0")?(h.allOf=h.allOf??[],h.allOf.push(p)):Object.assign(h,p),Object.assign(h,m),d._zod.parent===_)for(const b in h)b==="$ref"||b==="allOf"||b in m||delete h[b];if(p.$ref&&y.def)for(const b in h)b==="$ref"||b==="allOf"||b in y.def&&JSON.stringify(h[b])===JSON.stringify(y.def[b])&&delete h[b]}const v=d._zod.parent;if(v&&v!==_){r(v);const y=t.seen.get(v);if(y!=null&&y.schema.$ref&&(h.$ref=y.schema.$ref,y.def))for(const p in h)p==="$ref"||p==="allOf"||p in y.def&&JSON.stringify(h[p])===JSON.stringify(y.def[p])&&delete h[p]}t.override({zodSchema:d,jsonSchema:h,path:f.path??[]})};for(const d of[...t.seen.entries()].reverse())r(d[0]);const i={};if(t.target==="draft-2020-12"?i.$schema="https://json-schema.org/draft/2020-12/schema":t.target==="draft-07"?i.$schema="http://json-schema.org/draft-07/schema#":t.target==="draft-04"?i.$schema="http://json-schema.org/draft-04/schema#":t.target,(o=t.external)!=null&&o.uri){const d=(u=t.external.registry.get(e))==null?void 0:u.id;if(!d)throw new Error("Schema is missing an `id` property");i.$id=t.external.uri(d)}Object.assign(i,n.def??n.schema);const s=(l=t.metadataRegistry.get(e))==null?void 0:l.id;s!==void 0&&i.id===s&&delete i.id;const a=((c=t.external)==null?void 0:c.defs)??{};for(const d of t.seen.entries()){const f=d[1];f.def&&f.defId&&(f.def.id===f.defId&&delete f.def.id,a[f.defId]=f.def)}t.external||Object.keys(a).length>0&&(t.target==="draft-2020-12"?i.$defs=a:i.definitions=a);try{const d=JSON.parse(JSON.stringify(i));return Object.defineProperty(d,"~standard",{value:{...e["~standard"],jsonSchema:{input:jc(e,"input",t.processors),output:jc(e,"output",t.processors)}},enumerable:!1,writable:!1}),d}catch{throw new Error("Error converting schema to JSON.")}}function Nt(t,e){const n=e??{seen:new Set};if(n.seen.has(t))return!1;n.seen.add(t);const r=t._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Nt(r.element,n);if(r.type==="set")return Nt(r.valueType,n);if(r.type==="lazy")return Nt(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Nt(r.innerType,n);if(r.type==="intersection")return Nt(r.left,n)||Nt(r.right,n);if(r.type==="record"||r.type==="map")return Nt(r.keyType,n)||Nt(r.valueType,n);if(r.type==="pipe")return t._zod.traits.has("$ZodCodec")?!0:Nt(r.in,n)||Nt(r.out,n);if(r.type==="object"){for(const i in r.shape)if(Nt(r.shape[i],n))return!0;return!1}if(r.type==="union"){for(const i of r.options)if(Nt(i,n))return!0;return!1}if(r.type==="tuple"){for(const i of r.items)if(Nt(i,n))return!0;return!!(r.rest&&Nt(r.rest,n))}return!1}const t6=(t,e={})=>n=>{const r=Nc({...n,processors:e});return Ce(t,r),$c(r,t),Rc(r,t)},jc=(t,e,n={})=>r=>{const{libraryOptions:i,target:s}=r??{},a=Nc({...i??{},target:s,io:e,processors:n});return Ce(t,a),$c(a,t),Rc(a,t)},n6={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},HE=(t,e,n,r)=>{const i=n;i.type="string";const{minimum:s,maximum:a,format:o,patterns:u,contentEncoding:l}=t._zod.bag;if(typeof s=="number"&&(i.minLength=s),typeof a=="number"&&(i.maxLength=a),o&&(i.format=n6[o]??o,i.format===""&&delete i.format,o==="time"&&delete i.format),l&&(i.contentEncoding=l),u&&u.size>0){const c=[...u];c.length===1?i.pattern=c[0].source:c.length>1&&(i.allOf=[...c.map(d=>({...e.target==="draft-07"||e.target==="draft-04"||e.target==="openapi-3.0"?{type:"string"}:{},pattern:d.source}))])}},ZE=(t,e,n,r)=>{const i=n,{minimum:s,maximum:a,format:o,multipleOf:u,exclusiveMaximum:l,exclusiveMinimum:c}=t._zod.bag;typeof o=="string"&&o.includes("int")?i.type="integer":i.type="number";const d=typeof c=="number"&&c>=(s??Number.NEGATIVE_INFINITY),f=typeof l=="number"&&l<=(a??Number.POSITIVE_INFINITY),h=e.target==="draft-04"||e.target==="openapi-3.0";d?h?(i.minimum=c,i.exclusiveMinimum=!0):i.exclusiveMinimum=c:typeof s=="number"&&(i.minimum=s),f?h?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof a=="number"&&(i.maximum=a),typeof u=="number"&&(i.multipleOf=u)},r6=(t,e,n,r)=>{n.type="boolean"},i6=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema")},s6=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema")},a6=(t,e,n,r)=>{e.target==="openapi-3.0"?(n.type="string",n.nullable=!0,n.enum=[null]):n.type="null"},o6=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema")},u6=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema")},VE=(t,e,n,r)=>{n.not={}},l6=(t,e,n,r)=>{},KE=(t,e,n,r)=>{},c6=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema")},qE=(t,e,n,r)=>{const i=t._zod.def,s=bE(i.entries);s.every(a=>typeof a=="number")&&(n.type="number"),s.every(a=>typeof a=="string")&&(n.type="string"),n.enum=s},WE=(t,e,n,r)=>{const i=t._zod.def,s=[];for(const a of i.values)if(a===void 0){if(e.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof a=="bigint"){if(e.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");s.push(Number(a))}else s.push(a);if(s.length!==0)if(s.length===1){const a=s[0];n.type=a===null?"null":typeof a,e.target==="draft-04"||e.target==="openapi-3.0"?n.enum=[a]:n.const=a}else s.every(a=>typeof a=="number")&&(n.type="number"),s.every(a=>typeof a=="string")&&(n.type="string"),s.every(a=>typeof a=="boolean")&&(n.type="boolean"),s.every(a=>a===null)&&(n.type="null"),n.enum=s},d6=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema")},f6=(t,e,n,r)=>{const i=n,s=t._zod.pattern;if(!s)throw new Error("Pattern not found in template literal");i.type="string",i.pattern=s.source},h6=(t,e,n,r)=>{const i=n,s={type:"string",format:"binary",contentEncoding:"binary"},{minimum:a,maximum:o,mime:u}=t._zod.bag;a!==void 0&&(s.minLength=a),o!==void 0&&(s.maxLength=o),u?u.length===1?(s.contentMediaType=u[0],Object.assign(i,s)):(Object.assign(i,s),i.anyOf=u.map(l=>({contentMediaType:l}))):Object.assign(i,s)},p6=(t,e,n,r)=>{n.type="boolean"},GE=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},m6=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Function types cannot be represented in JSON Schema")},JE=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},g6=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema")},y6=(t,e,n,r)=>{if(e.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema")},XE=(t,e,n,r)=>{const i=n,s=t._zod.def,{minimum:a,maximum:o}=t._zod.bag;typeof a=="number"&&(i.minItems=a),typeof o=="number"&&(i.maxItems=o),i.type="array",i.items=Ce(s.element,e,{...r,path:[...r.path,"items"]})},QE=(t,e,n,r)=>{var l;const i=n,s=t._zod.def;i.type="object",i.properties={};const a=s.shape;for(const c in a)i.properties[c]=Ce(a[c],e,{...r,path:[...r.path,"properties",c]});const o=new Set(Object.keys(a)),u=new Set([...o].filter(c=>{const d=s.shape[c]._zod;return e.io==="input"?d.optin===void 0:d.optout===void 0}));u.size>0&&(i.required=Array.from(u)),((l=s.catchall)==null?void 0:l._zod.def.type)==="never"?i.additionalProperties=!1:s.catchall?s.catchall&&(i.additionalProperties=Ce(s.catchall,e,{...r,path:[...r.path,"additionalProperties"]})):e.io==="output"&&(i.additionalProperties=!1)},YE=(t,e,n,r)=>{const i=t._zod.def,s=i.inclusive===!1,a=i.options.map((o,u)=>Ce(o,e,{...r,path:[...r.path,s?"oneOf":"anyOf",u]}));s?n.oneOf=a:n.anyOf=a},eT=(t,e,n,r)=>{const i=t._zod.def,s=Ce(i.left,e,{...r,path:[...r.path,"allOf",0]}),a=Ce(i.right,e,{...r,path:[...r.path,"allOf",1]}),o=l=>"allOf"in l&&Object.keys(l).length===1,u=[...o(s)?s.allOf:[s],...o(a)?a.allOf:[a]];n.allOf=u},_6=(t,e,n,r)=>{const i=n,s=t._zod.def;i.type="array";const a=e.target==="draft-2020-12"?"prefixItems":"items",o=e.target==="draft-2020-12"||e.target==="openapi-3.0"?"items":"additionalItems",u=s.items.map((f,h)=>Ce(f,e,{...r,path:[...r.path,a,h]})),l=s.rest?Ce(s.rest,e,{...r,path:[...r.path,o,...e.target==="openapi-3.0"?[s.items.length]:[]]}):null;e.target==="draft-2020-12"?(i.prefixItems=u,l&&(i.items=l)):e.target==="openapi-3.0"?(i.items={anyOf:u},l&&i.items.anyOf.push(l),i.minItems=u.length,l||(i.maxItems=u.length)):(i.items=u,l&&(i.additionalItems=l));const{minimum:c,maximum:d}=t._zod.bag;typeof c=="number"&&(i.minItems=c),typeof d=="number"&&(i.maxItems=d)},tT=(t,e,n,r)=>{const i=n,s=t._zod.def;i.type="object";const a=s.keyType,o=a._zod.bag,u=o==null?void 0:o.patterns;if(s.mode==="loose"&&u&&u.size>0){const c=Ce(s.valueType,e,{...r,path:[...r.path,"patternProperties","*"]});i.patternProperties={};for(const d of u)i.patternProperties[d.source]=c}else(e.target==="draft-07"||e.target==="draft-2020-12")&&(i.propertyNames=Ce(s.keyType,e,{...r,path:[...r.path,"propertyNames"]})),i.additionalProperties=Ce(s.valueType,e,{...r,path:[...r.path,"additionalProperties"]});const l=a._zod.values;if(l){const c=[...l].filter(d=>typeof d=="string"||typeof d=="number");c.length>0&&(i.required=c)}},nT=(t,e,n,r)=>{const i=t._zod.def,s=Ce(i.innerType,e,r),a=e.seen.get(t);e.target==="openapi-3.0"?(a.ref=i.innerType,n.nullable=!0):n.anyOf=[s,{type:"null"}]},rT=(t,e,n,r)=>{const i=t._zod.def;Ce(i.innerType,e,r);const s=e.seen.get(t);s.ref=i.innerType},iT=(t,e,n,r)=>{const i=t._zod.def;Ce(i.innerType,e,r);const s=e.seen.get(t);s.ref=i.innerType,n.default=JSON.parse(JSON.stringify(i.defaultValue))},sT=(t,e,n,r)=>{const i=t._zod.def;Ce(i.innerType,e,r);const s=e.seen.get(t);s.ref=i.innerType,e.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(i.defaultValue)))},aT=(t,e,n,r)=>{const i=t._zod.def;Ce(i.innerType,e,r);const s=e.seen.get(t);s.ref=i.innerType;let a;try{a=i.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=a},oT=(t,e,n,r)=>{const i=t._zod.def,s=i.in._zod.traits.has("$ZodTransform"),a=e.io==="input"?s?i.out:i.in:i.out;Ce(a,e,r);const o=e.seen.get(t);o.ref=a},uT=(t,e,n,r)=>{const i=t._zod.def;Ce(i.innerType,e,r);const s=e.seen.get(t);s.ref=i.innerType,n.readOnly=!0},v6=(t,e,n,r)=>{const i=t._zod.def;Ce(i.innerType,e,r);const s=e.seen.get(t);s.ref=i.innerType},cy=(t,e,n,r)=>{const i=t._zod.def;Ce(i.innerType,e,r);const s=e.seen.get(t);s.ref=i.innerType},w6=(t,e,n,r)=>{const i=t._zod.innerType;Ce(i,e,r);const s=e.seen.get(t);s.ref=i},Q0={string:HE,number:ZE,boolean:r6,bigint:i6,symbol:s6,null:a6,undefined:o6,void:u6,never:VE,any:l6,unknown:KE,date:c6,enum:qE,literal:WE,nan:d6,template_literal:f6,file:h6,success:p6,custom:GE,function:m6,transform:JE,map:g6,set:y6,array:XE,object:QE,union:YE,intersection:eT,tuple:_6,record:tT,nullable:nT,nonoptional:rT,default:iT,prefault:sT,catch:aT,pipe:oT,readonly:uT,promise:v6,optional:cy,lazy:w6};function Bp(t,e){if("_idmap"in t){const r=t,i=Nc({...e,processors:Q0}),s={};for(const u of r._idmap.entries()){const[l,c]=u;Ce(c,i)}const a={},o={registry:r,uri:e==null?void 0:e.uri,defs:s};i.external=o;for(const u of r._idmap.entries()){const[l,c]=u;$c(i,c),a[l]=Rc(i,c)}if(Object.keys(s).length>0){const u=i.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[u]:s}}return{schemas:a}}const n=Nc({...e,processors:Q0});return Ce(t,n),$c(n,t),Rc(n,t)}function tn(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_zod"in e))return!1;const n=e._zod;return typeof n=="object"&&n!==null&&"def"in n}function Kr(t){if(typeof t!="object"||t===null)return!1;const e=t;if(!("_def"in e)||"_zod"in e)return!1;const n=e._def;return typeof n=="object"&&n!=null&&"typeName"in n}function gr(t){return!t||typeof t!="object"||Array.isArray(t)?!1:!!(tn(t)||Kr(t))}async function b6(t,e){if(tn(t))try{return{success:!0,data:await EE(t,e)}}catch(n){return{success:!1,error:n}}if(Kr(t))return await t.safeParseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function lT(t,e){if(tn(t))return await EE(t,e);if(Kr(t))return await t.parseAsync(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function dy(t){var e;if(tn(t))return(e=En.get(t))==null?void 0:e.description;if(Kr(t)||"description"in t&&typeof t.description=="string")return t.description}function x6(t){return gr(t)?Kr(t)?t._def.typeName==="ZodString":tn(t)?t._zod.def.type==="string":!1:!1}function k6(t){return typeof t=="object"&&t!==null&&"_def"in t&&typeof t._def=="object"&&t._def!==null&&"typeName"in t._def&&t._def.typeName==="ZodObject"}function bo(t){return tn(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="object":!1}function cT(t){return tn(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="array":!1}function S6(t){return tn(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="optional":!1}function A6(t){return tn(t)?typeof t=="object"&&t!==null&&"_zod"in t&&typeof t._zod=="object"&&t._zod!==null&&"def"in t._zod&&typeof t._zod.def=="object"&&t._zod.def!==null&&"type"in t._zod.def&&t._zod.def.type==="nullable":!1}function Hp(t,e=!1){if(k6(t))return t.strict();if(bo(t)){const n=t._zod.def.shape;if(e)for(const[s,a]of Object.entries(t._zod.def.shape)){if(bo(a))n[s]=Hp(a,e);else if(cT(a)){let u=a._zod.def.element;bo(u)&&(u=Hp(u,e)),n[s]=Jt(a,{...a._zod.def,element:u})}else n[s]=a;const o=En.get(a);o&&En.add(n[s],o)}const r=Jt(t,{...t._zod.def,shape:n,catchall:UE(LE)}),i=En.get(t);return i&&En.add(r,i),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function E6(t){return Kr(t)&&"typeName"in t._def&&t._def.typeName==="ZodEffects"}function T6(t){return tn(t)&&t._zod.def.type==="pipe"}function Fi(t,e,n){const r=n.get(t);if(r!==void 0)return r;if(Kr(t))return E6(t)?Fi(t._def.schema,e,n):t;if(tn(t)){let i=t;if(T6(t)&&(i=Fi(t._zod.def.in,e,n)),e){if(bo(i)){const a={};for(const[o,u]of Object.entries(i._zod.def.shape))a[o]=Fi(u,e,n);i=Jt(i,{...i._zod.def,shape:a})}else if(cT(i)){const a=Fi(i._zod.def.element,e,n);i=Jt(i,{...i._zod.def,element:a})}else if(S6(i)){const a=Fi(i._zod.def.innerType,e,n);i=Jt(i,{...i._zod.def,innerType:a})}else if(A6(i)){const a=Fi(i._zod.def.innerType,e,n);i=Jt(i,{...i._zod.def,innerType:a})}}const s=En.get(t);return s&&En.add(i,s),n.set(t,i),i}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function I6(t,e=!1){return Fi(t,e,new WeakMap)}function Jf(t){return t.replace(/[^a-zA-Z-_0-9]/g,"_")}const O6=["*","_","`"];function C6(t){let e="";for(const[n,r]of Object.entries(t))e+=` classDef ${n} ${r}; `;return e}function P6(t,e,n){const{firstNode:r,lastNode:i,nodeColors:s,withStyles:a=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=n??{};let l=a?`%%{init: {'flowchart': {'curve': '${o}'}}}%% graph TD; `:`graph TD; `;if(a){const m="default",_={[m]:"{0}({1})"};r!==void 0&&(_[r]="{0}([{1}]):::first"),i!==void 0&&(_[i]="{0}([{1}]):::last");for(const[v,y]of Object.entries(t)){const p=y.name.split(":").pop()??"";let g=O6.some(E=>p.startsWith(E)&&p.endsWith(E))?`<p>${p}</p>`:p;Object.keys(y.metadata??{}).length&&(g+=`<hr/><small><em>${Object.entries(y.metadata??{}).map(([E,T])=>`${E} = ${T}`).join(` `)}</em></small>`);const b=(_[v]??_[m]).replace("{0}",Jf(v)).replace("{1}",g);l+=` ${b} `}}const c={};for(const m of e){const _=m.source.split(":"),v=m.target.split(":"),y=_.filter((p,g)=>p===v[g]).join(":");c[y]||(c[y]=[]),c[y].push(m)}const d=new Set;function f(m){return[...m].sort((_,v)=>_.split(":").length-v.split(":").length)}function h(m,_){const v=m.length===1&&m[0].source===m[0].target;if(_&&!v){const p=_.split(":").pop();if(d.has(_))throw new Error(`Found duplicate subgraph '${p}' at '${_} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);d.add(_),l+=` subgraph ${p} `}const y=f(Object.keys(c).filter(p=>p.startsWith(`${_}:`)&&p!==_&&p.split(":").length===_.split(":").length+1));for(const p of y)h(c[p],p);for(const p of m){const{source:g,target:b,data:E,conditional:T}=p;let I="";if(E!==void 0){let k=E;const j=k.split(" ");j.length>u&&(k=Array.from({length:Math.ceil(j.length/u)},(N,L)=>j.slice(L*u,(L+1)*u).join(" ")).join(" <br> ")),I=T?` -. ${k} .-> `:` -- ${k} --> `}else I=T?" -.-> ":" --> ";l+=` ${Jf(g)}${I}${Jf(b)}; `}_&&!v&&(l+=` end `)}h(c[""]??[],"");for(const m in c)!m.includes(":")&&m!==""&&h(c[m],m);return a&&(l+=C6(s??{})),l}async function N6(t,e){let n=(e==null?void 0:e.backgroundColor)??"white";const r=(e==null?void 0:e.imageType)??"png",i=sM(t);n!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(n)||(n=`!${n}`));const s=`https://mermaid.ink/img/${i}?bgColor=${n}&type=${r}`,a=await fetch(s);if(!a.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${a.status}`,`Status text: ${a.statusText}`].join(` `));return await a.blob()}const $6=Symbol("Let zodToJsonSchema decide on which parser to use"),R6={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"},j6=t=>({...R6,...t}),L6=t=>{const e=j6(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,i])=>[i._def,{def:i._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}},dT=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")};function pn(t){if(t.target!=="openAi")return{};const e=[...t.basePath,t.definitionPath,t.openAiAnyTypeName];return t.flags.hasReferencedOpenAiAnyType=!0,{$ref:t.$refStrategy==="relative"?dT(e,t.currentPath):e.join("/")}}function fT(t,e,n,r){r!=null&&r.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function ke(t,e,n,r,i){t[e]=n,fT(t,e,r,i)}var _e;(function(t){t.assertEqual=i=>{};function e(i){}t.assertIs=e;function n(i){throw new Error}t.assertNever=n,t.arrayToEnum=i=>{const s={};for(const a of i)s[a]=a;return s},t.getValidEnumValues=i=>{const s=t.objectKeys(i).filter(o=>typeof i[i[o]]!="number"),a={};for(const o of s)a[o]=i[o];return t.objectValues(a)},t.objectValues=i=>t.objectKeys(i).map(function(s){return i[s]}),t.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{const s=[];for(const a in i)Object.prototype.hasOwnProperty.call(i,a)&&s.push(a);return s},t.find=(i,s)=>{for(const a of i)if(s(a))return a},t.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,s=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(s)}t.joinValues=r,t.jsonStringifyReplacer=(i,s)=>typeof s=="bigint"?s.toString():s})(_e||(_e={}));var Y0;(function(t){t.mergeShapes=(e,n)=>({...e,...n})})(Y0||(Y0={}));const X=_e.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ni=t=>{switch(typeof t){case"undefined":return X.undefined;case"string":return X.string;case"number":return Number.isNaN(t)?X.nan:X.number;case"boolean":return X.boolean;case"function":return X.function;case"bigint":return X.bigint;case"symbol":return X.symbol;case"object":return Array.isArray(t)?X.array:t===null?X.null:t.then&&typeof t.then=="function"&&t.catch&&typeof t.catch=="function"?X.promise:typeof Map<"u"&&t instanceof Map?X.map:typeof Set<"u"&&t instanceof Set?X.set:typeof Date<"u"&&t instanceof Date?X.date:X.object;default:return X.unknown}},B=_e.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]);class Br extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};const n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=e}format(e){const n=e||function(s){return s.message},r={_errors:[]},i=s=>{for(const a of s.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let o=r,u=0;for(;u<a.path.length;){const l=a.path[u];u===a.path.length-1?(o[l]=o[l]||{_errors:[]},o[l]._errors.push(n(a))):o[l]=o[l]||{_errors:[]},o=o[l],u++}}};return i(this),r}static assert(e){if(!(e instanceof Br))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,_e.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=n=>n.message){const n=Object.create(null),r=[];for(const i of this.issues)if(i.path.length>0){const s=i.path[0];n[s]=n[s]||[],n[s].push(e(i))}else r.push(e(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}}Br.create=t=>new Br(t);const Zp=(t,e)=>{let n;switch(t.code){case B.invalid_type:t.received===X.undefined?n="Required":n=`Expected ${t.expected}, received ${t.received}`;break;case B.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(t.expected,_e.jsonStringifyReplacer)}`;break;case B.unrecognized_keys:n=`Unrecognized key(s) in object: ${_e.joinValues(t.keys,", ")}`;break;case B.invalid_union:n="Invalid input";break;case B.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${_e.joinValues(t.options)}`;break;case B.invalid_enum_value:n=`Invalid enum value. Expected ${_e.joinValues(t.options)}, received '${t.received}'`;break;case B.invalid_arguments:n="Invalid function arguments";break;case B.invalid_return_type:n="Invalid function return type";break;case B.invalid_date:n="Invalid date";break;case B.invalid_string:typeof t.validation=="object"?"includes"in t.validation?(n=`Invalid input: must include "${t.validation.includes}"`,typeof t.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${t.validation.position}`)):"startsWith"in t.validation?n=`Invalid input: must start with "${t.validation.startsWith}"`:"endsWith"in t.validation?n=`Invalid input: must end with "${t.validation.endsWith}"`:_e.assertNever(t.validation):t.validation!=="regex"?n=`Invalid ${t.validation}`:n="Invalid";break;case B.too_small:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at least":"more than"} ${t.minimum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at least":"over"} ${t.minimum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="bigint"?n=`Number must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${t.minimum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly equal to ":t.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(t.minimum))}`:n="Invalid input";break;case B.too_big:t.type==="array"?n=`Array must contain ${t.exact?"exactly":t.inclusive?"at most":"less than"} ${t.maximum} element(s)`:t.type==="string"?n=`String must contain ${t.exact?"exactly":t.inclusive?"at most":"under"} ${t.maximum} character(s)`:t.type==="number"?n=`Number must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="bigint"?n=`BigInt must be ${t.exact?"exactly":t.inclusive?"less than or equal to":"less than"} ${t.maximum}`:t.type==="date"?n=`Date must be ${t.exact?"exactly":t.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(t.maximum))}`:n="Invalid input";break;case B.custom:n="Invalid input";break;case B.invalid_intersection_types:n="Intersection results could not be merged";break;case B.not_multiple_of:n=`Number must be a multiple of ${t.multipleOf}`;break;case B.not_finite:n="Number must be finite";break;default:n=e.defaultError,_e.assertNever(t)}return{message:n}};let M6=Zp;function z6(){return M6}const D6=t=>{const{data:e,path:n,errorMaps:r,issueData:i}=t,s=[...n,...i.path||[]],a={...i,path:s};if(i.message!==void 0)return{...i,path:s,message:i.message};let o="";const u=r.filter(l=>!!l).slice().reverse();for(const l of u)o=l(a,{data:e,defaultError:o}).message;return{...i,path:s,message:o}};function V(t,e){const n=z6(),r=D6({issueData:e,data:t.data,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,n,n===Zp?void 0:Zp].filter(i=>!!i)});t.common.issues.push(r)}class mn{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,n){const r=[];for(const i of n){if(i.status==="aborted")return se;i.status==="dirty"&&e.dirty(),r.push(i.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,n){const r=[];for(const i of n){const s=await i.key,a=await i.value;r.push({key:s,value:a})}return mn.mergeObjectSync(e,r)}static mergeObjectSync(e,n){const r={};for(const i of n){const{key:s,value:a}=i;if(s.status==="aborted"||a.status==="aborted")return se;s.status==="dirty"&&e.dirty(),a.status==="dirty"&&e.dirty(),s.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[s.value]=a.value)}return{status:e.value,value:r}}}const se=Object.freeze({status:"aborted"}),to=t=>({status:"dirty",value:t}),Pn=t=>({status:"valid",value:t}),ew=t=>t.status==="aborted",tw=t=>t.status==="dirty",da=t=>t.status==="valid",Lc=t=>typeof Promise<"u"&&t instanceof Promise;var Q;(function(t){t.errToObj=e=>typeof e=="string"?{message:e}:e||{},t.toString=e=>typeof e=="string"?e:e==null?void 0:e.message})(Q||(Q={}));class Ti{constructor(e,n,r,i){this._cachedPath=[],this.parent=e,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}}const nw=(t,e)=>{if(da(e))return{success:!0,data:e.value};if(!t.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const n=new Br(t.common.issues);return this._error=n,this._error}}};function ce(t){if(!t)return{};const{errorMap:e,invalid_type_error:n,required_error:r,description:i}=t;if(e&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(a,o)=>{const{message:u}=t;return a.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??r??o.defaultError}:a.code!=="invalid_type"?{message:o.defaultError}:{message:u??n??o.defaultError}},description:i}}let ge=class{get description(){return this._def.description}_getType(e){return ni(e.data)}_getOrReturnCtx(e,n){return n||{common:e.parent.common,data:e.data,parsedType:ni(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new mn,ctx:{common:e.parent.common,data:e.data,parsedType:ni(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const n=this._parse(e);if(Lc(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(e){const n=this._parse(e);return Promise.resolve(n)}parse(e,n){const r=this.safeParse(e,n);if(r.success)return r.data;throw r.error}safeParse(e,n){const r={common:{issues:[],async:(n==null?void 0:n.async)??!1,contextualErrorMap:n==null?void 0:n.errorMap},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ni(e)},i=this._parseSync({data:e,path:r.path,parent:r});return nw(r,i)}"~validate"(e){var r,i;const n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ni(e)};if(!this["~standard"].async)try{const s=this._parseSync({data:e,path:[],parent:n});return da(s)?{value:s.value}:{issues:n.common.issues}}catch(s){(i=(r=s==null?void 0:s.message)==null?void 0:r.toLowerCase())!=null&&i.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:n}).then(s=>da(s)?{value:s.value}:{issues:n.common.issues})}async parseAsync(e,n){const r=await this.safeParseAsync(e,n);if(r.success)return r.data;throw r.error}async safeParseAsync(e,n){const r={common:{issues:[],contextualErrorMap:n==null?void 0:n.errorMap,async:!0},path:(n==null?void 0:n.path)||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ni(e)},i=this._parse({data:e,path:r.path,parent:r}),s=await(Lc(i)?i:Promise.resolve(i));return nw(r,s)}refine(e,n){const r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,s)=>{const a=e(i),o=()=>s.addIssue({code:B.custom,...r(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(u=>u?!0:(o(),!1)):a?!0:(o(),!1)})}refinement(e,n){return this._refinement((r,i)=>e(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(e){return new ha({schema:this,typeName:$.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return _i.create(this,this._def)}nullable(){return pa.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fa.create(this)}promise(){return Uc.create(this,this._def)}or(e){return zc.create([this,e],this._def)}and(e){return Dc.create(this,e,this._def)}transform(e){return new ha({...ce(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const n=typeof e=="function"?e:()=>e;return new Jp({...ce(this._def),innerType:this,defaultValue:n,typeName:$.ZodDefault})}brand(){return new uD({typeName:$.ZodBranded,type:this,...ce(this._def)})}catch(e){const n=typeof e=="function"?e:()=>e;return new Xp({...ce(this._def),innerType:this,catchValue:n,typeName:$.ZodCatch})}describe(e){const n=this.constructor;return new n({...this._def,description:e})}pipe(e){return hy.create(this,e)}readonly(){return Qp.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const U6=/^c[^\s-]{8,}$/i,F6=/^[0-9a-z]+$/,B6=/^[0-9A-HJKMNP-TV-Z]{26}$/i,H6=/^[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}$/i,Z6=/^[a-z0-9_-]{21}$/i,V6=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,K6=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,q6=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,W6="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let Xf;const G6=/^(?:(?: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])$/,J6=/^(?:(?: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])$/,X6=/^(([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]))$/,Q6=/^(([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])$/,Y6=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,eD=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,hT="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",tD=new RegExp(`^${hT}$`);function pT(t){let e="[0-5]\\d";t.precision?e=`${e}\\.\\d{${t.precision}}`:t.precision==null&&(e=`${e}(\\.\\d+)?`);const n=t.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${n}`}function nD(t){return new RegExp(`^${pT(t)}$`)}function rD(t){let e=`${hT}T${pT(t)}`;const n=[];return n.push(t.local?"Z?":"Z"),t.offset&&n.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${n.join("|")})`,new RegExp(`^${e}$`)}function iD(t,e){return!!((e==="v4"||!e)&&G6.test(t)||(e==="v6"||!e)&&X6.test(t))}function sD(t,e){if(!V6.test(t))return!1;try{const[n]=t.split(".");if(!n)return!1;const r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&(i==null?void 0:i.typ)!=="JWT"||!i.alg||e&&i.alg!==e)}catch{return!1}}function aD(t,e){return!!((e==="v4"||!e)&&J6.test(t)||(e==="v6"||!e)&&Q6.test(t))}let Vp=class no extends ge{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==X.string){const s=this._getOrReturnCtx(e);return V(s,{code:B.invalid_type,expected:X.string,received:s.parsedType}),se}const r=new mn;let i;for(const s of this._def.checks)if(s.kind==="min")e.data.length<s.value&&(i=this._getOrReturnCtx(e,i),V(i,{code:B.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="max")e.data.length>s.value&&(i=this._getOrReturnCtx(e,i),V(i,{code:B.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!1,message:s.message}),r.dirty());else if(s.kind==="length"){const a=e.data.length>s.value,o=e.data.length<s.value;(a||o)&&(i=this._getOrReturnCtx(e,i),a?V(i,{code:B.too_big,maximum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}):o&&V(i,{code:B.too_small,minimum:s.value,type:"string",inclusive:!0,exact:!0,message:s.message}),r.dirty())}else if(s.kind==="email")q6.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"email",code:B.invalid_string,message:s.message}),r.dirty());else if(s.kind==="emoji")Xf||(Xf=new RegExp(W6,"u")),Xf.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"emoji",code:B.invalid_string,message:s.message}),r.dirty());else if(s.kind==="uuid")H6.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"uuid",code:B.invalid_string,message:s.message}),r.dirty());else if(s.kind==="nanoid")Z6.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"nanoid",code:B.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid")U6.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"cuid",code:B.invalid_string,message:s.message}),r.dirty());else if(s.kind==="cuid2")F6.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"cuid2",code:B.invalid_string,message:s.message}),r.dirty());else if(s.kind==="ulid")B6.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"ulid",code:B.invalid_string,message:s.message}),r.dirty());else if(s.kind==="url")try{new URL(e.data)}catch{i=this._getOrReturnCtx(e,i),V(i,{validation:"url",code:B.invalid_string,message:s.message}),r.dirty()}else s.kind==="regex"?(s.regex.lastIndex=0,s.regex.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"regex",code:B.invalid_string,message:s.message}),r.dirty())):s.kind==="trim"?e.data=e.data.trim():s.kind==="includes"?e.data.includes(s.value,s.position)||(i=this._getOrReturnCtx(e,i),V(i,{code:B.invalid_string,validation:{includes:s.value,position:s.position},message:s.message}),r.dirty()):s.kind==="toLowerCase"?e.data=e.data.toLowerCase():s.kind==="toUpperCase"?e.data=e.data.toUpperCase():s.kind==="startsWith"?e.data.startsWith(s.value)||(i=this._getOrReturnCtx(e,i),V(i,{code:B.invalid_string,validation:{startsWith:s.value},message:s.message}),r.dirty()):s.kind==="endsWith"?e.data.endsWith(s.value)||(i=this._getOrReturnCtx(e,i),V(i,{code:B.invalid_string,validation:{endsWith:s.value},message:s.message}),r.dirty()):s.kind==="datetime"?rD(s).test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{code:B.invalid_string,validation:"datetime",message:s.message}),r.dirty()):s.kind==="date"?tD.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{code:B.invalid_string,validation:"date",message:s.message}),r.dirty()):s.kind==="time"?nD(s).test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{code:B.invalid_string,validation:"time",message:s.message}),r.dirty()):s.kind==="duration"?K6.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"duration",code:B.invalid_string,message:s.message}),r.dirty()):s.kind==="ip"?iD(e.data,s.version)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"ip",code:B.invalid_string,message:s.message}),r.dirty()):s.kind==="jwt"?sD(e.data,s.alg)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"jwt",code:B.invalid_string,message:s.message}),r.dirty()):s.kind==="cidr"?aD(e.data,s.version)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"cidr",code:B.invalid_string,message:s.message}),r.dirty()):s.kind==="base64"?Y6.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"base64",code:B.invalid_string,message:s.message}),r.dirty()):s.kind==="base64url"?eD.test(e.data)||(i=this._getOrReturnCtx(e,i),V(i,{validation:"base64url",code:B.invalid_string,message:s.message}),r.dirty()):_e.assertNever(s);return{status:r.value,value:e.data}}_regex(e,n,r){return this.refinement(i=>e.test(i),{validation:n,code:B.invalid_string,...Q.errToObj(r)})}_addCheck(e){return new no({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...Q.errToObj(e)})}url(e){return this._addCheck({kind:"url",...Q.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...Q.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...Q.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...Q.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...Q.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...Q.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...Q.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...Q.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...Q.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...Q.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...Q.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...Q.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,offset:(e==null?void 0:e.offset)??!1,local:(e==null?void 0:e.local)??!1,...Q.errToObj(e==null?void 0:e.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof(e==null?void 0:e.precision)>"u"?null:e==null?void 0:e.precision,...Q.errToObj(e==null?void 0:e.message)})}duration(e){return this._addCheck({kind:"duration",...Q.errToObj(e)})}regex(e,n){return this._addCheck({kind:"regex",regex:e,...Q.errToObj(n)})}includes(e,n){return this._addCheck({kind:"includes",value:e,position:n==null?void 0:n.position,...Q.errToObj(n==null?void 0:n.message)})}startsWith(e,n){return this._addCheck({kind:"startsWith",value:e,...Q.errToObj(n)})}endsWith(e,n){return this._addCheck({kind:"endsWith",value:e,...Q.errToObj(n)})}min(e,n){return this._addCheck({kind:"min",value:e,...Q.errToObj(n)})}max(e,n){return this._addCheck({kind:"max",value:e,...Q.errToObj(n)})}length(e,n){return this._addCheck({kind:"length",value:e,...Q.errToObj(n)})}nonempty(e){return this.min(1,Q.errToObj(e))}trim(){return new no({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new no({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new no({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxLength(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}};Vp.create=t=>new Vp({checks:[],typeName:$.ZodString,coerce:(t==null?void 0:t.coerce)??!1,...ce(t)});function oD(t,e){const n=(t.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,i=n>r?n:r,s=Number.parseInt(t.toFixed(i).replace(".","")),a=Number.parseInt(e.toFixed(i).replace(".",""));return s%a/10**i}let rw=class Kp extends ge{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==X.number){const s=this._getOrReturnCtx(e);return V(s,{code:B.invalid_type,expected:X.number,received:s.parsedType}),se}let r;const i=new mn;for(const s of this._def.checks)s.kind==="int"?_e.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),V(r,{code:B.invalid_type,expected:"integer",received:"float",message:s.message}),i.dirty()):s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),V(r,{code:B.too_small,minimum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),V(r,{code:B.too_big,maximum:s.value,type:"number",inclusive:s.inclusive,exact:!1,message:s.message}),i.dirty()):s.kind==="multipleOf"?oD(e.data,s.value)!==0&&(r=this._getOrReturnCtx(e,r),V(r,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):s.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),V(r,{code:B.not_finite,message:s.message}),i.dirty()):_e.assertNever(s);return{status:i.value,value:e.data}}gte(e,n){return this.setLimit("min",e,!0,Q.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Q.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Q.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Q.toString(n))}setLimit(e,n,r,i){return new Kp({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Q.toString(i)}]})}_addCheck(e){return new Kp({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:Q.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Q.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Q.toString(n)})}finite(e){return this._addCheck({kind:"finite",message:Q.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Q.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Q.toString(e)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&_e.isInteger(e.value))}get isFinite(){let e=null,n=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(n)&&Number.isFinite(e)}};rw.create=t=>new rw({checks:[],typeName:$.ZodNumber,coerce:(t==null?void 0:t.coerce)||!1,...ce(t)});class Jo extends ge{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==X.bigint)return this._getInvalidInput(e);let r;const i=new mn;for(const s of this._def.checks)s.kind==="min"?(s.inclusive?e.data<s.value:e.data<=s.value)&&(r=this._getOrReturnCtx(e,r),V(r,{code:B.too_small,type:"bigint",minimum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="max"?(s.inclusive?e.data>s.value:e.data>=s.value)&&(r=this._getOrReturnCtx(e,r),V(r,{code:B.too_big,type:"bigint",maximum:s.value,inclusive:s.inclusive,message:s.message}),i.dirty()):s.kind==="multipleOf"?e.data%s.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),V(r,{code:B.not_multiple_of,multipleOf:s.value,message:s.message}),i.dirty()):_e.assertNever(s);return{status:i.value,value:e.data}}_getInvalidInput(e){const n=this._getOrReturnCtx(e);return V(n,{code:B.invalid_type,expected:X.bigint,received:n.parsedType}),se}gte(e,n){return this.setLimit("min",e,!0,Q.toString(n))}gt(e,n){return this.setLimit("min",e,!1,Q.toString(n))}lte(e,n){return this.setLimit("max",e,!0,Q.toString(n))}lt(e,n){return this.setLimit("max",e,!1,Q.toString(n))}setLimit(e,n,r,i){return new Jo({...this._def,checks:[...this._def.checks,{kind:e,value:n,inclusive:r,message:Q.toString(i)}]})}_addCheck(e){return new Jo({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:Q.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Q.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Q.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Q.toString(e)})}multipleOf(e,n){return this._addCheck({kind:"multipleOf",value:e,message:Q.toString(n)})}get minValue(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e}get maxValue(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e}}Jo.create=t=>new Jo({checks:[],typeName:$.ZodBigInt,coerce:(t==null?void 0:t.coerce)??!1,...ce(t)});class iw extends ge{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==X.boolean){const r=this._getOrReturnCtx(e);return V(r,{code:B.invalid_type,expected:X.boolean,received:r.parsedType}),se}return Pn(e.data)}}iw.create=t=>new iw({typeName:$.ZodBoolean,coerce:(t==null?void 0:t.coerce)||!1,...ce(t)});class Mc extends ge{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==X.date){const s=this._getOrReturnCtx(e);return V(s,{code:B.invalid_type,expected:X.date,received:s.parsedType}),se}if(Number.isNaN(e.data.getTime())){const s=this._getOrReturnCtx(e);return V(s,{code:B.invalid_date}),se}const r=new mn;let i;for(const s of this._def.checks)s.kind==="min"?e.data.getTime()<s.value&&(i=this._getOrReturnCtx(e,i),V(i,{code:B.too_small,message:s.message,inclusive:!0,exact:!1,minimum:s.value,type:"date"}),r.dirty()):s.kind==="max"?e.data.getTime()>s.value&&(i=this._getOrReturnCtx(e,i),V(i,{code:B.too_big,message:s.message,inclusive:!0,exact:!1,maximum:s.value,type:"date"}),r.dirty()):_e.assertNever(s);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new Mc({...this._def,checks:[...this._def.checks,e]})}min(e,n){return this._addCheck({kind:"min",value:e.getTime(),message:Q.toString(n)})}max(e,n){return this._addCheck({kind:"max",value:e.getTime(),message:Q.toString(n)})}get minDate(){let e=null;for(const n of this._def.checks)n.kind==="min"&&(e===null||n.value>e)&&(e=n.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const n of this._def.checks)n.kind==="max"&&(e===null||n.value<e)&&(e=n.value);return e!=null?new Date(e):null}}Mc.create=t=>new Mc({checks:[],coerce:(t==null?void 0:t.coerce)||!1,typeName:$.ZodDate,...ce(t)});class sw extends ge{_parse(e){if(this._getType(e)!==X.symbol){const r=this._getOrReturnCtx(e);return V(r,{code:B.invalid_type,expected:X.symbol,received:r.parsedType}),se}return Pn(e.data)}}sw.create=t=>new sw({typeName:$.ZodSymbol,...ce(t)});class aw extends ge{_parse(e){if(this._getType(e)!==X.undefined){const r=this._getOrReturnCtx(e);return V(r,{code:B.invalid_type,expected:X.undefined,received:r.parsedType}),se}return Pn(e.data)}}aw.create=t=>new aw({typeName:$.ZodUndefined,...ce(t)});class ow extends ge{_parse(e){if(this._getType(e)!==X.null){const r=this._getOrReturnCtx(e);return V(r,{code:B.invalid_type,expected:X.null,received:r.parsedType}),se}return Pn(e.data)}}ow.create=t=>new ow({typeName:$.ZodNull,...ce(t)});class qp extends ge{constructor(){super(...arguments),this._any=!0}_parse(e){return Pn(e.data)}}qp.create=t=>new qp({typeName:$.ZodAny,...ce(t)});let uw=class extends ge{constructor(){super(...arguments),this._unknown=!0}_parse(e){return Pn(e.data)}};uw.create=t=>new uw({typeName:$.ZodUnknown,...ce(t)});let Ii=class extends ge{_parse(e){const n=this._getOrReturnCtx(e);return V(n,{code:B.invalid_type,expected:X.never,received:n.parsedType}),se}};Ii.create=t=>new Ii({typeName:$.ZodNever,...ce(t)});class lw extends ge{_parse(e){if(this._getType(e)!==X.undefined){const r=this._getOrReturnCtx(e);return V(r,{code:B.invalid_type,expected:X.void,received:r.parsedType}),se}return Pn(e.data)}}lw.create=t=>new lw({typeName:$.ZodVoid,...ce(t)});let fa=class Ml extends ge{_parse(e){const{ctx:n,status:r}=this._processInputParams(e),i=this._def;if(n.parsedType!==X.array)return V(n,{code:B.invalid_type,expected:X.array,received:n.parsedType}),se;if(i.exactLength!==null){const a=n.data.length>i.exactLength.value,o=n.data.length<i.exactLength.value;(a||o)&&(V(n,{code:a?B.too_big:B.too_small,minimum:o?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(V(n,{code:B.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(V(n,{code:B.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,o)=>i.type._parseAsync(new Ti(n,a,n.path,o)))).then(a=>mn.mergeArray(r,a));const s=[...n.data].map((a,o)=>i.type._parseSync(new Ti(n,a,n.path,o)));return mn.mergeArray(r,s)}get element(){return this._def.type}min(e,n){return new Ml({...this._def,minLength:{value:e,message:Q.toString(n)}})}max(e,n){return new Ml({...this._def,maxLength:{value:e,message:Q.toString(n)}})}length(e,n){return new Ml({...this._def,exactLength:{value:e,message:Q.toString(n)}})}nonempty(e){return this.min(1,e)}};fa.create=(t,e)=>new fa({type:t,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...ce(e)});function xs(t){if(t instanceof Yn){const e={};for(const n in t.shape){const r=t.shape[n];e[n]=_i.create(xs(r))}return new Yn({...t._def,shape:()=>e})}else return t instanceof fa?new fa({...t._def,type:xs(t.element)}):t instanceof _i?_i.create(xs(t.unwrap())):t instanceof pa?pa.create(xs(t.unwrap())):t instanceof as?as.create(t.items.map(e=>xs(e))):t}let Yn=class Fn extends ge{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;const e=this._def.shape(),n=_e.objectKeys(e);return this._cached={shape:e,keys:n},this._cached}_parse(e){if(this._getType(e)!==X.object){const l=this._getOrReturnCtx(e);return V(l,{code:B.invalid_type,expected:X.object,received:l.parsedType}),se}const{status:r,ctx:i}=this._processInputParams(e),{shape:s,keys:a}=this._getCached(),o=[];if(!(this._def.catchall instanceof Ii&&this._def.unknownKeys==="strip"))for(const l in i.data)a.includes(l)||o.push(l);const u=[];for(const l of a){const c=s[l],d=i.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new Ti(i,d,i.path,l)),alwaysSet:l in i.data})}if(this._def.catchall instanceof Ii){const l=this._def.unknownKeys;if(l==="passthrough")for(const c of o)u.push({key:{status:"valid",value:c},value:{status:"valid",value:i.data[c]}});else if(l==="strict")o.length>0&&(V(i,{code:B.unrecognized_keys,keys:o}),r.dirty());else if(l!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const l=this._def.catchall;for(const c of o){const d=i.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new Ti(i,d,i.path,c)),alwaysSet:c in i.data})}}return i.common.async?Promise.resolve().then(async()=>{const l=[];for(const c of u){const d=await c.key,f=await c.value;l.push({key:d,value:f,alwaysSet:c.alwaysSet})}return l}).then(l=>mn.mergeObjectSync(r,l)):mn.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return Q.errToObj,new Fn({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(n,r)=>{var s,a;const i=((a=(s=this._def).errorMap)==null?void 0:a.call(s,n,r).message)??r.defaultError;return n.code==="unrecognized_keys"?{message:Q.errToObj(e).message??i}:{message:i}}}:{}})}strip(){return new Fn({...this._def,unknownKeys:"strip"})}passthrough(){return new Fn({...this._def,unknownKeys:"passthrough"})}extend(e){return new Fn({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new Fn({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:$.ZodObject})}setKey(e,n){return this.augment({[e]:n})}catchall(e){return new Fn({...this._def,catchall:e})}pick(e){const n={};for(const r of _e.objectKeys(e))e[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new Fn({...this._def,shape:()=>n})}omit(e){const n={};for(const r of _e.objectKeys(this.shape))e[r]||(n[r]=this.shape[r]);return new Fn({...this._def,shape:()=>n})}deepPartial(){return xs(this)}partial(e){const n={};for(const r of _e.objectKeys(this.shape)){const i=this.shape[r];e&&!e[r]?n[r]=i:n[r]=i.optional()}return new Fn({...this._def,shape:()=>n})}required(e){const n={};for(const r of _e.objectKeys(this.shape))if(e&&!e[r])n[r]=this.shape[r];else{let s=this.shape[r];for(;s instanceof _i;)s=s._def.innerType;n[r]=s}return new Fn({...this._def,shape:()=>n})}keyof(){return mT(_e.objectKeys(this.shape))}};Yn.create=(t,e)=>new Yn({shape:()=>t,unknownKeys:"strip",catchall:Ii.create(),typeName:$.ZodObject,...ce(e)});Yn.strictCreate=(t,e)=>new Yn({shape:()=>t,unknownKeys:"strict",catchall:Ii.create(),typeName:$.ZodObject,...ce(e)});Yn.lazycreate=(t,e)=>new Yn({shape:t,unknownKeys:"strip",catchall:Ii.create(),typeName:$.ZodObject,...ce(e)});let zc=class extends ge{_parse(e){const{ctx:n}=this._processInputParams(e),r=this._def.options;function i(s){for(const o of s)if(o.result.status==="valid")return o.result;for(const o of s)if(o.result.status==="dirty")return n.common.issues.push(...o.ctx.common.issues),o.result;const a=s.map(o=>new Br(o.ctx.common.issues));return V(n,{code:B.invalid_union,unionErrors:a}),se}if(n.common.async)return Promise.all(r.map(async s=>{const a={...n,common:{...n.common,issues:[]},parent:null};return{result:await s._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let s;const a=[];for(const u of r){const l={...n,common:{...n.common,issues:[]},parent:null},c=u._parseSync({data:n.data,path:n.path,parent:l});if(c.status==="valid")return c;c.status==="dirty"&&!s&&(s={result:c,ctx:l}),l.common.issues.length&&a.push(l.common.issues)}if(s)return n.common.issues.push(...s.ctx.common.issues),s.result;const o=a.map(u=>new Br(u));return V(n,{code:B.invalid_union,unionErrors:o}),se}}get options(){return this._def.options}};zc.create=(t,e)=>new zc({options:t,typeName:$.ZodUnion,...ce(e)});function Wp(t,e){const n=ni(t),r=ni(e);if(t===e)return{valid:!0,data:t};if(n===X.object&&r===X.object){const i=_e.objectKeys(e),s=_e.objectKeys(t).filter(o=>i.indexOf(o)!==-1),a={...t,...e};for(const o of s){const u=Wp(t[o],e[o]);if(!u.valid)return{valid:!1};a[o]=u.data}return{valid:!0,data:a}}else if(n===X.array&&r===X.array){if(t.length!==e.length)return{valid:!1};const i=[];for(let s=0;s<t.length;s++){const a=t[s],o=e[s],u=Wp(a,o);if(!u.valid)return{valid:!1};i.push(u.data)}return{valid:!0,data:i}}else return n===X.date&&r===X.date&&+t==+e?{valid:!0,data:t}:{valid:!1}}let Dc=class extends ge{_parse(e){const{status:n,ctx:r}=this._processInputParams(e),i=(s,a)=>{if(ew(s)||ew(a))return se;const o=Wp(s.value,a.value);return o.valid?((tw(s)||tw(a))&&n.dirty(),{status:n.value,value:o.data}):(V(r,{code:B.invalid_intersection_types}),se)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([s,a])=>i(s,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};Dc.create=(t,e,n)=>new Dc({left:t,right:e,typeName:$.ZodIntersection,...ce(n)});class as extends ge{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==X.array)return V(r,{code:B.invalid_type,expected:X.array,received:r.parsedType}),se;if(r.data.length<this._def.items.length)return V(r,{code:B.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),se;!this._def.rest&&r.data.length>this._def.items.length&&(V(r,{code:B.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());const s=[...r.data].map((a,o)=>{const u=this._def.items[o]||this._def.rest;return u?u._parse(new Ti(r,a,r.path,o)):null}).filter(a=>!!a);return r.common.async?Promise.all(s).then(a=>mn.mergeArray(n,a)):mn.mergeArray(n,s)}get items(){return this._def.items}rest(e){return new as({...this._def,rest:e})}}as.create=(t,e)=>{if(!Array.isArray(t))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new as({items:t,typeName:$.ZodTuple,rest:null,...ce(e)})};class cw extends ge{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==X.map)return V(r,{code:B.invalid_type,expected:X.map,received:r.parsedType}),se;const i=this._def.keyType,s=this._def.valueType,a=[...r.data.entries()].map(([o,u],l)=>({key:i._parse(new Ti(r,o,r.path,[l,"key"])),value:s._parse(new Ti(r,u,r.path,[l,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const u of a){const l=await u.key,c=await u.value;if(l.status==="aborted"||c.status==="aborted")return se;(l.status==="dirty"||c.status==="dirty")&&n.dirty(),o.set(l.value,c.value)}return{status:n.value,value:o}})}else{const o=new Map;for(const u of a){const l=u.key,c=u.value;if(l.status==="aborted"||c.status==="aborted")return se;(l.status==="dirty"||c.status==="dirty")&&n.dirty(),o.set(l.value,c.value)}return{status:n.value,value:o}}}}cw.create=(t,e,n)=>new cw({valueType:e,keyType:t,typeName:$.ZodMap,...ce(n)});class Xo extends ge{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.parsedType!==X.set)return V(r,{code:B.invalid_type,expected:X.set,received:r.parsedType}),se;const i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(V(r,{code:B.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(V(r,{code:B.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());const s=this._def.valueType;function a(u){const l=new Set;for(const c of u){if(c.status==="aborted")return se;c.status==="dirty"&&n.dirty(),l.add(c.value)}return{status:n.value,value:l}}const o=[...r.data.values()].map((u,l)=>s._parse(new Ti(r,u,r.path,l)));return r.common.async?Promise.all(o).then(u=>a(u)):a(o)}min(e,n){return new Xo({...this._def,minSize:{value:e,message:Q.toString(n)}})}max(e,n){return new Xo({...this._def,maxSize:{value:e,message:Q.toString(n)}})}size(e,n){return this.min(e,n).max(e,n)}nonempty(e){return this.min(1,e)}}Xo.create=(t,e)=>new Xo({valueType:t,minSize:null,maxSize:null,typeName:$.ZodSet,...ce(e)});class dw extends ge{get schema(){return this._def.getter()}_parse(e){const{ctx:n}=this._processInputParams(e);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}}dw.create=(t,e)=>new dw({getter:t,typeName:$.ZodLazy,...ce(e)});let fw=class extends ge{_parse(e){if(e.data!==this._def.value){const n=this._getOrReturnCtx(e);return V(n,{received:n.data,code:B.invalid_literal,expected:this._def.value}),se}return{status:"valid",value:e.data}}get value(){return this._def.value}};fw.create=(t,e)=>new fw({value:t,typeName:$.ZodLiteral,...ce(e)});function mT(t,e){return new fy({values:t,typeName:$.ZodEnum,...ce(e)})}let fy=class Gp extends ge{_parse(e){if(typeof e.data!="string"){const n=this._getOrReturnCtx(e),r=this._def.values;return V(n,{expected:_e.joinValues(r),received:n.parsedType,code:B.invalid_type}),se}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const n=this._getOrReturnCtx(e),r=this._def.values;return V(n,{received:n.data,code:B.invalid_enum_value,options:r}),se}return Pn(e.data)}get options(){return this._def.values}get enum(){const e={};for(const n of this._def.values)e[n]=n;return e}get Values(){const e={};for(const n of this._def.values)e[n]=n;return e}get Enum(){const e={};for(const n of this._def.values)e[n]=n;return e}extract(e,n=this._def){return Gp.create(e,{...this._def,...n})}exclude(e,n=this._def){return Gp.create(this.options.filter(r=>!e.includes(r)),{...this._def,...n})}};fy.create=mT;class hw extends ge{_parse(e){const n=_e.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==X.string&&r.parsedType!==X.number){const i=_e.objectValues(n);return V(r,{expected:_e.joinValues(i),received:r.parsedType,code:B.invalid_type}),se}if(this._cache||(this._cache=new Set(_e.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const i=_e.objectValues(n);return V(r,{received:r.data,code:B.invalid_enum_value,options:i}),se}return Pn(e.data)}get enum(){return this._def.values}}hw.create=(t,e)=>new hw({values:t,typeName:$.ZodNativeEnum,...ce(e)});class Uc extends ge{unwrap(){return this._def.type}_parse(e){const{ctx:n}=this._processInputParams(e);if(n.parsedType!==X.promise&&n.common.async===!1)return V(n,{code:B.invalid_type,expected:X.promise,received:n.parsedType}),se;const r=n.parsedType===X.promise?n.data:Promise.resolve(n.data);return Pn(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}}Uc.create=(t,e)=>new Uc({type:t,typeName:$.ZodPromise,...ce(e)});class ha extends ge{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:n,ctx:r}=this._processInputParams(e),i=this._def.effect||null,s={addIssue:a=>{V(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(s.addIssue=s.addIssue.bind(s),i.type==="preprocess"){const a=i.transform(r.data,s);if(r.common.async)return Promise.resolve(a).then(async o=>{if(n.value==="aborted")return se;const u=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return u.status==="aborted"?se:u.status==="dirty"||n.value==="dirty"?to(u.value):u});{if(n.value==="aborted")return se;const o=this._def.schema._parseSync({data:a,path:r.path,parent:r});return o.status==="aborted"?se:o.status==="dirty"||n.value==="dirty"?to(o.value):o}}if(i.type==="refinement"){const a=o=>{const u=i.refinement(o,s);if(r.common.async)return Promise.resolve(u);if(u instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return o};if(r.common.async===!1){const o=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?se:(o.status==="dirty"&&n.dirty(),a(o.value),{status:n.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?se:(o.status==="dirty"&&n.dirty(),a(o.value).then(()=>({status:n.value,value:o.value}))))}if(i.type==="transform")if(r.common.async===!1){const a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!da(a))return se;const o=i.transform(a.value,s);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>da(a)?Promise.resolve(i.transform(a.value,s)).then(o=>({status:n.value,value:o})):se);_e.assertNever(i)}}ha.create=(t,e,n)=>new ha({schema:t,typeName:$.ZodEffects,effect:e,...ce(n)});ha.createWithPreprocess=(t,e,n)=>new ha({schema:e,effect:{type:"preprocess",transform:t},typeName:$.ZodEffects,...ce(n)});let _i=class extends ge{_parse(e){return this._getType(e)===X.undefined?Pn(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};_i.create=(t,e)=>new _i({innerType:t,typeName:$.ZodOptional,...ce(e)});let pa=class extends ge{_parse(e){return this._getType(e)===X.null?Pn(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};pa.create=(t,e)=>new pa({innerType:t,typeName:$.ZodNullable,...ce(e)});let Jp=class extends ge{_parse(e){const{ctx:n}=this._processInputParams(e);let r=n.data;return n.parsedType===X.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};Jp.create=(t,e)=>new Jp({innerType:t,typeName:$.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...ce(e)});let Xp=class extends ge{_parse(e){const{ctx:n}=this._processInputParams(e),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Lc(i)?i.then(s=>({status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new Br(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Br(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};Xp.create=(t,e)=>new Xp({innerType:t,typeName:$.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...ce(e)});class pw extends ge{_parse(e){if(this._getType(e)!==X.nan){const r=this._getOrReturnCtx(e);return V(r,{code:B.invalid_type,expected:X.nan,received:r.parsedType}),se}return{status:"valid",value:e.data}}}pw.create=t=>new pw({typeName:$.ZodNaN,...ce(t)});class uD extends ge{_parse(e){const{ctx:n}=this._processInputParams(e),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}}class hy extends ge{_parse(e){const{status:n,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const s=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?se:s.status==="dirty"?(n.dirty(),to(s.value)):this._def.out._parseAsync({data:s.value,path:r.path,parent:r})})();{const i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?se:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(e,n){return new hy({in:e,out:n,typeName:$.ZodPipeline})}}let Qp=class extends ge{_parse(e){const n=this._def.innerType._parse(e),r=i=>(da(i)&&(i.value=Object.freeze(i.value)),i);return Lc(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};Qp.create=(t,e)=>new Qp({innerType:t,typeName:$.ZodReadonly,...ce(e)});Yn.lazycreate;var $;(function(t){t.ZodString="ZodString",t.ZodNumber="ZodNumber",t.ZodNaN="ZodNaN",t.ZodBigInt="ZodBigInt",t.ZodBoolean="ZodBoolean",t.ZodDate="ZodDate",t.ZodSymbol="ZodSymbol",t.ZodUndefined="ZodUndefined",t.ZodNull="ZodNull",t.ZodAny="ZodAny",t.ZodUnknown="ZodUnknown",t.ZodNever="ZodNever",t.ZodVoid="ZodVoid",t.ZodArray="ZodArray",t.ZodObject="ZodObject",t.ZodUnion="ZodUnion",t.ZodDiscriminatedUnion="ZodDiscriminatedUnion",t.ZodIntersection="ZodIntersection",t.ZodTuple="ZodTuple",t.ZodRecord="ZodRecord",t.ZodMap="ZodMap",t.ZodSet="ZodSet",t.ZodFunction="ZodFunction",t.ZodLazy="ZodLazy",t.ZodLiteral="ZodLiteral",t.ZodEnum="ZodEnum",t.ZodEffects="ZodEffects",t.ZodNativeEnum="ZodNativeEnum",t.ZodOptional="ZodOptional",t.ZodNullable="ZodNullable",t.ZodDefault="ZodDefault",t.ZodCatch="ZodCatch",t.ZodPromise="ZodPromise",t.ZodBranded="ZodBranded",t.ZodPipeline="ZodPipeline",t.ZodReadonly="ZodReadonly"})($||($={}));const gT=Vp.create,mw=qp.create;Ii.create;fa.create;const yT=Yn.create;Yn.strictCreate;zc.create;Dc.create;as.create;fy.create;Uc.create;_i.create;pa.create;function lD(t,e){var r,i,s;const n={type:"array"};return(r=t.type)!=null&&r._def&&((s=(i=t.type)==null?void 0:i._def)==null?void 0:s.typeName)!==$.ZodAny&&(n.items=we(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&ke(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&ke(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(ke(n,"minItems",t.exactLength.value,t.exactLength.message,e),ke(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function cD(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ke(n,"minimum",r.value,r.message,e):ke(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ke(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ke(n,"maximum",r.value,r.message,e):ke(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ke(n,"maximum",r.value,r.message,e));break;case"multipleOf":ke(n,"multipleOf",r.value,r.message,e);break}return n}function dD(){return{type:"boolean"}}function _T(t,e){return we(t.type._def,e)}const fD=(t,e)=>we(t.innerType._def,e);function vT(t,e,n){const r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map(i=>vT(t,e,i))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return hD(t,e)}}const hD=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const r of t.checks)switch(r.kind){case"min":ke(n,"minimum",r.value,r.message,e);break;case"max":ke(n,"maximum",r.value,r.message,e);break}return n};function pD(t,e){return{...we(t.innerType._def,e),default:t.defaultValue()}}function mD(t,e){return e.effectStrategy==="input"?we(t.schema._def,e):pn(e)}function gD(t){return{type:"string",enum:Array.from(t.values)}}const yD=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function _D(t,e){const n=[we(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),we(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const i=[];return n.forEach(s=>{if(yD(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...u}=s;a=u}else r=void 0;i.push(a)}}),i.length?{allOf:i,...r}:void 0}function vD(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let Qf;const Ln={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:()=>(Qf===void 0&&(Qf=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Qf),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 wT(t,e){const n={type:"string"};if(t.checks)for(const r of t.checks)switch(r.kind){case"min":ke(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e);break;case"max":ke(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Mn(n,"email",r.message,e);break;case"format:idn-email":Mn(n,"idn-email",r.message,e);break;case"pattern:zod":Ot(n,Ln.email,r.message,e);break}break;case"url":Mn(n,"uri",r.message,e);break;case"uuid":Mn(n,"uuid",r.message,e);break;case"regex":Ot(n,r.regex,r.message,e);break;case"cuid":Ot(n,Ln.cuid,r.message,e);break;case"cuid2":Ot(n,Ln.cuid2,r.message,e);break;case"startsWith":Ot(n,RegExp(`^${Yf(r.value,e)}`),r.message,e);break;case"endsWith":Ot(n,RegExp(`${Yf(r.value,e)}$`),r.message,e);break;case"datetime":Mn(n,"date-time",r.message,e);break;case"date":Mn(n,"date",r.message,e);break;case"time":Mn(n,"time",r.message,e);break;case"duration":Mn(n,"duration",r.message,e);break;case"length":ke(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,r.value):r.value,r.message,e),ke(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,r.value):r.value,r.message,e);break;case"includes":Ot(n,RegExp(Yf(r.value,e)),r.message,e);break;case"ip":r.version!=="v6"&&Mn(n,"ipv4",r.message,e),r.version!=="v4"&&Mn(n,"ipv6",r.message,e);break;case"base64url":Ot(n,Ln.base64url,r.message,e);break;case"jwt":Ot(n,Ln.jwt,r.message,e);break;case"cidr":r.version!=="v6"&&Ot(n,Ln.ipv4Cidr,r.message,e),r.version!=="v4"&&Ot(n,Ln.ipv6Cidr,r.message,e);break;case"emoji":Ot(n,Ln.emoji(),r.message,e);break;case"ulid":Ot(n,Ln.ulid,r.message,e);break;case"base64":switch(e.base64Strategy){case"format:binary":Mn(n,"binary",r.message,e);break;case"contentEncoding:base64":ke(n,"contentEncoding","base64",r.message,e);break;case"pattern:zod":Ot(n,Ln.base64,r.message,e);break}break;case"nanoid":Ot(n,Ln.nanoid,r.message,e);break}return n}function Yf(t,e){return e.patternStrategy==="escape"?bD(t):t}const wD=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function bD(t){let e="";for(let n=0;n<t.length;n++)wD.has(t[n])||(e+="\\"),e+=t[n];return e}function Mn(t,e,n,r){var i;t.format||(i=t.anyOf)!=null&&i.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):ke(t,"format",e,n,r)}function Ot(t,e,n,r){var i;t.pattern||(i=t.allOf)!=null&&i.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:gw(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):ke(t,"pattern",gw(e,r),n,r)}function gw(t,e){var u;if(!e.applyRegexFlags||!t.flags)return t.source;const n={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},r=n.i?t.source.toLowerCase():t.source;let i="",s=!1,a=!1,o=!1;for(let l=0;l<r.length;l++){if(s){i+=r[l],s=!1;continue}if(n.i){if(a){if(r[l].match(/[a-z]/)){o?(i+=r[l],i+=`${r[l-2]}-${r[l]}`.toUpperCase(),o=!1):r[l+1]==="-"&&((u=r[l+2])!=null&&u.match(/[a-z]/))?(i+=r[l],o=!0):i+=`${r[l]}${r[l].toUpperCase()}`;continue}}else if(r[l].match(/[a-z]/)){i+=`[${r[l]}${r[l].toUpperCase()}]`;continue}}if(n.m){if(r[l]==="^"){i+=`(^|(?<=[\r ]))`;continue}else if(r[l]==="$"){i+=`($|(?=[\r ]))`;continue}}if(n.s&&r[l]==="."){i+=a?`${r[l]}\r `:`[${r[l]}\r ]`;continue}i+=r[l],r[l]==="\\"?s=!0:a&&r[l]==="]"?a=!1:!a&&r[l]==="["&&(a=!0)}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),t.source}return i}function bT(t,e){var r,i,s,a,o,u;if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&((r=t.keyType)==null?void 0:r._def.typeName)===$.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((l,c)=>({...l,[c]:we(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",c]})??pn(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const n={type:"object",additionalProperties:we(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return n;if(((i=t.keyType)==null?void 0:i._def.typeName)===$.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const{type:l,...c}=wT(t.keyType._def,e);return{...n,propertyNames:c}}else{if(((a=t.keyType)==null?void 0:a._def.typeName)===$.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};if(((o=t.keyType)==null?void 0:o._def.typeName)===$.ZodBranded&&t.keyType._def.type._def.typeName===$.ZodString&&((u=t.keyType._def.type._def.checks)!=null&&u.length)){const{type:l,...c}=_T(t.keyType._def,e);return{...n,propertyNames:c}}}return n}function xD(t,e){return e.mapStrategy==="record"?bT(t,e):{type:"array",maxItems:125,items:{type:"array",items:[we(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||pn(e),we(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||pn(e)],minItems:2,maxItems:2}}}function kD(t){const e=t.values,n=Object.keys(t.values).filter(i=>typeof e[e[i]]!="number").map(i=>e[i]),r=Array.from(new Set(n.map(i=>typeof i)));return{type:r.length===1?r[0]==="string"?"string":"number":["string","number"],enum:n}}function SD(t){return t.target==="openAi"?void 0:{not:pn({...t,currentPath:[...t.currentPath,"not"]})}}function AD(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Fc={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function ED(t,e){if(e.target==="openApi3")return yw(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Fc&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((i,s)=>{const a=Fc[s._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((i,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];case"bigint":return[...i,"integer"];case"object":return s._def.value===null?[...i,"null"]:i;default:return i}},[]);if(r.length===n.length){const i=r.filter((s,a,o)=>o.indexOf(s)===a);return{type:i.length>1?i:i[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,i)=>[...r,...i._def.values.filter(s=>!r.includes(s))],[])};return yw(t,e)}const yw=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,i)=>we(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function TD(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"?{type:Fc[t.innerType._def.typeName],nullable:!0}:{type:[Fc[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=we(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=we(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function ID(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",fT(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ke(n,"minimum",r.value,r.message,e):ke(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),ke(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ke(n,"maximum",r.value,r.message,e):ke(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),ke(n,"maximum",r.value,r.message,e));break;case"multipleOf":ke(n,"multipleOf",r.value,r.message,e);break}return n}function OD(t,e){const n=e.target==="openAi",r={type:"object",properties:{}},i=[],s=t.shape();for(const o in s){let u=s[o];if(u===void 0||u._def===void 0)continue;let l=PD(u);l&&n&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),l=!1);const c=we(u._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});c!==void 0&&(r.properties[o]=c,l||i.push(o))}i.length&&(r.required=i);const a=CD(t,e);return a!==void 0&&(r.additionalProperties=a),r}function CD(t,e){if(t.catchall._def.typeName!=="ZodNever")return we(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(t.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function PD(t){try{return t.isOptional()}catch{return!0}}const ND=(t,e)=>{var r;if(e.currentPath.toString()===((r=e.propertyPath)==null?void 0:r.toString()))return we(t.innerType._def,e);const n=we(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:pn(e)},n]}:pn(e)},$D=(t,e)=>{if(e.pipeStrategy==="input")return we(t.in._def,e);if(e.pipeStrategy==="output")return we(t.out._def,e);const n=we(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]});return{allOf:[n,we(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]})].filter(r=>r!==void 0)}};function RD(t,e){return we(t.type._def,e)}function jD(t,e){const n={type:"array",uniqueItems:!0,items:we(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&ke(n,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&ke(n,"maxItems",t.maxSize.value,t.maxSize.message,e),n}function LD(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>we(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:we(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>we(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function MD(t){return{not:pn(t)}}function zD(t){return pn(t)}const DD=(t,e)=>we(t.innerType._def,e),UD=(t,e,n)=>{switch(e){case $.ZodString:return wT(t,n);case $.ZodNumber:return ID(t,n);case $.ZodObject:return OD(t,n);case $.ZodBigInt:return cD(t,n);case $.ZodBoolean:return dD();case $.ZodDate:return vT(t,n);case $.ZodUndefined:return MD(n);case $.ZodNull:return AD(n);case $.ZodArray:return lD(t,n);case $.ZodUnion:case $.ZodDiscriminatedUnion:return ED(t,n);case $.ZodIntersection:return _D(t,n);case $.ZodTuple:return LD(t,n);case $.ZodRecord:return bT(t,n);case $.ZodLiteral:return vD(t,n);case $.ZodEnum:return gD(t);case $.ZodNativeEnum:return kD(t);case $.ZodNullable:return TD(t,n);case $.ZodOptional:return ND(t,n);case $.ZodMap:return xD(t,n);case $.ZodSet:return jD(t,n);case $.ZodLazy:return()=>t.getter()._def;case $.ZodPromise:return RD(t,n);case $.ZodNaN:case $.ZodNever:return SD(n);case $.ZodEffects:return mD(t,n);case $.ZodAny:return pn(n);case $.ZodUnknown:return zD(n);case $.ZodDefault:return pD(t,n);case $.ZodBranded:return _T(t,n);case $.ZodReadonly:return DD(t,n);case $.ZodCatch:return fD(t,n);case $.ZodPipeline:return $D(t,n);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(r=>{})()}};function we(t,e,n=!1){var o;const r=e.seen.get(t);if(e.override){const u=(o=e.override)==null?void 0:o.call(e,t,e,r,n);if(u!==$6)return u}if(r&&!n){const u=FD(r,e);if(u!==void 0)return u}const i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);const s=UD(t,t.typeName,e),a=typeof s=="function"?we(s(),e):s;if(a&&BD(t,e,a),e.postProcess){const u=e.postProcess(a,t,e);return i.jsonSchema=a,u}return i.jsonSchema=a,a}const FD=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"relative":return{$ref:dT(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((n,r)=>e.currentPath[r]===n)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),pn(e)):e.$refStrategy==="seen"?pn(e):void 0}},BD=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),HD=(t,e)=>{const n=L6(e);let r;const i=e==null?void 0:e.name,s=we(t._def,n,!1)??pn(n);n.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:n.$refStrategy==="relative"?"1":[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join("/")}}));const a=i===void 0?r?{...s,[n.definitionPath]:r}:s:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,i].join("/"),[n.definitionPath]:{...r,[i]:s}};return n.target==="jsonSchema7"?a.$schema="http://json-schema.org/draft-07/schema#":(n.target==="jsonSchema2019-09"||n.target==="openAi")&&(a.$schema="https://json-schema.org/draft/2019-09/schema#"),n.target==="openAi"&&("anyOf"in a||"oneOf"in a||"allOf"in a||"type"in a&&Array.isArray(a.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),a};function ZD(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"validate"in t["~standard"]}function xT(t){return(typeof t=="object"||typeof t=="function")&&t!==null&&"~standard"in t&&typeof t["~standard"]=="object"&&t["~standard"]!==null&&"jsonSchema"in t["~standard"]}function ma(t){return ZD(t)&&xT(t)}function Yp(t,e){const n=typeof t;if(n!==typeof e)return!1;if(Array.isArray(t)){if(!Array.isArray(e))return!1;const r=t.length;if(r!==e.length)return!1;for(let i=0;i<r;i++)if(!Yp(t[i],e[i]))return!1;return!0}if(n==="object"){if(!t||!e)return t===e;const r=Object.keys(t),i=Object.keys(e);if(r.length!==i.length)return!1;for(const a of r)if(!Yp(t[a],e[a]))return!1;return!0}return t===e}const _w=new WeakMap;function vi(t,e){const n=!e&&t!=null&&typeof t=="object";if(n){const i=_w.get(t);if(i)return i}let r;if(xT(t)&&!tn(t))r=t["~standard"].jsonSchema.input({target:"draft-07"});else if(tn(t)){const i=I6(t,!0);bo(i)?r=Bp(Hp(i,!0),e):r=Bp(t,e)}else Kr(t)?r=HD(t):r=t;return n&&r!=null&&typeof r=="object"&&_w.set(t,r),r}function VD(t,e){if(t!==void 0&&!Pl(t))return t;if(ry(e))try{let n=e.getName();return n=n.startsWith("Runnable")?n.slice(8):n,n}catch{return e.getName()}else return e.name??"UnknownSchema"}function KD(t){return ry(t.data)?{type:"runnable",data:{id:t.data.lc_id,name:t.data.getName()}}:{type:"schema",data:{...vi(t.data.schema),title:t.data.name}}}var kT=class ST{constructor(e){A(this,"nodes",{});A(this,"edges",[]);this.nodes=(e==null?void 0:e.nodes)??this.nodes,this.edges=(e==null?void 0:e.edges)??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((n,r)=>{e[n.id]=Pl(n.id)?r:n.id}),{nodes:Object.values(this.nodes).map(n=>({id:e[n.id],...KD(n)})),edges:this.edges.map(n=>{const r={source:e[n.source],target:e[n.target]};return typeof n.data<"u"&&(r.data=n.data),typeof n.conditional<"u"&&(r.conditional=n.conditional),r})}}addNode(e,n,r){if(n!==void 0&&this.nodes[n]!==void 0)throw new Error(`Node with id ${n} already exists`);const i=n??W2(),s={id:i,data:e,name:VD(n,e),metadata:r};return this.nodes[i]=s,s}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(n=>n.source!==e.id&&n.target!==e.id)}addEdge(e,n,r,i){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[n.id]===void 0)throw new Error(`Target node ${n.id} not in graph`);const s={source:e.id,target:n.id,data:r,conditional:i};return this.edges.push(s),s}firstNode(){return vw(this)}lastNode(){return ww(this)}extend(e,n=""){let r=n;Object.values(e.nodes).map(u=>u.id).every(Pl)&&(r="");const i=u=>r?`${r}:${u}`:u;Object.entries(e.nodes).forEach(([u,l])=>{this.nodes[i(u)]={...l,id:i(u)}});const s=e.edges.map(u=>({...u,source:i(u.source),target:i(u.target)}));this.edges=[...this.edges,...s];const a=e.firstNode(),o=e.lastNode();return[a?{id:i(a.id),data:a.data}:void 0,o?{id:i(o.id),data:o.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&vw(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&ww(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(i=>[i.id,i.name])),n=new Map;Object.values(e).forEach(i=>{n.set(i,(n.get(i)||0)+1)});const r=i=>{const s=e[i];return Pl(i)&&n.get(s)===1?s:i};return new ST({nodes:Object.fromEntries(Object.entries(this.nodes).map(([i,s])=>[r(i),{...s,id:r(i)}])),edges:this.edges.map(i=>({...i,source:r(i.source),target:r(i.target)}))})}drawMermaid(e){const{withStyles:n,curveStyle:r,nodeColors:i={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:s}=e??{},a=this.reid(),o=a.firstNode(),u=a.lastNode();return P6(a.nodes,a.edges,{firstNode:o==null?void 0:o.id,lastNode:u==null?void 0:u.id,withStyles:n,curveStyle:r,nodeColors:i,wrapLabelNWords:s})}async drawMermaidPng(e){return N6(this.drawMermaid(e),{backgroundColor:e==null?void 0:e.backgroundColor})}};function vw(t,e=[]){const n=new Set(t.edges.filter(i=>!e.includes(i.source)).map(i=>i.target)),r=[];for(const i of Object.values(t.nodes))!e.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function ww(t,e=[]){const n=new Set(t.edges.filter(i=>!e.includes(i.target)).map(i=>i.source)),r=[];for(const i of Object.values(t.nodes))!e.includes(i.id)&&!n.has(i.id)&&r.push(i);return r.length===1?r[0]:void 0}function qD(t){const e=new TextEncoder,n=new ReadableStream({async start(r){for await(const i of t)r.enqueue(e.encode(`event: data data: ${JSON.stringify(i)} `));r.enqueue(e.encode(`event: end `)),r.close()}});return br.fromReadableStream(n)}function bw(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.iterator]=="function"&&typeof t.next=="function"}const WD=t=>t!=null&&typeof t=="object"&&"next"in t&&typeof t.next=="function";function em(t){return typeof t=="object"&&t!==null&&typeof t[Symbol.asyncIterator]=="function"}function*xw(t,e){for(;;){const{value:n,done:r}=Ei.runWithConfig(ua(t),e.next.bind(e),!0);if(r)break;yield n}}async function*tm(t,e){const n=e[Symbol.asyncIterator]();for(;;){const{value:r,done:i}=await Ei.runWithConfig(ua(t),n.next.bind(e),!0);if(i)break;yield r}}function ot(t,e){return t&&!Array.isArray(t)&&!(t instanceof Date)&&typeof t=="object"?t:{[e]:t}}var mt=class extends Bo{constructor(){super(...arguments);A(this,"lc_runnable",!0);A(this,"name")}getName(e){const n=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${n}${e}`:n}withRetry(e){return new ET({bound:this,kwargs:{},config:{},maxAttemptNumber:e==null?void 0:e.stopAfterAttempt,...e})}withConfig(e){return new Bc({bound:this,config:e,kwargs:{}})}withFallbacks(e){const n=Array.isArray(e)?e:e.fallbacks;return new XD({runnable:this,fallbacks:n})}_getOptionsList(e,n=0){if(Array.isArray(e)&&e.length!==n)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${n} inputs`);if(Array.isArray(e))return e.map(xe);if(n>1&&!Array.isArray(e)&&e.runId){console.warn("Provided runId will be used only for the first element of the batch.");const r=Object.fromEntries(Object.entries(e).filter(([i])=>i!=="runId"));return Array.from({length:n},(i,s)=>xe(s===0?e:r))}return Array.from({length:n},()=>xe(e))}async batch(e,n,r){var o;const i=this._getOptionsList(n??{},e.length),s=new Cd({maxConcurrency:((o=i[0])==null?void 0:o.maxConcurrency)??(r==null?void 0:r.maxConcurrency),onFailedAttempt:u=>{throw u}}),a=e.map((u,l)=>s.call(async()=>{try{return await this.invoke(u,i[l])}catch(c){if(r!=null&&r.returnExceptions)return c;throw c}}));return Promise.all(a)}async*_streamIterator(e,n){yield this.invoke(e,n)}async stream(e,n){const r=xe(n),i=new xa({generator:this._streamIterator(e,r),config:r});return await i.setup,br.fromAsyncGenerator(i)}_separateRunnableConfigFromCallOptions(e){let n;e===void 0?n=xe(e):n=xe({callbacks:e.callbacks,tags:e.tags,metadata:e.metadata,runName:e.runName,configurable:e.configurable,recursionLimit:e.recursionLimit,maxConcurrency:e.maxConcurrency,runId:e.runId,timeout:e.timeout,signal:e.signal});const r={...e};return delete r.callbacks,delete r.tags,delete r.metadata,delete r.runName,delete r.configurable,delete r.recursionLimit,delete r.maxConcurrency,delete r.runId,delete r.timeout,delete r.signal,[n,r]}async _callWithConfig(e,n,r){var o;const i=xe(r),s=await((o=await Xn(i))==null?void 0:o.handleChainStart(this.toJSON(),ot(n,"input"),i.runId,i==null?void 0:i.runType,void 0,void 0,(i==null?void 0:i.runName)??this.getName()));delete i.runId;let a;try{a=await Dr(e.call(this,n,i,s),i.signal)}catch(u){throw await(s==null?void 0:s.handleChainError(u)),u}return await(s==null?void 0:s.handleChainEnd(ot(a,"output"))),a}async _batchWithConfig(e,n,r,i){var l;const s=this._getOptionsList(r??{},n.length),a=await Promise.all(s.map(Xn)),o=await Promise.all(a.map(async(c,d)=>{const f=await(c==null?void 0:c.handleChainStart(this.toJSON(),ot(n[d],"input"),s[d].runId,s[d].runType,void 0,void 0,s[d].runName??this.getName()));return delete s[d].runId,f}));let u;try{u=await Dr(e.call(this,n,s,o,i),(l=s==null?void 0:s[0])==null?void 0:l.signal)}catch(c){throw await Promise.all(o.map(d=>d==null?void 0:d.handleChainError(c))),c}return await Promise.all(o.map(c=>c==null?void 0:c.handleChainEnd(ot(u,"output")))),u}_concatOutputChunks(e,n){return Od(e,n)}async*_transformStreamWithConfig(e,n,r){let i,s=!0,a,o=!0;const u=xe(r),l=await Xn(u),c=this;async function*d(){for await(const h of e){if(s)if(i===void 0)i=h;else try{i=c._concatOutputChunks(i,h)}catch{i=void 0,s=!1}yield h}}let f;try{const h=await IL(n.bind(this),d(),async()=>l==null?void 0:l.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName(),void 0,{lc_defers_inputs:!0}),u.signal,u);delete u.runId,f=h.setup;const m=f==null?void 0:f.handlers.find(DL);let _=h.output;m!==void 0&&f!==void 0&&(_=m.tapOutputIterable(f.runId,_));const v=f==null?void 0:f.handlers.find(ML);v!==void 0&&f!==void 0&&(_=v.tapOutputIterable(f.runId,_));for await(const y of _)if(yield y,o)if(a===void 0)a=y;else try{a=this._concatOutputChunks(a,y)}catch{a=void 0,o=!1}}catch(h){throw await(f==null?void 0:f.handleChainError(h,void 0,void 0,void 0,{inputs:ot(i,"input")})),h}await(f==null?void 0:f.handleChainEnd(a??{},void 0,void 0,void 0,{inputs:ot(i,"input")}))}getGraph(e){const n=new kT,r=n.addNode({name:`${this.getName()}Input`,schema:mw()}),i=n.addNode(this),s=n.addNode({name:`${this.getName()}Output`,schema:mw()});return n.addEdge(r,i),n.addEdge(i,s),n}pipe(e){return new py({first:this,last:Gi(e)})}pick(e){return this.pipe(new QD(e))}assign(e){return this.pipe(new CT(new Md({steps:e})))}async*transform(e,n){let r;for await(const i of e)r===void 0?r=i:r=this._concatOutputChunks(r,i);yield*this._streamIterator(r,xe(n))}async*streamLog(e,n,r){const i=new P0({...r,autoClose:!1,_schemaFormat:"original"}),s=xe(n);yield*this._streamLog(e,i,s)}async*_streamLog(e,n,r){const{callbacks:i}=r;if(i===void 0)r.callbacks=[n];else if(Array.isArray(i))r.callbacks=i.concat([n]);else{const u=i.copy();u.addHandler(n,!0),r.callbacks=u}const s=this.stream(e,r);async function a(){try{const u=await s;for await(const l of u){const c=new ti({ops:[{op:"add",path:"/streamed_output/-",value:l}]});await n.writer.write(c)}}finally{await n.writer.close()}}const o=a();try{for await(const u of n)yield u}finally{await o}}streamEvents(e,n,r){let i;if(n.version==="v1")i=this._streamEventsV1(e,n,r);else if(n.version==="v2")i=this._streamEventsV2(e,n,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return n.encoding==="text/event-stream"?qD(i):br.fromAsyncGenerator(i)}async*_streamEventsV2(e,n,r){var m;const i=new UL({...r,autoClose:!1}),s=xe(n),a=s.runId??ei();s.runId=a;const o=s.callbacks;if(o===void 0)s.callbacks=[i];else if(Array.isArray(o))s.callbacks=o.concat(i);else{const _=o.copy();_.addHandler(i,!0),s.callbacks=_}const u=new AbortController,l=this;async function c(){let _;try{if(s.signal)if("any"in AbortSignal)_=AbortSignal.any([u.signal,s.signal]);else{const p=new AbortController;s.signal.addEventListener("abort",()=>p.abort(),{once:!0}),u.signal.addEventListener("abort",()=>p.abort(),{once:!0}),_=p.signal}else _=u.signal;const v=await l.stream(e,{...s,signal:_}),y=i.tapOutputIterable(a,v);for await(const p of y)if(u.signal.aborted)break}finally{await i.finish()}}const d=c();let f=!1,h;try{for await(const _ of i){if(!f){_.data.input=e,f=!0,h=_.run_id,yield _;continue}_.run_id===h&&_.event.endsWith("_end")&&(m=_.data)!=null&&m.input&&delete _.data.input,yield _}}finally{u.abort(),await d}}async*_streamEventsV1(e,n,r){let i,s=!1;const a=xe(n),o=a.tags??[],u=a.metadata??{},l=a.runName??this.getName(),c=new P0({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new iM({...r}),f=this._streamLog(e,c,a);for await(const m of f){if(i?i=i.concat(m):i=hE.fromRunLogPatch(m),i.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!s){s=!0;const p={...i.state},g={run_id:p.id,event:`on_${p.type}_start`,name:l,tags:o,metadata:u,data:{input:e}};d.includeEvent(g,p.type)&&(yield g)}const _=m.ops.filter(p=>p.path.startsWith("/logs/")).map(p=>p.path.split("/")[2]),v=[...new Set(_)];for(const p of v){let g,b={};const E=i.state.logs[p];if(E.end_time===void 0?E.streamed_output.length>0?g="stream":g="start":g="end",g==="start")E.inputs!==void 0&&(b.input=E.inputs);else if(g==="end")E.inputs!==void 0&&(b.input=E.inputs),b.output=E.final_output;else if(g==="stream"){const T=E.streamed_output.length;if(T!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${T} instead. Encountered in: "${E.name}"`);b={chunk:E.streamed_output[0]},E.streamed_output=[]}yield{event:`on_${E.type}_${g}`,name:E.name,run_id:E.id,tags:E.tags,metadata:E.metadata,data:b}}const{state:y}=i;if(y.streamed_output.length>0){const p=y.streamed_output.length;if(p!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${p} instead. Encountered in: "${y.name}"`);const g={chunk:y.streamed_output[0]};y.streamed_output=[];const b={event:`on_${y.type}_stream`,run_id:y.id,tags:o,metadata:u,name:l,data:g};d.includeEvent(b,y.type)&&(yield b)}}const h=i==null?void 0:i.state;if(h!==void 0){const m={event:`on_${h.type}_end`,name:l,run_id:h.id,tags:o,metadata:u,data:{output:h.final_output}};d.includeEvent(m,h.type)&&(yield m)}}static isRunnable(e){return ry(e)}withListeners({onStart:e,onEnd:n,onError:r}){return new Bc({bound:this,config:{},configFactories:[i=>({callbacks:[new vE({config:i,onStart:e,onEnd:n,onError:r})]})]})}asTool(e){return YD(this,e)}},Bc=class AT extends mt{constructor(n){super(n);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"lc_serializable",!0);A(this,"bound");A(this,"config");A(this,"kwargs");A(this,"configFactories");this.bound=n.bound,this.kwargs=n.kwargs,this.config=n.config,this.configFactories=n.configFactories}static lc_name(){return"RunnableBinding"}getName(n){return this.bound.getName(n)}async _mergeConfig(...n){const r=T0(this.config,...n);return T0(r,...this.configFactories?await Promise.all(this.configFactories.map(async i=>await i(r))):[])}withConfig(n){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...n}})}withRetry(n){return new ET({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:n==null?void 0:n.stopAfterAttempt,...n})}async invoke(n,r){return this.bound.invoke(n,await this._mergeConfig(r,this.kwargs))}async batch(n,r,i){const s=Array.isArray(r)?await Promise.all(r.map(async a=>this._mergeConfig(xe(a),this.kwargs))):await this._mergeConfig(xe(r),this.kwargs);return this.bound.batch(n,s,i)}_concatOutputChunks(n,r){return this.bound._concatOutputChunks(n,r)}async*_streamIterator(n,r){yield*this.bound._streamIterator(n,await this._mergeConfig(xe(r),this.kwargs))}async stream(n,r){return this.bound.stream(n,await this._mergeConfig(xe(r),this.kwargs))}async*transform(n,r){yield*this.bound.transform(n,await this._mergeConfig(xe(r),this.kwargs))}streamEvents(n,r,i){const s=this,a=async function*(){yield*s.bound.streamEvents(n,{...await s._mergeConfig(xe(r),s.kwargs),version:r.version},i)};return br.fromAsyncGenerator(a())}static isRunnableBinding(n){return n.bound&&mt.isRunnable(n.bound)}withListeners({onStart:n,onEnd:r,onError:i}){return new AT({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new vE({config:s,onStart:n,onEnd:r,onError:i})]})]})}},ET=class extends Bc{constructor(e){super(e);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"maxAttemptNumber",3);A(this,"onFailedAttempt",()=>{});this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}static lc_name(){return"RunnableRetry"}_patchConfigForRetry(e,n,r){const i=e>1?`retry:attempt:${e}`:void 0;return Lt(n,{callbacks:r==null?void 0:r.getChild(i)})}async _invoke(e,n,r){return zp(i=>super.invoke(e,this._patchConfigForRetry(i,n,r)),{onFailedAttempt:({error:i})=>this.onFailedAttempt(i,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,n){return this._callWithConfig(this._invoke.bind(this),e,n)}async _batch(e,n,r,i){const s={};try{await zp(async a=>{const o=e.map((f,h)=>h).filter(f=>s[f.toString()]===void 0||s[f.toString()]instanceof Error),u=o.map(f=>e[f]),l=o.map(f=>this._patchConfigForRetry(a,n==null?void 0:n[f],r==null?void 0:r[f])),c=await super.batch(u,l,{...i,returnExceptions:!0});let d;for(let f=0;f<c.length;f+=1){const h=c[f],m=o[f];h instanceof Error&&d===void 0&&(d=h,d.input=u[f]),s[m.toString()]=h}if(d)throw d;return c},{onFailedAttempt:({error:a})=>this.onFailedAttempt(a,a.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(a){if((i==null?void 0:i.returnExceptions)!==!0)throw a}return Object.keys(s).sort((a,o)=>parseInt(a,10)-parseInt(o,10)).map(a=>s[parseInt(a,10)])}async batch(e,n,r){return this._batchWithConfig(this._batch.bind(this),e,n,r)}},py=class ro extends mt{constructor(n){super(n);A(this,"first");A(this,"middle",[]);A(this,"last");A(this,"omitSequenceTags",!1);A(this,"lc_serializable",!0);A(this,"lc_namespace",["langchain_core","runnables"]);this.first=n.first,this.middle=n.middle??this.middle,this.last=n.last,this.name=n.name,this.omitSequenceTags=n.omitSequenceTags??this.omitSequenceTags}static lc_name(){return"RunnableSequence"}get steps(){return[this.first,...this.middle,this.last]}async invoke(n,r){var u,l;const i=xe(r),s=await((u=await Xn(i))==null?void 0:u.handleChainStart(this.toJSON(),ot(n,"input"),i.runId,void 0,void 0,void 0,i==null?void 0:i.runName));delete i.runId;let a=n,o;try{const c=[this.first,...this.middle];for(let d=0;d<c.length;d+=1)a=await Dr(c[d].invoke(a,Lt(i,{callbacks:s==null?void 0:s.getChild(this.omitSequenceTags?void 0:`seq:step:${d+1}`)})),i.signal);if((l=i.signal)!=null&&l.aborted)throw Ac(i.signal);o=await this.last.invoke(a,Lt(i,{callbacks:s==null?void 0:s.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(c){throw await(s==null?void 0:s.handleChainError(c)),c}return await(s==null?void 0:s.handleChainEnd(ot(o,"output"))),o}async batch(n,r,i){var l;const s=this._getOptionsList(r??{},n.length),a=await Promise.all(s.map(Xn)),o=await Promise.all(a.map(async(c,d)=>{const f=await(c==null?void 0:c.handleChainStart(this.toJSON(),ot(n[d],"input"),s[d].runId,void 0,void 0,void 0,s[d].runName));return delete s[d].runId,f}));let u=n;try{for(let c=0;c<this.steps.length;c+=1)u=await Dr(this.steps[c].batch(u,o.map((d,f)=>{const h=d==null?void 0:d.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`);return Lt(s[f],{callbacks:h})}),i),(l=s[0])==null?void 0:l.signal)}catch(c){throw await Promise.all(o.map(d=>d==null?void 0:d.handleChainError(c))),c}return await Promise.all(o.map(c=>c==null?void 0:c.handleChainEnd(ot(u,"output")))),u}_concatOutputChunks(n,r){return this.last._concatOutputChunks(n,r)}async*_streamIterator(n,r){var f;const i=await Xn(r),{runId:s,...a}=r??{},o=await(i==null?void 0:i.handleChainStart(this.toJSON(),ot(n,"input"),s,void 0,void 0,void 0,a==null?void 0:a.runName)),u=[this.first,...this.middle,this.last];let l=!0,c;async function*d(){yield n}try{let h=u[0].transform(d(),Lt(a,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let m=1;m<u.length;m+=1)h=await u[m].transform(h,Lt(a,{callbacks:o==null?void 0:o.getChild(this.omitSequenceTags?void 0:`seq:step:${m+1}`)}));for await(const m of h)if((f=r==null?void 0:r.signal)==null||f.throwIfAborted(),yield m,l)if(c===void 0)c=m;else try{c=this._concatOutputChunks(c,m)}catch{c=void 0,l=!1}}catch(h){throw await(o==null?void 0:o.handleChainError(h)),h}await(o==null?void 0:o.handleChainEnd(ot(c,"output")))}getGraph(n){const r=new kT;let i=null;return this.steps.forEach((s,a)=>{const o=s.getGraph(n);a!==0&&o.trimFirstNode(),a!==this.steps.length-1&&o.trimLastNode(),r.extend(o);const u=o.firstNode();if(!u)throw new Error(`Runnable ${s} has no first node`);i&&r.addEdge(i,u),i=o.lastNode()}),r}pipe(n){return ro.isRunnableSequence(n)?new ro({first:this.first,middle:this.middle.concat([this.last,n.first,...n.middle]),last:n.last,name:this.name??n.name}):new ro({first:this.first,middle:[...this.middle,this.last],last:Gi(n),name:this.name})}static isRunnableSequence(n){return Array.isArray(n.middle)&&mt.isRunnable(n)}static from([n,...r],i){let s={};return typeof i=="string"?s.name=i:i!==void 0&&(s=i),new ro({...s,first:Gi(n),middle:r.slice(0,-1).map(Gi),last:Gi(r[r.length-1])})}},Md=class TT extends mt{constructor(n){super(n);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"lc_serializable",!0);A(this,"steps");this.steps={};for(const[r,i]of Object.entries(n.steps))this.steps[r]=Gi(i)}static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}static from(n){return new TT({steps:n})}async invoke(n,r){var o;const i=xe(r),s=await((o=await Xn(i))==null?void 0:o.handleChainStart(this.toJSON(),{input:n},i.runId,void 0,void 0,void 0,i==null?void 0:i.runName));delete i.runId;const a={};try{const u=Object.entries(this.steps).map(async([l,c])=>{a[l]=await c.invoke(n,Lt(i,{callbacks:s==null?void 0:s.getChild(`map:key:${l}`)}))});await Dr(Promise.all(u),i.signal)}catch(u){throw await(s==null?void 0:s.handleChainError(u)),u}return await(s==null?void 0:s.handleChainEnd(a)),a}async*_transform(n,r,i){const s={...this.steps},a=cE(n,Object.keys(s).length),o=new Map(Object.entries(s).map(([u,l],c)=>{const d=l.transform(a[c],Lt(i,{callbacks:r==null?void 0:r.getChild(`map:key:${u}`)}));return[u,d.next().then(f=>({key:u,gen:d,result:f}))]}));for(;o.size;){const{key:u,result:l,gen:c}=await Dr(Promise.race(o.values()),i==null?void 0:i.signal);o.delete(u),l.done||(yield{[u]:l.value},o.set(u,c.next().then(d=>({key:u,gen:c,result:d}))))}}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*i(){yield n}const s=xe(r),a=new xa({generator:this.transform(i(),s),config:s});return await a.setup,br.fromAsyncGenerator(a)}},GD=class IT extends mt{constructor(n){super(n);A(this,"lc_serializable",!1);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"func");if(!Zg(n.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=n.func}async invoke(n,r){const[i]=this._getOptionsList(r??{},1),s=await Xn(i);return Dr(this.func(Lt(i,{callbacks:s}),n),i==null?void 0:i.signal)}async*_streamIterator(n,r){var a,o;const[i]=this._getOptionsList(r??{},1),s=await this.invoke(n,r);if(em(s)){for await(const u of s)(a=i==null?void 0:i.signal)==null||a.throwIfAborted(),yield u;return}if(WD(s)){for(;;){(o=i==null?void 0:i.signal)==null||o.throwIfAborted();const u=s.next();if(u.done)break;yield u.value}return}yield s}static from(n){return new IT({func:n})}};function JD(t){if(Zg(t))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}var zd=class OT extends mt{constructor(n){if(Zg(n.func))return GD.from(n.func);super(n);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"func");JD(n.func),this.func=n.func}static lc_name(){return"RunnableLambda"}static from(n){return new OT({func:n})}async _invoke(n,r,i){return new Promise((s,a)=>{const o=Lt(r,{callbacks:i==null?void 0:i.getChild(),recursionLimit:((r==null?void 0:r.recursionLimit)??25)-1});Ei.runWithConfig(ua(o),async()=>{var u,l;try{let c=await this.func(n,{...o});if(c&&mt.isRunnable(c)){if((r==null?void 0:r.recursionLimit)===0)throw new Error("Recursion limit reached.");c=await c.invoke(n,{...o,recursionLimit:(o.recursionLimit??25)-1})}else if(em(c)){let d;for await(const f of tm(o,c))if((u=r==null?void 0:r.signal)==null||u.throwIfAborted(),d===void 0)d=f;else try{d=this._concatOutputChunks(d,f)}catch{d=f}c=d}else if(bw(c)){let d;for(const f of xw(o,c))if((l=r==null?void 0:r.signal)==null||l.throwIfAborted(),d===void 0)d=f;else try{d=this._concatOutputChunks(d,f)}catch{d=f}c=d}s(c)}catch(c){a(c)}})})}async invoke(n,r){return this._callWithConfig(this._invoke.bind(this),n,r)}async*_transform(n,r,i){var u,l;let s;for await(const c of n)if(s===void 0)s=c;else try{s=this._concatOutputChunks(s,c)}catch{s=c}const a=Lt(i,{callbacks:r==null?void 0:r.getChild(),recursionLimit:((i==null?void 0:i.recursionLimit)??25)-1}),o=await new Promise((c,d)=>{Ei.runWithConfig(ua(a),async()=>{try{c(await this.func(s,{...a,config:a}))}catch(f){d(f)}})});if(o&&mt.isRunnable(o)){if((i==null?void 0:i.recursionLimit)===0)throw new Error("Recursion limit reached.");const c=await o.stream(s,a);for await(const d of c)yield d}else if(em(o))for await(const c of tm(a,o))(u=i==null?void 0:i.signal)==null||u.throwIfAborted(),yield c;else if(bw(o))for(const c of xw(a,o))(l=i==null?void 0:i.signal)==null||l.throwIfAborted(),yield c;else yield o}transform(n,r){return this._transformStreamWithConfig(n,this._transform.bind(this),r)}async stream(n,r){async function*i(){yield n}const s=xe(r),a=new xa({generator:this.transform(i(),s),config:s});return await a.setup,br.fromAsyncGenerator(a)}},XD=class extends mt{constructor(e){super(e);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"lc_serializable",!0);A(this,"runnable");A(this,"fallbacks");this.runnable=e.runnable,this.fallbacks=e.fallbacks}static lc_name(){return"RunnableWithFallbacks"}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,n){const r=xe(n),i=await Xn(r),{runId:s,...a}=r,o=await(i==null?void 0:i.handleChainStart(this.toJSON(),ot(e,"input"),s,void 0,void 0,void 0,a==null?void 0:a.runName)),u=Lt(a,{callbacks:o==null?void 0:o.getChild()});return await Ei.runWithConfig(u,async()=>{var c;let l;for(const d of this.runnables()){(c=r==null?void 0:r.signal)==null||c.throwIfAborted();try{const f=await d.invoke(e,u);return await(o==null?void 0:o.handleChainEnd(ot(f,"output"))),f}catch(f){l===void 0&&(l=f)}}throw l===void 0?new Error("No error stored at end of fallback."):(await(o==null?void 0:o.handleChainError(l)),l)})}async*_streamIterator(e,n){var d;const r=xe(n),i=await Xn(r),{runId:s,...a}=r,o=await(i==null?void 0:i.handleChainStart(this.toJSON(),ot(e,"input"),s,void 0,void 0,void 0,a==null?void 0:a.runName));let u,l;for(const f of this.runnables()){(d=r==null?void 0:r.signal)==null||d.throwIfAborted();const h=Lt(a,{callbacks:o==null?void 0:o.getChild()});try{l=tm(h,await f.stream(e,h));break}catch(m){u===void 0&&(u=m)}}if(l===void 0){const f=u??new Error("No error stored at end of fallback.");throw await(o==null?void 0:o.handleChainError(f)),f}let c;try{for await(const f of l){yield f;try{c=c===void 0?c:this._concatOutputChunks(c,f)}catch{c=void 0}}}catch(f){throw await(o==null?void 0:o.handleChainError(f)),f}await(o==null?void 0:o.handleChainEnd(ot(c,"output")))}async batch(e,n,r){var u;if(r!=null&&r.returnExceptions)throw new Error("Not implemented.");const i=this._getOptionsList(n??{},e.length),s=await Promise.all(i.map(l=>Xn(l))),a=await Promise.all(s.map(async(l,c)=>{const d=await(l==null?void 0:l.handleChainStart(this.toJSON(),ot(e[c],"input"),i[c].runId,void 0,void 0,void 0,i[c].runName));return delete i[c].runId,d}));let o;for(const l of this.runnables()){(u=i[0].signal)==null||u.throwIfAborted();try{const c=await l.batch(e,a.map((d,f)=>Lt(i[f],{callbacks:d==null?void 0:d.getChild()})),r);return await Promise.all(a.map((d,f)=>d==null?void 0:d.handleChainEnd(ot(c[f],"output")))),c}catch(c){o===void 0&&(o=c)}}throw o?(await Promise.all(a.map(l=>l==null?void 0:l.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}};function Gi(t){if(typeof t=="function")return new zd({func:t});if(mt.isRunnable(t))return t;if(!Array.isArray(t)&&typeof t=="object"){const e={};for(const[n,r]of Object.entries(t))e[n]=Gi(r);return new Md({steps:e})}else throw new Error(`Expected a Runnable, function or object. Instead got an unsupported type.`)}var CT=class extends mt{constructor(e){e instanceof Md&&(e={mapper:e});super(e);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"lc_serializable",!0);A(this,"mapper");this.mapper=e.mapper}static lc_name(){return"RunnableAssign"}async invoke(e,n){const r=await this.mapper.invoke(e,n);return{...e,...r}}async*_transform(e,n,r){const i=this.mapper.getStepsKeys(),[s,a]=cE(e),o=this.mapper.transform(a,Lt(r,{callbacks:n==null?void 0:n.getChild()})),u=o.next();for await(const l of s){if(typeof l!="object"||Array.isArray(l))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof l}`);const c=Object.fromEntries(Object.entries(l).filter(([d])=>!i.includes(d)));Object.keys(c).length>0&&(yield c)}yield(await u).value;for await(const l of o)yield l}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}const i=xe(n),s=new xa({generator:this.transform(r(),i),config:i});return await s.setup,br.fromAsyncGenerator(s)}},QD=class extends mt{constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e});super(e);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"lc_serializable",!0);A(this,"keys");this.keys=e.keys}static lc_name(){return"RunnablePick"}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const n=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return n.length===0?void 0:Object.fromEntries(n)}}async invoke(e,n){return this._callWithConfig(this._pick.bind(this),e,n)}async*_transform(e){for await(const n of e){const r=await this._pick(n);r!==void 0&&(yield r)}}transform(e,n){return this._transformStreamWithConfig(e,this._transform.bind(this),n)}async stream(e,n){async function*r(){yield e}const i=xe(n),s=new xa({generator:this.transform(r(),i),config:i});return await s.setup,br.fromAsyncGenerator(s)}},kw=class extends Bc{constructor(e){const n=py.from([zd.from(async r=>{let i;if(TS(r))try{i=await lT(this.schema,r.args)}catch{throw new P2("Received tool input did not match expected schema",JSON.stringify(r.args))}else i=r;return i}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:n,config:e.config??{}});A(this,"name");A(this,"description");A(this,"schema");this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}};function YD(t,e){const n=e.name??t.getName(),r=e.description??dy(e.schema);return x6(e.schema)?new kw({name:n,description:r,schema:yT({input:gT()}).transform(i=>i.input),bound:t}):new kw({name:n,description:r,schema:e.schema,bound:t})}const Pr=t=>t();function fu(t){return t?!!(/^o\d/.test(t??"")||t.startsWith("gpt-5")&&!t.startsWith("gpt-5-chat")):!1}function e5(t){return t.role!=="system"&&t.role!=="developer"&&t.role!=="assistant"&&t.role!=="user"&&t.role!=="function"&&t.role!=="tool"&&console.warn(`Unknown message role: ${t.role}`),t.role}function nm(t){var e,n,r;return((e=t.metadata)==null?void 0:e.filename)??((n=t.metadata)==null?void 0:n.name)??((r=t.metadata)==null?void 0:r.title)}const t5="LC_AUTOGENERATED";function Qo(t){var n,r,i;const e=((n=t.metadata)==null?void 0:n.filename)??((r=t.metadata)==null?void 0:r.name)??((i=t.metadata)==null?void 0:i.title);return e||(console.warn("OpenAI may require a filename for file uploads. Specify a filename in the content block metadata, e.g.: { type: 'file', mimeType: '...', data: '...', metadata: { filename: 'my-file.pdf' } }. Using placeholder filename 'LC_AUTOGENERATED'."),t5)}function hu(t){const e=t._getType();switch(e){case"system":return"system";case"ai":return"assistant";case"human":return"user";case"function":return"function";case"tool":return"tool";case"generic":if(!zg.isInstance(t))throw new Error("Invalid generic chat message");return e5(t);default:throw new Error(`Unknown message type: ${e}`)}}function n5(t){return!!(t.includes("gpt-5.2-pro")||t.includes("gpt-5.4-pro")||t.includes("gpt-5.5-pro")||t.includes("codex"))}function PT(t){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:n,azureOpenAIApiKey:r,azureOpenAIBasePath:i,baseURL:s,azureADTokenProvider:a,azureOpenAIEndpoint:o}=t;if((r||a)&&i&&e)return`${i}/${e}`;if((r||a)&&o&&e)return`${o}/openai/deployments/${e}`;if(r||a){if(!n)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${n}.openai.azure.com/openai/deployments/${e}`}return s}function Sw(t){return typeof Headers<"u"&&t!==null&&typeof t=="object"&&Object.prototype.toString.call(t)==="[object Headers]"}function r5(t){const e=Pr(()=>{if(Sw(t))return t;if(Array.isArray(t))return new Headers(t);if(typeof t=="object"&&t!==null&&"values"in t&&Sw(t.values))return t.values;if(typeof t=="object"&&t!==null){const n=Object.entries(t).filter(([,r])=>typeof r=="string").map(([r,i])=>[r,i]);return new Headers(n)}return new Headers});return Object.fromEntries(e.entries())}function i5(){let t=jS();return(t==="node"||t==="deno")&&(t=`(${t}/${process.version}; ${process.platform}; ${process.arch})`),t}function NT(t,e=!1,n="1.0.0"){const r=r5(t),i=i5(),s=`langchainjs${e?"-azure":""}-openai`;return{...r,"User-Agent":r["User-Agent"]?`${s}/${n} (${i})${r["User-Agent"]}`:`${s}/${n} (${i})`}}function s5(t){return t!==void 0&&Array.isArray(t.lc_namespace)}function a5(t){return t!==void 0&&mt.isRunnable(t)&&"lc_name"in t.constructor&&typeof t.constructor.lc_name=="function"&&t.constructor.lc_name()==="RunnableToolLike"}function o5(t){return!!t&&typeof t=="object"&&"name"in t&&"schema"in t&&(gr(t.schema)||t.schema!=null&&typeof t.schema=="object"&&"type"in t.schema&&typeof t.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(t.schema.type))}function my(t){return o5(t)||a5(t)||s5(t)}function u5(t,e){return{name:t.name,description:t.description,parameters:vi(t.schema)}}function l5(t,e){let n;return my(t)?n={type:"function",function:u5(t)}:n=t,n}function c5(t,e){let n;return my(t)?n=l5(t):n=t,(e==null?void 0:e.strict)!==void 0&&(n.function.strict=e.strict),n}function d5(t){return t.anyOf!==void 0&&Array.isArray(t.anyOf)}function f5(t){const e=["namespace functions {",""];for(const n of t)n.description&&e.push(`// ${n.description}`),Object.keys(n.parameters.properties??{}).length>0?(e.push(`type ${n.name} = (_: {`),e.push($T(n.parameters,0)),e.push("}) => any;")):e.push(`type ${n.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(` `)}function $T(t,e){var r;const n=[];for(const[i,s]of Object.entries(t.properties??{}))s.description&&e<2&&n.push(`// ${s.description}`),(r=t.required)!=null&&r.includes(i)?n.push(`${i}: ${Hc(s,e)},`):n.push(`${i}?: ${Hc(s,e)},`);return n.map(i=>" ".repeat(e)+i).join(` `)}function Hc(t,e){if(d5(t))return t.anyOf.map(n=>Hc(n,e)).join(" | ");switch(t.type){case"string":return t.enum?t.enum.map(n=>`"${n}"`).join(" | "):"string";case"number":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"integer":return t.enum?t.enum.map(n=>`${n}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",$T(t,e+2),"}"].join(` `);case"array":return t.items?`${Hc(t.items,e)}[]`:"any[]";default:return""}}function RT(t){if(t)return t==="any"||t==="required"?"required":t==="auto"?"auto":t==="none"?"none":typeof t=="string"?{type:"function",function:{name:t}}:t}function gy(t){return"type"in t&&t.type!=="function"}function h5(t){return typeof t=="object"&&t!==null&&"extras"in t&&typeof t.extras=="object"&&t.extras!==null&&"providerToolDefinition"in t.extras&&typeof t.extras.providerToolDefinition=="object"&&t.extras.providerToolDefinition!==null}function p5(t){return t!=null&&typeof t=="object"&&"type"in t&&t.type!=="function"}function Zc(t){return typeof t=="object"&&t!==null&&"metadata"in t&&typeof t.metadata=="object"&&t.metadata!==null&&"customTool"in t.metadata&&typeof t.metadata.customTool=="object"&&t.metadata.customTool!==null}function jT(t){return"type"in t&&t.type==="custom"&&"custom"in t&&typeof t.custom=="object"&&t.custom!==null}function m5(t){if(t.type==="custom_tool_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:t.name,isCustomTool:!0,args:{input:t.input}}}function g5(t){if(t.type==="computer_call")return{...t,type:"tool_call",call_id:t.id,id:t.call_id,name:"computer_use",isComputerTool:!0,args:{action:t.action}}}function y5(t){return typeof t=="object"&&t!==null&&"type"in t&&t.type==="tool_call"&&"isComputerTool"in t&&t.isComputerTool===!0}function _5(t,e){return typeof t!="object"||t===null||!("type"in t)||t.type!=="tool_call"?!1:!!("isCustomTool"in t&&t.isCustomTool===!0||e&&"id"in t&&typeof t.id=="string"&&t.id in e)}function v5(t){const e=()=>{if(t.custom.format){if(t.custom.format.type==="grammar")return{type:"grammar",definition:t.custom.format.grammar.definition,syntax:t.custom.format.grammar.syntax};if(t.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:t.custom.name,description:t.custom.description,format:e()}}function w5(t){const e=()=>{if(t.format){if(t.format.type==="grammar")return{type:"grammar",grammar:{definition:t.format.definition,syntax:t.format.syntax}};if(t.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:t.name,description:t.description,format:e()}}}const b5=R("ZodISODateTime",(t,e)=>{Oz.init(t,e),Be.init(t,e)});function x5(t){return $3(b5,t)}const k5=R("ZodISODate",(t,e)=>{Cz.init(t,e),Be.init(t,e)});function S5(t){return R3(k5,t)}const A5=R("ZodISOTime",(t,e)=>{Pz.init(t,e),Be.init(t,e)});function E5(t){return j3(A5,t)}const T5=R("ZodISODuration",(t,e)=>{Nz.init(t,e),Be.init(t,e)});function I5(t){return L3(T5,t)}const O5=(t,e)=>{AE.init(t,e),t.name="ZodError",Object.defineProperties(t,{format:{value:n=>bM(t,n)},flatten:{value:n=>wM(t,n)},addIssue:{value:n=>{t.issues.push(n),t.message=JSON.stringify(t.issues,Up,2)}},addIssues:{value:n=>{t.issues.push(...n),t.message=JSON.stringify(t.issues,Up,2)}},isEmpty:{get(){return t.issues.length===0}}})},Nn=R("ZodError",O5,{Parent:Error}),C5=Nd(Nn),P5=$d(Nn),N5=Rd(Nn),$5=jd(Nn),R5=AM(Nn),j5=EM(Nn),L5=TM(Nn),M5=IM(Nn),z5=OM(Nn),D5=CM(Nn),U5=PM(Nn),F5=NM(Nn),Aw=new WeakMap;function pu(t,e,n){const r=Object.getPrototypeOf(t);let i=Aw.get(r);if(i||(i=new Set,Aw.set(r,i)),!i.has(e)){i.add(e);for(const s in n){const a=n[s];Object.defineProperty(r,s,{configurable:!0,enumerable:!1,get(){const o=a.bind(this);return Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:o}),o},set(o){Object.defineProperty(this,s,{configurable:!0,writable:!0,enumerable:!0,value:o})}})}}}const Ke=R("ZodType",(t,e)=>(Ve.init(t,e),Object.assign(t["~standard"],{jsonSchema:{input:jc(t,"input"),output:jc(t,"output")}}),t.toJSONSchema=t6(t,{}),t.def=e,t.type=e.type,Object.defineProperty(t,"_def",{value:e}),t.parse=(n,r)=>C5(t,n,r,{callee:t.parse}),t.safeParse=(n,r)=>N5(t,n,r),t.parseAsync=async(n,r)=>P5(t,n,r,{callee:t.parseAsync}),t.safeParseAsync=async(n,r)=>$5(t,n,r),t.spa=t.safeParseAsync,t.encode=(n,r)=>R5(t,n,r),t.decode=(n,r)=>j5(t,n,r),t.encodeAsync=async(n,r)=>L5(t,n,r),t.decodeAsync=async(n,r)=>M5(t,n,r),t.safeEncode=(n,r)=>z5(t,n,r),t.safeDecode=(n,r)=>D5(t,n,r),t.safeEncodeAsync=async(n,r)=>U5(t,n,r),t.safeDecodeAsync=async(n,r)=>F5(t,n,r),pu(t,"ZodType",{check(...n){const r=this.def;return this.clone(Ni(r,{checks:[...r.checks??[],...n.map(i=>typeof i=="function"?{_zod:{check:i,def:{check:"custom"},onattach:[]}}:i)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return Jt(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check($U(n,r))},superRefine(n,r){return this.check(RU(n,r))},overwrite(n){return this.check(ka(n))},optional(){return Cw(this)},exactOptional(){return wU(this)},nullable(){return Pw(this)},nullish(){return Cw(Pw(this))},nonoptional(n){return EU(this,n)},array(){return mu(this)},or(n){return Dd([this,n])},and(n){return pU(this,n)},transform(n){return Nw(this,_U(n))},default(n){return kU(this,n)},prefault(n){return AU(this,n)},catch(n){return IU(this,n)},pipe(n){return Nw(this,n)},readonly(){return PU(this)},describe(n){const r=this.clone();return En.add(r,{description:n}),r},meta(...n){if(n.length===0)return En.get(this);const r=this.clone();return En.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(t,"description",{get(){var n;return(n=En.get(t))==null?void 0:n.description},configurable:!0}),t)),LT=R("_ZodString",(t,e)=>{ly.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(r,i,s)=>HE(t,r,i);const n=t._zod.bag;t.format=n.format??null,t.minLength=n.minimum??null,t.maxLength=n.maximum??null,pu(t,"_ZodString",{regex(...r){return this.check(U3(...r))},includes(...r){return this.check(H3(...r))},startsWith(...r){return this.check(Z3(...r))},endsWith(...r){return this.check(V3(...r))},min(...r){return this.check(Pc(...r))},max(...r){return this.check(FE(...r))},length(...r){return this.check(BE(...r))},nonempty(...r){return this.check(Pc(1,...r))},lowercase(r){return this.check(F3(r))},uppercase(r){return this.check(B3(r))},trim(){return this.check(q3())},normalize(...r){return this.check(K3(...r))},toLowerCase(){return this.check(W3())},toUpperCase(){return this.check(G3())},slugify(){return this.check(J3())}})}),B5=R("ZodString",(t,e)=>{ly.init(t,e),LT.init(t,e),t.email=n=>t.check(f3(H5,n)),t.url=n=>t.check(y3(Z5,n)),t.jwt=n=>t.check(N3(sU,n)),t.emoji=n=>t.check(_3(V5,n)),t.guid=n=>t.check(W0(Ew,n)),t.uuid=n=>t.check(h3(tl,n)),t.uuidv4=n=>t.check(p3(tl,n)),t.uuidv6=n=>t.check(m3(tl,n)),t.uuidv7=n=>t.check(g3(tl,n)),t.nanoid=n=>t.check(v3(K5,n)),t.guid=n=>t.check(W0(Ew,n)),t.cuid=n=>t.check(w3(q5,n)),t.cuid2=n=>t.check(b3(W5,n)),t.ulid=n=>t.check(x3(G5,n)),t.base64=n=>t.check(O3(nU,n)),t.base64url=n=>t.check(C3(rU,n)),t.xid=n=>t.check(k3(J5,n)),t.ksuid=n=>t.check(S3(X5,n)),t.ipv4=n=>t.check(A3(Q5,n)),t.ipv6=n=>t.check(E3(Y5,n)),t.cidrv4=n=>t.check(T3(eU,n)),t.cidrv6=n=>t.check(I3(tU,n)),t.e164=n=>t.check(P3(iU,n)),t.datetime=n=>t.check(x5(n)),t.date=n=>t.check(S5(n)),t.time=n=>t.check(E5(n)),t.duration=n=>t.check(I5(n))});function Wt(t){return d3(B5,t)}const Be=R("ZodStringFormat",(t,e)=>{Me.init(t,e),LT.init(t,e)}),H5=R("ZodEmail",(t,e)=>{wz.init(t,e),Be.init(t,e)}),Ew=R("ZodGUID",(t,e)=>{_z.init(t,e),Be.init(t,e)}),tl=R("ZodUUID",(t,e)=>{vz.init(t,e),Be.init(t,e)}),Z5=R("ZodURL",(t,e)=>{bz.init(t,e),Be.init(t,e)}),V5=R("ZodEmoji",(t,e)=>{xz.init(t,e),Be.init(t,e)}),K5=R("ZodNanoID",(t,e)=>{kz.init(t,e),Be.init(t,e)}),q5=R("ZodCUID",(t,e)=>{Sz.init(t,e),Be.init(t,e)}),W5=R("ZodCUID2",(t,e)=>{Az.init(t,e),Be.init(t,e)}),G5=R("ZodULID",(t,e)=>{Ez.init(t,e),Be.init(t,e)}),J5=R("ZodXID",(t,e)=>{Tz.init(t,e),Be.init(t,e)}),X5=R("ZodKSUID",(t,e)=>{Iz.init(t,e),Be.init(t,e)}),Q5=R("ZodIPv4",(t,e)=>{$z.init(t,e),Be.init(t,e)}),Y5=R("ZodIPv6",(t,e)=>{Rz.init(t,e),Be.init(t,e)}),eU=R("ZodCIDRv4",(t,e)=>{jz.init(t,e),Be.init(t,e)}),tU=R("ZodCIDRv6",(t,e)=>{Lz.init(t,e),Be.init(t,e)}),nU=R("ZodBase64",(t,e)=>{Mz.init(t,e),Be.init(t,e)}),rU=R("ZodBase64URL",(t,e)=>{Dz.init(t,e),Be.init(t,e)}),iU=R("ZodE164",(t,e)=>{Uz.init(t,e),Be.init(t,e)}),sU=R("ZodJWT",(t,e)=>{Bz.init(t,e),Be.init(t,e)}),MT=R("ZodNumber",(t,e)=>{jE.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(r,i,s)=>ZE(t,r,i),pu(t,"ZodNumber",{gt(r,i){return this.check(J0(r,i))},gte(r,i){return this.check(Gf(r,i))},min(r,i){return this.check(Gf(r,i))},lt(r,i){return this.check(G0(r,i))},lte(r,i){return this.check(Wf(r,i))},max(r,i){return this.check(Wf(r,i))},int(r){return this.check(Tw(r))},safe(r){return this.check(Tw(r))},positive(r){return this.check(J0(0,r))},nonnegative(r){return this.check(Gf(0,r))},negative(r){return this.check(G0(0,r))},nonpositive(r){return this.check(Wf(0,r))},multipleOf(r,i){return this.check(X0(r,i))},step(r,i){return this.check(X0(r,i))},finite(){return this}});const n=t._zod.bag;t.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,t.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,t.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),t.isFinite=!0,t.format=n.format??null});function xt(t){return M3(MT,t)}const aU=R("ZodNumberFormat",(t,e)=>{Hz.init(t,e),MT.init(t,e)});function Tw(t){return z3(aU,t)}const oU=R("ZodUnknown",(t,e)=>{Zz.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>KE()});function Iw(){return D3(oU)}const uU=R("ZodNever",(t,e)=>{LE.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>VE(t,n,r)});function lU(t){return UE(uU,t)}const cU=R("ZodArray",(t,e)=>{Vz.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>XE(t,n,r,i),t.element=e.element,pu(t,"ZodArray",{min(n,r){return this.check(Pc(n,r))},nonempty(n){return this.check(Pc(1,n))},max(n,r){return this.check(FE(n,r))},length(n,r){return this.check(BE(n,r))},unwrap(){return this.element}})});function mu(t,e){return X3(cU,t,e)}const dU=R("ZodObject",(t,e)=>{qz.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>QE(t,n,r,i),Te(t,"shape",()=>e.shape),pu(t,"ZodObject",{keyof(){return yy(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Iw()})},loose(){return this.clone({...this._zod.def,catchall:Iw()})},strict(){return this.clone({...this._zod.def,catchall:lU()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return pM(this,n)},safeExtend(n){return mM(this,n)},merge(n){return gM(this,n)},pick(n){return fM(this,n)},omit(n){return hM(this,n)},partial(...n){return yM(zT,this,n[0])},required(...n){return _M(DT,this,n[0])}})});function At(t,e){const n={type:"object",shape:t??{},...ee(e)};return new dU(n)}const fU=R("ZodUnion",(t,e)=>{Wz.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>YE(t,n,r,i),t.options=e.options});function Dd(t,e){return new fU({type:"union",options:t,...ee(e)})}const hU=R("ZodIntersection",(t,e)=>{Gz.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>eT(t,n,r,i)});function pU(t,e){return new hU({type:"intersection",left:t,right:e})}const Ow=R("ZodRecord",(t,e)=>{Jz.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>tT(t,n,r,i),t.keyType=e.keyType,t.valueType=e.valueType});function mU(t,e,n){return!e||!e._zod?new Ow({type:"record",keyType:Wt(),valueType:t,...ee(e)}):new Ow({type:"record",keyType:t,valueType:e,...ee(n)})}const rm=R("ZodEnum",(t,e)=>{Xz.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(r,i,s)=>qE(t,r,i),t.enum=e.entries,t.options=Object.values(e.entries);const n=new Set(Object.keys(e.entries));t.extract=(r,i)=>{const s={};for(const a of r)if(n.has(a))s[a]=e.entries[a];else throw new Error(`Key ${a} not found in enum`);return new rm({...e,checks:[],...ee(i),entries:s})},t.exclude=(r,i)=>{const s={...e.entries};for(const a of r)if(n.has(a))delete s[a];else throw new Error(`Key ${a} not found in enum`);return new rm({...e,checks:[],...ee(i),entries:s})}});function yy(t,e){const n=Array.isArray(t)?Object.fromEntries(t.map(r=>[r,r])):t;return new rm({type:"enum",entries:n,...ee(e)})}const gU=R("ZodLiteral",(t,e)=>{Qz.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>WE(t,n,r),t.values=new Set(e.values),Object.defineProperty(t,"value",{get(){if(e.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return e.values[0]}})});function wn(t,e){return new gU({type:"literal",values:Array.isArray(t)?t:[t],...ee(e)})}const yU=R("ZodTransform",(t,e)=>{Yz.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>JE(t,n),t._zod.parse=(n,r)=>{if(r.direction==="backward")throw new wE(t.constructor.name);n.addIssue=s=>{if(typeof s=="string")n.issues.push(Go(s,n.value,e));else{const a=s;a.fatal&&(a.continue=!1),a.code??(a.code="custom"),a.input??(a.input=n.value),a.inst??(a.inst=t),n.issues.push(Go(a))}};const i=e.transform(n.value,n);return i instanceof Promise?i.then(s=>(n.value=s,n.fallback=!0,n)):(n.value=i,n.fallback=!0,n)}});function _U(t){return new yU({type:"transform",transform:t})}const zT=R("ZodOptional",(t,e)=>{DE.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>cy(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function Cw(t){return new zT({type:"optional",innerType:t})}const vU=R("ZodExactOptional",(t,e)=>{e3.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>cy(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function wU(t){return new vU({type:"optional",innerType:t})}const bU=R("ZodNullable",(t,e)=>{t3.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>nT(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function Pw(t){return new bU({type:"nullable",innerType:t})}const xU=R("ZodDefault",(t,e)=>{n3.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>iT(t,n,r,i),t.unwrap=()=>t._zod.def.innerType,t.removeDefault=t.unwrap});function kU(t,e){return new xU({type:"default",innerType:t,get defaultValue(){return typeof e=="function"?e():kE(e)}})}const SU=R("ZodPrefault",(t,e)=>{r3.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>sT(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function AU(t,e){return new SU({type:"prefault",innerType:t,get defaultValue(){return typeof e=="function"?e():kE(e)}})}const DT=R("ZodNonOptional",(t,e)=>{i3.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>rT(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function EU(t,e){return new DT({type:"nonoptional",innerType:t,...ee(e)})}const TU=R("ZodCatch",(t,e)=>{s3.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>aT(t,n,r,i),t.unwrap=()=>t._zod.def.innerType,t.removeCatch=t.unwrap});function IU(t,e){return new TU({type:"catch",innerType:t,catchValue:typeof e=="function"?e:()=>e})}const OU=R("ZodPipe",(t,e)=>{a3.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>oT(t,n,r,i),t.in=e.in,t.out=e.out});function Nw(t,e){return new OU({type:"pipe",in:t,out:e})}const CU=R("ZodReadonly",(t,e)=>{o3.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>uT(t,n,r,i),t.unwrap=()=>t._zod.def.innerType});function PU(t){return new CU({type:"readonly",innerType:t})}const NU=R("ZodCustom",(t,e)=>{u3.init(t,e),Ke.init(t,e),t._zod.processJSONSchema=(n,r,i)=>GE(t,n)});function $U(t,e={}){return Q3(NU,t,e)}function RU(t,e){return Y3(t,e)}const jU=Symbol("Let zodToJsonSchema decide on which parser to use"),$w={name:void 0,$refStrategy:"root",effectStrategy:"input",pipeStrategy:"all",dateStrategy:"format:date-time",mapStrategy:"entries",nullableStrategy:"from-target",removeAdditionalStrategy:"passthrough",definitionPath:"definitions",target:"jsonSchema7",strictUnions:!1,errorMessages:!1,markdownDescription:!1,patternStrategy:"escape",applyRegexFlags:!1,emailStrategy:"format:email",base64Strategy:"contentEncoding:base64",nameStrategy:"ref"},LU=t=>typeof t=="string"?{...$w,basePath:["#"],definitions:{},name:t}:{...$w,basePath:["#"],definitions:{},...t},im=t=>"_def"in t?t._def:t;function MU(t){if(!t)return!0;for(const e in t)return!1;return!0}const zU=t=>{const e=LU(t),n=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:n,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([r,i])=>[im(i),{def:im(i),path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function UT(t,e,n,r){r!=null&&r.errorMessages&&n&&(t.errorMessage={...t.errorMessage,[e]:n})}function Se(t,e,n,r,i){t[e]=n,UT(t,e,r,i)}function DU(){return{}}function UU(t,e){var r,i;const n={type:"array"};return((i=(r=t.type)==null?void 0:r._def)==null?void 0:i.typeName)!==$.ZodAny&&(n.items=ve(t.type._def,{...e,currentPath:[...e.currentPath,"items"]})),t.minLength&&Se(n,"minItems",t.minLength.value,t.minLength.message,e),t.maxLength&&Se(n,"maxItems",t.maxLength.value,t.maxLength.message,e),t.exactLength&&(Se(n,"minItems",t.exactLength.value,t.exactLength.message,e),Se(n,"maxItems",t.exactLength.value,t.exactLength.message,e)),n}function FU(t,e){const n={type:"integer",format:"int64"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?Se(n,"minimum",r.value,r.message,e):Se(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Se(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Se(n,"maximum",r.value,r.message,e):Se(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Se(n,"maximum",r.value,r.message,e));break;case"multipleOf":Se(n,"multipleOf",r.value,r.message,e);break}return n}function BU(){return{type:"boolean"}}function HU(t,e){return ve(t.type._def,e)}const ZU=(t,e)=>ve(t.innerType._def,e);function FT(t,e,n){const r=n??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((i,s)=>FT(t,e,i))};switch(r){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return VU(t,e)}}const VU=(t,e)=>{const n={type:"integer",format:"unix-time"};if(e.target==="openApi3")return n;for(const r of t.checks)switch(r.kind){case"min":Se(n,"minimum",r.value,r.message,e);break;case"max":Se(n,"maximum",r.value,r.message,e);break}return n};function KU(t,e){return{...ve(t.innerType._def,e),default:t.defaultValue()}}function qU(t,e,n){return e.effectStrategy==="input"?ve(t.schema._def,e,n):{}}function WU(t){return{type:"string",enum:[...t.values]}}const GU=t=>"type"in t&&t.type==="string"?!1:"allOf"in t;function JU(t,e){const n=[ve(t.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),ve(t.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(s=>!!s);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const i=[];return n.forEach(s=>{if(GU(s))i.push(...s.allOf),s.unevaluatedProperties===void 0&&(r=void 0);else{let a=s;if("additionalProperties"in s&&s.additionalProperties===!1){const{additionalProperties:o,...u}=s;a=u}else r=void 0;i.push(a)}}),i.length?{allOf:i,...r}:void 0}function XU(t,e){const n=typeof t.value;return n!=="bigint"&&n!=="number"&&n!=="boolean"&&n!=="string"?{type:Array.isArray(t.value)?"array":"object"}:e.target==="openApi3"?{type:n==="bigint"?"integer":n,enum:[t.value]}:{type:n==="bigint"?"integer":n,const:t.value}}let eh;const Li={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:()=>(eh===void 0&&(eh=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),eh),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])$/,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})))$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function BT(t,e){const n={type:"string"};function r(i){return e.patternStrategy==="escape"?QU(i):i}if(t.checks)for(const i of t.checks)switch(i.kind){case"min":Se(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value,i.message,e);break;case"max":Se(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value,i.message,e);break;case"email":switch(e.emailStrategy){case"format:email":zn(n,"email",i.message,e);break;case"format:idn-email":zn(n,"idn-email",i.message,e);break;case"pattern:zod":Dn(n,Li.email,i.message,e);break}break;case"url":zn(n,"uri",i.message,e);break;case"uuid":zn(n,"uuid",i.message,e);break;case"regex":Dn(n,i.regex,i.message,e);break;case"cuid":Dn(n,Li.cuid,i.message,e);break;case"cuid2":Dn(n,Li.cuid2,i.message,e);break;case"startsWith":Dn(n,RegExp(`^${r(i.value)}`),i.message,e);break;case"endsWith":Dn(n,RegExp(`${r(i.value)}$`),i.message,e);break;case"datetime":zn(n,"date-time",i.message,e);break;case"date":zn(n,"date",i.message,e);break;case"time":zn(n,"time",i.message,e);break;case"duration":zn(n,"duration",i.message,e);break;case"length":Se(n,"minLength",typeof n.minLength=="number"?Math.max(n.minLength,i.value):i.value,i.message,e),Se(n,"maxLength",typeof n.maxLength=="number"?Math.min(n.maxLength,i.value):i.value,i.message,e);break;case"includes":{Dn(n,RegExp(r(i.value)),i.message,e);break}case"ip":{i.version!=="v6"&&zn(n,"ipv4",i.message,e),i.version!=="v4"&&zn(n,"ipv6",i.message,e);break}case"emoji":Dn(n,Li.emoji,i.message,e);break;case"ulid":{Dn(n,Li.ulid,i.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{zn(n,"binary",i.message,e);break}case"contentEncoding:base64":{Se(n,"contentEncoding","base64",i.message,e);break}case"pattern:zod":{Dn(n,Li.base64,i.message,e);break}}break}case"nanoid":Dn(n,Li.nanoid,i.message,e)}return n}const QU=t=>Array.from(t).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),zn=(t,e,n,r)=>{var i;t.format||(i=t.anyOf)!=null&&i.some(s=>s.format)?(t.anyOf||(t.anyOf=[]),t.format&&(t.anyOf.push({format:t.format,...t.errorMessage&&r.errorMessages&&{errorMessage:{format:t.errorMessage.format}}}),delete t.format,t.errorMessage&&(delete t.errorMessage.format,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.anyOf.push({format:e,...n&&r.errorMessages&&{errorMessage:{format:n}}})):Se(t,"format",e,n,r)},Dn=(t,e,n,r)=>{var i;t.pattern||(i=t.allOf)!=null&&i.some(s=>s.pattern)?(t.allOf||(t.allOf=[]),t.pattern&&(t.allOf.push({pattern:t.pattern,...t.errorMessage&&r.errorMessages&&{errorMessage:{pattern:t.errorMessage.pattern}}}),delete t.pattern,t.errorMessage&&(delete t.errorMessage.pattern,Object.keys(t.errorMessage).length===0&&delete t.errorMessage)),t.allOf.push({pattern:Rw(e,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):Se(t,"pattern",Rw(e,r),n,r)},Rw=(t,e)=>{var l;const n=typeof t=="function"?t():t;if(!e.applyRegexFlags||!n.flags)return n.source;const r={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},i=r.i?n.source.toLowerCase():n.source;let s="",a=!1,o=!1,u=!1;for(let c=0;c<i.length;c++){if(a){s+=i[c],a=!1;continue}if(r.i){if(o){if(i[c].match(/[a-z]/)){u?(s+=i[c],s+=`${i[c-2]}-${i[c]}`.toUpperCase(),u=!1):i[c+1]==="-"&&((l=i[c+2])!=null&&l.match(/[a-z]/))?(s+=i[c],u=!0):s+=`${i[c]}${i[c].toUpperCase()}`;continue}}else if(i[c].match(/[a-z]/)){s+=`[${i[c]}${i[c].toUpperCase()}]`;continue}}if(r.m){if(i[c]==="^"){s+=`(^|(?<=[\r ]))`;continue}else if(i[c]==="$"){s+=`($|(?=[\r ]))`;continue}}if(r.s&&i[c]==="."){s+=o?`${i[c]}\r `:`[${i[c]}\r ]`;continue}s+=i[c],i[c]==="\\"?a=!0:o&&i[c]==="]"?o=!1:!o&&i[c]==="["&&(o=!0)}try{const c=new RegExp(s)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),n.source}return s};function HT(t,e){var r,i,s,a;if(e.target==="openApi3"&&((r=t.keyType)==null?void 0:r._def.typeName)===$.ZodEnum)return{type:"object",required:t.keyType._def.values,properties:t.keyType._def.values.reduce((o,u)=>({...o,[u]:ve(t.valueType._def,{...e,currentPath:[...e.currentPath,"properties",u]})??{}}),{}),additionalProperties:!1};const n={type:"object",additionalProperties:ve(t.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return n;if(((i=t.keyType)==null?void 0:i._def.typeName)===$.ZodString&&((s=t.keyType._def.checks)!=null&&s.length)){const o=Object.entries(BT(t.keyType._def,e)).reduce((u,[l,c])=>l==="type"?u:{...u,[l]:c},{});return{...n,propertyNames:o}}else if(((a=t.keyType)==null?void 0:a._def.typeName)===$.ZodEnum)return{...n,propertyNames:{enum:t.keyType._def.values}};return n}function YU(t,e){if(e.mapStrategy==="record")return HT(t,e);const n=ve(t.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=ve(t.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[n,r],minItems:2,maxItems:2}}}function e8(t){const e=t.values,r=Object.keys(t.values).filter(s=>typeof e[e[s]]!="number").map(s=>e[s]),i=Array.from(new Set(r.map(s=>typeof s)));return{type:i.length===1?i[0]==="string"?"string":"number":["string","number"],enum:r}}function t8(){return{not:{}}}function n8(t){return t.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const Vc={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function r8(t,e){if(e.target==="openApi3")return jw(t,e);const n=t.options instanceof Map?Array.from(t.options.values()):t.options;if(n.every(r=>r._def.typeName in Vc&&(!r._def.checks||!r._def.checks.length))){const r=n.reduce((i,s)=>{const a=Vc[s._def.typeName];return a&&!i.includes(a)?[...i,a]:i},[]);return{type:r.length>1?r:r[0]}}else if(n.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=n.reduce((i,s)=>{const a=typeof s._def.value;switch(a){case"string":case"number":case"boolean":return[...i,a];case"bigint":return[...i,"integer"];case"object":if(s._def.value===null)return[...i,"null"];case"symbol":case"undefined":case"function":default:return i}},[]);if(r.length===n.length){const i=r.filter((s,a,o)=>o.indexOf(s)===a);return{type:i.length>1?i:i[0],enum:n.reduce((s,a)=>s.includes(a._def.value)?s:[...s,a._def.value],[])}}}else if(n.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:n.reduce((r,i)=>[...r,...i._def.values.filter(s=>!r.includes(s))],[])};return jw(t,e)}const jw=(t,e)=>{const n=(t.options instanceof Map?Array.from(t.options.values()):t.options).map((r,i)=>ve(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${i}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return n.length?{anyOf:n}:void 0};function i8(t,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(t.innerType._def.typeName)&&(!t.innerType._def.checks||!t.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:Vc[t.innerType._def.typeName],nullable:!0}:{type:[Vc[t.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=ve(t.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const n=ve(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return n&&{anyOf:[n,{type:"null"}]}}function s8(t,e){const n={type:"number"};if(!t.checks)return n;for(const r of t.checks)switch(r.kind){case"int":n.type="integer",UT(n,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?Se(n,"minimum",r.value,r.message,e):Se(n,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(n.exclusiveMinimum=!0),Se(n,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?Se(n,"maximum",r.value,r.message,e):Se(n,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(n.exclusiveMaximum=!0),Se(n,"maximum",r.value,r.message,e));break;case"multipleOf":Se(n,"multipleOf",r.value,r.message,e);break}return n}function a8(t,e){return e.removeAdditionalStrategy==="strict"?t.catchall._def.typeName==="ZodNever"?t.unknownKeys!=="strict":ve(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:t.catchall._def.typeName==="ZodNever"?t.unknownKeys==="passthrough":ve(t.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function o8(t,e){const n={type:"object",...Object.entries(t.shape()).reduce((r,[i,s])=>{var u;if(s===void 0||s._def===void 0)return r;const a=[...e.currentPath,"properties",i],o=ve(s._def,{...e,currentPath:a,propertyPath:a});if(o===void 0)return r;if(e.openaiStrictMode&&s.isOptional()&&!s.isNullable()&&typeof((u=s._def)==null?void 0:u.defaultValue)>"u")throw new Error(`Zod field at \`${a.join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);return{properties:{...r.properties,[i]:o},required:s.isOptional()&&!e.openaiStrictMode?r.required:[...r.required,i]}},{properties:{},required:[]}),additionalProperties:a8(t,e)};return n.required.length||delete n.required,n}const u8=(t,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return ve(t.innerType._def,{...e,currentPath:e.currentPath});const n=ve(t.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return n?{anyOf:[{not:{}},n]}:{}},l8=(t,e)=>{if(e.pipeStrategy==="input")return ve(t.in._def,e);if(e.pipeStrategy==="output")return ve(t.out._def,e);const n=ve(t.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=ve(t.out._def,{...e,currentPath:[...e.currentPath,"allOf",n?"1":"0"]});return{allOf:[n,r].filter(i=>i!==void 0)}};function c8(t,e){return ve(t.type._def,e)}function d8(t,e){const r={type:"array",uniqueItems:!0,items:ve(t.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return t.minSize&&Se(r,"minItems",t.minSize.value,t.minSize.message,e),t.maxSize&&Se(r,"maxItems",t.maxSize.value,t.maxSize.message,e),r}function f8(t,e){return t.rest?{type:"array",minItems:t.items.length,items:t.items.map((n,r)=>ve(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[]),additionalItems:ve(t.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:t.items.length,maxItems:t.items.length,items:t.items.map((n,r)=>ve(n._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((n,r)=>r===void 0?n:[...n,r],[])}}function h8(){return{not:{}}}function p8(){return{}}const m8=(t,e)=>ve(t.innerType._def,e);function ve(t,e,n=!1){var a;const r=e.seen.get(t);if(e.override){const o=(a=e.override)==null?void 0:a.call(e,t,e,r,n);if(o!==jU)return o}if(r&&!n){const o=g8(r,e);if(o!==void 0)return"$ref"in o&&e.seenRefs.add(o.$ref),o}const i={def:t,path:e.currentPath,jsonSchema:void 0};e.seen.set(t,i);const s=_8(t,t.typeName,e,n);return s&&v8(t,e,s),i.jsonSchema=s,s}const g8=(t,e)=>{switch(e.$refStrategy){case"root":return{$ref:t.path.join("/")};case"extract-to-root":const n=t.path.slice(e.basePath.length+1).join("_");return n!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[n]=t.def),{$ref:[...e.basePath,e.definitionPath,n].join("/")};case"relative":return{$ref:y8(e.currentPath,t.path)};case"none":case"seen":return t.path.length<e.currentPath.length&&t.path.every((r,i)=>e.currentPath[i]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},y8=(t,e)=>{let n=0;for(;n<t.length&&n<e.length&&t[n]===e[n];n++);return[(t.length-n).toString(),...e.slice(n)].join("/")},_8=(t,e,n,r)=>{switch(e){case $.ZodString:return BT(t,n);case $.ZodNumber:return s8(t,n);case $.ZodObject:return o8(t,n);case $.ZodBigInt:return FU(t,n);case $.ZodBoolean:return BU();case $.ZodDate:return FT(t,n);case $.ZodUndefined:return h8();case $.ZodNull:return n8(n);case $.ZodArray:return UU(t,n);case $.ZodUnion:case $.ZodDiscriminatedUnion:return r8(t,n);case $.ZodIntersection:return JU(t,n);case $.ZodTuple:return f8(t,n);case $.ZodRecord:return HT(t,n);case $.ZodLiteral:return XU(t,n);case $.ZodEnum:return WU(t);case $.ZodNativeEnum:return e8(t);case $.ZodNullable:return i8(t,n);case $.ZodOptional:return u8(t,n);case $.ZodMap:return YU(t,n);case $.ZodSet:return d8(t,n);case $.ZodLazy:return ve(t.getter()._def,n);case $.ZodPromise:return c8(t,n);case $.ZodNaN:case $.ZodNever:return t8();case $.ZodEffects:return qU(t,n,r);case $.ZodAny:return DU();case $.ZodUnknown:return p8();case $.ZodDefault:return KU(t,n);case $.ZodBranded:return HU(t,n);case $.ZodReadonly:return m8(t,n);case $.ZodCatch:return ZU(t,n);case $.ZodPipeline:return l8(t,n);case $.ZodFunction:case $.ZodVoid:case $.ZodSymbol:return;default:return(i=>{})()}},v8=(t,e,n)=>(t.description&&(n.description=t.description,e.markdownDescription&&(n.markdownDescription=t.description)),n),w8=(t,e)=>{const n=zU(e),r=typeof e=="string"?e:(e==null?void 0:e.nameStrategy)==="title"||e==null?void 0:e.name,i=ve(t._def,r===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,r]},!1)??{},s=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;s!==void 0&&(i.title=s);const a=(()=>{if(MU(n.definitions))return;const u={},l=new Set;for(let c=0;c<500;c++){const d=Object.entries(n.definitions).filter(([f])=>!l.has(f));if(d.length===0)break;for(const[f,h]of d)u[f]=ve(im(h),{...n,currentPath:[...n.basePath,n.definitionPath,f]},!0)??{},l.add(f)}return u})(),o=r===void 0?a?{...i,[n.definitionPath]:a}:i:n.nameStrategy==="duplicate-ref"?{...i,...a||n.seenRefs.size?{[n.definitionPath]:{...a,...n.seenRefs.size?{[r]:i}:void 0}}:void 0}:{$ref:[...n.$refStrategy==="relative"?[]:n.basePath,n.definitionPath,r].join("/"),[n.definitionPath]:{...a,[r]:i}};return n.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":n.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function b8(t){if(t.type!=="object")throw new Error(`Root schema must have type: 'object' but got type: ${t.type?`'${t.type}'`:"undefined"}`);const e=structuredClone(t);return Sr(e,[],e)}function sm(t){if(typeof t=="boolean")return!1;if(t.type==="null")return!0;for(const e of t.oneOf??[])if(sm(e))return!0;for(const e of t.anyOf??[])if(sm(e))return!0;return!1}function Sr(t,e,n){if(typeof t=="boolean")throw new TypeError(`Expected object schema but got boolean; path=${e.join("/")}`);if(!Bi(t))throw new TypeError(`Expected ${JSON.stringify(t)} to be an object; path=${e.join("/")}`);const r=t.$defs;if(Bi(r))for(const[f,h]of Object.entries(r))Sr(h,[...e,"$defs",f],n);const i=t.definitions;if(Bi(i))for(const[f,h]of Object.entries(i))Sr(h,[...e,"definitions",f],n);t.type==="object"&&!("additionalProperties"in t)&&(t.additionalProperties=!1);const a=t.required??[],o=t.properties;if(Bi(o)){for(const[f,h]of Object.entries(o))if(!sm(h)&&!a.includes(f))throw new Error(`Zod field at \`${[...e,"properties",f].join("/")}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`);t.required=Object.keys(o),t.properties=Object.fromEntries(Object.entries(o).map(([f,h])=>[f,Sr(h,[...e,"properties",f],n)]))}const u=t.items;Bi(u)&&(t.items=Sr(u,[...e,"items"],n));const l=t.anyOf;Array.isArray(l)&&(t.anyOf=l.map((f,h)=>Sr(f,[...e,"anyOf",String(h)],n)));const c=t.allOf;if(Array.isArray(c))if(c.length===1){const f=Sr(c[0],[...e,"allOf","0"],n);Object.assign(t,f),delete t.allOf}else t.allOf=c.map((f,h)=>Sr(f,[...e,"allOf",String(h)],n));t.default===null&&delete t.default;const d=t.$ref;if(d&&k8(t,1)){if(typeof d!="string")throw new TypeError(`Received non-string $ref - ${d}; path=${e.join("/")}`);const f=x8(n,d);if(typeof f=="boolean")throw new Error(`Expected \`$ref: ${d}\` to resolve to an object schema but got boolean`);if(!Bi(f))throw new Error(`Expected \`$ref: ${d}\` to resolve to an object but got ${JSON.stringify(f)}`);return Object.assign(t,{...f,...t}),delete t.$ref,Sr(t,e,n)}return t}function x8(t,e){if(!e.startsWith("#/"))throw new Error(`Unexpected $ref format ${JSON.stringify(e)}; Does not start with #/`);const n=e.slice(2).split("/");let r=t;for(const i of n){if(!Bi(r))throw new Error(`encountered non-object entry while resolving ${e} - ${JSON.stringify(r)}`);const s=r[i];if(s===void 0)throw new Error(`Key ${i} not found while resolving ${e}`);r=s}return r}function Bi(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function k8(t,e){let n=0;for(const r in t)if(n++,n>e)return!0;return!1}function S8(t,e){return w8(t,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function A8(t){return b8(Bp(t,{target:"draft-7"}))}function E8(t){return"_zod"in t}function T8(t,e,n){return QP({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:E8(t)?A8(t):S8(t,{name:e})}},r=>t.parse(JSON.parse(r)))}const Lw=["jsonSchema","functionCalling","jsonMode"];function I8(t,e){if(typeof e<"u"&&!Lw.includes(e))throw new Error(`Invalid method: ${e}. Supported methods are: ${Lw.join(", ")}`);const n=!t.startsWith("gpt-3")&&!t.startsWith("gpt-4-")&&t!=="gpt-4";if(n&&!e)return"jsonSchema";if(!n&&e==="jsonSchema")throw new Error(`JSON Schema is not supported for model "${t}". Please use a different method, e.g. "functionCalling" or "jsonMode".`);return e??"functionCalling"}function O8(t,e){const n={...t};return Object.defineProperties(n,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),n}function C8(t,e,n){if(Kr(t))return T8(t,e,n);if(tn(t))return O8({type:"json_schema",json_schema:{...n,name:e,strict:!0,schema:vi(t,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=e}})}},r=>xM(t,JSON.parse(r)));throw new Error("Unsupported schema response format")}function P8(t,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const n=e.images.filter(r=>{var i;return typeof((i=r==null?void 0:r.image_url)==null?void 0:i.url)=="string"}).map(r=>({type:"image",url:r.image_url.url}));return[{type:"text",text:t},...n]}return t}const N8={"gpt-4o-2024-11-20":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:272e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-mini":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-ada-002":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-chat-latest":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"codex-mini-latest":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex-max":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-05-13":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o1:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini-deep-research":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.3-codex-spark":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},o3:{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-small":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1536,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-nano":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"text-embedding-3-large":{maxInputTokens:8191,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:3072,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-3.5-turbo":{maxInputTokens:16385,imageInputs:!1,audioInputs:!1,pdfInputs:!1,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!1,imageUrlInputs:!1,pdfToolMessage:!1,imageToolMessage:!1,toolChoice:!0},"gpt-5.1-codex-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4-turbo":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:4096,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o4-mini":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4.1-mini":{maxInputTokens:1047576,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-preview":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:32768,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.4-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:13e4,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.5-pro":{maxInputTokens:105e4,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-pro":{maxInputTokens:2e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-codex":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.2-pro":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o3-mini":{maxInputTokens:2e5,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:1e5,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o-2024-08-06":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-mini":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5.1-chat-latest":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4":{maxInputTokens:8192,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:8192,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-5-nano":{maxInputTokens:4e5,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:128e3,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"o1-mini":{maxInputTokens:128e3,imageInputs:!1,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:65536,reasoningOutput:!0,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!1,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0},"gpt-4o":{maxInputTokens:128e3,imageInputs:!0,audioInputs:!1,pdfInputs:!0,videoInputs:!1,maxOutputTokens:16384,reasoningOutput:!1,imageOutputs:!1,audioOutputs:!1,videoOutputs:!1,toolCalling:!0,structuredOutput:!0,imageUrlInputs:!0,pdfToolMessage:!0,imageToolMessage:!0,toolChoice:!0}};/** * [js-sha256]{@link https://github.com/emn178/js-sha256} * * @version 0.11.1 * @author Chen, Yi-Cyuan [emn178@gmail.com] * @copyright Chen, Yi-Cyuan 2014-2025 * @license MIT */var J="0123456789abcdef".split(""),$8=[-2147483648,8388608,32768,128],Un=[24,16,8,0],nl=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],it=[];function er(t,e){e?(it[0]=it[16]=it[1]=it[2]=it[3]=it[4]=it[5]=it[6]=it[7]=it[8]=it[9]=it[10]=it[11]=it[12]=it[13]=it[14]=it[15]=0,this.blocks=it):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}er.prototype.update=function(t){if(!this.finalized){var e,n=typeof t;if(n!=="string"){if(n==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var r,i=0,s,a=t.length,o=this.blocks;i<a;){if(this.hashed&&(this.hashed=!1,o[0]=this.block,this.block=o[16]=o[1]=o[2]=o[3]=o[4]=o[5]=o[6]=o[7]=o[8]=o[9]=o[10]=o[11]=o[12]=o[13]=o[14]=o[15]=0),e)for(s=this.start;i<a&&s<64;++i)o[s>>>2]|=t[i]<<Un[s++&3];else for(s=this.start;i<a&&s<64;++i)r=t.charCodeAt(i),r<128?o[s>>>2]|=r<<Un[s++&3]:r<2048?(o[s>>>2]|=(192|r>>>6)<<Un[s++&3],o[s>>>2]|=(128|r&63)<<Un[s++&3]):r<55296||r>=57344?(o[s>>>2]|=(224|r>>>12)<<Un[s++&3],o[s>>>2]|=(128|r>>>6&63)<<Un[s++&3],o[s>>>2]|=(128|r&63)<<Un[s++&3]):(r=65536+((r&1023)<<10|t.charCodeAt(++i)&1023),o[s>>>2]|=(240|r>>>18)<<Un[s++&3],o[s>>>2]|=(128|r>>>12&63)<<Un[s++&3],o[s>>>2]|=(128|r>>>6&63)<<Un[s++&3],o[s>>>2]|=(128|r&63)<<Un[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=o[16],this.start=s-64,this.hash(),this.hashed=!0):this.start=s}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};er.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=$8[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};er.prototype.hash=function(){var t=this.h0,e=this.h1,n=this.h2,r=this.h3,i=this.h4,s=this.h5,a=this.h6,o=this.h7,u=this.blocks,l,c,d,f,h,m,_,v,y,p,g;for(l=16;l<64;++l)h=u[l-15],c=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=u[l-2],d=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,u[l]=u[l-16]+c+u[l-7]+d<<0;for(g=e&n,l=0;l<64;l+=4)this.first?(this.is224?(v=300032,h=u[0]-1413257819,o=h-150054599<<0,r=h+24177077<<0):(v=704751109,h=u[0]-210244248,o=h-1521486534<<0,r=h+143694565<<0),this.first=!1):(c=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),d=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),v=t&e,f=v^t&n^g,_=i&s^~i&a,h=o+d+_+nl[l]+u[l],m=c+f,o=r+h<<0,r=h+m<<0),c=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),d=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),y=r&t,f=y^r&e^v,_=a&o^~a&i,h=s+d+_+nl[l+1]+u[l+1],m=c+f,a=n+h<<0,n=h+m<<0,c=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),d=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),p=n&r,f=p^n&t^y,_=s&a^~s&o,h=i+d+_+nl[l+2]+u[l+2],m=c+f,s=e+h<<0,e=h+m<<0,c=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),d=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),g=e&n,f=g^e&r^p,_=s&a^~s&o,h=i+d+_+nl[l+3]+u[l+3],m=c+f,i=t+h<<0,t=h+m<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+n<<0,this.h3=this.h3+r<<0,this.h4=this.h4+i<<0,this.h5=this.h5+s<<0,this.h6=this.h6+a<<0,this.h7=this.h7+o<<0};er.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,i=this.h4,s=this.h5,a=this.h6,o=this.h7,u=J[t>>>28&15]+J[t>>>24&15]+J[t>>>20&15]+J[t>>>16&15]+J[t>>>12&15]+J[t>>>8&15]+J[t>>>4&15]+J[t&15]+J[e>>>28&15]+J[e>>>24&15]+J[e>>>20&15]+J[e>>>16&15]+J[e>>>12&15]+J[e>>>8&15]+J[e>>>4&15]+J[e&15]+J[n>>>28&15]+J[n>>>24&15]+J[n>>>20&15]+J[n>>>16&15]+J[n>>>12&15]+J[n>>>8&15]+J[n>>>4&15]+J[n&15]+J[r>>>28&15]+J[r>>>24&15]+J[r>>>20&15]+J[r>>>16&15]+J[r>>>12&15]+J[r>>>8&15]+J[r>>>4&15]+J[r&15]+J[i>>>28&15]+J[i>>>24&15]+J[i>>>20&15]+J[i>>>16&15]+J[i>>>12&15]+J[i>>>8&15]+J[i>>>4&15]+J[i&15]+J[s>>>28&15]+J[s>>>24&15]+J[s>>>20&15]+J[s>>>16&15]+J[s>>>12&15]+J[s>>>8&15]+J[s>>>4&15]+J[s&15]+J[a>>>28&15]+J[a>>>24&15]+J[a>>>20&15]+J[a>>>16&15]+J[a>>>12&15]+J[a>>>8&15]+J[a>>>4&15]+J[a&15];return this.is224||(u+=J[o>>>28&15]+J[o>>>24&15]+J[o>>>20&15]+J[o>>>16&15]+J[o>>>12&15]+J[o>>>8&15]+J[o>>>4&15]+J[o&15]),u};er.prototype.toString=er.prototype.hex;er.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,n=this.h2,r=this.h3,i=this.h4,s=this.h5,a=this.h6,o=this.h7,u=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255];return this.is224||u.push(o>>>24&255,o>>>16&255,o>>>8&255,o&255),u};er.prototype.array=er.prototype.digest;er.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};const R8=(...t)=>new er(!1,!0).update(t.join("")).hex(),j8=(...t)=>R8(t.join("_"));var L8=class{constructor(){A(this,"keyEncoder",j8)}makeDefaultKeyEncoder(t){this.keyEncoder=t}};const M8=new Map;var z8=class ZT extends L8{constructor(n){super();A(this,"cache");this.cache=n??new Map}lookup(n,r){return Promise.resolve(this.cache.get(this.keyEncoder(n,r))??null)}async update(n,r,i){this.cache.set(this.keyEncoder(n,r),i)}static global(){return new ZT(M8)}},VT=class extends Bo{},D8=class extends VT{constructor(e){super({value:e});A(this,"lc_namespace",["langchain_core","prompt_values"]);A(this,"lc_serializable",!0);A(this,"value");this.value=e}static lc_name(){return"StringPromptValue"}toString(){return this.value}toChatMessages(){return[new Zo(this.value)]}},U8=class extends VT{constructor(e){Array.isArray(e)&&(e={messages:e});super(e);A(this,"lc_namespace",["langchain_core","prompt_values"]);A(this,"lc_serializable",!0);A(this,"messages");this.messages=e.messages}static lc_name(){return"ChatPromptValue"}toString(){return NS(this.messages)}toChatMessages(){return this.messages}},Ud={};Ud.byteLength=H8;Ud.toByteArray=V8;Ud.fromByteArray=W8;var fr=[],xn=[],F8=typeof Uint8Array<"u"?Uint8Array:Array,th="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(var ys=0,B8=th.length;ys<B8;++ys)fr[ys]=th[ys],xn[th.charCodeAt(ys)]=ys;xn[45]=62;xn[95]=63;function KT(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=t.indexOf("=");n===-1&&(n=e);var r=n===e?0:4-n%4;return[n,r]}function H8(t){var e=KT(t),n=e[0],r=e[1];return(n+r)*3/4-r}function Z8(t,e,n){return(e+n)*3/4-n}function V8(t){var e,n=KT(t),r=n[0],i=n[1],s=new F8(Z8(t,r,i)),a=0,o=i>0?r-4:r,u;for(u=0;u<o;u+=4)e=xn[t.charCodeAt(u)]<<18|xn[t.charCodeAt(u+1)]<<12|xn[t.charCodeAt(u+2)]<<6|xn[t.charCodeAt(u+3)],s[a++]=e>>16&255,s[a++]=e>>8&255,s[a++]=e&255;return i===2&&(e=xn[t.charCodeAt(u)]<<2|xn[t.charCodeAt(u+1)]>>4,s[a++]=e&255),i===1&&(e=xn[t.charCodeAt(u)]<<10|xn[t.charCodeAt(u+1)]<<4|xn[t.charCodeAt(u+2)]>>2,s[a++]=e>>8&255,s[a++]=e&255),s}function K8(t){return fr[t>>18&63]+fr[t>>12&63]+fr[t>>6&63]+fr[t&63]}function q8(t,e,n){for(var r,i=[],s=e;s<n;s+=3)r=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(K8(r));return i.join("")}function W8(t){for(var e,n=t.length,r=n%3,i=[],s=16383,a=0,o=n-r;a<o;a+=s)i.push(q8(t,a,a+s>o?o:a+s));return r===1?(e=t[n-1],i.push(fr[e>>2]+fr[e<<4&63]+"==")):r===2&&(e=(t[n-2]<<8)+t[n-1],i.push(fr[e>>10]+fr[e>>4&63]+fr[e<<2&63]+"=")),i.join("")}var G8=Object.defineProperty,J8=(t,e,n)=>e in t?G8(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n,X8=(t,e,n)=>(J8(t,e+"",n),n);function Q8(t,e){let n=Array.from({length:t.length},(r,i)=>({start:i,end:i+1}));for(;n.length>1;){let r=null;for(let i=0;i<n.length-1;i++){const s=t.slice(n[i].start,n[i+1].end),a=e.get(s.join(","));a!=null&&(r==null||a<r[0])&&(r=[a,i])}if(r!=null){const i=r[1];n[i]={start:n[i].start,end:n[i+1].end},n.splice(i+1,1)}else break}return n}function Y8(t,e){return t.length===1?[e.get(t.join(","))]:Q8(t,e).map(n=>e.get(t.slice(n.start,n.end).join(","))).filter(n=>n!=null)}function eF(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var am=class{constructor(t,e){A(this,"specialTokens");A(this,"inverseSpecialTokens");A(this,"patStr");A(this,"textEncoder",new TextEncoder);A(this,"textDecoder",new TextDecoder("utf-8"));A(this,"rankMap",new Map);A(this,"textMap",new Map);this.patStr=t.pat_str;const n=t.bpe_ranks.split(` `).filter(Boolean).reduce((r,i)=>{const[s,a,...o]=i.split(" "),u=Number.parseInt(a,10);return o.forEach((l,c)=>r[l]=u+c),r},{});for(const[r,i]of Object.entries(n)){const s=Ud.toByteArray(r);this.rankMap.set(s.join(","),i),this.textMap.set(i,s)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[i,s])=>(r[s]=this.textEncoder.encode(i),r),{})}encode(t,e=[],n="all"){const r=new RegExp(this.patStr,"ug"),i=am.specialTokenRegex(Object.keys(this.specialTokens)),s=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(n==="all"?Object.keys(this.specialTokens).filter(l=>!a.has(l)):n);if(o.size>0){const l=am.specialTokenRegex([...o]),c=t.match(l);if(c!=null)throw new Error(`The text contains a special token that is not allowed: ${c[0]}`)}let u=0;for(;;){let l=null,c=u;for(;i.lastIndex=c,l=i.exec(t),!(l==null||a.has(l[0]));)c=l.index+1;const d=(l==null?void 0:l.index)??t.length;for(const h of t.substring(u,d).matchAll(r)){const m=this.textEncoder.encode(h[0]),_=this.rankMap.get(m.join(","));if(_!=null){s.push(_);continue}s.push(...Y8(m,this.rankMap))}if(l==null)break;let f=this.specialTokens[l[0]];s.push(f),u=l.index+l[0].length}return s}decode(t){const e=[];let n=0;for(let s=0;s<t.length;++s){const a=t[s],o=this.textMap.get(a)??this.inverseSpecialTokens[a];o!=null&&(e.push(o),n+=o.length)}const r=new Uint8Array(n);let i=0;for(const s of e)r.set(s,i),i+=s.length;return this.textDecoder.decode(r)}},qT=am;X8(qT,"specialTokenRegex",t=>new RegExp(t.map(e=>eF(e)).join("|"),"g"));function tF(t){switch(t){case"gpt2":return"gpt2";case"code-cushman-001":case"code-cushman-002":case"code-davinci-001":case"code-davinci-002":case"cushman-codex":case"davinci-codex":case"davinci-002":case"text-davinci-002":case"text-davinci-003":return"p50k_base";case"code-davinci-edit-001":case"text-davinci-edit-001":return"p50k_edit";case"ada":case"babbage":case"babbage-002":case"code-search-ada-code-001":case"code-search-babbage-code-001":case"curie":case"davinci":case"text-ada-001":case"text-babbage-001":case"text-curie-001":case"text-davinci-001":case"text-search-ada-doc-001":case"text-search-babbage-doc-001":case"text-search-curie-doc-001":case"text-search-davinci-doc-001":case"text-similarity-ada-001":case"text-similarity-babbage-001":case"text-similarity-curie-001":case"text-similarity-davinci-001":return"r50k_base";case"gpt-3.5-turbo-instruct-0914":case"gpt-3.5-turbo-instruct":case"gpt-3.5-turbo-16k-0613":case"gpt-3.5-turbo-16k":case"gpt-3.5-turbo-0613":case"gpt-3.5-turbo-0301":case"gpt-3.5-turbo":case"gpt-4-32k-0613":case"gpt-4-32k-0314":case"gpt-4-32k":case"gpt-4-0613":case"gpt-4-0314":case"gpt-4":case"gpt-3.5-turbo-1106":case"gpt-35-turbo":case"gpt-4-1106-preview":case"gpt-4-vision-preview":case"gpt-3.5-turbo-0125":case"gpt-4-turbo":case"gpt-4-turbo-2024-04-09":case"gpt-4-turbo-preview":case"gpt-4-0125-preview":case"text-embedding-ada-002":case"text-embedding-3-small":case"text-embedding-3-large":return"cl100k_base";case"gpt-4o":case"gpt-4o-2024-05-13":case"gpt-4o-2024-08-06":case"gpt-4o-2024-11-20":case"gpt-4o-mini-2024-07-18":case"gpt-4o-mini":case"gpt-4o-search-preview":case"gpt-4o-search-preview-2025-03-11":case"gpt-4o-mini-search-preview":case"gpt-4o-mini-search-preview-2025-03-11":case"gpt-4o-audio-preview":case"gpt-4o-audio-preview-2024-12-17":case"gpt-4o-audio-preview-2024-10-01":case"gpt-4o-mini-audio-preview":case"gpt-4o-mini-audio-preview-2024-12-17":case"o1":case"o1-2024-12-17":case"o1-mini":case"o1-mini-2024-09-12":case"o1-preview":case"o1-preview-2024-09-12":case"o1-pro":case"o1-pro-2025-03-19":case"o3":case"o3-2025-04-16":case"o3-mini":case"o3-mini-2025-01-31":case"o4-mini":case"o4-mini-2025-04-16":case"chatgpt-4o-latest":case"gpt-4o-realtime":case"gpt-4o-realtime-preview-2024-10-01":case"gpt-4o-realtime-preview-2024-12-17":case"gpt-4o-mini-realtime-preview":case"gpt-4o-mini-realtime-preview-2024-12-17":case"gpt-4.1":case"gpt-4.1-2025-04-14":case"gpt-4.1-mini":case"gpt-4.1-mini-2025-04-14":case"gpt-4.1-nano":case"gpt-4.1-nano-2025-04-14":case"gpt-4.5-preview":case"gpt-4.5-preview-2025-02-27":case"gpt-5":case"gpt-5-2025-08-07":case"gpt-5-nano":case"gpt-5-nano-2025-08-07":case"gpt-5-mini":case"gpt-5-mini-2025-08-07":case"gpt-5-chat-latest":return"o200k_base";default:throw new Error("Unknown model")}}const rl={},nF=new Cd({});async function rF(t){return t in rl||(rl[t]=nF.fetch(`https://tiktoken.pages.dev/js/${t}.json`).then(e=>e.json()).then(e=>new qT(e)).catch(e=>{throw delete rl[t],e})),await rl[t]}async function iF(t){return rF(tF(t))}const sF=t=>t.startsWith("gpt-5")?"gpt-5":t.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":t.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":t.startsWith("gpt-4-32k")?"gpt-4-32k":t.startsWith("gpt-4-")?"gpt-4":t.startsWith("gpt-4o")?"gpt-4o":t;function WT(t){return typeof t!="object"||!t?!1:!!("type"in t&&t.type==="function"&&"function"in t&&typeof t.function=="object"&&t.function&&"name"in t.function&&"parameters"in t.function)}const aF=()=>!1;var oF=class extends mt{constructor(e){super(e);A(this,"verbose");A(this,"callbacks");A(this,"tags");A(this,"metadata");this.verbose=e.verbose??aF(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{},this._addVersion("@langchain/core","1.2.1")}get lc_attributes(){return{callbacks:void 0,verbose:void 0}}_addVersion(e,n){var i;const r=(i=this.metadata)==null?void 0:i.versions;this.metadata={...this.metadata,versions:{...typeof r=="object"&&r!==null?r:{},[e]:n}}}},uF=class extends oF{constructor({callbacks:e,callbackManager:n,...r}){const{cache:i,...s}=r;super({callbacks:e??n,...s});A(this,"caller");A(this,"cache");A(this,"_encoding");typeof i=="object"?this.cache=i:i?this.cache=z8.global():this.cache=void 0,this.caller=new Cd(r??{})}get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}async getNumTokens(e){let n;typeof e=="string"?n=e:n=e.map(i=>typeof i=="string"?i:i.type==="text"&&"text"in i?i.text:"").join("");let r=Math.ceil(n.length/4);if(!this._encoding)try{this._encoding=await iF("modelName"in this?sF(this.modelName):"gpt2")}catch(i){console.warn("Failed to calculate number of tokens, falling back to approximate count",i)}if(this._encoding)try{r=this._encoding.encode(n).length}catch(i){console.warn("Failed to calculate number of tokens, falling back to approximate count",i)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new D8(e):Array.isArray(e)?new U8(e.map(Cl)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...n}){const r={...this._identifyingParams(),...n,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([i,s])=>s!==void 0).map(([i,s])=>`${i}:${JSON.stringify(s)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}get profile(){return{}}_filterInvocationParamsForTracing(e){const{tools:n,functions:r,messages:i,response_format:s,...a}=e;return a}};const lF=t=>t();function il(t){const e=t.constructor;return new e({...t,content:t.contentBlocks,response_metadata:{...t.response_metadata,output_version:"v1"}})}var Mw=class extends mt{constructor(e){super(e);A(this,"lc_namespace",["langchain_core","runnables"]);A(this,"lc_serializable",!0);A(this,"func");e&&(this.func=e.func)}static lc_name(){return"RunnablePassthrough"}async invoke(e,n){const r=xe(n);return this.func&&await this.func(e,r),this._callWithConfig(i=>Promise.resolve(i),e,r)}async*transform(e,n){const r=xe(n);let i,s=!0;for await(const a of this._transformStreamWithConfig(e,o=>o,r))if(yield a,s)if(i===void 0)i=a;else try{i=Od(i,a)}catch{i=void 0,s=!1}this.func&&i!==void 0&&await this.func(i,r)}static assign(e){return new CT(new Md({steps:e}))}},cF=class extends mt{parseResultWithPrompt(t,e,n){return this.parseResult(t,n)}_baseMessageToString(t){return typeof t.content=="string"?t.content:this._baseMessageContentToString(t.content)}_baseMessageContentToString(t){return JSON.stringify(t)}async invoke(t,e){return typeof t=="string"?this._callWithConfig(async(n,r)=>this.parseResult([{text:n}],r==null?void 0:r.callbacks),t,{...e,runType:"parser"}):this._callWithConfig(async(n,r)=>this.parseResult([{message:n,text:this._baseMessageToString(n)}],r==null?void 0:r.callbacks),t,{...e,runType:"parser"})}},_y=class extends cF{parseResult(t,e){return this.parse(t[0].text,e)}async parseWithPrompt(t,e,n){return this.parse(t,n)}_type(){throw new Error("_type not implemented")}},Yo=class extends Error{constructor(e,n,r,i=!1){super(e);A(this,"llmOutput");A(this,"observation");A(this,"sendToLLM");if(this.llmOutput=n,this.observation=r,this.sendToLLM=i,i&&(r===void 0||n===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");hS(this,"OUTPUT_PARSING_FAILURE")}},dF=class extends _y{async*_transform(t){for await(const e of t)typeof e=="string"?yield this.parseResult([{text:e}]):yield this.parseResult([{message:e,text:this._baseMessageToString(e)}])}async*transform(t,e){yield*this._transformStreamWithConfig(t,this._transform.bind(this),{...e,runType:"parser"})}},GT=class extends dF{constructor(e){super(e);A(this,"diff",!1);this.diff=(e==null?void 0:e.diff)??this.diff}async*_transform(e){let n,r;for await(const i of e){if(typeof i!="string"&&typeof i.content!="string")throw new Error("Cannot handle non-string output.");let s;if(h2(i)){if(typeof i.content!="string")throw new Error("Cannot handle non-string message output.");s=new Wo({message:i,text:i.content})}else if(Rg(i)){if(typeof i.content!="string")throw new Error("Cannot handle non-string message output.");s=new Wo({message:D2(i),text:i.content})}else s=new Ic({text:i});r===void 0?r=s:r=r.concat(s);const a=await this.parsePartialResult([r]);a!=null&&!Yp(a,n)&&(this.diff?yield this._diff(n,a):yield a,n=a)}}getFormatInstructions(){return""}},JT=class extends GT{constructor(){super(...arguments);A(this,"lc_namespace",["langchain_core","output_parsers"]);A(this,"lc_serializable",!0)}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,n){return this.diff?super._concatOutputChunks(e,n):n}_diff(e,n){if(n)return e?LL(e,n):[{op:"replace",path:"",value:n}]}async parsePartialResult(e){return pp(e[0].text)}async parse(e){return pp(e,JSON.parse)}getFormatInstructions(){return""}_baseMessageToString(e){return e.text}},fF=class extends _y{constructor(e){super();A(this,"lc_namespace",["langchain","output_parsers","standard_schema"]);A(this,"schema");this.schema=e}static lc_name(){return"StandardSchemaOutputParser"}static fromSerializableSchema(e){return new this(e)}async parse(e){try{const n=pp(e,JSON.parse),r=await this.schema["~standard"].validate(n);if(r.issues)throw new Error(`Validation failed: ${JSON.stringify(r.issues)}`);return r.value}catch(n){throw new Yo(`Failed to parse. Text: "${e}". Error: ${n}`,e)}}_baseMessageToString(e){return e.text}getFormatInstructions(){return""}},hF=class extends _y{constructor(e){super(e);A(this,"lc_namespace",["langchain","output_parsers","structured"]);this.schema=e}static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const n=yT(Object.fromEntries(Object.entries(e).map(([r,i])=>[r,gT().describe(i)])));return new this(n)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance. "JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings. Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas! Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: \`\`\`json ${JSON.stringify(vi(this.schema))} \`\`\` `}async parse(e){var n,r;try{const i=e.trim(),s=(((n=i.match(/^```(?:json)?\s*([\s\S]*?)```/))==null?void 0:n[1])||((r=i.match(/```json\s*([\s\S]*?)```/))==null?void 0:r[1])||i).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(a,o)=>`"${o.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await lT(this.schema,JSON.parse(s))}catch(i){throw new Yo(`Failed to parse. Text: "${e}". Error: ${i}`,e)}}_baseMessageToString(e){return e.text}};const pF=function(){const t={};t.parser=function(S,x){return new n(S,x)},t.SAXParser=n,t.SAXStream=l,t.createStream=u,t.MAX_BUFFER_LENGTH=64*1024;const e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function n(S,x){if(!(this instanceof n))return new n(S,x);var M=this;i(M),M.q=M.c="",M.bufferCheckPosition=t.MAX_BUFFER_LENGTH,M.opt=x||{},M.opt.lowercase=M.opt.lowercase||M.opt.lowercasetags,M.looseCase=M.opt.lowercase?"toLowerCase":"toUpperCase",M.tags=[],M.closed=M.closedRoot=M.sawRoot=!1,M.tag=M.error=null,M.strict=!!S,M.noscript=!!(S||M.opt.noscript),M.state=k.BEGIN,M.strictEntities=M.opt.strictEntities,M.ENTITIES=M.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),M.attribList=[],M.opt.xmlns&&(M.ns=Object.create(m)),M.trackPosition=M.opt.position!==!1,M.trackPosition&&(M.position=M.line=M.column=0),N(M,"onready")}Object.create||(Object.create=function(S){function x(){}return x.prototype=S,new x}),Object.keys||(Object.keys=function(S){var x=[];for(var M in S)S.hasOwnProperty(M)&&x.push(M);return x});function r(S){for(var x=Math.max(t.MAX_BUFFER_LENGTH,10),M=0,C=0,be=e.length;C<be;C++){var Je=S[e[C]].length;if(Je>x)switch(e[C]){case"textNode":ue(S);break;case"cdata":L(S,"oncdata",S.cdata),S.cdata="";break;case"script":L(S,"onscript",S.script),S.script="";break;default:Et(S,"Max buffer length exceeded: "+e[C])}M=Math.max(M,Je)}S.bufferCheckPosition=t.MAX_BUFFER_LENGTH-M+S.position}function i(S){for(var x=0,M=e.length;x<M;x++)S[e[x]]=""}function s(S){ue(S),S.cdata!==""&&(L(S,"oncdata",S.cdata),S.cdata=""),S.script!==""&&(L(S,"onscript",S.script),S.script="")}n.prototype={end:function(){tr(this)},write:Aa,resume:function(){return this.error=null,this},close:function(){return this.write(null)},flush:function(){s(this)}};var a=ReadableStream;a||(a=function(){});var o=t.EVENTS.filter(function(S){return S!=="error"&&S!=="end"});function u(S,x){return new l(S,x)}function l(S,x){if(!(this instanceof l))return new l(S,x);a.apply(this),this._parser=new n(S,x),this.writable=!0,this.readable=!0;var M=this;this._parser.onend=function(){M.emit("end")},this._parser.onerror=function(C){M.emit("error",C),M._parser.error=null},this._decoder=null,o.forEach(function(C){Object.defineProperty(M,"on"+C,{get:function(){return M._parser["on"+C]},set:function(be){if(!be)return M.removeAllListeners(C),M._parser["on"+C]=be,be;M.on(C,be)},enumerable:!0,configurable:!1})})}l.prototype=Object.create(a.prototype,{constructor:{value:l}}),l.prototype.write=function(S){return this._parser.write(S.toString()),this.emit("data",S),!0},l.prototype.end=function(S){return S&&S.length&&this.write(S),this._parser.end(),!0},l.prototype.on=function(S,x){var M=this;return!M._parser["on"+S]&&o.indexOf(S)!==-1&&(M._parser["on"+S]=function(){var C=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);C.splice(0,0,S),M.emit.apply(M,C)}),a.prototype.on.call(M,S,x)};var c="[CDATA[",d="DOCTYPE",f="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",m={xml:f,xmlns:h},_=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,v=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,y=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,p=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function g(S){return S===" "||S===` `||S==="\r"||S===" "}function b(S){return S==='"'||S==="'"}function E(S){return S===">"||g(S)}function T(S,x){return S.test(x)}function I(S,x){return!T(S,x)}var k=0;t.STATE={BEGIN:k++,BEGIN_WHITESPACE:k++,TEXT:k++,TEXT_ENTITY:k++,OPEN_WAKA:k++,SGML_DECL:k++,SGML_DECL_QUOTED:k++,DOCTYPE:k++,DOCTYPE_QUOTED:k++,DOCTYPE_DTD:k++,DOCTYPE_DTD_QUOTED:k++,COMMENT_STARTING:k++,COMMENT:k++,COMMENT_ENDING:k++,COMMENT_ENDED:k++,CDATA:k++,CDATA_ENDING:k++,CDATA_ENDING_2:k++,PROC_INST:k++,PROC_INST_BODY:k++,PROC_INST_ENDING:k++,OPEN_TAG:k++,OPEN_TAG_SLASH:k++,ATTRIB:k++,ATTRIB_NAME:k++,ATTRIB_NAME_SAW_WHITE:k++,ATTRIB_VALUE:k++,ATTRIB_VALUE_QUOTED:k++,ATTRIB_VALUE_CLOSED:k++,ATTRIB_VALUE_UNQUOTED:k++,ATTRIB_VALUE_ENTITY_Q:k++,ATTRIB_VALUE_ENTITY_U:k++,CLOSE_TAG:k++,CLOSE_TAG_SAW_WHITE:k++,SCRIPT:k++,SCRIPT_ENDING:k++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(S){var x=t.ENTITIES[S],M=typeof x=="number"?String.fromCharCode(x):x;t.ENTITIES[S]=M});for(var j in t.STATE)t.STATE[t.STATE[j]]=j;k=t.STATE;function N(S,x,M){S[x]&&S[x](M)}function L(S,x,M){S.textNode&&ue(S),N(S,x,M)}function ue(S){S.textNode=Ee(S.opt,S.textNode),S.textNode&&N(S,"ontext",S.textNode),S.textNode=""}function Ee(S,x){return S.trim&&(x=x.trim()),S.normalize&&(x=x.replace(/\s+/g," ")),x}function Et(S,x){return ue(S),S.trackPosition&&(x+=` Line: `+S.line+` Column: `+S.column+` Char: `+S.c),x=new Error(x),S.error=x,N(S,"onerror",x),S}function tr(S){return S.sawRoot&&!S.closedRoot&&ye(S,"Unclosed root tag"),S.state!==k.BEGIN&&S.state!==k.BEGIN_WHITESPACE&&S.state!==k.TEXT&&Et(S,"Unexpected end"),ue(S),S.c="",S.closed=!0,N(S,"onend"),n.call(S,S.strict,S.opt),S}function ye(S,x){if(typeof S!="object"||!(S instanceof n))throw new Error("bad call to strictFail");S.strict&&Et(S,x)}function Sa(S){S.strict||(S.tagName=S.tagName[S.looseCase]());var x=S.tags[S.tags.length-1]||S,M=S.tag={name:S.tagName,attributes:{}};S.opt.xmlns&&(M.ns=x.ns),S.attribList.length=0,L(S,"onopentagstart",M)}function K(S,x){var M=S.indexOf(":")<0?["",S]:S.split(":"),C=M[0],be=M[1];return x&&S==="xmlns"&&(C="xmlns",be=""),{prefix:C,local:be}}function ie(S){if(S.strict||(S.attribName=S.attribName[S.looseCase]()),S.attribList.indexOf(S.attribName)!==-1||S.tag.attributes.hasOwnProperty(S.attribName)){S.attribName=S.attribValue="";return}if(S.opt.xmlns){var x=K(S.attribName,!0),M=x.prefix,C=x.local;if(M==="xmlns")if(C==="xml"&&S.attribValue!==f)ye(S,"xml: prefix must be bound to "+f+` Actual: `+S.attribValue);else if(C==="xmlns"&&S.attribValue!==h)ye(S,"xmlns: prefix must be bound to "+h+` Actual: `+S.attribValue);else{var be=S.tag,Je=S.tags[S.tags.length-1]||S;be.ns===Je.ns&&(be.ns=Object.create(Je.ns)),be.ns[C]=S.attribValue}S.attribList.push([S.attribName,S.attribValue])}else S.tag.attributes[S.attribName]=S.attribValue,L(S,"onattribute",{name:S.attribName,value:S.attribValue});S.attribName=S.attribValue=""}function re(S,x){if(S.opt.xmlns){var M=S.tag,C=K(S.tagName);M.prefix=C.prefix,M.local=C.local,M.uri=M.ns[C.prefix]||"",M.prefix&&!M.uri&&(ye(S,"Unbound namespace prefix: "+JSON.stringify(S.tagName)),M.uri=C.prefix);var be=S.tags[S.tags.length-1]||S;M.ns&&be.ns!==M.ns&&Object.keys(M.ns).forEach(function(Ty){L(S,"onopennamespace",{prefix:Ty,uri:M.ns[Ty]})});for(var Je=0,rn=S.attribList.length;Je<rn;Je++){var Tt=S.attribList[Je],$n=Tt[0],Ri=Tt[1],_t=K($n,!0),ji=_t.prefix,iI=_t.local,Ey=ji===""?"":M.ns[ji]||"",Fd={name:$n,value:Ri,prefix:ji,local:iI,uri:Ey};ji&&ji!=="xmlns"&&!Ey&&(ye(S,"Unbound namespace prefix: "+JSON.stringify(ji)),Fd.uri=ji),S.tag.attributes[$n]=Fd,L(S,"onattribute",Fd)}S.attribList.length=0}S.tag.isSelfClosing=!!x,S.sawRoot=!0,S.tags.push(S.tag),L(S,"onopentag",S.tag),x||(!S.noscript&&S.tagName.toLowerCase()==="script"?S.state=k.SCRIPT:S.state=k.TEXT,S.tag=null,S.tagName=""),S.attribName=S.attribValue="",S.attribList.length=0}function Pe(S){if(!S.tagName){ye(S,"Weird empty close tag."),S.textNode+="</>",S.state=k.TEXT;return}if(S.script){if(S.tagName!=="script"){S.script+="</"+S.tagName+">",S.tagName="",S.state=k.SCRIPT;return}L(S,"onscript",S.script),S.script=""}var x=S.tags.length,M=S.tagName;S.strict||(M=M[S.looseCase]());for(var C=M;x--&&S.tags[x].name!==C;)ye(S,"Unexpected close tag");if(x<0){ye(S,"Unmatched closing tag: "+S.tagName),S.textNode+="</"+S.tagName+">",S.state=k.TEXT;return}S.tagName=M;for(var be=S.tags.length;be-- >x;){var Je=S.tag=S.tags.pop();S.tagName=S.tag.name,L(S,"onclosetag",S.tagName);var rn={};for(var Tt in Je.ns)rn[Tt]=Je.ns[Tt];var $n=S.tags[S.tags.length-1]||S;S.opt.xmlns&&Je.ns!==$n.ns&&Object.keys(Je.ns).forEach(function(Ri){var _t=Je.ns[Ri];L(S,"onclosenamespace",{prefix:Ri,uri:_t})})}x===0&&(S.closedRoot=!0),S.tagName=S.attribValue=S.attribName="",S.attribList.length=0,S.state=k.TEXT}function qe(S){var x=S.entity,M=x.toLowerCase(),C,be="";return S.ENTITIES[x]?S.ENTITIES[x]:S.ENTITIES[M]?S.ENTITIES[M]:(x=M,x.charAt(0)==="#"&&(x.charAt(1)==="x"?(x=x.slice(2),C=parseInt(x,16),be=C.toString(16)):(x=x.slice(1),C=parseInt(x,10),be=C.toString(10))),x=x.replace(/^0+/,""),isNaN(C)||be.toLowerCase()!==x?(ye(S,"Invalid character entity"),"&"+S.entity+";"):String.fromCodePoint(C))}function $i(S,x){x==="<"?(S.state=k.OPEN_WAKA,S.startTagPosition=S.position):g(x)||(ye(S,"Non-whitespace before first tag."),S.textNode=x,S.state=k.TEXT)}function nr(S,x){var M="";return x<S.length&&(M=S.charAt(x)),M}function Aa(S){var x=this;if(this.error)throw this.error;if(x.closed)return Et(x,"Cannot write after close. Assign an onready handler.");if(S===null)return tr(x);typeof S=="object"&&(S=S.toString());for(var M=0,C="";C=nr(S,M++),x.c=C,!!C;)switch(x.trackPosition&&(x.position++,C===` `?(x.line++,x.column=0):x.column++),x.state){case k.BEGIN:if(x.state=k.BEGIN_WHITESPACE,C==="\uFEFF")continue;$i(x,C);continue;case k.BEGIN_WHITESPACE:$i(x,C);continue;case k.TEXT:if(x.sawRoot&&!x.closedRoot){for(var be=M-1;C&&C!=="<"&&C!=="&";)C=nr(S,M++),C&&x.trackPosition&&(x.position++,C===` `?(x.line++,x.column=0):x.column++);x.textNode+=S.substring(be,M-1)}C==="<"&&!(x.sawRoot&&x.closedRoot&&!x.strict)?(x.state=k.OPEN_WAKA,x.startTagPosition=x.position):(!g(C)&&(!x.sawRoot||x.closedRoot)&&ye(x,"Text data outside of root node."),C==="&"?x.state=k.TEXT_ENTITY:x.textNode+=C);continue;case k.SCRIPT:C==="<"?x.state=k.SCRIPT_ENDING:x.script+=C;continue;case k.SCRIPT_ENDING:C==="/"?x.state=k.CLOSE_TAG:(x.script+="<"+C,x.state=k.SCRIPT);continue;case k.OPEN_WAKA:if(C==="!")x.state=k.SGML_DECL,x.sgmlDecl="";else if(!g(C))if(T(_,C))x.state=k.OPEN_TAG,x.tagName=C;else if(C==="/")x.state=k.CLOSE_TAG,x.tagName="";else if(C==="?")x.state=k.PROC_INST,x.procInstName=x.procInstBody="";else{if(ye(x,"Unencoded <"),x.startTagPosition+1<x.position){var Je=x.position-x.startTagPosition;C=new Array(Je).join(" ")+C}x.textNode+="<"+C,x.state=k.TEXT}continue;case k.SGML_DECL:(x.sgmlDecl+C).toUpperCase()===c?(L(x,"onopencdata"),x.state=k.CDATA,x.sgmlDecl="",x.cdata=""):x.sgmlDecl+C==="--"?(x.state=k.COMMENT,x.comment="",x.sgmlDecl=""):(x.sgmlDecl+C).toUpperCase()===d?(x.state=k.DOCTYPE,(x.doctype||x.sawRoot)&&ye(x,"Inappropriately located doctype declaration"),x.doctype="",x.sgmlDecl=""):C===">"?(L(x,"onsgmldeclaration",x.sgmlDecl),x.sgmlDecl="",x.state=k.TEXT):(b(C)&&(x.state=k.SGML_DECL_QUOTED),x.sgmlDecl+=C);continue;case k.SGML_DECL_QUOTED:C===x.q&&(x.state=k.SGML_DECL,x.q=""),x.sgmlDecl+=C;continue;case k.DOCTYPE:C===">"?(x.state=k.TEXT,L(x,"ondoctype",x.doctype),x.doctype=!0):(x.doctype+=C,C==="["?x.state=k.DOCTYPE_DTD:b(C)&&(x.state=k.DOCTYPE_QUOTED,x.q=C));continue;case k.DOCTYPE_QUOTED:x.doctype+=C,C===x.q&&(x.q="",x.state=k.DOCTYPE);continue;case k.DOCTYPE_DTD:x.doctype+=C,C==="]"?x.state=k.DOCTYPE:b(C)&&(x.state=k.DOCTYPE_DTD_QUOTED,x.q=C);continue;case k.DOCTYPE_DTD_QUOTED:x.doctype+=C,C===x.q&&(x.state=k.DOCTYPE_DTD,x.q="");continue;case k.COMMENT:C==="-"?x.state=k.COMMENT_ENDING:x.comment+=C;continue;case k.COMMENT_ENDING:C==="-"?(x.state=k.COMMENT_ENDED,x.comment=Ee(x.opt,x.comment),x.comment&&L(x,"oncomment",x.comment),x.comment=""):(x.comment+="-"+C,x.state=k.COMMENT);continue;case k.COMMENT_ENDED:C!==">"?(ye(x,"Malformed comment"),x.comment+="--"+C,x.state=k.COMMENT):x.state=k.TEXT;continue;case k.CDATA:C==="]"?x.state=k.CDATA_ENDING:x.cdata+=C;continue;case k.CDATA_ENDING:C==="]"?x.state=k.CDATA_ENDING_2:(x.cdata+="]"+C,x.state=k.CDATA);continue;case k.CDATA_ENDING_2:C===">"?(x.cdata&&L(x,"oncdata",x.cdata),L(x,"onclosecdata"),x.cdata="",x.state=k.TEXT):C==="]"?x.cdata+="]":(x.cdata+="]]"+C,x.state=k.CDATA);continue;case k.PROC_INST:C==="?"?x.state=k.PROC_INST_ENDING:g(C)?x.state=k.PROC_INST_BODY:x.procInstName+=C;continue;case k.PROC_INST_BODY:if(!x.procInstBody&&g(C))continue;C==="?"?x.state=k.PROC_INST_ENDING:x.procInstBody+=C;continue;case k.PROC_INST_ENDING:C===">"?(L(x,"onprocessinginstruction",{name:x.procInstName,body:x.procInstBody}),x.procInstName=x.procInstBody="",x.state=k.TEXT):(x.procInstBody+="?"+C,x.state=k.PROC_INST_BODY);continue;case k.OPEN_TAG:T(v,C)?x.tagName+=C:(Sa(x),C===">"?re(x):C==="/"?x.state=k.OPEN_TAG_SLASH:(g(C)||ye(x,"Invalid character in tag name"),x.state=k.ATTRIB));continue;case k.OPEN_TAG_SLASH:C===">"?(re(x,!0),Pe(x)):(ye(x,"Forward-slash in opening tag not followed by >"),x.state=k.ATTRIB);continue;case k.ATTRIB:if(g(C))continue;C===">"?re(x):C==="/"?x.state=k.OPEN_TAG_SLASH:T(_,C)?(x.attribName=C,x.attribValue="",x.state=k.ATTRIB_NAME):ye(x,"Invalid attribute name");continue;case k.ATTRIB_NAME:C==="="?x.state=k.ATTRIB_VALUE:C===">"?(ye(x,"Attribute without value"),x.attribValue=x.attribName,ie(x),re(x)):g(C)?x.state=k.ATTRIB_NAME_SAW_WHITE:T(v,C)?x.attribName+=C:ye(x,"Invalid attribute name");continue;case k.ATTRIB_NAME_SAW_WHITE:if(C==="=")x.state=k.ATTRIB_VALUE;else{if(g(C))continue;ye(x,"Attribute without value"),x.tag.attributes[x.attribName]="",x.attribValue="",L(x,"onattribute",{name:x.attribName,value:""}),x.attribName="",C===">"?re(x):T(_,C)?(x.attribName=C,x.state=k.ATTRIB_NAME):(ye(x,"Invalid attribute name"),x.state=k.ATTRIB)}continue;case k.ATTRIB_VALUE:if(g(C))continue;b(C)?(x.q=C,x.state=k.ATTRIB_VALUE_QUOTED):(ye(x,"Unquoted attribute value"),x.state=k.ATTRIB_VALUE_UNQUOTED,x.attribValue=C);continue;case k.ATTRIB_VALUE_QUOTED:if(C!==x.q){C==="&"?x.state=k.ATTRIB_VALUE_ENTITY_Q:x.attribValue+=C;continue}ie(x),x.q="",x.state=k.ATTRIB_VALUE_CLOSED;continue;case k.ATTRIB_VALUE_CLOSED:g(C)?x.state=k.ATTRIB:C===">"?re(x):C==="/"?x.state=k.OPEN_TAG_SLASH:T(_,C)?(ye(x,"No whitespace between attributes"),x.attribName=C,x.attribValue="",x.state=k.ATTRIB_NAME):ye(x,"Invalid attribute name");continue;case k.ATTRIB_VALUE_UNQUOTED:if(!E(C)){C==="&"?x.state=k.ATTRIB_VALUE_ENTITY_U:x.attribValue+=C;continue}ie(x),C===">"?re(x):x.state=k.ATTRIB;continue;case k.CLOSE_TAG:if(x.tagName)C===">"?Pe(x):T(v,C)?x.tagName+=C:x.script?(x.script+="</"+x.tagName,x.tagName="",x.state=k.SCRIPT):(g(C)||ye(x,"Invalid tagname in closing tag"),x.state=k.CLOSE_TAG_SAW_WHITE);else{if(g(C))continue;I(_,C)?x.script?(x.script+="</"+C,x.state=k.SCRIPT):ye(x,"Invalid tagname in closing tag."):x.tagName=C}continue;case k.CLOSE_TAG_SAW_WHITE:if(g(C))continue;C===">"?Pe(x):ye(x,"Invalid characters in closing tag");continue;case k.TEXT_ENTITY:case k.ATTRIB_VALUE_ENTITY_Q:case k.ATTRIB_VALUE_ENTITY_U:var rn,Tt;switch(x.state){case k.TEXT_ENTITY:rn=k.TEXT,Tt="textNode";break;case k.ATTRIB_VALUE_ENTITY_Q:rn=k.ATTRIB_VALUE_QUOTED,Tt="attribValue";break;case k.ATTRIB_VALUE_ENTITY_U:rn=k.ATTRIB_VALUE_UNQUOTED,Tt="attribValue";break}if(C===";")if(x.opt.unparsedEntities){var $n=qe(x);x.entity="",x.state=rn,x.write($n)}else x[Tt]+=qe(x),x.entity="",x.state=rn;else T(x.entity.length?p:y,C)?x.entity+=C:(ye(x,"Invalid character in entity name"),x[Tt]+="&"+x.entity+C,x.entity="",x.state=rn);continue;default:throw new Error(x,"Unknown state: "+x.state)}return x.position>=x.bufferCheckPosition&&r(x),x}/*! http://mths.be/fromcodepoint v0.1.0 by @mathias */return String.fromCodePoint||function(){var S=String.fromCharCode,x=Math.floor,M=function(){var C=16384,be=[],Je,rn,Tt=-1,$n=arguments.length;if(!$n)return"";for(var Ri="";++Tt<$n;){var _t=Number(arguments[Tt]);if(!isFinite(_t)||_t<0||_t>1114111||x(_t)!==_t)throw RangeError("Invalid code point: "+_t);_t<=65535?be.push(_t):(_t-=65536,Je=(_t>>10)+55296,rn=_t%1024+56320,be.push(Je,rn)),(Tt+1===$n||be.length>C)&&(Ri+=S.apply(null,be),be.length=0)}return Ri};Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:M,configurable:!0,writable:!0}):String.fromCodePoint=M}(),t};pF();function vy(t,e){if(t.function===void 0)return;let n;if(e!=null&&e.partial)try{n=Mg(t.function.arguments??"{}")}catch{return}else try{n=JSON.parse(t.function.arguments)}catch(i){throw new Yo([`Function "${t.function.name}" arguments:`,"",t.function.arguments,"","are not valid JSON.",`Error: ${i.message}`].join(` `))}const r={name:t.function.name,args:n,type:"tool_call"};return e!=null&&e.returnId&&(r.id=t.id),r}function XT(t){if(t.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:t.id,type:"function",function:{name:t.name,arguments:JSON.stringify(t.args)}}}function zl(t,e){var n,r;return{name:(n=t.function)==null?void 0:n.name,args:(r=t.function)==null?void 0:r.arguments,id:t.id,error:e,type:"invalid_tool_call"}}var mF=class extends GT{constructor(e){super(e);A(this,"returnId",!1);A(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);A(this,"lc_serializable",!0);this.returnId=(e==null?void 0:e.returnId)??this.returnId}static lc_name(){return"JsonOutputToolsParser"}_diff(){throw new Error("Not supported.")}async parse(){throw new Error("Not implemented.")}async parseResult(e){return await this.parsePartialResult(e,!1)}async parsePartialResult(e,n=!0){var a;const r=e[0].message;let i;if(Dg(r)&&((a=r.tool_calls)!=null&&a.length)?i=r.tool_calls.map(o=>{const{id:u,...l}=o;return this.returnId?{id:u,...l}:l}):r.additional_kwargs.tool_calls!==void 0&&(i=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(o=>vy(o,{returnId:this.returnId,partial:n}))),!i)return[];const s=[];for(const o of i)if(o!==void 0){const u={type:o.name,args:o.args,id:o.id};s.push(u)}return s}},gF=class extends mF{constructor(e){super(e);A(this,"lc_namespace",["langchain","output_parsers","openai_tools"]);A(this,"lc_serializable",!0);A(this,"returnId",!1);A(this,"keyName");A(this,"returnSingle",!1);A(this,"zodSchema");A(this,"serializableSchema");this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,"zodSchema"in e&&(this.zodSchema=e.zodSchema),"serializableSchema"in e&&(this.serializableSchema=e.serializableSchema)}static lc_name(){return"JsonOutputKeyToolsParser"}async _validateResult(e){var r;if(this.serializableSchema!==void 0){const i=await this.serializableSchema["~standard"].validate(e);if(i.issues)throw new Yo(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(i.issues)}`,JSON.stringify(e,null,2));return i.value}if(this.zodSchema===void 0)return e;const n=await b6(this.zodSchema,e);if(n.success)return n.data;throw new Yo(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify((r=n.error)==null?void 0:r.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const n=(await super.parsePartialResult(e)).filter(i=>i.type===this.keyName);let r=n;if(n.length)return this.returnId||(r=n.map(i=>i.args)),this.returnSingle?r[0]:r}async parseResult(e){const n=(await super.parsePartialResult(e,!1)).filter(i=>i.type===this.keyName);let r=n;if(n.length)return this.returnId||(r=n.map(i=>i.args)),this.returnSingle?this._validateResult(r[0]):await Promise.all(r.map(i=>this._validateResult(i)))}};function zw(t){return gr(t)?hF.fromZodSchema(t):ma(t)?fF.fromSerializableSchema(t):new JT}function yF(t,e,n){const r=gF;return gr(t)?new r({returnSingle:!0,keyName:e,zodSchema:t}):ma(t)?new r({returnSingle:!0,keyName:e,serializableSchema:t}):new r({returnSingle:!0,keyName:e})}function QT(t,e,n,r){if(!n){const u=t.pipe(e);return r?u.withConfig({runName:r}):u}const i=Mw.assign({parsed:(u,l)=>e.invoke(u.raw,l)}),s=Mw.assign({parsed:()=>null}),a=i.withFallbacks({fallbacks:[s]}),o=py.from([{raw:t},a]);return r?o.withConfig({runName:r}):o}var _F=class{constructor(){A(this,"events",[]);A(this,"finished",!1);A(this,"waiters",[]);A(this,"error",null)}push(t){this.events.push(t);const e=this.waiters.splice(0);for(const n of e)n()}finish(){this.finished=!0;const t=this.waiters.splice(0);for(const e of t)e()}setError(t){this.error=t,this.finished=!0;const e=this.waiters.splice(0);for(const n of e)n()}async*iterate(){if(this.finished){if(this.error)throw this.error;yield*this.events;return}let t=0;for(;;){for(;t<this.events.length;)yield this.events[t],t++;if(this.finished){if(this.error)throw this.error;return}await new Promise(e=>{if(t<this.events.length||this.finished){e();return}this.waiters.push(e)})}}};function vF(t,e){switch(e.type){case"text-delta":return t.type==="text"?{...t,text:(t.text??"")+e.text}:t;case"reasoning-delta":return t.type==="thinking"?{...t,thinking:(t.thinking??"")+e.reasoning}:t.type==="reasoning"?{...t,reasoning:(t.reasoning??"")+e.reasoning}:t;case"data-delta":return{...t,data:(t.data??"")+e.data};case"block-delta":return{...t,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function eu(t){if(t.event!=="content-block-delta")return;if("delta"in t&&t.delta)return t.delta;const e=t.content;if(e==null||typeof e!="object")return;const n=e;if(n.type==="text"&&typeof n.text=="string")return{type:"text-delta",text:n.text};if(n.type==="reasoning"&&typeof n.reasoning=="string")return{type:"reasoning-delta",reasoning:n.reasoning};if(n.type==="thinking"&&typeof n.thinking=="string")return{type:"reasoning-delta",reasoning:n.thinking};if(typeof n.data=="string")return{type:"data-delta",data:n.data,encoding:"base64"};if(typeof n.type=="string")return{type:"block-delta",fields:{...n,type:n.type}}}function Dw(t){if(t==null||typeof t!="object")return;const e=t;if(e.type==="reasoning"&&typeof e.reasoning=="string")return e.reasoning;if(e.type==="thinking"&&typeof e.thinking=="string")return e.thinking}function sl(t){if(t==null||typeof t!="object")return!1;const e=t.type;return e==="reasoning"||e==="thinking"}function Xs(t){if(t)return{...t,input_tokens:t.input_tokens??0,output_tokens:t.output_tokens??0,total_tokens:t.total_tokens??0}}function wF(t){if(t!=null&&typeof t=="object"&&!Array.isArray(t))return t;if(typeof t!="string"||t.length===0)return{};try{const e=JSON.parse(t);return e!=null&&typeof e=="object"&&!Array.isArray(e)?e:{}}catch{return{}}}function bF(t){const e=t;if(t.type==="tool_call"||t.type!=="tool_call_chunk"&&t.type!=="tool_use"&&t.type!=="input_json_delta")return t;const n=typeof e.name=="string"?e.name:void 0;if(n==null)return t;const r=e.args??e.input;return{...e,type:"tool_call",name:n,args:wF(r)}}var xF=class{constructor(t){A(this,"_buffer");this._buffer=t}get full(){const t=this._buffer;return{async*[Symbol.asyncIterator](){let e="";for await(const n of t.iterate()){const r=eu(n);(r==null?void 0:r.type)==="text-delta"&&(e+=r.text,yield e)}}}}[Symbol.asyncIterator](){const t=this._buffer;async function*e(){for await(const n of t.iterate()){const r=eu(n);(r==null?void 0:r.type)==="text-delta"&&(yield r.text)}}return e()}then(t,e){return(async()=>{let n="";for await(const r of this)n+=r;return n})().then(t,e)}},kF=class{constructor(t){A(this,"_buffer");this._buffer=t}get full(){const t=this._buffer;return{async*[Symbol.asyncIterator](){const e=[];for await(const n of t.iterate())n.event==="content-block-finish"&&n.content.type==="tool_call"&&(e.push(n.content),yield[...e])}}}[Symbol.asyncIterator](){const t=this._buffer;async function*e(){for await(const n of t.iterate())n.event==="content-block-finish"&&n.content.type==="tool_call"&&(yield n.content)}return e()}then(t,e){return(async()=>{const n=[];for await(const r of this)n.push(r);return n})().then(t,e)}},SF=class{constructor(t){A(this,"_buffer");this._buffer=t}get full(){const t=this._buffer;return{async*[Symbol.asyncIterator](){let e="",n=!1;for await(const r of t.iterate())if(r.event==="content-block-start"){if(!sl(r.content)){if(n)return;continue}n=!0;const i=Dw(r.content);if(i==null||i.length===0)continue;e+=i,yield e}else if(r.event==="content-block-delta"){const i=eu(r);if((i==null?void 0:i.type)!=="reasoning-delta")continue;n=!0;const s=i.reasoning;if(s==null||s.length===0)continue;e+=s,yield e}else{if(r.event==="content-block-finish"&&sl(r.content))return;if(r.event==="message-finish")return}}}}[Symbol.asyncIterator](){const t=this._buffer;async function*e(){let n=!1;for await(const r of t.iterate())if(r.event==="content-block-start"){if(!sl(r.content)){if(n)return;continue}n=!0;const i=Dw(r.content);i!=null&&i.length>0&&(yield i)}else if(r.event==="content-block-delta"){const i=eu(r);if((i==null?void 0:i.type)!=="reasoning-delta")continue;n=!0;const s=i.reasoning;s!=null&&s.length>0&&(yield s)}else{if(r.event==="content-block-finish"&&sl(r.content))return;if(r.event==="message-finish")return}}return e()}then(t,e){return(async()=>{let n="";for await(const r of this)n+=r;return n})().then(t,e)}},AF=class{constructor(t){A(this,"_buffer");this._buffer=t}[Symbol.asyncIterator](){const t=this._buffer;async function*e(){for await(const n of t.iterate())if(n.event==="usage"){const r=Xs(n.usage);r&&(yield r)}else if(n.event==="message-start"&&n.usage){const r=Xs(n.usage);r&&(yield r)}else if(n.event==="message-finish"&&n.usage){const r=Xs(n.usage);r&&(yield r)}}return e()}then(t,e){return(async()=>{let n;for await(const r of this)n=r;return n})().then(t,e)}},Uw=class{constructor(t){A(this,"_buffer");this._buffer=new _F,this._consume(t)}async _consume(t){try{for await(const e of t)this._buffer.push(e);this._buffer.finish()}catch(e){this._buffer.setError(e instanceof Error?e:new Error(String(e)))}}[Symbol.asyncIterator](){return this._buffer.iterate()}get text(){return new xF(this._buffer)}get toolCalls(){return new kF(this._buffer)}get reasoning(){return new SF(this._buffer)}get usage(){return new AF(this._buffer)}get output(){return this._assembleMessage()}then(t,e){return this._assembleMessage().then(t,e)}async _assembleMessage(){const t=[];let e,n,r={},i;for await(const a of this._buffer.iterate())switch(a.event){case"message-start":e=a.id??e,a.usage&&(n=Xs(a.usage));break;case"content-block-start":t[a.index]=a.content;break;case"content-block-delta":{const o=t[a.index],u=eu(a);o&&u&&(t[a.index]=vF(o,u));break}case"content-block-finish":t[a.index]=a.content;break;case"usage":n=Xs(a.usage);break;case"message-finish":i=a.reason,a.usage&&(n=Xs(a.usage)),a.responseMetadata&&(r={...r,...a.responseMetadata});break}const s=t.filter(a=>a!=null).map(bF);return new Cn({id:e,content:s,usage_metadata:n,response_metadata:{...r,...i?{finish_reason:i}:{},output_version:"v1"}})}};const EF={wav:"audio/wav",mp3:"audio/mpeg",flac:"audio/flac",opus:"audio/opus",aac:"audio/aac",pcm16:"audio/pcm"},TF={png:"image/png",jpeg:"image/jpeg",jpg:"image/jpeg",webp:"image/webp",gif:"image/gif"};function Fw(t){let e=0;for(const n of t.keys())n>=e&&(e=n+1);return e}function YT(t){const e=t.additional_kwargs;return e!=null&&typeof e=="object"?e:{}}function IF(t){const e=YT(t).tool_outputs;if(!Array.isArray(e))return[];const n=[];for(const r of e){if(r==null||typeof r!="object")continue;const i=r;if(i.type!=="image_generation_call")continue;const s=typeof i.result=="string"?i.result:void 0,a=typeof i.url=="string"?i.url:void 0;if(s==null&&a==null)continue;const o=typeof i.output_format=="string"?i.output_format.toLowerCase():void 0,u=(o!=null?TF[o]:void 0)??"image/png";n.push({type:"image",...typeof i.id=="string"?{id:i.id}:{},...a!=null?{url:a}:{},...s!=null?{data:s}:{},mimeType:u})}return n}function OF(t){const e=YT(t).audio;if(e==null||typeof e!="object")return;const n=e,r=typeof n.data=="string"?n.data:void 0,i=typeof n.url=="string"?n.url:void 0,s=typeof n.transcript=="string"?n.transcript:void 0;if(r==null&&i==null&&s==null)return;const a=typeof n.mime_type=="string"?n.mime_type:typeof n.mimeType=="string"?n.mimeType:void 0,o=typeof n.format=="string"?n.format.toLowerCase():void 0,u=a??(o!=null?EF[o]:void 0)??(r!=null?"audio/wav":"audio/pcm");return{...typeof n.id=="string"?{id:n.id}:{},...r!=null?{data:r}:{},...i!=null?{url:i}:{},...s!=null?{transcript:s}:{},mimeType:u}}async function*CF(t,e){var o;const n=new Map;let r=!1,i,s;const a=new Set;for await(const u of t){(o=e==null?void 0:e.signal)==null||o.throwIfAborted();const l=u.message;let c=!1;if(!r){r=!0;const h={event:"message-start",id:l.id??void 0};vr.isInstance(l)&&l.usage_metadata&&(h.usage=l.usage_metadata,i={...l.usage_metadata},c=!0),yield h}const d=l.content;if(typeof d=="string"){if(d!==""){if(!n.has(0)){const _={type:"text",text:""};n.set(0,{type:"text",accumulated:_}),yield{event:"content-block-start",index:0,content:_}}const m=n.get(0);m.accumulated={...m.accumulated,text:(m.accumulated.text??"")+d},yield{event:"content-block-delta",index:0,delta:{type:"text-delta",text:d}}}}else if(Array.isArray(d))for(const h of d){const m=typeof h.index=="number"?h.index:n.size;if(!n.has(m))n.set(m,{type:h.type,accumulated:{...h}}),yield{event:"content-block-start",index:m,content:{...h}};else{const _=n.get(m),v=NF(h);_.accumulated=PF(_.accumulated,v),yield{event:"content-block-delta",index:m,delta:v}}}if(vr.isInstance(l)&&l.tool_call_chunks&&l.tool_call_chunks.length>0)for(const h of l.tool_call_chunks){const m=typeof h.index=="number"?h.index:n.size;if(!n.has(m)){const v={type:"tool_call_chunk",id:h.id,name:h.name,args:"",index:m};n.set(m,{type:"tool_call_chunk",accumulated:v}),yield{event:"content-block-start",index:m,content:v}}const _=n.get(m).accumulated;h.id!=null&&(_.id=h.id),h.name!=null&&(_.name=h.name),_.args=(_.args??"")+(h.args??""),yield{event:"content-block-delta",index:m,delta:{type:"block-delta",fields:{type:"tool_call_chunk",..."id"in _&&_.id!=null?{id:_.id}:{},..."name"in _&&_.name!=null?{name:_.name}:{},args:_.args}}}}const f=OF(l);if(f!=null){if(s==null){const m=Fw(n);s={index:m,id:f.id,mimeType:f.mimeType,transcript:""};const _={type:"audio",...f.id!=null?{id:f.id}:{},...f.url!=null?{url:f.url}:{},data:"",mimeType:f.mimeType};n.set(m,{type:"audio",accumulated:_}),yield{event:"content-block-start",index:m,content:_}}const h=n.get(s.index);if(h!=null){const m=h.accumulated;f.id!=null&&s.id==null&&(s.id=f.id,m.id=f.id),f.transcript!=null&&(s.transcript+=f.transcript,m.transcript=s.transcript,yield{event:"content-block-delta",index:s.index,delta:{type:"block-delta",fields:{type:"audio",transcript:s.transcript}}}),f.data!=null&&f.data.length>0&&(m.data=(m.data??"")+f.data,yield{event:"content-block-delta",index:s.index,delta:{type:"data-delta",data:f.data,encoding:"base64"}})}}for(const h of IF(l)){const m=h,_=m.id??m.url??(m.data!=null?`${m.data.length}:${m.data.slice(0,32)}`:void 0);if(_!=null&&a.has(_))continue;_!=null&&a.add(_);const v=Fw(n);n.set(v,{type:"image",accumulated:h}),yield{event:"content-block-start",index:v,content:h}}if(!c&&vr.isInstance(l)&&l.usage_metadata){const h=l.usage_metadata;i?i={input_tokens:i.input_tokens+h.input_tokens,output_tokens:i.output_tokens+h.output_tokens,total_tokens:i.total_tokens+h.total_tokens}:i={...h},yield{event:"usage",usage:{...i}}}}for(const[u,l]of n)yield{event:"content-block-finish",index:u,content:wy(l.accumulated)};yield{event:"message-finish",reason:"stop",...i?{usage:i}:{}}}function PF(t,e){switch(e.type){case"text-delta":return t.type==="text"?{...t,text:(t.text??"")+e.text}:t;case"reasoning-delta":return t.type==="thinking"?{...t,thinking:(t.thinking??"")+e.reasoning}:t.type==="reasoning"?{...t,reasoning:(t.reasoning??"")+e.reasoning}:t;case"data-delta":return{...t,data:(t.data??"")+e.data};case"block-delta":return{...t,...e.fields};default:throw new Error(`Unknown delta type: ${JSON.stringify(e)}`)}}function NF(t){if(t.type==="text")return{type:"text-delta",text:t.text};if(t.type==="reasoning")return{type:"reasoning-delta",reasoning:t.reasoning};if(t.type==="thinking"&&typeof t.thinking=="string")return{type:"reasoning-delta",reasoning:t.thinking};if(typeof t.data=="string")return{type:"data-delta",data:t.data,encoding:"base64"};if(typeof t.type=="string")return{type:"block-delta",fields:{...t}};throw new Error(`Unsupported content block delta: ${JSON.stringify(t)}`)}function wy(t){if(t.type==="tool_call_chunk"){const e=t;let n;try{n=JSON.parse(e.args??"{}")}catch{return{type:"invalid_tool_call",id:e.id,name:e.name,args:e.args,error:"Failed to parse tool call arguments as JSON"}}return{type:"tool_call",id:e.id,name:e.name,args:n}}return t}function nh(t){const e=[];for(const n of t){let r=n;if(Array.isArray(n.content))for(let i=0;i<n.content.length;i++){const s=n.content[i];(gS(s)||yS(s))&&r===n&&(r=new n.constructor({...r,content:[...n.content.slice(0,i),CN(s),...n.content.slice(i+1)]}))}e.push(r)}return e}var $F=class or extends uF{constructor(n){super(n);A(this,"lc_namespace",["langchain","chat_models",this._llmType()]);A(this,"disableStreaming",!1);A(this,"outputVersion");this.outputVersion=lF(()=>{const r=n.outputVersion??Jn("LC_OUTPUT_VERSION");return r&&["v0","v1"].includes(r)?r:"v0"})}get callKeys(){return[...super.callKeys,"outputVersion"]}_separateRunnableConfigFromCallOptionsCompat(n){const[r,i]=super._separateRunnableConfigFromCallOptions(n);return i.signal=r.signal,[r,i]}async invoke(n,r){const i=or._convertInputToPromptValue(n);return(await this.generatePrompt([i],r,r==null?void 0:r.callbacks)).generations[0][0].message}async*_streamResponseChunks(n,r,i){throw new Error("Not implemented.")}async*_streamChatModelEvents(n,r,i){yield*CF(this._streamResponseChunks(n,r,i),{signal:r.signal})}streamEvents(n,r,i){if((r==null?void 0:r.version)==="v1"||(r==null?void 0:r.version)==="v2")return super.streamEvents(n,r,i);const s=or._convertInputToPromptValue(n).toChatMessages(),[,a]=this._separateRunnableConfigFromCallOptionsCompat(r);return new Uw(this._streamChatModelEvents(s,a))}streamV2(n,r){return this.streamEvents(n,r)}async*_streamIterator(n,r){var i,s,a;if(this._streamResponseChunks===or.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(n,r);else{const o=or._convertInputToPromptValue(n).toChatMessages(),[u,l]=this._separateRunnableConfigFromCallOptionsCompat(r),c={...u.metadata,...this.getLsParamsWithDefaults(l)},d=this.invocationParams(l),f=await Rr.configure(u.callbacks,this.callbacks,u.tags,this.tags,c,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(d)}),h={options:l,invocation_params:d,batch_size:1},m=l.outputVersion??this.outputVersion,_=await(f==null?void 0:f.handleChatModelStart(this.toJSON(),[nh(o)],u.runId,void 0,h,void 0,void 0,u.runName));let v,y;try{for await(const p of this._streamResponseChunks(o,l,_==null?void 0:_[0])){if((i=l.signal)==null||i.throwIfAborted(),p.message.id==null){const g=(s=_==null?void 0:_.at(0))==null?void 0:s.runId;g!=null&&p.message._updateId(`run-${g}`)}p.message.response_metadata={...p.generationInfo,...p.message.response_metadata},m==="v1"?yield il(p.message):yield p.message,v?v=v.concat(p):v=p,Nv(p.message)&&p.message.usage_metadata!==void 0&&(y={tokenUsage:{promptTokens:p.message.usage_metadata.input_tokens,completionTokens:p.message.usage_metadata.output_tokens,totalTokens:p.message.usage_metadata.total_tokens}})}(a=l.signal)==null||a.throwIfAborted()}catch(p){throw await Promise.all((_??[]).map(g=>g==null?void 0:g.handleLLMError(p))),p}await Promise.all((_??[]).map(p=>p==null?void 0:p.handleLLMEnd({generations:[[v]],llmOutput:y})))}}getLsParams(n){const r=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:n.stop,ls_provider:r}}getLsParamsWithDefaults(n){return{...this.getLsParams(n),ls_integration:"langchain_chat_model"}}async _generateUncached(n,r,i,s){var m,_,v,y,p,g;const a=n.map(b=>b.map(Cl));let o;if(s!==void 0&&s.length===a.length)o=s;else{const b={...i.metadata,...this.getLsParamsWithDefaults(r)},E=this.invocationParams(r),T=await Rr.configure(i.callbacks,this.callbacks,i.tags,this.tags,b,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(E)}),I={options:r,invocation_params:E,batch_size:1};o=await(T==null?void 0:T.handleChatModelStart(this.toJSON(),a.map(nh),i.runId,void 0,I,void 0,void 0,i.runName))}const u=r.outputVersion??this.outputVersion,l=[],c=[],d=!!(o!=null&&o[0].handlers.find(r$)),f=!!(o!=null&&o[0].handlers.find(n$));if(d&&!this.disableStreaming&&a.length===1&&(this._streamChatModelEvents!==or.prototype._streamChatModelEvents||this._streamResponseChunks!==or.prototype._streamResponseChunks))try{let b=!1;const E=o==null?void 0:o[0],T=this._streamChatModelEvents(a[0],r),I=await new Uw({async*[Symbol.asyncIterator](){var N;for await(const L of T){(N=r.signal)==null||N.throwIfAborted(),b=!0;const ue=L.event==="message-start"&&L.id==null&&(E==null?void 0:E.runId)!=null?{...L,id:`run-${E.runId}`}:L;await(E==null?void 0:E.handleChatModelStreamEvent(ue)),yield ue}}});if((m=r.signal)==null||m.throwIfAborted(),!b)throw new Error("Received empty response from chat model call.");if(I.id==null){const N=(_=o==null?void 0:o.at(0))==null?void 0:_.runId;N!=null&&I._updateId(`run-${N}`)}const k={text:I.text,message:I};l.push([k]);const j=I.usage_metadata!==void 0?{tokenUsage:{promptTokens:I.usage_metadata.input_tokens,completionTokens:I.usage_metadata.output_tokens,totalTokens:I.usage_metadata.total_tokens}}:void 0;await(o==null?void 0:o[0].handleLLMEnd({generations:l,llmOutput:j}))}catch(b){throw await(o==null?void 0:o[0].handleLLMError(b)),b}else if(f&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==or.prototype._streamResponseChunks)try{const b=await this._streamResponseChunks(a[0],r,o==null?void 0:o[0]);let E,T;for await(const I of b){if((v=r.signal)!=null&&v.aborted){const k=E==null?void 0:E.message;throw new pv("Model invocation was aborted.",k)}if(I.message.id==null){const k=(y=o==null?void 0:o.at(0))==null?void 0:y.runId;k!=null&&I.message._updateId(`run-${k}`)}E===void 0?E=I:E=Od(E,I),Nv(I.message)&&I.message.usage_metadata!==void 0&&(T={tokenUsage:{promptTokens:I.message.usage_metadata.input_tokens,completionTokens:I.message.usage_metadata.output_tokens,totalTokens:I.message.usage_metadata.total_tokens}})}if((p=r.signal)!=null&&p.aborted){const I=E==null?void 0:E.message;throw new pv("Model invocation was aborted.",I)}if(E===void 0)throw new Error("Received empty response from chat model call.");u==="v1"&&(E.message=il(E.message)),l.push([E]),await(o==null?void 0:o[0].handleLLMEnd({generations:l,llmOutput:T}))}catch(b){throw await(o==null?void 0:o[0].handleLLMError(b)),b}else{const b=await Promise.allSettled(a.map(async(E,T)=>{const I=await this._generate(E,{...r,promptIndex:T},o==null?void 0:o[T]);if(u==="v1")for(const k of I.generations)k.message=il(k.message);return I}));await Promise.all(b.map(async(E,T)=>{var I,k,j;if(E.status==="fulfilled"){const N=E.value;for(const L of N.generations){if(L.message.id==null){const ue=(I=o==null?void 0:o.at(0))==null?void 0:I.runId;ue!=null&&L.message._updateId(`run-${ue}`)}L.message.response_metadata={...L.generationInfo,...L.message.response_metadata}}return N.generations.length===1&&(N.generations[0].message.response_metadata={...N.llmOutput,...N.generations[0].message.response_metadata}),l[T]=N.generations,c[T]=N.llmOutput,(k=o==null?void 0:o[T])==null?void 0:k.handleLLMEnd({generations:[N.generations],llmOutput:N.llmOutput})}else return await((j=o==null?void 0:o[T])==null?void 0:j.handleLLMError(E.reason)),Promise.reject(E.reason)}))}const h={generations:l,llmOutput:c.length?(g=this._combineLLMOutput)==null?void 0:g.call(this,...c):void 0};return Object.defineProperty(h,N0,{value:o?{runIds:o==null?void 0:o.map(b=>b.runId)}:void 0,configurable:!0}),h}async _generateCached({messages:n,cache:r,llmStringKey:i,parsedOptions:s,handledOptions:a}){const o=n.map(p=>p.map(Cl)),u={...a.metadata,...this.getLsParamsWithDefaults(s)},l=this.invocationParams(s),c=await Rr.configure(a.callbacks,this.callbacks,a.tags,this.tags,u,this.metadata,{verbose:this.verbose,tracerInheritableMetadata:this._filterInvocationParamsForTracing(l)}),d={options:s,invocation_params:l,batch_size:1},f=await(c==null?void 0:c.handleChatModelStart(this.toJSON(),o.map(nh),a.runId,void 0,d,void 0,void 0,a.runName)),h=[],m=(await Promise.allSettled(o.map(async(p,g)=>{const b=or._convertInputToPromptValue(p).toString(),E=await r.lookup(b,i);return E==null&&h.push(g),E}))).map((p,g)=>({result:p,runManager:f==null?void 0:f[g]})).filter(({result:p})=>p.status==="fulfilled"&&p.value!=null||p.status==="rejected"),_=s.outputVersion??this.outputVersion,v=[];await Promise.all(m.map(async({result:p,runManager:g},b)=>{if(p.status==="fulfilled"){const E=p.value;return v[b]=E.map(T=>("message"in T&&Rg(T.message)&&Dg(T.message)&&(T.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0},_==="v1"&&(T.message=il(T.message))),T.generationInfo={...T.generationInfo,tokenUsage:{}},T)),E.length&&await(g==null?void 0:g.handleLLMNewToken(E[0].text)),g==null?void 0:g.handleLLMEnd({generations:[E]},void 0,void 0,void 0,{cached:!0})}else return await(g==null?void 0:g.handleLLMError(p.reason,void 0,void 0,void 0,{cached:!0})),Promise.reject(p.reason)}));const y={generations:v,missingPromptIndices:h,startedRunManagers:f};return Object.defineProperty(y,N0,{value:f?{runIds:f==null?void 0:f.map(p=>p.runId)}:void 0,configurable:!0}),y}async generate(n,r,i){let s;Array.isArray(r)?s={stop:r}:s=r;const a=n.map(_=>_.map(Cl)),[o,u]=this._separateRunnableConfigFromCallOptionsCompat(s);if(o.callbacks=o.callbacks??i,!this.cache)return this._generateUncached(a,u,o);const{cache:l}=this,c=this._getSerializedCacheKeyParametersForCall(u),{generations:d,missingPromptIndices:f,startedRunManagers:h}=await this._generateCached({messages:a,cache:l,llmStringKey:c,parsedOptions:u,handledOptions:o});let m={};if(f.length>0){const _=await this._generateUncached(f.map(v=>a[v]),u,o,h!==void 0?f.map(v=>h==null?void 0:h[v]):void 0);await Promise.all(_.generations.map(async(v,y)=>{const p=f[y];d[p]=v;const g=or._convertInputToPromptValue(a[p]).toString();return l.update(g,c,v)})),m=_.llmOutput??{}}return{generations:d,llmOutput:m}}invocationParams(n){return{}}_modelType(){return"base_chat_model"}async generatePrompt(n,r,i){const s=n.map(a=>a.toChatMessages());return this.generate(s,r,i)}withStructuredOutput(n,r){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(r!=null&&r.strict)throw new Error('"strict" mode is not supported for this model by default.');const i=n,s=r==null?void 0:r.name,a=dy(i)??"A function available to call.",o=r==null?void 0:r.method,u=r==null?void 0:r.includeRaw;if(o==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let l=s??"extract";!gr(i)&&!ma(i)&&"name"in i&&(l=i.name);const c=gr(i)||ma(i)?vi(i):i,d=[{type:"function",function:{name:l,description:a,parameters:c}}];return QT(this.bindTools(d),zd.from(f=>{if(!vr.isInstance(f))throw new Error("Input is not an AIMessageChunk.");if(!f.tool_calls||f.tool_calls.length===0)throw new Error("No tool calls found in the response.");const h=f.tool_calls.find(m=>m.name===l);if(!h)throw new Error(`No tool call found with name ${l}.`);return h.args}),u,u?"StructuredOutputRunnable":"StructuredOutput")}};function by(t,e){return typeof t=="string"?{model:t,...e??{}}:t??e}var xy=class extends $F{constructor(e){var r,i,s,a;super(e??{});A(this,"temperature");A(this,"topP");A(this,"frequencyPenalty");A(this,"presencePenalty");A(this,"n");A(this,"logitBias");A(this,"model","gpt-3.5-turbo");A(this,"modelKwargs");A(this,"stop");A(this,"stopSequences");A(this,"user");A(this,"timeout");A(this,"streaming",!1);A(this,"streamUsage",!0);A(this,"maxTokens");A(this,"logprobs");A(this,"topLogprobs");A(this,"apiKey");A(this,"organization");A(this,"__includeRawResponse");A(this,"client");A(this,"clientConfig");A(this,"supportsStrictToolCalling");A(this,"audio");A(this,"modalities");A(this,"reasoning");A(this,"zdrEnabled");A(this,"service_tier");A(this,"promptCacheKey");A(this,"promptCacheRetention");A(this,"verbosity");A(this,"defaultOptions");A(this,"lc_serializable",!0);const n=typeof((r=e==null?void 0:e.configuration)==null?void 0:r.apiKey)=="string"||typeof((i=e==null?void 0:e.configuration)==null?void 0:i.apiKey)=="function"?(s=e==null?void 0:e.configuration)==null?void 0:s.apiKey:void 0;this.apiKey=(e==null?void 0:e.apiKey)??n??Jn("OPENAI_API_KEY"),this.organization=((a=e==null?void 0:e.configuration)==null?void 0:a.organization)??Jn("OPENAI_ORGANIZATION"),this.model=(e==null?void 0:e.model)??(e==null?void 0:e.modelName)??this.model,this.modelKwargs=(e==null?void 0:e.modelKwargs)??{},this.timeout=e==null?void 0:e.timeout,this.temperature=(e==null?void 0:e.temperature)??this.temperature,this.topP=(e==null?void 0:e.topP)??this.topP,this.frequencyPenalty=(e==null?void 0:e.frequencyPenalty)??this.frequencyPenalty,this.presencePenalty=(e==null?void 0:e.presencePenalty)??this.presencePenalty,this.logprobs=e==null?void 0:e.logprobs,this.topLogprobs=e==null?void 0:e.topLogprobs,this.n=(e==null?void 0:e.n)??this.n,this.logitBias=e==null?void 0:e.logitBias,this.stop=(e==null?void 0:e.stopSequences)??(e==null?void 0:e.stop),this.stopSequences=this.stop,this.user=e==null?void 0:e.user,this.__includeRawResponse=e==null?void 0:e.__includeRawResponse,this.audio=e==null?void 0:e.audio,this.modalities=e==null?void 0:e.modalities,this.reasoning=e==null?void 0:e.reasoning,this.maxTokens=(e==null?void 0:e.maxCompletionTokens)??(e==null?void 0:e.maxTokens),this.promptCacheKey=(e==null?void 0:e.promptCacheKey)??this.promptCacheKey,this.promptCacheRetention=(e==null?void 0:e.promptCacheRetention)??this.promptCacheRetention,this.verbosity=(e==null?void 0:e.verbosity)??this.verbosity,this.disableStreaming=(e==null?void 0:e.disableStreaming)===!0,this.streaming=(e==null?void 0:e.streaming)===!0,this.disableStreaming&&(this.streaming=!1),(e==null?void 0:e.streaming)===!1&&(this.disableStreaming=!0),this.streamUsage=(e==null?void 0:e.streamUsage)??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e==null?void 0:e.configuration},(e==null?void 0:e.supportsStrictToolCalling)!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),(e==null?void 0:e.service_tier)!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=(e==null?void 0:e.zdrEnabled)??!1,this._addVersion("@langchain/openai","1.5.2")}_llmType(){return"openai"}static lc_name(){return"ChatOpenAI"}get callKeys(){return[...super.callKeys,"options","function_call","functions","tools","tool_choice","promptIndex","response_format","seed","reasoning","reasoning_effort","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model"}}get lc_serializable_keys(){return["configuration","logprobs","topLogprobs","prefixMessages","supportsStrictToolCalling","modalities","audio","temperature","maxTokens","topP","frequencyPenalty","presencePenalty","n","logitBias","user","streaming","streamUsage","model","modelName","modelKwargs","stop","stopSequences","timeout","apiKey","cache","maxConcurrency","maxRetries","verbose","callbacks","tags","metadata","disableStreaming","zdrEnabled","reasoning","promptCacheKey","promptCacheRetention","verbosity"]}getLsParams(e){const n=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:n.temperature??void 0,ls_max_tokens:n.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}_getReasoningParams(e){if(!fu(this.model))return;let n;return this.reasoning!==void 0&&(n={...n,...this.reasoning}),(e==null?void 0:e.reasoning)!==void 0&&(n={...n,...e.reasoning}),(e==null?void 0:e.reasoningEffort)!==void 0&&(n==null?void 0:n.effort)===void 0&&(n={...n,effort:e.reasoningEffort}),n}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&gr(e.json_schema.schema)?C8(e.json_schema.schema,e.json_schema.name,{description:e.json_schema.description}):e}_combineCallOptions(e){return{...this.defaultOptions,...e??{}}}_getClientOptions(e){if(!this.client){const n=PT({baseURL:this.clientConfig.baseURL}),r={...this.clientConfig,baseURL:n,timeout:this.timeout,maxRetries:0};r.baseURL||delete r.baseURL,r.defaultHeaders=NT(r.defaultHeaders),this.client=new oe(r)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,n){return Zc(e)?w5(e.metadata.customTool):WT(e)?(n==null?void 0:n.strict)!==void 0?{...e,function:{...e.function,strict:n.strict}}:e:c5(e,n)}bindTools(e,n){let r;return(n==null?void 0:n.strict)!==void 0?r=n.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(i=>{var a;if(gy(i)||Zc(i))return i;if(h5(i))return i.extras.providerToolDefinition;const s=this._convertChatOpenAIToolToCompletionsTool(i,{strict:r});return my(i)&&((a=i.extras)==null?void 0:a.defer_loading)===!0?{...s,defer_loading:!0}:s}),...n})}async stream(e,n){return super.stream(e,this._combineCallOptions(n))}async invoke(e,n){return super.invoke(e,this._combineCallOptions(n))}_combineLLMOutput(...e){return e.reduce((n,r)=>(r&&r.tokenUsage&&(n.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,n.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,n.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),n),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let n=0,r=0,i=0;this.model==="gpt-3.5-turbo-0301"?(r=4,i=-1):(r=3,i=1);const s=await Promise.all(e.map(async a=>{var f,h,m,_,v,y;const[o,u]=await Promise.all([this.getNumTokens(a.content),this.getNumTokens(hu(a))]),l=a.name!==void 0?i+await this.getNumTokens(a.name):0;let c=o+r+u+l;const d=a;if(d._getType()==="function"&&(c-=2),(f=d.additional_kwargs)!=null&&f.function_call&&(c+=3),(h=d==null?void 0:d.additional_kwargs.function_call)!=null&&h.name&&(c+=await this.getNumTokens((m=d.additional_kwargs.function_call)==null?void 0:m.name)),(_=d.additional_kwargs.function_call)!=null&&_.arguments)try{c+=await this.getNumTokens(JSON.stringify(JSON.parse((v=d.additional_kwargs.function_call)==null?void 0:v.arguments)))}catch(p){console.error("Error parsing function arguments",p,JSON.stringify(d.additional_kwargs.function_call)),c+=await this.getNumTokens((y=d.additional_kwargs.function_call)==null?void 0:y.arguments)}return n+=c,c}));return n+=3,{totalCount:n,countPerMessage:s}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async n=>{var r;return(r=n.message.additional_kwargs)!=null&&r.function_call?(await this.getNumTokensFromMessages([n.message])).countPerMessage[0]:await this.getNumTokens(n.message.content)}))).reduce((n,r)=>n+r,0)}async _getEstimatedTokenCountFromPrompt(e,n,r){let i=(await this.getNumTokensFromMessages(e)).totalCount;if(n&&r!=="auto"){const s=f5(n);i+=await this.getNumTokens(s),i+=9}return n&&e.find(s=>s._getType()==="system")&&(i-=4),r==="none"?i+=1:typeof r=="object"&&(i+=await this.getNumTokens(r.name)+4),i}async moderateContent(e,n){const r=this._getClientOptions(n==null?void 0:n.options),i={input:e,model:(n==null?void 0:n.model)??"omni-moderation-latest"};return this.caller.call(async()=>{try{return await this.client.moderations.create(i,r)}catch(s){throw Fo(s)}})}get profile(){return N8[this.model]??{}}_getStructuredOutputMethod(e){const n={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if((n==null?void 0:n.method)===void 0)return"jsonSchema"}else n.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return n.method}withStructuredOutput(e,n){let r,i;const{schema:s,name:a,includeRaw:o}={...n,schema:e};if((n==null?void 0:n.strict)!==void 0&&n.method==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");const u=I8(this.model,n==null?void 0:n.method);if(u==="jsonMode"){i=zw(s);const l=vi(s);r=this.withConfig({outputVersion:"v0",response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:a??"extract",...l}}})}else if(u==="jsonSchema"){const l=vi(s),c={name:a??"extract",description:dy(l),schema:gr(s)?s:l,strict:n==null?void 0:n.strict};if(r=this.withConfig({outputVersion:"v0",response_format:{type:"json_schema",json_schema:c},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:c.name,description:c.description,...l}}}),gr(s)||ma(s)){const d=zw(s);i=zd.from(async f=>"parsed"in f.additional_kwargs?f.additional_kwargs.parsed:d.invoke(f.content))}else i=new JT}else{let l=a??"extract";const c=vi(s);let d;gr(s)||ma(s)?d={name:l,description:c.description,parameters:c}:typeof s.name=="string"&&typeof s.parameters=="object"&&s.parameters!=null?(d=s,l=s.name):(l=s.title??l,d={name:l,description:s.description??"",parameters:s}),r=this.withConfig({outputVersion:"v0",tools:[{type:"function",function:d}],tool_choice:{type:"function",function:{name:l}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:l,...c}},...(n==null?void 0:n.strict)!==void 0?{strict:n.strict}:{}}),i=yF(s,l)}return QT(r,i,o)}};const eI={providerName:"ChatOpenAI",fromStandardTextBlock(t){return{type:"text",text:t.text}},fromStandardImageBlock(t){var e,n;if(t.source_type==="url")return{type:"image_url",image_url:{url:t.url,...(e=t.metadata)!=null&&e.detail?{detail:t.metadata.detail}:{}}};if(t.source_type==="base64")return{type:"image_url",image_url:{url:`data:${t.mime_type??""};base64,${t.data}`,...(n=t.metadata)!=null&&n.detail?{detail:t.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(t){if(t.source_type==="url"){const e=_c({dataUrl:t.url});if(!e)throw new Error(`URL audio blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);const n=e.mime_type||t.mime_type||"";let r;try{r=mv(n)}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(r.type!=="audio"||r.subtype!=="wav"&&r.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:r.subtype,data:e.data}}}if(t.source_type==="base64"){let e;try{e=mv(t.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`)}if(e.type!=="audio"||e.subtype!=="wav"&&e.subtype!=="mp3")throw new Error(`Audio blocks with source_type ${t.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:t.data}}}throw new Error(`Audio content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(t){if(t.source_type==="url"){const e=_c({dataUrl:t.url}),n=Qo(t);if(!e)throw new Error(`URL file blocks with source_type ${t.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:t.url,filename:n}}}if(t.source_type==="base64"){const e=Qo(t);return{type:"file",file:{file_data:`data:${t.mime_type??""};base64,${t.data}`,filename:e}}}if(t.source_type==="id")return{type:"file",file:{file_id:t.id}};throw new Error(`File content blocks with source_type ${t.source_type} are not supported for ChatOpenAI`)}},RF=({message:t,rawResponse:e,includeRawResponse:n})=>{var s,a;const r=t.tool_calls,i=t.reasoning_content;switch(t.role){case"assistant":{const o=[],u=[];for(const d of r??[])try{o.push(vy(d,{returnId:!0}))}catch(f){u.push(zl(d,f.message))}const l={function_call:t.function_call,tool_calls:r};n!==void 0&&(l.__raw_response=e),i!==void 0&&(l.reasoning_content=i);const c={model_provider:"openai",model_name:e.model,...e.system_fingerprint?{usage:{...e.usage},system_fingerprint:e.system_fingerprint}:{}};return t.audio&&(l.audio=t.audio),new Cn({content:P8(t.content||"",(a=(s=e.choices)==null?void 0:s[0])==null?void 0:a.message),tool_calls:o,invalid_tool_calls:u,additional_kwargs:l,response_metadata:c,id:e.id})}default:return new zg(t.content||"",t.role??"unknown")}},jF=({delta:t,rawResponse:e,includeRawResponse:n,defaultRole:r})=>{var u,l;const i=t.role??r,s=t.content??"";let a;t.function_call?a={function_call:t.function_call}:t.tool_calls?a={tool_calls:t.tool_calls}:a={},n&&(a.__raw_response=e),t.reasoning_content!==void 0&&(a.reasoning_content=t.reasoning_content),t.audio&&(a.audio={...t.audio,index:e.choices[0].index});const o={model_provider:"openai",usage:{...e.usage}};if(i==="user")return new PS({content:s,response_metadata:o});if(i==="assistant"){const c=[];if(Array.isArray(t.tool_calls))for(const d of t.tool_calls)c.push({name:(u=d.function)==null?void 0:u.name,args:(l=d.function)==null?void 0:l.arguments,id:d.id,index:d.index,type:"tool_call_chunk"});return new vr({content:s,tool_call_chunks:c,additional_kwargs:a,id:e.id,response_metadata:o})}else return i==="system"?new gp({content:s,response_metadata:o}):i==="developer"?new gp({content:s,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):i==="function"?new CS({content:s,additional_kwargs:a,name:t.name,response_metadata:o}):i==="tool"?new y2({content:s,additional_kwargs:a,tool_call_id:t.tool_call_id,response_metadata:o}):new OS({content:s,role:i,response_metadata:o})},LF=t=>{if(t.type==="image"){if(t.url)return{type:"image_url",image_url:{url:t.url}};if(t.data)return{type:"image_url",image_url:{url:`data:${t.mimeType};base64,${t.data}`}}}if(t.type==="audio"&&t.data){const e=j2(()=>{const[,n]=t.mimeType.split("/");return n==="wav"||n==="mp3"?n:"wav"});return{type:"input_audio",input_audio:{data:t.data.toString(),format:e}}}if(t.type==="file"){if(t.data){const e=Qo(t);return{type:"file",file:{file_data:`data:${t.mimeType};base64,${t.data}`,filename:e}}}if(t.fileId)return{type:"file",file:{file_id:t.fileId}}}},MF=({message:t,model:e})=>{var i;let n=hu(t);if(n==="system"&&fu(e)&&(n="developer"),n==="developer")return{role:"developer",content:t.contentBlocks.filter(s=>s.type==="text")};if(n==="system")return{role:"system",content:t.contentBlocks.filter(s=>s.type==="text")};if(n==="assistant"){const s={role:"assistant",content:t.contentBlocks.filter(a=>a.type==="text")};return Cn.isInstance(t)&&((i=t.tool_calls)!=null&&i.length)?s.tool_calls=t.tool_calls.map(XT):t.additional_kwargs.tool_calls!=null&&(s.tool_calls=t.additional_kwargs.tool_calls),s}else{if(n==="tool"&&jg.isInstance(t))return{role:"tool",tool_call_id:t.tool_call_id,content:t.contentBlocks.filter(s=>s.type==="text")};if(n==="function")return{role:"function",name:t.name??"",content:t.contentBlocks.filter(s=>s.type==="text").join("")}}function*r(s){for(const a of s){a.type==="text"&&(yield{type:"text",text:a.text});const o=LF(a);o&&(yield o)}}return{role:"user",content:Array.from(r(t.contentBlocks))}},rh=({messages:t,model:e})=>t.flatMap(n=>{var a,o;if("output_version"in n.response_metadata&&((a=n.response_metadata)==null?void 0:a.output_version)==="v1")return MF({message:n});let r=hu(n);r==="system"&&fu(e)&&(r="developer");const i=typeof n.content=="string"?n.content:n.content.flatMap(u=>ki(u)?_S(u,eI):typeof u=="object"&&u!==null&&"type"in u&&u.type==="tool_use"?[]:u),s={role:r,content:i};return n.name!=null&&(s.name=n.name),n.additional_kwargs.function_call!=null&&(s.function_call=n.additional_kwargs.function_call),Cn.isInstance(n)&&((o=n.tool_calls)!=null&&o.length)?s.tool_calls=n.tool_calls.map(XT):(n.additional_kwargs.tool_calls!=null&&(s.tool_calls=n.additional_kwargs.tool_calls),jg.isInstance(n)&&n.tool_call_id!=null&&(s.tool_call_id=n.tool_call_id)),n.additional_kwargs.audio&&typeof n.additional_kwargs.audio=="object"&&"id"in n.additional_kwargs.audio?[s,{role:"assistant",audio:{id:n.additional_kwargs.audio.id}}]:s});async function*zF(t,e={}){var m,_,v,y,p,g;const n=e.streamUsage??!0,r=e.provider??"openai",i=e.mapChunk,s=new Map,a=new Map;let o=0,u=!1,l,c,d,f=!1;const h=(b,E)=>{const T=a.get(b);if(T!==void 0)return{index:T,isNew:!1};const I=o++;return a.set(b,I),s.set(I,{...E}),{index:I,isNew:!0}};for await(let b of t){i&&(b=i(b)),u||(u=!0,yield{event:"message-start",id:b.id}),!f&&(b.model||b.service_tier)&&(f=!0,yield{event:"provider",provider:r,name:"stream_metadata",payload:{model:b.model,service_tier:b.service_tier}}),b.usage&&n&&(l=BF(b.usage),yield{event:"usage",usage:l});const E=(m=b.x_groq)==null?void 0:m.usage;E&&n&&(l=UF(E),yield{event:"usage",usage:l});const T=(_=b.choices)==null?void 0:_[0];if(!T)continue;T.finish_reason!=null&&(c=FF(T.finish_reason),d=HF(b,T));const{delta:I}=T;if(!I)continue;const k=DF(I);if(k){const{index:j,isNew:N}=h("reasoning",{type:"reasoning",reasoning:""});N&&(yield{event:"content-block-start",index:j,content:{type:"reasoning",reasoning:""}});const L=s.get(j);L.reasoning=(L.reasoning??"")+k,yield{event:"content-block-delta",index:j,delta:{type:"reasoning-delta",reasoning:k}}}if(I.content){const{index:j,isNew:N}=h("text",{type:"text",text:""});N&&(yield{event:"content-block-start",index:j,content:{type:"text",text:""}});const L=s.get(j);L.text=(L.text??"")+I.content,yield{event:"content-block-delta",index:j,delta:{type:"text-delta",text:I.content}}}if(Array.isArray(I.tool_calls))for(const j of I.tool_calls){const N=j.index??0,{index:L,isNew:ue}=h(`tool:${N}`,{type:"tool_call_chunk",id:j.id,name:(v=j.function)==null?void 0:v.name,args:"",index:N});ue&&(yield{event:"content-block-start",index:L,content:{type:"tool_call_chunk",id:j.id,name:(y=j.function)==null?void 0:y.name,args:"",index:N}});const Ee=s.get(L);j.id!=null&&(Ee.id=j.id),((p=j.function)==null?void 0:p.name)!=null&&(Ee.name=j.function.name);const Et=((g=j.function)==null?void 0:g.arguments)??"";Ee.args=(Ee.args??"")+Et,yield{event:"content-block-delta",index:L,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...Ee.id!=null?{id:Ee.id}:{},...Ee.name!=null?{name:Ee.name}:{},args:Ee.args}}}}if(I.audio){const{index:j,isNew:N}=h("audio",{type:"audio",id:I.audio.id,data:"",mimeType:"audio/pcm",transcript:I.audio.transcript??""});N&&(yield{event:"content-block-start",index:j,content:{type:"audio",id:I.audio.id,data:"",mimeType:"audio/pcm",transcript:I.audio.transcript??""}});const L=s.get(j);I.audio.transcript&&(L.transcript=(L.transcript??"")+I.audio.transcript,yield{event:"content-block-delta",index:j,delta:{type:"block-delta",fields:{type:"audio",transcript:L.transcript}}}),I.audio.data&&(L.data=(L.data??"")+I.audio.data,yield{event:"content-block-delta",index:j,delta:{type:"data-delta",data:I.audio.data,encoding:"base64"}})}I.function_call&&(yield{event:"provider",provider:r,name:"function_call",payload:I.function_call}),T.logprobs&&(yield{event:"provider",provider:r,name:"logprobs",payload:T.logprobs})}for(const[b,E]of s)yield{event:"content-block-finish",index:b,content:wy(E)};yield{event:"message-finish",reason:c,...l?{usage:l}:{},...d?{responseMetadata:d}:{}}}function DF(t){const e=t.reasoning_content??t.reasoning;return typeof e=="string"&&e.length>0?e:void 0}function UF(t){return{input_tokens:t.prompt_tokens??0,output_tokens:t.completion_tokens??0,total_tokens:t.total_tokens??0}}function FF(t){switch(t){case"stop":return"stop";case"length":case"max_tokens":return"length";case"tool_calls":case"function_call":return"tool_use";case"content_filter":return"content_filter";default:return"stop"}}function BF(t){var r,i,s,a;const e={...((r=t.prompt_tokens_details)==null?void 0:r.audio_tokens)!=null&&{audio:t.prompt_tokens_details.audio_tokens},...((i=t.prompt_tokens_details)==null?void 0:i.cached_tokens)!=null&&{cache_read:t.prompt_tokens_details.cached_tokens}},n={...((s=t.completion_tokens_details)==null?void 0:s.audio_tokens)!=null&&{audio:t.completion_tokens_details.audio_tokens},...((a=t.completion_tokens_details)==null?void 0:a.reasoning_tokens)!=null&&{reasoning:t.completion_tokens_details.reasoning_tokens}};return{input_tokens:t.prompt_tokens??0,output_tokens:t.completion_tokens??0,total_tokens:t.total_tokens??0,...Object.keys(e).length>0&&{input_token_details:e},...Object.keys(n).length>0&&{output_token_details:n}}}function HF(t,e){return{model_provider:"openai",model_name:t.model,system_fingerprint:t.system_fingerprint,service_tier:t.service_tier,finish_reason:e.finish_reason,...t.usage?{usage:t.usage}:{}}}var ZF=class extends xy{constructor(t,e){super(by(t,e))}invocationParams(t,e){var a;let n;(t==null?void 0:t.strict)!==void 0?n=t.strict:this.supportsStrictToolCalling!==void 0&&(n=this.supportsStrictToolCalling);let r={};(t==null?void 0:t.stream_options)!==void 0?r={stream_options:t.stream_options}:this.streamUsage&&(this.streaming||e!=null&&e.streaming)&&(r={stream_options:{include_usage:!0}});const i={model:this.model,temperature:this.temperature,top_p:this.topP,frequency_penalty:this.frequencyPenalty,presence_penalty:this.presencePenalty,logprobs:this.logprobs,top_logprobs:this.topLogprobs,n:this.n,logit_bias:this.logitBias,stop:(t==null?void 0:t.stop)??this.stopSequences,user:this.user,stream:this.streaming,functions:t==null?void 0:t.functions,function_call:t==null?void 0:t.function_call,tools:(a=t==null?void 0:t.tools)!=null&&a.length?t.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:n})):void 0,tool_choice:RT(t==null?void 0:t.tool_choice),response_format:this._getResponseFormat(t==null?void 0:t.response_format),seed:t==null?void 0:t.seed,...r,parallel_tool_calls:t==null?void 0:t.parallel_tool_calls,...this.audio||t!=null&&t.audio?{audio:this.audio||(t==null?void 0:t.audio)}:{},...this.modalities||t!=null&&t.modalities?{modalities:this.modalities||(t==null?void 0:t.modalities)}:{},...this.modelKwargs,prompt_cache_key:(t==null?void 0:t.promptCacheKey)??this.promptCacheKey,prompt_cache_retention:(t==null?void 0:t.promptCacheRetention)??this.promptCacheRetention,verbosity:(t==null?void 0:t.verbosity)??this.verbosity};(t==null?void 0:t.prediction)!==void 0&&(i.prediction=t.prediction),this.service_tier!==void 0&&(i.service_tier=this.service_tier),(t==null?void 0:t.service_tier)!==void 0&&(i.service_tier=t.service_tier);const s=this._getReasoningParams(t);return s!==void 0&&s.effort!==void 0&&(i.reasoning_effort=s.effort),fu(i.model)?i.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:i.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,i}async _generate(t,e,n){var a,o,u;(a=e.signal)==null||a.throwIfAborted();const r={},i=this.invocationParams(e),s=rh({messages:t,model:this.model});if(i.stream){const l=this._streamResponseChunks(t,e,n),c={};for await(const v of l){v.message.response_metadata={...v.generationInfo,...v.message.response_metadata};const y=((o=v.generationInfo)==null?void 0:o.completion)??0;c[y]===void 0?c[y]=v:c[y]=c[y].concat(v)}const d=Object.entries(c).sort(([v],[y])=>parseInt(v,10)-parseInt(y,10)).map(([v,y])=>y),{functions:f,function_call:h}=this.invocationParams(e),m=await this._getEstimatedTokenCountFromPrompt(t,f,h),_=await this._getNumTokensFromGenerations(d);return r.input_tokens=m,r.output_tokens=_,r.total_tokens=m+_,{generations:d,llmOutput:{estimatedTokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}else{const l=await this.completionWithRetry({...i,stream:!1,messages:s},{signal:e==null?void 0:e.signal,...e==null?void 0:e.options}),{completion_tokens:c,prompt_tokens:d,total_tokens:f,prompt_tokens_details:h,completion_tokens_details:m}=(l==null?void 0:l.usage)??{};c&&(r.output_tokens=(r.output_tokens??0)+c),d&&(r.input_tokens=(r.input_tokens??0)+d),f&&(r.total_tokens=(r.total_tokens??0)+f),((h==null?void 0:h.audio_tokens)!==null||(h==null?void 0:h.cached_tokens)!==null)&&(r.input_token_details={...(h==null?void 0:h.audio_tokens)!==null&&{audio:h==null?void 0:h.audio_tokens},...(h==null?void 0:h.cached_tokens)!==null&&{cache_read:h==null?void 0:h.cached_tokens}}),((m==null?void 0:m.audio_tokens)!==null||(m==null?void 0:m.reasoning_tokens)!==null)&&(r.output_token_details={...(m==null?void 0:m.audio_tokens)!==null&&{audio:m==null?void 0:m.audio_tokens},...(m==null?void 0:m.reasoning_tokens)!==null&&{reasoning:m==null?void 0:m.reasoning_tokens}});const _=[];for(const v of(l==null?void 0:l.choices)??[]){const y={text:((u=v.message)==null?void 0:u.content)??"",message:this._convertCompletionsMessageToBaseMessage(v.message??{role:"assistant"},l)};y.generationInfo={...v.finish_reason?{finish_reason:v.finish_reason}:{},...v.logprobs?{logprobs:v.logprobs}:{}},Dg(y.message)&&(y.message.usage_metadata=r),y.message=new Cn(Object.fromEntries(Object.entries(y.message).filter(([p])=>!p.startsWith("lc_")))),_.push(y)}return{generations:_,llmOutput:{tokenUsage:{promptTokens:r.input_tokens,completionTokens:r.output_tokens,totalTokens:r.total_tokens}}}}}async*_streamChatModelEvents(t,e,n){const r=rh({messages:t,model:this.model}),i={...this.invocationParams(e,{streaming:!0}),messages:r,stream:!0},s=await this.completionWithRetry(i,e),a=this.streamUsage??e.streamUsage;yield*zF(async function*(u,l){for await(const c of u){if(l!=null&&l.aborted)return;yield c}}(s,e.signal),{streamUsage:a??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,n){var u,l,c,d,f,h,m,_,v,y,p;const r=rh({messages:t,model:this.model}),i={...this.invocationParams(e,{streaming:!0}),messages:r,stream:!0};let s;const a=await this.completionWithRetry(i,e);let o;for await(const g of a){if((u=e.signal)!=null&&u.aborted)return;const b=(l=g==null?void 0:g.choices)==null?void 0:l[0];if(g.usage&&(o=g.usage),!b)continue;const{delta:E}=b;if(!E)continue;const T=this._convertCompletionsDeltaToBaseMessageChunk(E,g,s);s=E.role??s;const I={prompt:e.promptIndex??0,completion:b.index??0};if(typeof T.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const k={...I};b.finish_reason!=null&&(k.finish_reason=b.finish_reason,k.system_fingerprint=g.system_fingerprint,k.model_name=g.model,k.service_tier=g.service_tier),this.logprobs&&(k.logprobs=b.logprobs);const j=new Wo({message:T,text:T.content,generationInfo:k});yield j,await(n==null?void 0:n.handleLLMNewToken(j.text??"",I,void 0,void 0,void 0,{chunk:j}))}if(o){const g={...((c=o.prompt_tokens_details)==null?void 0:c.audio_tokens)!==null&&{audio:(d=o.prompt_tokens_details)==null?void 0:d.audio_tokens},...((f=o.prompt_tokens_details)==null?void 0:f.cached_tokens)!==null&&{cache_read:(h=o.prompt_tokens_details)==null?void 0:h.cached_tokens}},b={...((m=o.completion_tokens_details)==null?void 0:m.audio_tokens)!==null&&{audio:(_=o.completion_tokens_details)==null?void 0:_.audio_tokens},...((v=o.completion_tokens_details)==null?void 0:v.reasoning_tokens)!==null&&{reasoning:(y=o.completion_tokens_details)==null?void 0:y.reasoning_tokens}},E=new Wo({message:new vr({content:"",response_metadata:{usage:{...o}},usage_metadata:{input_tokens:o.prompt_tokens,output_tokens:o.completion_tokens,total_tokens:o.total_tokens,...Object.keys(g).length>0&&{input_token_details:g},...Object.keys(b).length>0&&{output_token_details:b}}}),text:""});yield E,await(n==null?void 0:n.handleLLMNewToken(E.text??"",{prompt:0,completion:0},void 0,void 0,void 0,{chunk:E}))}if((p=e.signal)!=null&&p.aborted)throw new Error("AbortError")}async completionWithRetry(t,e){const n=this._getClientOptions(e),r=t.response_format&&t.response_format.type==="json_schema";return this.caller.call(async()=>{try{return r&&!t.stream?await this.client.chat.completions.parse(t,n):await this.client.chat.completions.create(t,n)}catch(i){throw Fo(i)}})}_convertCompletionsDeltaToBaseMessageChunk(t,e,n){return jF({delta:t,rawResponse:e,includeRawResponse:this.__includeRawResponse,defaultRole:n})}_convertCompletionsMessageToBaseMessage(t,e){return RF({message:t,rawResponse:e,includeRawResponse:this.__includeRawResponse})}};const Fs="__openai_function_call_ids__",Bs="__openai_custom_tool_call_ids__";function tI(t){return t.type==="url_citation"?{type:"citation",source:"url_citation",url:t.url,title:t.title,startIndex:t.start_index,endIndex:t.end_index}:t.type==="file_citation"?{type:"citation",source:"file_citation",title:t.filename,startIndex:t.index,file_id:t.file_id}:t.type==="container_file_citation"?{type:"citation",source:"container_file_citation",title:t.filename,startIndex:t.start_index,endIndex:t.end_index,file_id:t.file_id,container_id:t.container_id}:t.type==="file_path"?{type:"citation",source:"file_path",startIndex:t.index,file_id:t.file_id}:{type:"non_standard",value:t}}function VF(t){if(t.type==="url_citation"||t.type==="file_citation"||t.type==="container_file_citation"||t.type==="file_path")return t;if(t.type==="citation"){const e=t;if(e.source==="url_citation")return{type:"url_citation",url:e.url??"",title:e.title??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_citation")return{type:"file_citation",file_id:e.file_id??"",filename:e.title??"",index:e.startIndex??0};if(e.source==="container_file_citation")return{type:"container_file_citation",file_id:e.file_id??"",filename:e.title??"",container_id:e.container_id??"",start_index:e.startIndex??0,end_index:e.endIndex??0};if(e.source==="file_path")return{type:"file_path",file_id:e.file_id??"",index:e.startIndex??0}}return t.type==="non_standard"?t.value:t}const ky=t=>{var r,i,s,a;const e={...((r=t==null?void 0:t.input_tokens_details)==null?void 0:r.cached_tokens)!=null&&{cache_read:(i=t==null?void 0:t.input_tokens_details)==null?void 0:i.cached_tokens}},n={...((s=t==null?void 0:t.output_tokens_details)==null?void 0:s.reasoning_tokens)!=null&&{reasoning:(a=t==null?void 0:t.output_tokens_details)==null?void 0:a.reasoning_tokens}};return{input_tokens:(t==null?void 0:t.input_tokens)??0,output_tokens:(t==null?void 0:t.output_tokens)??0,total_tokens:(t==null?void 0:t.total_tokens)??0,input_token_details:e,output_token_details:n}},nI=t=>{var o;if(t.error){const u=new Error(t.error.message);throw u.name=t.error.code,u}const e=[],n=[],r=[],i=t.output.map(u=>{if(u.type==="function_call"&&"parsed_arguments"in u){const l={...u};return delete l.parsed_arguments,l}return u}),s={model_provider:"openai",model:t.model,created_at:t.created_at,id:t.id,incomplete_details:t.incomplete_details,metadata:t.metadata,object:t.object,output:i,status:t.status,user:t.user,service_tier:t.service_tier,model_name:t.model},a={};for(const u of t.output)if(u.type==="message")e.push(...u.content.flatMap(l=>l.type==="output_text"?("parsed"in l&&l.parsed!=null&&(a.parsed=l.parsed),{type:"text",text:l.text,annotations:l.annotations.map(tI),...u.phase!==null?{phase:u.phase}:{}}):l.type==="refusal"?(a.refusal=l.refusal,[]):l));else if(u.type==="function_call"){const l={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{n.push(vy(l,{returnId:!0}))}catch(c){let d;typeof c=="object"&&c!=null&&"message"in c&&typeof c.message=="string"&&(d=c.message),r.push(zl(l,d))}a[Fs]??(a[Fs]={}),u.id&&(a[Fs][u.call_id]=u.id)}else if(u.type==="reasoning"){a.reasoning=u;const l=(o=u.summary)==null?void 0:o.map(c=>c.text).filter(Boolean).join("");l&&e.push({type:"reasoning",reasoning:l})}else if(u.type==="custom_tool_call"){const l=m5(u);l?(n.push(l),a[Bs]??(a[Bs]={}),u.id&&u.call_id&&(a[Bs][u.call_id]=u.id)):r.push(zl(u,"Malformed custom tool call"))}else if(u.type==="computer_call"){const l=g5(u);l?n.push(l):r.push(zl(u,"Malformed computer call"))}else u.type==="image_generation_call"?(u.result&&e.push({type:"image",mimeType:"image/png",data:u.result,id:u.id,metadata:{status:u.status}}),a.tool_outputs??(a.tool_outputs=[]),a.tool_outputs.push(u)):(a.tool_outputs??(a.tool_outputs=[]),a.tool_outputs.push(u));return new Cn({id:t.id,content:e,tool_calls:n,invalid_tool_calls:r,usage_metadata:ky(t.usage),additional_kwargs:a,response_metadata:s})},KF=t=>{const e=(t.summary.length>1?t.summary.reduce((n,r)=>{const i=n[n.length-1];return i.index===r.index?i.text+=r.text:n.push(r),n},[{...t.summary[0]}]):t.summary).map(n=>Object.fromEntries(Object.entries(n).filter(([r])=>r!=="index")));return{...t,summary:e}},qF=t=>{var u,l,c;const e=[];let n={},r;const i=[],s={model_provider:"openai"},a={};let o;if(t.type==="response.output_text.delta")e.push({type:"text",text:t.delta,index:t.content_index});else if(t.type==="response.output_text.annotation.added")e.push({type:"text",text:"",annotations:[tI(t.annotation)],index:t.content_index});else if(t.type==="response.output_item.added"&&t.item.type==="message"){const d="phase"in t.item?t.item.phase:void 0;d&&e.push({type:"text",text:"",phase:d,index:0})}else if(t.type==="response.output_item.added"&&t.item.type==="function_call")i.push({type:"tool_call_chunk",name:t.item.name,args:t.item.arguments,id:t.item.call_id,index:t.output_index}),a[Fs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.added"&&t.item.type==="custom_tool_call")i.push({type:"tool_call_chunk",isCustomTool:!0,name:t.item.name,args:t.item.input,id:t.item.call_id,index:t.output_index}),a[Bs]={[t.item.call_id]:t.item.id};else if(t.type==="response.output_item.done"&&t.item.type==="computer_call")i.push({type:"tool_call_chunk",name:"computer_use",args:JSON.stringify({action:t.item.action}),id:t.item.call_id,index:t.output_index}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&t.item.type==="image_generation_call")t.item.result&&e.push({type:"image",mimeType:"image/png",data:t.item.result,id:t.item.id,metadata:{status:t.item.status}}),a.tool_outputs=[t.item];else if(t.type==="response.output_item.done"&&["web_search_call","file_search_call","code_interpreter_call","shell_call","local_shell_call","mcp_call","mcp_list_tools","mcp_approval_request","custom_tool_call","tool_search_call","tool_search_output"].includes(t.item.type))a.tool_outputs=[t.item];else if(t.type==="response.created")o=t.response.id,s.id=t.response.id,s.model_name=t.response.model,s.model=t.response.model;else if(t.type==="response.completed"||t.type==="response.incomplete"){o=t.response.id;const d=nI(t.response);if(r=ky(t.response.usage),((l=(u=t.response.text)==null?void 0:u.format)==null?void 0:l.type)==="json_schema"&&d.text)try{a.parsed??(a.parsed=JSON.parse(d.text))}catch{}for(const[f,h]of Object.entries(t.response))f!=="id"&&(f==="output"?s[f]=d.response_metadata.output:s[f]=h)}else if(t.type==="response.function_call_arguments.delta"||t.type==="response.custom_tool_call_input.delta")i.push({type:"tool_call_chunk",args:t.delta,index:t.output_index,...t.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});else if(t.type==="response.web_search_call.in_progress"||t.type==="response.web_search_call.searching"||t.type==="response.web_search_call.completed"||t.type==="response.file_search_call.in_progress"||t.type==="response.file_search_call.searching"||t.type==="response.file_search_call.completed"||t.type==="response.image_generation_call.in_progress"||t.type==="response.image_generation_call.generating"||t.type==="response.image_generation_call.completed"){const[,d,f]=t.type.match(/^response\.(.*)\.([^.]+)$/)??["","",""];n={tool_outputs:{id:t.item_id,type:d,status:f}}}else if(t.type==="response.refusal.done")a.refusal=t.refusal;else if(t.type==="response.output_item.added"&&"item"in t&&t.item.type==="reasoning"){const d=t.item.summary?t.item.summary.map((h,m)=>({...h,index:m})):void 0;a.reasoning={id:t.item.id,type:t.item.type,...d?{summary:d}:{}};const f=(c=t.item.summary)==null?void 0:c.map(h=>h.text).filter(Boolean).join("");f&&e.push({type:"reasoning",reasoning:f})}else if(t.type==="response.reasoning_summary_part.added")a.reasoning={type:"reasoning",summary:[{...t.part,index:t.summary_index}]},t.part.text&&e.push({type:"reasoning",reasoning:t.part.text,index:t.summary_index});else if(t.type==="response.reasoning_summary_text.delta")a.reasoning={type:"reasoning",summary:[{text:t.delta,type:"summary_text",index:t.summary_index}]},t.delta&&e.push({type:"reasoning",reasoning:t.delta,index:t.summary_index});else return t.type==="response.image_generation_call.partial_image",null;return new Wo({text:e.map(d=>d.text).join(""),message:new vr({id:o,content:e,tool_call_chunks:i,usage_metadata:r,additional_kwargs:a,response_metadata:s}),generationInfo:n})},WF=t=>{var r;const e=Cn.isInstance(t)&&((r=t.response_metadata)==null?void 0:r.model_provider)==="openai";function*n(){const i=Pr(()=>{try{const p=hu(t);return p==="system"||p==="developer"||p==="assistant"||p==="user"?p:"assistant"}catch{return"assistant"}});let s;const a=new Set,o=new Set,u=new Map,l=new Map;function*c(){if(!s)return;const p=s.content;(typeof p=="string"&&p.length>0||Array.isArray(p)&&p.length>0)&&(yield s),s=void 0}const d=(p,g)=>{s||(s={type:"message",role:i,content:[],...g?{phase:g}:{}}),typeof s.content=="string"?s.content=s.content.length>0?[{type:"input_text",text:s.content},...p]:[...p]:s.content.push(...p)},f=p=>{if(typeof p=="string")return p;try{return JSON.stringify(p??{})}catch{return"{}"}},h=p=>{const g=Pr(()=>{var E;const b=(E=p.metadata)==null?void 0:E.detail;return b==="low"||b==="high"||b==="auto"?b:"auto"});if(p.fileId)return{type:"input_image",detail:g,file_id:p.fileId};if(p.url)return{type:"input_image",detail:g,image_url:p.url};if(p.data){const b=typeof p.data=="string"?p.data:Buffer.from(p.data).toString("base64");return{type:"input_image",detail:g,image_url:`data:${p.mimeType??"image/png"};base64,${b}`}}},m=p=>{if(p.fileId){const g=nm(p);return{type:"input_file",file_id:p.fileId,...g?{filename:g}:{}}}if(p.url){const g=nm(p);return{...g?{filename:g}:{},type:"input_file",file_url:p.url}}if(p.data){const g=Qo(p),b=typeof p.data=="string"?p.data:Buffer.from(p.data).toString("base64");return{type:"input_file",file_data:`data:${p.mimeType??"application/octet-stream"};base64,${b}`,filename:g}}},_=p=>{const g=Pr(()=>{var E;if(Array.isArray(p.summary)){const T=((E=p.summary)==null?void 0:E.map(I=>I==null?void 0:I.text).filter(I=>typeof I=="string"))??[];if(T.length>0)return T}return p.reasoning?[p.reasoning]:[]}),b=g.length>0?g.map(E=>({type:"summary_text",text:E})):[{type:"summary_text",text:""}];return{type:"reasoning",...p.id?{id:p.id}:{},summary:b}},v=p=>({type:"function_call",name:p.name??"",call_id:p.id??"",arguments:f(p.args)}),y=p=>{const g=f(p.output),b=p.status==="success"?"completed":p.status==="error"?"incomplete":void 0;return{type:"function_call_output",call_id:p.toolCallId??"",output:g,...b?{status:b}:{}}};for(const p of t.contentBlocks)if(p.type==="text"){const g=Pr(()=>{if("extras"in p&&typeof p.extras=="object"&&p.extras!==null&&"phase"in p.extras)return p.extras.phase});d([{type:"input_text",text:p.text}],g)}else if(p.type!=="invalid_tool_call"){if(p.type==="reasoning")yield*c(),yield _(p);else if(p.type==="tool_call"){yield*c();const g=p.id??"";g&&(a.add(g),u.delete(g)),yield v(p)}else if(p.type==="tool_call_chunk"){if(p.id){const g=u.get(p.id)??{name:p.name,args:[]};p.name&&(g.name=p.name),p.args&&g.args.push(p.args),u.set(p.id,g)}}else if(p.type==="server_tool_call"){yield*c();const g=p.id??"";g&&(o.add(g),l.delete(g)),yield v(p)}else if(p.type==="server_tool_call_chunk"){if(p.id){const g=l.get(p.id)??{name:p.name,args:[]};p.name&&(g.name=p.name),p.args&&g.args.push(p.args),l.set(p.id,g)}}else if(p.type==="server_tool_call_result")yield*c(),yield y(p);else if(p.type!=="audio")if(p.type==="file"){const g=m(p);g&&d([g])}else if(p.type==="image"){const g=h(p);g&&d([g])}else if(p.type==="video"){const g=m(p);g&&d([g])}else p.type==="text-plain"?p.text&&d([{type:"input_text",text:p.text}]):p.type==="non_standard"&&e&&(yield*c(),yield p.value)}yield*c();for(const[p,g]of u){if(!p||a.has(p))continue;const b=g.args.join("");!g.name&&!b||(yield{type:"function_call",call_id:p,name:g.name??"",arguments:b})}for(const[p,g]of l){if(!p||o.has(p))continue;const b=g.args.join("");!g.name&&!b||(yield{type:"function_call",call_id:p,name:g.name??"",arguments:b})}}return Array.from(n())},ih=({messages:t,zdrEnabled:e,model:n})=>t.flatMap(r=>{var o,u,l,c;const i=r.response_metadata;if((i==null?void 0:i.output_version)==="v1")return WF(r);const s=r.additional_kwargs;let a=hu(r);if(a==="system"&&fu(n)&&(a="developer"),a==="function")throw new Error("Function messages are not supported in Responses API");if(a==="tool"){const d=r;if((s==null?void 0:s.type)==="computer_call_output")return{type:"computer_call_output",output:(()=>{if(typeof d.content=="string")return{type:"input_image",image_url:d.content};if(Array.isArray(d.content)){const h=d.content.find(v=>v.type==="input_image");if(h)return h;const m=d.content.find(v=>v.type==="computer_screenshot");if(m)return m;const _=d.content.find(v=>v.type==="image_url");if(_)return{type:"input_image",image_url:typeof _.image_url=="string"?_.image_url:_.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:d.tool_call_id};if((o=d.additional_kwargs)!=null&&o.customTool)return{type:"custom_tool_call_output",call_id:d.tool_call_id,output:d.content};const f=Array.isArray(d.content)&&d.content.every(h=>typeof h=="object"&&h!==null&&"type"in h&&(h.type==="input_file"||h.type==="input_image"||h.type==="input_text"));return{type:"function_call_output",call_id:d.tool_call_id,id:(u=d.id)!=null&&u.startsWith("fc_")?d.id:void 0,output:f?d.content:typeof d.content!="string"?JSON.stringify(d.content):d.content}}if(a==="assistant"){if(!e&&(i==null?void 0:i.output)!=null&&Array.isArray(i==null?void 0:i.output)&&(i==null?void 0:i.output.length)>0&&(i!=null&&i.output.every(g=>"type"in g)))return i==null?void 0:i.output;const d=[],f=s==null?void 0:s.reasoning,h=!!(f!=null&&f.encrypted_content);if(f&&(!e||h)){const g=KF(f);d.push(g)}let{content:m}=r;if(s!=null&&s.refusal&&(typeof m=="string"&&(m=[{type:"output_text",text:m,annotations:[]}]),m=[...m,{type:"refusal",refusal:s.refusal}]),typeof m=="string"||m.length>0){const g={type:"message",role:"assistant",...r.id&&!e&&r.id.startsWith("msg_")?{id:r.id}:{},content:Pr(()=>typeof m=="string"?m:m.flatMap(b=>{if(b.type==="text"){const E=b;return{type:"output_text",text:E.text,annotations:(E.annotations??[]).map(VF)}}return b.type==="output_text"||b.type==="refusal"?b:[]})),phase:Pr(()=>{var b;if(Array.isArray(m))return(b=m.find(E=>"phase"in E&&typeof E.phase=="string"))==null?void 0:b.phase})};d.push(g)}const _=s==null?void 0:s[Fs],v=s==null?void 0:s[Bs];Cn.isInstance(r)&&((l=r.tool_calls)!=null&&l.length)?d.push(...r.tool_calls.map(g=>_5(g,v)?{type:"custom_tool_call",id:"call_id"in g&&typeof g.call_id=="string"?g.call_id:(v==null?void 0:v[g.id??""])??"",call_id:g.id??"",input:g.args.input,name:g.name}:y5(g)?{type:"computer_call",id:g.call_id,call_id:g.id??"",action:g.args.action}:{type:"function_call",name:g.name,arguments:JSON.stringify(g.args),call_id:g.id,...e?{}:{id:_==null?void 0:_[g.id]}})):s!=null&&s.tool_calls&&d.push(...s.tool_calls.map(g=>({type:"function_call",name:g.function.name,call_id:g.id,arguments:g.function.arguments,...e?{}:{id:_==null?void 0:_[g.id]}})));const y=(c=i==null?void 0:i.output)!=null&&c.length?i==null?void 0:i.output:s.tool_outputs,p=["computer_call","mcp_call","code_interpreter_call","image_generation_call","shell_call","local_shell_call"];if(y!=null){const g=y==null?void 0:y.filter(b=>p.includes(b.type));g.length>0&&d.push(...g)}return d}if(a==="user"||a==="system"||a==="developer"){if(typeof r.content=="string")return{type:"message",role:a,content:r.content};const d=[],f=r.content.flatMap(h=>{if(h.type==="mcp_approval_response"&&d.push({type:"mcp_approval_response",approval_request_id:h.approval_request_id,approve:h.approve}),ki(h)){if(h.type==="file"){const m=nm(h);if(h.source_type==="url")return{type:"input_file",file_url:h.url,...m?{filename:m}:{}};if(h.source_type==="id")return{type:"input_file",file_id:h.id,...m?{filename:m}:{}};if(h.source_type==="base64")return{type:"input_file",file_data:`data:${h.mime_type??""};base64,${h.data}`,filename:Qo(h)}}return _S(h,eI)}return h.type==="text"?{type:"input_text",text:h.text}:h.type==="image_url"?{type:"input_image",image_url:Pr(()=>{if(typeof h.image_url=="string")return h.image_url;if(typeof h.image_url=="object"&&h.image_url!==null&&"url"in h.image_url)return h.image_url.url}),detail:Pr(()=>{if(typeof h.image_url=="string")return"auto";if(typeof h.image_url=="object"&&h.image_url!==null&&"detail"in h.image_url)return h.image_url.detail})}:h.type==="input_text"||h.type==="input_image"||h.type==="input_file"?h:[]});return f.length>0&&d.push({type:"message",role:a,content:f}),d}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${a}`),[]});async function*GF(t,e={}){const n=e.streamUsage??!0,r=e.provider??"openai",i=new Map,s=new Map;let a=0,o=!1,u,l,c,d;const f=new Set,h=(v,y)=>{const p=s.get(v);if(p!==void 0)return{index:p,isNew:!1};const g=a++;return s.set(v,g),i.set(g,{...y}),{index:g,isNew:!0}},m=function*(){o||(o=!0,yield{event:"message-start",id:u})},_=function*(v){if(f.has(v))return;const y=i.get(v);y&&(f.add(v),yield{event:"content-block-finish",index:v,content:wy(y)})};for await(const v of t){if(v.type==="response.created"){u=v.response.id,yield*m(),yield{event:"provider",provider:r,name:"response.created",payload:{model:v.response.model,id:v.response.id}};continue}if(v.type==="response.output_text.delta"){yield*m();const{index:y,isNew:p}=h(`text:${v.output_index}:${v.content_index}`,{type:"text",text:""});p&&(yield{event:"content-block-start",index:y,content:{type:"text",text:""}});const g=i.get(y);g.text=(g.text??"")+v.delta,yield{event:"content-block-delta",index:y,delta:{type:"text-delta",text:v.delta}};continue}if(v.type==="response.reasoning_summary_text.delta"){yield*m();const{index:y,isNew:p}=h(`reasoning:${v.output_index}:${v.summary_index}`,{type:"reasoning",reasoning:""});p&&(yield{event:"content-block-start",index:y,content:{type:"reasoning",reasoning:""}});const g=i.get(y);g.reasoning=(g.reasoning??"")+v.delta,yield{event:"content-block-delta",index:y,delta:{type:"reasoning-delta",reasoning:v.delta}};continue}if(v.type==="response.output_item.added"&&(v.item.type==="function_call"||v.item.type==="custom_tool_call")){yield*m();const y=`tool:${v.output_index}`,p=v.item.type==="custom_tool_call",g=v.item.type==="function_call"?v.item.arguments??"":v.item.input??"",{index:b,isNew:E}=h(y,{type:"tool_call_chunk",id:v.item.call_id,name:v.item.name,args:g,index:v.output_index,...p?{isCustomTool:!0}:{}});if(E&&(yield{event:"content-block-start",index:b,content:{type:"tool_call_chunk",id:v.item.call_id,name:v.item.name,args:g,index:v.output_index}}),g){const T=i.get(b);yield{event:"content-block-delta",index:b,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...T.id!=null?{id:T.id}:{},...T.name!=null?{name:T.name}:{},args:T.args}}}}continue}if(v.type==="response.function_call_arguments.delta"||v.type==="response.custom_tool_call_input.delta"){yield*m();const{index:y,isNew:p}=h(`tool:${v.output_index}`,{type:"tool_call_chunk",args:"",index:v.output_index,...v.type==="response.custom_tool_call_input.delta"?{isCustomTool:!0}:{}});p&&(yield{event:"content-block-start",index:y,content:{type:"tool_call_chunk",args:"",index:v.output_index}});const g=i.get(y);g.args=(g.args??"")+v.delta,yield{event:"content-block-delta",index:y,delta:{type:"block-delta",fields:{type:"tool_call_chunk",...g.id!=null?{id:g.id}:{},...g.name!=null?{name:g.name}:{},args:g.args}}};continue}if(v.type==="response.output_item.done"&&(v.item.type==="function_call"||v.item.type==="custom_tool_call")){yield*m();const y=`tool:${v.output_index}`,p=v.item.type==="function_call"?v.item.arguments??"":v.item.input??"",{index:g,isNew:b}=h(y,{type:"tool_call_chunk",id:v.item.call_id,name:v.item.name,args:p,index:v.output_index});if(b)yield{event:"content-block-start",index:g,content:{type:"tool_call_chunk",id:v.item.call_id,name:v.item.name,args:p,index:v.output_index}};else{const E=i.get(g);E.args=p,E.id=v.item.call_id,E.name=v.item.name}yield*_(g);continue}if(v.type==="response.completed"||v.type==="response.incomplete"){yield*m(),u=v.response.id,c=JF(v.response.status,v.type),d={model_provider:r,id:v.response.id,model:v.response.model,status:v.response.status},n&&v.response.usage&&(l=ky(v.response.usage),yield{event:"usage",usage:l});continue}v.type!=="response.image_generation_call.partial_image"&&(yield*m(),yield{event:"provider",provider:r,name:v.type,payload:v})}o||(yield{event:"message-start"});for(const[v]of i)f.has(v)||(yield*_(v));yield{event:"message-finish",reason:c,...l?{usage:l}:{},...d?{responseMetadata:d}:{}}}function JF(t,e){return e==="response.incomplete"?"length":t==="completed"?"stop":t==="incomplete"?"length":"stop"}var XF=class extends xy{constructor(t,e){super(by(t,e))}invocationParams(t){var i;let e;(t==null?void 0:t.strict)!==void 0&&(e=t.strict),e===void 0&&this.supportsStrictToolCalling!==void 0&&(e=this.supportsStrictToolCalling);const n={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,service_tier:this.service_tier,stream:this.streaming,previous_response_id:t==null?void 0:t.previous_response_id,truncation:t==null?void 0:t.truncation,include:t==null?void 0:t.include,tools:(i=t==null?void 0:t.tools)!=null&&i.length?this._reduceChatOpenAITools(t.tools,{stream:this.streaming,strict:e}):void 0,tool_choice:p5(t==null?void 0:t.tool_choice)?t==null?void 0:t.tool_choice:(()=>{const s=RT(t==null?void 0:t.tool_choice);if(typeof s=="object"&&"type"in s){if(s.type==="function")return{type:"function",name:s.function.name};if(s.type==="allowed_tools")return{type:"allowed_tools",mode:s.allowed_tools.mode,tools:s.allowed_tools.tools};if(s.type==="custom")return{type:"custom",name:s.custom.name}}})(),text:(()=>{if(t!=null&&t.text)return t.text;const s=this._getResponseFormat(t==null?void 0:t.response_format);return(s==null?void 0:s.type)==="json_schema"?s.json_schema.schema!=null?{format:{type:"json_schema",schema:s.json_schema.schema,description:s.json_schema.description,name:s.json_schema.name,strict:s.json_schema.strict},verbosity:t==null?void 0:t.verbosity}:void 0:{format:s,verbosity:t==null?void 0:t.verbosity}})(),parallel_tool_calls:t==null?void 0:t.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:(t==null?void 0:t.promptCacheKey)??this.promptCacheKey,prompt_cache_retention:(t==null?void 0:t.promptCacheRetention)??this.promptCacheRetention,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},r=this._getReasoningParams(t);return r!==void 0&&(n.reasoning=r),n}async _generate(t,e,n){var i,s;(i=e.signal)==null||i.throwIfAborted();const r=this.invocationParams(e);if(r.stream){const a=this._streamResponseChunks(t,e,n);let o;for await(const u of a)u.message.response_metadata={...u.generationInfo,...u.message.response_metadata},o=(o==null?void 0:o.concat(u))??u;return{generations:o?[o]:[],llmOutput:{estimatedTokenUsage:(s=o==null?void 0:o.message)==null?void 0:s.usage_metadata}}}else{const a=await this.completionWithRetry({input:ih({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),...r,stream:!1},{signal:e==null?void 0:e.signal,...e==null?void 0:e.options});return{generations:[{text:a.output_text,message:nI(a)}],llmOutput:{id:a.id,estimatedTokenUsage:a.usage?{promptTokens:a.usage.input_tokens,completionTokens:a.usage.output_tokens,totalTokens:a.usage.total_tokens}:void 0}}}}async*_streamChatModelEvents(t,e,n){const r=await this.completionWithRetry({...this.invocationParams(e),input:ih({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e),i=this.streamUsage??e.streamUsage;yield*GF(async function*(a,o){for await(const u of a){if(o!=null&&o.aborted)return;yield u}}(r,e.signal),{streamUsage:i??!0,provider:this.streamEventProvider})}get streamEventProvider(){return"openai"}async*_streamResponseChunks(t,e,n){var i;const r=await this.completionWithRetry({...this.invocationParams(e),input:ih({messages:t,zdrEnabled:this.zdrEnabled??!1,model:this.model}),stream:!0},e);try{for await(const s of r){if((i=e.signal)!=null&&i.aborted)return;const a=qF(s);a!=null&&(yield a,await(n==null?void 0:n.handleLLMNewToken(a.text||"",{prompt:e.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:a})))}}catch(s){throw Fo(s)}}async completionWithRetry(t,e){return this.caller.call(async()=>{var r,i;const n=this._getClientOptions(e);try{return((i=(r=t.text)==null?void 0:r.format)==null?void 0:i.type)==="json_schema"&&!t.stream?await this.client.responses.parse(t,n):await this.client.responses.create(t,n)}catch(s){throw Fo(s)}})}_reduceChatOpenAITools(t,e){const n=[];for(const r of t)if(gy(r))r.type==="image_generation"&&(e!=null&&e.stream)&&(r.partial_images=1),n.push(r);else if(Zc(r)){const i=r.metadata.customTool;n.push({type:"custom",name:i.name,description:i.description,format:i.format})}else if(WT(r)){const i={};for(const[s,a]of Object.entries(r))s!=="type"&&s!=="function"&&(i[s]=a);n.push({type:"function",name:r.function.name,parameters:r.function.parameters,description:r.function.description,strict:(e==null?void 0:e.strict)??null,...i})}else jT(r)&&n.push(v5(r));return n}},QF=class rI extends xy{constructor(n,r){const i=by(n,r);super(i);A(this,"useResponsesApi",!1);A(this,"responses");A(this,"completions");A(this,"fields");this.fields=i,this.useResponsesApi=(i==null?void 0:i.useResponsesApi)??!1,this.responses=(i==null?void 0:i.responses)??new XF(i),this.completions=(i==null?void 0:i.completions)??new ZF(i)}get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}get callKeys(){return[...super.callKeys,"useResponsesApi"]}_useResponsesApi(n){var a,o,u,l,c;const r=(a=n==null?void 0:n.tools)==null?void 0:a.some(gy),i=(n==null?void 0:n.previous_response_id)!=null||(n==null?void 0:n.text)!=null||(n==null?void 0:n.truncation)!=null||(n==null?void 0:n.include)!=null||((o=n==null?void 0:n.reasoning)==null?void 0:o.summary)!=null||((u=this.reasoning)==null?void 0:u.summary)!=null,s=((l=n==null?void 0:n.tools)==null?void 0:l.some(jT))||((c=n==null?void 0:n.tools)==null?void 0:c.some(Zc));return this.useResponsesApi||r||i||s||n5(this.model)}getLsParams(n){const r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.getLsParams(r):this.completions.getLsParams(r)}invocationParams(n){const r=this._combineCallOptions(n);return this._useResponsesApi(n)?this.responses.invocationParams(r):this.completions.invocationParams(r)}async _generate(n,r,i){return this._useResponsesApi(r)?this.responses._generate(n,r,i):this.completions._generate(n,r,i)}async*_streamChatModelEvents(n,r,i){if(this._useResponsesApi(r)){yield*this.responses._streamChatModelEvents(n,this._combineCallOptions(r),i);return}yield*this.completions._streamChatModelEvents(n,this._combineCallOptions(r),i)}async*_streamResponseChunks(n,r,i){if(this._useResponsesApi(r)){yield*this.responses._streamResponseChunks(n,this._combineCallOptions(r),i);return}yield*this.completions._streamResponseChunks(n,this._combineCallOptions(r),i)}withConfig(n){const r=new rI(this.fields);return r.defaultOptions={...this.defaultOptions,...n},r}};const YF=(t,e)=>t.reduce((n,r,i)=>{const s=Math.floor(i/e);return n[s]=(n[s]||[]).concat([r]),n},[]);var e9=class{constructor(t){A(this,"caller");this.caller=new Cd(t??{})}},t9=class extends e9{constructor(e){var i;const n={maxConcurrency:2,...e};super(n);A(this,"model","text-embedding-ada-002");A(this,"modelName");A(this,"batchSize",512);A(this,"stripNewLines",!0);A(this,"dimensions");A(this,"timeout");A(this,"organization");A(this,"encodingFormat");A(this,"client");A(this,"clientConfig");A(this,"apiKey");const r=(n==null?void 0:n.apiKey)??(n==null?void 0:n.openAIApiKey)??Jn("OPENAI_API_KEY");this.organization=((i=n==null?void 0:n.configuration)==null?void 0:i.organization)??Jn("OPENAI_ORGANIZATION"),this.model=(n==null?void 0:n.model)??(n==null?void 0:n.modelName)??this.model,this.modelName=this.model,this.batchSize=(n==null?void 0:n.batchSize)??this.batchSize,this.stripNewLines=(n==null?void 0:n.stripNewLines)??this.stripNewLines,this.timeout=n==null?void 0:n.timeout,this.dimensions=n==null?void 0:n.dimensions,this.encodingFormat=n==null?void 0:n.encodingFormat,this.clientConfig={apiKey:r,organization:this.organization,dangerouslyAllowBrowser:!0,...e==null?void 0:e.configuration}}async embedDocuments(e){const n=YF(this.stripNewLines?e.map(a=>a.replace(/\n/g," ")):e,this.batchSize),r=n.map(a=>{const o={model:this.model,input:a};return this.dimensions&&(o.dimensions=this.dimensions),this.encodingFormat&&(o.encoding_format=this.encodingFormat),this.embeddingWithRetry(o)}),i=await Promise.all(r),s=[];for(let a=0;a<i.length;a+=1){const o=n[a],{data:u}=i[a];for(let l=0;l<o.length;l+=1)s.push(u[l].embedding)}return s}async embedQuery(e){const n={model:this.model,input:this.stripNewLines?e.replace(/\n/g," "):e};this.dimensions&&(n.dimensions=this.dimensions),this.encodingFormat&&(n.encoding_format=this.encodingFormat);const{data:r}=await this.embeddingWithRetry(n);return r[0].embedding}async embeddingWithRetry(e){if(!this.client){const r=PT({baseURL:this.clientConfig.baseURL}),i={...this.clientConfig,baseURL:r,timeout:this.timeout,maxRetries:0};i.baseURL||delete i.baseURL,i.defaultHeaders=NT(i.defaultHeaders),this.client=new oe(i)}const n={};return this.caller.call(async()=>{try{return await this.client.embeddings.create(e,n)}catch(r){throw Fo(r)}})}};const n9=At({type:wn("screenshot")}),r9=At({type:wn("click"),x:xt(),y:xt(),button:yy(["left","right","wheel","back","forward"]).default("left")}),i9=At({type:wn("double_click"),x:xt(),y:xt(),button:yy(["left","right","wheel","back","forward"]).default("left")}),s9=At({type:wn("drag"),path:mu(At({x:xt(),y:xt()}))}),a9=At({type:wn("keypress"),keys:mu(Wt())}),o9=At({type:wn("move"),x:xt(),y:xt()}),u9=At({type:wn("scroll"),x:xt(),y:xt(),scroll_x:xt(),scroll_y:xt()}),l9=At({type:wn("type"),text:Wt()}),c9=At({type:wn("wait"),duration:xt().optional()}),d9=Dd([n9,r9,i9,s9,a9,o9,u9,l9,c9]);At({action:d9});const f9=At({type:wn("exec"),command:mu(Wt()),env:mU(Wt(),Wt()).optional(),working_directory:Wt().optional(),timeout_ms:xt().optional(),user:Wt().optional()});Dd([f9]);At({commands:mu(Wt()).describe("Array of shell commands to execute"),timeout_ms:xt().optional().describe("Optional timeout in milliseconds for the commands"),max_output_length:xt().optional().describe("Optional maximum number of characters to return from each command")});const h9=At({type:wn("create_file"),path:Wt(),diff:Wt()}),p9=At({type:wn("update_file"),path:Wt(),diff:Wt()}),m9=At({type:wn("delete_file"),path:Wt()});Dd([h9,p9,m9]);const g9=[{title:"Company Overview",text:"KimblyLabs is a technology-driven company specializing in Algorithmic Trading, Data Science, HRMS, and Hospitality Solutions. With over a decade of experience, we have developed business-critical applications for clients in India and abroad, including renowned brands. Founded by seasoned traders and software engineers, we understand the complexities of modern trading and strive to simplify them. Our team combines deep market knowledge with cutting-edge technology to deliver solutions that work. We have successfully served clients across various industries, building robust trading systems, analytical tools, and custom applications that drive business growth and operational efficiency."},{title:"Mission",text:"KimblyLabs mission is to democratize algorithmic trading, making professional-grade tools accessible to traders of all levels — whether you are a day trader, swing trader, or long-term investor. We provide advanced algorithmic trading solutions for modern traders, specializing in strategy backtesting, trading bots, market scanners and consultancy. We have 500+ happy clients, a 95% success rate, 50+ bots built, and over 10 years of experience."},{title:"Strategy Backtesting Service",text:"KimblyLabs offers Strategy Backtesting services. Test your trading strategies against historical data to validate performance before risking real capital. Features include: customized backtesting code, ultra fast backtesting, parameter optimization, and detailed analytics & metrics."},{title:"Trading Bot Creation Service",text:"KimblyLabs builds custom algorithmic trading bots designed to execute your strategies with precision. Features include: 24/7 automated trading, emotion-free execution, support for equities & derivatives, and commodities trading. Trading bots run continuously without human intervention."},{title:"Market Scanners Service",text:"KimblyLabs provides Market Scanners — advanced analytical tools to identify market trends, patterns, and potential trading opportunities. Features include: real-time scanning, pattern recognition, trend analysis, and data-driven decisions."},{title:"Consultancy Service",text:"KimblyLabs offers comprehensive algo trading consultancy including technology integration and custom strategy creation. Services include: technology integration, custom strategies, backtesting services, and cloud deployment."},{title:"Training Service",text:"KimblyLabs provides online & offline expert-led courses on strategy development, backtesting techniques, and programming. Topics covered: strategy development, backtesting techniques, programming skills, and deployment strategies."},{title:"Custom Indicators Service",text:"KimblyLabs creates TradingView indicators customized from Pine Script to Python to identify market patterns. Features include: Pine Script to Python conversion, pattern identification, custom indicators, and decision-making tools."},{title:"Industries Served",text:"KimblyLabs serves clients across various industries: Algorithmic Trading (custom trading bots and automated strategies), Artificial Intelligence (algorithmic trading & portfolio optimization), Data Science (advanced analytics and machine learning solutions), HRMS Solutions (human resource management systems), and Hospitality Solutions (custom applications for the hospitality industry)."},{title:"Key Features - High Accuracy and Multi-Platform",text:"KimblyLabs offers High Accuracy with advanced algorithms designed for precision trading in any market condition — features include precision trading, market adaptability, consistent performance, and risk optimization. Multi-Platform Integration provides seamless integration with major exchanges and trading platforms worldwide — supports major exchanges, multiple platforms, easy integration, and global reach."},{title:"Key Features - Real-Time Execution and Web UI",text:"KimblyLabs provides Real-Time Execution with a low-latency execution system to seize fleeting market opportunities instantly — features include low latency, instant execution, market opportunities, and speed advantage. Web Based UI offers fast and interactive bot management through an intuitive web-based interface — features include interactive UI, easy management, real-time monitoring, and intuitive design."},{title:"Key Features - Security and Analytics",text:"KimblyLabs implements Bank-Level Security with enterprise-grade encryption ensuring complete protection of your data and assets — features include bank-level encryption, data protection, asset security, and privacy assured. Advanced Analytics provides comprehensive visualizations and performance metrics for informed decision making — features include visual analytics, performance metrics, data insights, and smart decisions."},{title:"Key Features - Cloud and Notifications",text:"KimblyLabs offers Cloud Deployment with VPS-based execution ensuring 24/7 uptime and reliable trading operations — features include VPS deployment, 24/7 operation, high reliability, and cloud infrastructure. Mobile Notifications provide real-time alerts via Telegram and Pushover for instant updates — features include Telegram alerts, Pushover notifications, real-time updates, and mobile friendly interface."},{title:"Contact Information",text:"Contact KimblyLabs: Email: kimblylabs@gmail.com. Phone: +91 9873098686 (Mon-Fri 9am to 6pm IST). Address: UG-178, Palam Corporate Plaza, Gurugram (our development center). For support calls, you can also reach us at +91 7971442242. Schedule a free 30-minute consultation to discuss your algorithmic trading requirements."},{title:"Client Testimonials",text:'KimblyLabs client testimonials: Sai Krishna Boyina (Head BPA Digital Processes – Operations & Day Trader) said: "Thank you for a wonderful job done. Very clear communication, clarity, and professional service provided. Very prompt in bug fixing too." Jason Coleman (Trader, United States) said: "Great Work!" Leon Leon (Researcher, United States) said: "Great Experience, looking forward to work again!" Jarvis Jones (Trader, United States) said: "Keep Doing the Great Work!"'},{title:"Team and Expertise",text:"The KimblyLabs team consists of expert leadership led by seasoned traders and software engineers with over a decade of combined experience in financial markets and technology. The team has deep market expertise and understanding of market dynamics, trading strategies, and risk management across various asset classes and market conditions. Technical excellence with a cutting-edge technology stack ensures robust, scalable, and high-performance trading solutions."}];function y9(t,e){let n=0,r=0,i=0;for(let s=0;s<t.length;s++)n+=t[s]*e[s],r+=t[s]*t[s],i+=e[s]*e[s];return n/(Math.sqrt(r)*Math.sqrt(i))}let Sy=[],Ay=null,om=null,al=null;async function _9(){const t="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",e={dangerouslyAllowBrowser:!0};om=new t9({apiKey:t,modelName:"text-embedding-3-small",configuration:e}),Ay=new QF({apiKey:t,modelName:"gpt-3.5-turbo",temperature:.3,configuration:e});const n=g9.map(i=>`${i.title} ${i.text}`),r=await om.embedDocuments(n);Sy=n.map((i,s)=>({text:i,embedding:r[s]}))}async function v9(){if(!(Sy.length>0&&Ay))return al||(al=_9().catch(t=>{throw al=null,t})),al}async function w9(t,e=4){const n=await om.embedQuery(t);return Sy.map(i=>({text:i.text,score:y9(n,i.embedding)})).sort((i,s)=>s.score-i.score).slice(0,e).map(i=>i.text).join(` `)}async function b9(t,e=[]){await v9();const r=`You are a helpful customer support assistant for KimblyLabs, a technology company specializing in algorithmic trading solutions. Answer questions based on the following context: ${await w9(t)} Guidelines: - Be concise, friendly, and professional - For pricing or quotes, suggest contacting kimblylabs@gmail.com or calling +91 9873098686 - If unsure, recommend reaching out directly - Keep responses under 150 words`,i=e.map(a=>a.role==="user"?new Zo(a.content):new Cn(a.content));return(await Ay.invoke([new mp(r),...i,new Zo(t)])).content}const x9={id:0,role:"assistant",content:"Hi! I'm KimblyLabs support assistant. Ask me anything about our algorithmic trading services, features, pricing, or how to get started."};function k9(){const[t,e]=je.useState(!1),[n,r]=je.useState([x9]),[i,s]=je.useState(""),[a,o]=je.useState(!1),[u,l]=je.useState(!1),[c,d]=je.useState(null),f=je.useRef(null),h=je.useRef(null),m=je.useRef(1);je.useEffect(()=>{var v,y;t&&((v=f.current)==null||v.scrollIntoView({behavior:"smooth"}),(y=h.current)==null||y.focus())},[n,t]);const _=async v=>{v.preventDefault();const y=i.trim();if(!y||a)return;s(""),d(null);const p={id:m.current++,role:"user",content:y};r(b=>[...b,p]),n.length===1&&l(!0),o(!0);try{const b=n.slice(1).map(T=>({role:T.role,content:T.content})),E=await b9(y,b);r(T=>[...T,{id:m.current++,role:"assistant",content:E}])}catch(b){const E=b instanceof Error?b.message:"Something went wrong. Please try again.";d(E)}finally{o(!1),l(!1)}};return w.jsxs("div",{className:"fixed bottom-6 right-6 z-50 flex flex-col items-end",children:[t&&w.jsxs("div",{className:"mb-4 bg-white rounded-2xl shadow-2xl border border-gray-100 w-80 flex flex-col overflow-hidden",style:{height:"480px"},children:[w.jsxs("div",{className:"bg-indigo-600 px-4 py-3 flex items-center justify-between flex-shrink-0",children:[w.jsxs("div",{className:"flex items-center gap-2",children:[w.jsx("div",{className:"w-8 h-8 bg-white/20 rounded-full flex items-center justify-center",children:w.jsx(vl,{size:16,className:"text-white"})}),w.jsxs("div",{children:[w.jsx("p",{className:"text-white font-semibold text-sm",children:"KimblyLabs Support"}),w.jsx("p",{className:"text-indigo-200 text-xs",children:"AI-powered · Typically replies instantly"})]})]}),w.jsx("button",{onClick:()=>e(!1),className:"text-white/70 hover:text-white transition-colors","aria-label":"Close chat",children:w.jsx(lc,{size:18})})]}),w.jsxs("div",{className:"flex-1 overflow-y-auto px-4 py-3 space-y-3",children:[n.map(v=>w.jsxs("div",{className:`flex items-start gap-2 ${v.role==="user"?"flex-row-reverse":""}`,children:[w.jsx("div",{className:`w-7 h-7 rounded-full flex-shrink-0 flex items-center justify-center ${v.role==="assistant"?"bg-indigo-100":"bg-gray-200"}`,children:v.role==="assistant"?w.jsx(vl,{size:14,className:"text-indigo-600"}):w.jsx(s1,{size:14,className:"text-gray-600"})}),w.jsx("div",{className:`max-w-[210px] px-3 py-2 rounded-2xl text-sm leading-relaxed ${v.role==="assistant"?"bg-gray-100 text-gray-800 rounded-tl-sm":"bg-indigo-600 text-white rounded-tr-sm"}`,children:v.content})]},v.id)),a&&w.jsxs("div",{className:"flex items-start gap-2",children:[w.jsx("div",{className:"w-7 h-7 rounded-full bg-indigo-100 flex items-center justify-center flex-shrink-0",children:w.jsx(vl,{size:14,className:"text-indigo-600"})}),w.jsx("div",{className:"bg-gray-100 px-3 py-2 rounded-2xl rounded-tl-sm",children:u?w.jsxs("span",{className:"text-xs text-gray-500 flex items-center gap-1",children:[w.jsx(qC,{size:12,className:"animate-spin"})," Initializing AI…"]}):w.jsxs("span",{className:"flex gap-1 py-1",children:[w.jsx("span",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce",style:{animationDelay:"0ms"}}),w.jsx("span",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce",style:{animationDelay:"150ms"}}),w.jsx("span",{className:"w-1.5 h-1.5 bg-gray-400 rounded-full animate-bounce",style:{animationDelay:"300ms"}})]})})]}),c&&w.jsx("div",{className:"bg-red-50 border border-red-200 text-red-600 text-xs rounded-xl px-3 py-2",children:c}),w.jsx("div",{ref:f})]}),w.jsxs("form",{onSubmit:_,className:"border-t border-gray-100 px-3 py-3 flex gap-2 flex-shrink-0",children:[w.jsx("input",{ref:h,type:"text",value:i,onChange:v=>s(v.target.value),placeholder:"Ask about our services…",disabled:a,className:"flex-1 text-sm border border-gray-200 rounded-xl px-3 py-2 focus:outline-none focus:border-indigo-400 focus:ring-1 focus:ring-indigo-200 disabled:opacity-50 transition-colors"}),w.jsx("button",{type:"submit",disabled:!i.trim()||a,className:"w-9 h-9 bg-indigo-600 hover:bg-indigo-700 disabled:bg-gray-200 rounded-xl flex items-center justify-center transition-colors flex-shrink-0","aria-label":"Send message",children:w.jsx(QC,{size:15,className:a?"text-gray-400":"text-white"})})]})]}),w.jsx("button",{onClick:()=>e(!t),className:`w-14 h-14 rounded-full shadow-lg flex items-center justify-center transition-all duration-200 ${t?"bg-gray-600 hover:bg-gray-700":"bg-indigo-600 hover:bg-indigo-700 hover:scale-110"}`,"aria-label":"Open chat support",title:"Chat Support",children:t?w.jsx(lc,{size:22,className:"text-white"}):w.jsx(GC,{size:22,className:"text-white"})})]})}function S9(){return w.jsxs(w.Fragment,{children:[w.jsx(hP,{}),w.jsx(k9,{})]})}function A9(){return w.jsxs("div",{className:"min-h-screen",children:[w.jsx(rP,{}),w.jsx(iP,{}),w.jsx(sP,{}),w.jsx(aP,{}),w.jsx(oP,{}),w.jsx(uP,{}),w.jsx(lP,{}),w.jsx(cP,{}),w.jsx(S9,{})]})}t1(document.getElementById("root")).render(w.jsx(je.StrictMode,{children:w.jsx(A9,{})}));
修改文件时间
将文件时间修改为当前时间的前一年
删除文件