scordi-extension 1.14.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +243 -0
- package/dist/.vite/manifest.json +67 -0
- package/dist/assets/DataExtractBlock-B7AuVonx.js +6 -0
- package/dist/assets/index-B9PKMhAi.js +6 -0
- package/dist/assets/index-CMlx_xZE.css +1 -0
- package/dist/assets/index-CZjAbH8z.js +1 -0
- package/dist/assets/index-DkFIvNAm.css +1 -0
- package/dist/assets/index-r5QRyJ4m.js +1 -0
- package/dist/assets/index.html-BIbPySIb.js +74 -0
- package/dist/assets/index.html-cr-_Qdxq.js +49 -0
- package/dist/assets/index.ts-BqxJYCmp.js +160 -0
- package/dist/assets/internal-messages-Drf0Gb9U.js +1 -0
- package/dist/assets/loading-page-1924caaa.js +51 -0
- package/dist/assets/main.tsx-BEyI95mZ.js +2 -0
- package/dist/assets/main.tsx-BKzdlur-.js +2 -0
- package/dist/assets/main.tsx-loader-BYP9L25W.js +13 -0
- package/dist/assets/main.tsx-loader-FYb0LhDu.js +13 -0
- package/dist/assets/schemas-C8r0jYHO.js +21 -0
- package/dist/blocks/AiParseDataBlock.d.ts +183 -0
- package/dist/blocks/AiParseDataBlock.d.ts.map +1 -0
- package/dist/blocks/ClearValueFormBlock.d.ts +49 -0
- package/dist/blocks/ClearValueFormBlock.d.ts.map +1 -0
- package/dist/blocks/DataExtractBlock.d.ts +23 -0
- package/dist/blocks/DataExtractBlock.d.ts.map +1 -0
- package/dist/blocks/ElementExistsBlock.d.ts +45 -0
- package/dist/blocks/ElementExistsBlock.d.ts.map +1 -0
- package/dist/blocks/EventClickBlock.d.ts +67 -0
- package/dist/blocks/EventClickBlock.d.ts.map +1 -0
- package/dist/blocks/FetchApiBlock.d.ts +49 -0
- package/dist/blocks/FetchApiBlock.d.ts.map +1 -0
- package/dist/blocks/GetAttributeValueBlock.d.ts +49 -0
- package/dist/blocks/GetAttributeValueBlock.d.ts.map +1 -0
- package/dist/blocks/GetElementDataBlock.d.ts +88 -0
- package/dist/blocks/GetElementDataBlock.d.ts.map +1 -0
- package/dist/blocks/GetTextBlock.d.ts +85 -0
- package/dist/blocks/GetTextBlock.d.ts.map +1 -0
- package/dist/blocks/GetValueFormBlock.d.ts +49 -0
- package/dist/blocks/GetValueFormBlock.d.ts.map +1 -0
- package/dist/blocks/KeypressBlock.d.ts +31 -0
- package/dist/blocks/KeypressBlock.d.ts.map +1 -0
- package/dist/blocks/SaveAssetsBlock.d.ts +45 -0
- package/dist/blocks/SaveAssetsBlock.d.ts.map +1 -0
- package/dist/blocks/ScrollBlock.d.ts +65 -0
- package/dist/blocks/ScrollBlock.d.ts.map +1 -0
- package/dist/blocks/SetValueFormBlock.d.ts +53 -0
- package/dist/blocks/SetValueFormBlock.d.ts.map +1 -0
- package/dist/blocks/WaitBlock.d.ts +19 -0
- package/dist/blocks/WaitBlock.d.ts.map +1 -0
- package/dist/blocks/index.d.ts +667 -0
- package/dist/blocks/index.d.ts.map +1 -0
- package/dist/blocks/types.d.ts +53 -0
- package/dist/blocks/types.d.ts.map +1 -0
- package/dist/content/elements/finders/CssSelector.d.ts +8 -0
- package/dist/content/elements/finders/CssSelector.d.ts.map +1 -0
- package/dist/content/elements/finders/ElementSelector.d.ts +6 -0
- package/dist/content/elements/finders/ElementSelector.d.ts.map +1 -0
- package/dist/content/elements/finders/IframeSelector.d.ts +6 -0
- package/dist/content/elements/finders/IframeSelector.d.ts.map +1 -0
- package/dist/content/elements/finders/ShadowDOMSelector.d.ts +20 -0
- package/dist/content/elements/finders/ShadowDOMSelector.d.ts.map +1 -0
- package/dist/content/elements/finders/XPathFinder.d.ts +6 -0
- package/dist/content/elements/finders/XPathFinder.d.ts.map +1 -0
- package/dist/content/elements/index.d.ts +13 -0
- package/dist/content/elements/index.d.ts.map +1 -0
- package/dist/content/elements/utils/CSSSelectorGenerator.d.ts +23 -0
- package/dist/content/elements/utils/CSSSelectorGenerator.d.ts.map +1 -0
- package/dist/content/elements/utils/XPathGenerator.d.ts +25 -0
- package/dist/content/elements/utils/XPathGenerator.d.ts.map +1 -0
- package/dist/logo.png +0 -0
- package/dist/manifest.json +58 -0
- package/dist/public/logo.png +0 -0
- package/dist/sdk/EightGClient.d.ts +18 -0
- package/dist/sdk/EightGClient.d.ts.map +1 -0
- package/dist/sdk/errors.d.ts +10 -0
- package/dist/sdk/errors.d.ts.map +1 -0
- package/dist/sdk/index.d.ts +4 -0
- package/dist/sdk/index.d.ts.map +1 -0
- package/dist/sdk/index.js +7904 -0
- package/dist/sdk/logo.png +0 -0
- package/dist/sdk/types.d.ts +109 -0
- package/dist/sdk/types.d.ts.map +1 -0
- package/dist/service-worker-loader.js +1 -0
- package/dist/src/blocks/AiParseDataBlock.ts.js +101 -0
- package/dist/src/blocks/ClearValueFormBlock.ts.js +55 -0
- package/dist/src/blocks/DataExtractBlock.ts.js +28 -0
- package/dist/src/blocks/ElementExistsBlock.ts.js +26 -0
- package/dist/src/blocks/EventClickBlock.ts.js +143 -0
- package/dist/src/blocks/FetchApiBlock.ts.js +50 -0
- package/dist/src/blocks/GetAttributeValueBlock.ts.js +33 -0
- package/dist/src/blocks/GetElementDataBlock.ts.js +114 -0
- package/dist/src/blocks/GetTextBlock.ts.js +152 -0
- package/dist/src/blocks/GetValueFormBlock.ts.js +52 -0
- package/dist/src/blocks/KeypressBlock.ts.js +89 -0
- package/dist/src/blocks/SaveAssetsBlock.ts.js +35 -0
- package/dist/src/blocks/ScrollBlock.ts.js +111 -0
- package/dist/src/blocks/SetValueFormBlock.ts.js +56 -0
- package/dist/src/blocks/WaitBlock.ts.js +24 -0
- package/dist/src/blocks/index.ts.js +163 -0
- package/dist/src/blocks/types.ts.js +11 -0
- package/dist/src/content/elements/finders/CssSelector.ts.js +51 -0
- package/dist/src/content/elements/finders/ElementSelector.ts.js +20 -0
- package/dist/src/content/elements/finders/IframeSelector.ts.js +32 -0
- package/dist/src/content/elements/finders/ShadowDOMSelector.ts.js +38 -0
- package/dist/src/content/elements/finders/XPathFinder.ts.js +32 -0
- package/dist/src/content/elements/index.ts.js +26 -0
- package/dist/src/content/elements/utils/CSSSelectorGenerator.ts.js +72 -0
- package/dist/src/content/elements/utils/XPathGenerator.ts.js +62 -0
- package/dist/src/content/handler/ExternalMessageHandler.ts.js +78 -0
- package/dist/src/content/handler/InternalMessageHandler.ts.js +18 -0
- package/dist/src/content/kernel/MessageKernel.ts.js +83 -0
- package/dist/src/content/main.tsx-loader.js +22 -0
- package/dist/src/content/main.tsx.js +13 -0
- package/dist/src/content/utils/index.ts.js +1 -0
- package/dist/src/content/utils/synchronizedLock.ts.js +35 -0
- package/dist/src/popup/index.html +11 -0
- package/dist/src/types/internal-messages.ts.js +15 -0
- package/dist/types/external-messages.d.ts +29 -0
- package/dist/types/external-messages.d.ts.map +1 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/index.d.ts.map +1 -0
- package/dist/types/internal-messages.d.ts +58 -0
- package/dist/types/internal-messages.d.ts.map +1 -0
- package/dist/vendor/.vite-deps-chunk-PR4QN5HX.js__v--ba9031c0.js +42 -0
- package/dist/vendor/.vite-deps-jsonata.js__v--ba9031c0.js +5761 -0
- package/dist/vendor/.vite-deps-zod.js__v--ba9031c0.js +12651 -0
- package/dist/vendor/crx-client-port.js +66 -0
- package/dist/vendor/crx-client-preamble.js +4 -0
- package/dist/vendor/react-refresh.js +670 -0
- package/dist/vendor/vite-client.js +1098 -0
- package/dist/vendor/vite-dist-client-env.mjs.js +19 -0
- package/dist/vendor/webcomponents-custom-elements.js +47 -0
- package/package.json +70 -0
|
@@ -0,0 +1,160 @@
|
|
|
1
|
+
import{i as Sf,b as Ef,c as Of,d as xf}from"./internal-messages-Drf0Gb9U.js";import{g as sn,o as Vs,a as Jo,b as mn,c as kf,l as Tf,u as Af,n as If,_ as Rf,s as Pf}from"./schemas-C8r0jYHO.js";class Cf{activeTabs=new Map;async createTab(e,t=!1,r=2e3){const s=await chrome.tabs.create({url:e,active:t});if(!s.id)throw new Error("Failed to create new tab");return this.activeTabs.set(s.id,{url:e,createdAt:Date.now()}),await this.waitForTabLoad(s.id),await new Promise(a=>setTimeout(a,r)),s}async closeTab(e){await chrome.tabs.remove(e),this.activeTabs.delete(e)}async waitForTabLoad(e,t=3e4){return new Promise((r,s)=>{const a=setTimeout(()=>{chrome.tabs.onUpdated.removeListener(i),s(new Error("Tab load timeout"))},t),i=(o,u)=>{o===e&&u.status==="complete"&&(clearTimeout(a),chrome.tabs.onUpdated.removeListener(i),console.log("[8G TabManager] Tab loaded successfully:",e),r())};chrome.tabs.onUpdated.addListener(i)})}async executeBlock(e,t){return new Promise((r,s)=>{const a={isBlock:!0,type:"EXECUTE_BLOCK",data:e};chrome.tabs.sendMessage(t,a,i=>{chrome.runtime.lastError?(console.log("Error sending message:",chrome.runtime.lastError),s(new Error(chrome.runtime.lastError.message||"Communication error"))):Sf(i)?(console.log("Content script error:",i.message),s(new Error(i.message))):(console.log("Received response from content script:",i),r(i||{data:null}))})})}}function B(n,e,t,r,s){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function w(n,e,t,r){if(t==="a"&&!r)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?r:t==="a"?r.call(n):r?r.value:e.get(n)}let Bl=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return Bl=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,r=>(+r^t()&15>>+r/4).toString(16))};function Si(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const Ei=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class F extends Error{}class ke extends F{constructor(e,t,r,s){super(`${ke.makeMessage(e,t,r)}`),this.status=e,this.headers=s,this.requestID=s?.get("x-request-id"),this.error=t;const a=t;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,r){const s=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):r;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,t,r,s){if(!e||!s)return new Ss({message:r,cause:Ei(t)});const a=t?.error;return e===400?new zl(e,a,r,s):e===401?new ql(e,a,r,s):e===403?new Zl(e,a,r,s):e===404?new Hl(e,a,r,s):e===409?new Gl(e,a,r,s):e===422?new Jl(e,a,r,s):e===429?new Wl(e,a,r,s):e>=500?new Vl(e,a,r,s):new ke(e,a,r,s)}}class qe extends ke{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ss extends ke{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Es extends Ss{constructor({message:e}={}){super({message:e??"Request timed out."})}}class zl extends ke{}class ql extends ke{}class Zl extends ke{}class Hl extends ke{}class Gl extends ke{}class Jl extends ke{}class Wl extends ke{}class Vl extends ke{}class Kl extends F{constructor(){super("Could not parse response content as the length limit was reached")}}class Xl extends F{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Rr extends Error{constructor(e){super(e)}}const $f=/^[a-z][a-z0-9+.-]*:/i,Nf=n=>$f.test(n);let Le=n=>(Le=Array.isArray,Le(n)),Wo=Le;function jf(n){return typeof n!="object"?{}:n??{}}function Lf(n){if(!n)return!0;for(const e in n)return!1;return!0}function Mf(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Ks(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const Uf=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new F(`${n} must be an integer`);if(e<0)throw new F(`${n} must be a positive integer`);return e},Df=n=>{try{return JSON.parse(n)}catch{return}},an=n=>new Promise(e=>setTimeout(e,n)),nr="5.12.2",Ff=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Bf(){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 zf=()=>{const n=Bf();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nr,"X-Stainless-OS":Ko(Deno.build.os),"X-Stainless-Arch":Vo(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nr,"X-Stainless-OS":Ko(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Vo(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=qf();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nr,"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":nr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function qf(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const r=t.exec(navigator.userAgent);if(r){const s=r[1]||0,a=r[2]||0,i=r[3]||0;return{browser:e,version:`${s}.${a}.${i}`}}}return null}const Vo=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",Ko=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let Xo;const Zf=()=>Xo??(Xo=zf());function Hf(){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 Ql(...n){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(...n)}function Yl(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Ql({start(){},async pull(t){const{done:r,value:s}=await e.next();r?t.close():t.enqueue(s)},async cancel(){await e.return?.()}})}function ed(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Gf(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const Jf=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),td="RFC3986",rd=n=>String(n),Qo={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:rd},Wf="RFC1738";let Oi=(n,e)=>(Oi=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Oi(n,e));const ot=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),Xs=1024,Vf=(n,e,t,r,s)=>{if(n.length===0)return n;let a=n;if(typeof n=="symbol"?a=Symbol.prototype.toString.call(n):typeof n!="string"&&(a=String(n)),t==="iso-8859-1")return escape(a).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let i="";for(let o=0;o<a.length;o+=Xs){const u=a.length>=Xs?a.slice(o,o+Xs):a,c=[];for(let l=0;l<u.length;++l){let d=u.charCodeAt(l);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||s===Wf&&(d===40||d===41)){c[c.length]=u.charAt(l);continue}if(d<128){c[c.length]=ot[d];continue}if(d<2048){c[c.length]=ot[192|d>>6]+ot[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=ot[224|d>>12]+ot[128|d>>6&63]+ot[128|d&63];continue}l+=1,d=65536+((d&1023)<<10|u.charCodeAt(l)&1023),c[c.length]=ot[240|d>>18]+ot[128|d>>12&63]+ot[128|d>>6&63]+ot[128|d&63]}i+=c.join("")}return i};function Kf(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function Yo(n,e){if(Le(n)){const t=[];for(let r=0;r<n.length;r+=1)t.push(e(n[r]));return t}return e(n)}const nd={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},sd=function(n,e){Array.prototype.push.apply(n,Le(e)?e:[e])};let eu;const ge={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Vf,encodeValuesOnly:!1,format:td,formatter:rd,indices:!1,serializeDate(n){return(eu??(eu=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Xf(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const Qs={};function ad(n,e,t,r,s,a,i,o,u,c,l,d,h,f,p,m,g,y){let _=n,b=y,v=0,S=!1;for(;(b=b.get(Qs))!==void 0&&!S;){const Q=b.get(n);if(v+=1,typeof Q<"u"){if(Q===v)throw new RangeError("Cyclic object value");S=!0}typeof b.get(Qs)>"u"&&(v=0)}if(typeof c=="function"?_=c(e,_):_ instanceof Date?_=h?.(_):t==="comma"&&Le(_)&&(_=Yo(_,function(Q){return Q instanceof Date?h?.(Q):Q})),_===null){if(a)return u&&!m?u(e,ge.encoder,g,"key",f):e;_=""}if(Xf(_)||Kf(_)){if(u){const Q=m?e:u(e,ge.encoder,g,"key",f);return[p?.(Q)+"="+p?.(u(_,ge.encoder,g,"value",f))]}return[p?.(e)+"="+p?.(String(_))]}const R=[];if(typeof _>"u")return R;let P;if(t==="comma"&&Le(_))m&&u&&(_=Yo(_,u)),P=[{value:_.length>0?_.join(",")||null:void 0}];else if(Le(c))P=c;else{const Q=Object.keys(_);P=l?Q.sort(l):Q}const x=o?String(e).replace(/\./g,"%2E"):String(e),K=r&&Le(_)&&_.length===1?x+"[]":x;if(s&&Le(_)&&_.length===0)return K+"[]";for(let Q=0;Q<P.length;++Q){const ae=P[Q],Ve=typeof ae=="object"&&typeof ae.value<"u"?ae.value:_[ae];if(i&&Ve===null)continue;const Ut=d&&o?ae.replace(/\./g,"%2E"):ae,I=Le(_)?typeof t=="function"?t(K,Ut):K:K+(d?"."+Ut:"["+Ut+"]");y.set(n,v);const k=new WeakMap;k.set(Qs,y),sd(R,ad(Ve,I,t,r,s,a,i,o,t==="comma"&&m&&Le(_)?null:u,c,l,d,h,f,p,m,g,k))}return R}function Qf(n=ge){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||ge.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=td;if(typeof n.format<"u"){if(!Oi(Qo,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const r=Qo[t];let s=ge.filter;(typeof n.filter=="function"||Le(n.filter))&&(s=n.filter);let a;if(n.arrayFormat&&n.arrayFormat in nd?a=n.arrayFormat:"indices"in n?a=n.indices?"indices":"repeat":a=ge.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const i=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:ge.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:ge.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:ge.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:ge.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?ge.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:ge.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:ge.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:ge.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:ge.encodeValuesOnly,filter:s,format:t,formatter:r,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:ge.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:ge.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:ge.strictNullHandling}}function Yf(n,e={}){let t=n;const r=Qf(e);let s,a;typeof r.filter=="function"?(a=r.filter,t=a("",t)):Le(r.filter)&&(a=r.filter,s=a);const i=[];if(typeof t!="object"||t===null)return"";const o=nd[r.arrayFormat],u=o==="comma"&&r.commaRoundTrip;s||(s=Object.keys(t)),r.sort&&s.sort(r.sort);const c=new WeakMap;for(let h=0;h<s.length;++h){const f=s[h];r.skipNulls&&t[f]===null||sd(i,ad(t[f],f,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,c))}const l=i.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&"),l.length>0?d+l:""}function ep(n){let e=0;for(const s of n)e+=s.length;const t=new Uint8Array(e);let r=0;for(const s of n)t.set(s,r),r+=s.length;return t}let tu;function no(n){let e;return(tu??(e=new globalThis.TextEncoder,tu=e.encode.bind(e)))(n)}let ru;function nu(n){let e;return(ru??(e=new globalThis.TextDecoder,ru=e.decode.bind(e)))(n)}var De,Fe;class Os{constructor(){De.set(this,void 0),Fe.set(this,void 0),B(this,De,new Uint8Array),B(this,Fe,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?no(e):e;B(this,De,ep([w(this,De,"f"),t]));const r=[];let s;for(;(s=tp(w(this,De,"f"),w(this,Fe,"f")))!=null;){if(s.carriage&&w(this,Fe,"f")==null){B(this,Fe,s.index);continue}if(w(this,Fe,"f")!=null&&(s.index!==w(this,Fe,"f")+1||s.carriage)){r.push(nu(w(this,De,"f").subarray(0,w(this,Fe,"f")-1))),B(this,De,w(this,De,"f").subarray(w(this,Fe,"f"))),B(this,Fe,null);continue}const a=w(this,Fe,"f")!==null?s.preceding-1:s.preceding,i=nu(w(this,De,"f").subarray(0,a));r.push(i),B(this,De,w(this,De,"f").subarray(s.index)),B(this,Fe,null)}return r}flush(){return w(this,De,"f").length?this.decode(`
|
|
2
|
+
`):[]}}De=new WeakMap,Fe=new WeakMap;Os.NEWLINE_CHARS=new Set([`
|
|
3
|
+
`,"\r"]);Os.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function tp(n,e){for(let s=e??0;s<n.length;s++){if(n[s]===10)return{preceding:s,index:s+1,carriage:!1};if(n[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function rp(n){for(let r=0;r<n.length-1;r++){if(n[r]===10&&n[r+1]===10||n[r]===13&&n[r+1]===13)return r+2;if(n[r]===13&&n[r+1]===10&&r+3<n.length&&n[r+2]===13&&n[r+3]===10)return r+4}return-1}const Kn={off:0,error:200,warn:300,info:400,debug:500},su=(n,e,t)=>{if(n){if(Mf(Kn,n))return n;Oe(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Kn))}`)}};function Pr(){}function gn(n,e,t){return!e||Kn[n]>Kn[t]?Pr:e[n].bind(e)}const np={error:Pr,warn:Pr,info:Pr,debug:Pr};let au=new WeakMap;function Oe(n){const e=n.logger,t=n.logLevel??"off";if(!e)return np;const r=au.get(e);if(r&&r[0]===t)return r[1];const s={error:gn("error",e,t),warn:gn("warn",e,t),info:gn("info",e,t),debug:gn("debug",e,t)};return au.set(e,[t,s]),s}const Ft=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var xr;class lt{constructor(e,t,r){this.iterator=e,xr.set(this,void 0),this.controller=t,B(this,xr,r)}static fromSSEResponse(e,t,r){let s=!1;const a=r?Oe(r):console;async function*i(){if(s)throw new F("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const u of sp(e,t))if(!o){if(u.data.startsWith("[DONE]")){o=!0;continue}if(u.event===null||!u.event.startsWith("thread.")){let c;try{c=JSON.parse(u.data)}catch(l){throw a.error("Could not parse message into JSON:",u.data),a.error("From chunk:",u.raw),l}if(c&&c.error)throw new ke(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(u.data)}catch(l){throw console.error("Could not parse message into JSON:",u.data),console.error("From chunk:",u.raw),l}if(u.event=="error")throw new ke(void 0,c.error,c.message,void 0);yield{event:u.event,data:c}}}o=!0}catch(u){if(Si(u))return;throw u}finally{o||t.abort()}}return new lt(i,t,r)}static fromReadableStream(e,t,r){let s=!1;async function*a(){const o=new Os,u=ed(e);for await(const c of u)for(const l of o.decode(c))yield l;for(const c of o.flush())yield c}async function*i(){if(s)throw new F("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let o=!1;try{for await(const u of a())o||u&&(yield JSON.parse(u));o=!0}catch(u){if(Si(u))return;throw u}finally{o||t.abort()}}return new lt(i,t,r)}[(xr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],r=this.iterator(),s=a=>({next:()=>{if(a.length===0){const i=r.next();e.push(i),t.push(i)}return a.shift()}});return[new lt(()=>s(e),this.controller,w(this,xr,"f")),new lt(()=>s(t),this.controller,w(this,xr,"f"))]}toReadableStream(){const e=this;let t;return Ql({async start(){t=e[Symbol.asyncIterator]()},async pull(r){try{const{value:s,done:a}=await t.next();if(a)return r.close();const i=no(JSON.stringify(s)+`
|
|
4
|
+
`);r.enqueue(i)}catch(s){r.error(s)}},async cancel(){await t.return?.()}})}}async function*sp(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new F("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 F("Attempted to iterate over a response with no body");const t=new ip,r=new Os,s=ed(n.body);for await(const a of ap(s))for(const i of r.decode(a)){const o=t.decode(i);o&&(yield o)}for(const a of r.flush()){const i=t.decode(a);i&&(yield i)}}async function*ap(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const r=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?no(t):t;let s=new Uint8Array(e.length+r.length);s.set(e),s.set(r,e.length),e=s;let a;for(;(a=rp(e))!==-1;)yield e.slice(0,a),e=e.slice(a)}e.length>0&&(yield e)}class ip{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const a={event:this.event,data:this.data.join(`
|
|
5
|
+
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],a}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,r,s]=op(e,":");return s.startsWith(" ")&&(s=s.substring(1)),t==="event"?this.event=s:t==="data"&&this.data.push(s),null}}function op(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function id(n,e){const{response:t,requestLogID:r,retryOfRequestLogID:s,startTime:a}=e,i=await(async()=>{if(e.options.stream)return Oe(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):lt.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const u=t.headers.get("content-type")?.split(";")[0]?.trim();if(u?.includes("application/json")||u?.endsWith("+json")){const d=await t.json();return od(d,t)}return await t.text()})();return Oe(n).debug(`[${r}] response parsed`,Ft({retryOfRequestLogID:s,url:t.url,status:t.status,body:i,durationMs:Date.now()-a})),i}function od(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Cr;class xs extends Promise{constructor(e,t,r=id){super(s=>{s(null)}),this.responsePromise=t,this.parseResponse=r,Cr.set(this,void 0),B(this,Cr,e)}_thenUnwrap(e){return new xs(w(this,Cr,"f"),this.responsePromise,async(t,r)=>od(e(await this.parseResponse(t,r),r),r.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(w(this,Cr,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Cr=new WeakMap;var yn;class ud{constructor(e,t,r,s){yn.set(this,void 0),B(this,yn,e),this.options=s,this.response=t,this.body=r}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new F("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await w(this,yn,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(yn=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class up extends xs{constructor(e,t,r){super(e,t,async(s,a)=>new r(s,a.response,await id(s,a),a.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class ks extends ud{constructor(e,t,r,s){super(e,t,r,s),this.data=r.data||[],this.object=r.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class he extends ud{constructor(e,t,r,s){super(e,t,r,s),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(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...jf(this.options.query),after:t}}:null}}const cd=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function zr(n,e,t){return cd(),new File(n,e??"unknown_file",t)}function Un(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const ld=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Jt=async(n,e)=>({...n,body:await lp(n.body,e)}),iu=new WeakMap;function cp(n){const e=typeof n=="function"?n:n.fetch,t=iu.get(e);if(t)return t;const r=(async()=>{try{const s="Response"in e?e.Response:(await e("data:,")).constructor,a=new FormData;return a.toString()!==await new s(a).text()}catch{return!0}})();return iu.set(e,r),r}const lp=async(n,e)=>{if(!await cp(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([r,s])=>xi(t,r,s))),t},dp=n=>n instanceof Blob&&"name"in n,xi=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,zr([await t.blob()],Un(t)));else if(ld(t))n.append(e,zr([await new Response(Yl(t)).blob()],Un(t)));else if(dp(t))n.append(e,t,Un(t));else if(Array.isArray(t))await Promise.all(t.map(r=>xi(n,e+"[]",r)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([r,s])=>xi(n,`${e}[${r}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},dd=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",hp=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&dd(n),fp=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function pp(n,e,t){if(cd(),n=await n,hp(n))return n instanceof File?n:zr([await n.arrayBuffer()],n.name);if(fp(n)){const s=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),zr(await ki(s),e,t)}const r=await ki(n);if(e||(e=Un(n)),!t?.type){const s=r.find(a=>typeof a=="object"&&"type"in a&&a.type);typeof s=="string"&&(t={...t,type:s})}return zr(r,e,t)}async function ki(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(dd(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(ld(n))for await(const t of n)e.push(...await ki(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${mp(n)}`)}return e}function mp(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class z{constructor(e){this._client=e}}function hd(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const ou=Object.freeze(Object.create(null)),gp=(n=hd)=>function(t,...r){if(t.length===1)return t[0];let s=!1;const a=[],i=t.reduce((l,d,h)=>{/[?#]/.test(d)&&(s=!0);const f=r[h];let p=(s?encodeURIComponent:n)(""+f);return h!==r.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??ou)??ou)?.toString)&&(p=f+"",a.push({start:l.length+d.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),l+d+(h===r.length?"":p)},""),o=i.split(/[?#]/,1)[0],u=new RegExp("(?<=^|\\/)(?:\\.|%2e){1,2}(?=\\/|$)","gi");let c;for(;(c=u.exec(o))!==null;)a.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(a.sort((l,d)=>l.start-d.start),a.length>0){let l=0;const d=a.reduce((h,f)=>{const p=" ".repeat(f.start-l),m="^".repeat(f.length);return l=f.start+f.length,h+p+m},"");throw new F(`Path parameters result in path with invalid segments:
|
|
6
|
+
${a.map(h=>h.error).join(`
|
|
7
|
+
`)}
|
|
8
|
+
${i}
|
|
9
|
+
${d}`)}return i},T=gp(hd);let fd=class extends z{list(e,t={},r){return this._client.getAPIList(T`/chat/completions/${e}/messages`,he,{query:t,...r})}};function Xn(n){return n!==void 0&&"function"in n&&n.function!==void 0}function yp(n,e){const t={...n};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function so(n){return n?.$brand==="auto-parseable-response-format"}function on(n){return n?.$brand==="auto-parseable-tool"}function _p(n,e){return!e||!pd(e)?{...n,choices:n.choices.map(t=>(md(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:ao(n,e)}function ao(n,e){const t=n.choices.map(r=>{if(r.finish_reason==="length")throw new Kl;if(r.finish_reason==="content_filter")throw new Xl;return md(r.message.tool_calls),{...r,message:{...r.message,...r.message.tool_calls?{tool_calls:r.message.tool_calls?.map(s=>wp(e,s))??void 0}:void 0,parsed:r.message.content&&!r.message.refusal?bp(e,r.message.content):null}}});return{...n,choices:t}}function bp(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function wp(n,e){const t=n.tools?.find(r=>Xn(r)&&r.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:on(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function vp(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(r=>Xn(r)&&r.function?.name===e.function.name);return Xn(t)&&(on(t)||t?.function.strict||!1)}function pd(n){return so(n.response_format)?!0:n.tools?.some(e=>on(e)||e.type==="function"&&e.function.strict===!0)??!1}function md(n){for(const e of n||[])if(e.type!=="function")throw new F(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Sp(n){for(const e of n??[]){if(e.type!=="function")throw new F(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new F(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Qn=n=>n?.role==="assistant",gd=n=>n?.role==="tool";var Ti,Dn,Fn,$r,Nr,Bn,jr,gt,Lr,Yn,es,sr,yd;class io{constructor(){Ti.add(this),this.controller=new AbortController,Dn.set(this,void 0),Fn.set(this,()=>{}),$r.set(this,()=>{}),Nr.set(this,void 0),Bn.set(this,()=>{}),jr.set(this,()=>{}),gt.set(this,{}),Lr.set(this,!1),Yn.set(this,!1),es.set(this,!1),sr.set(this,!1),B(this,Dn,new Promise((e,t)=>{B(this,Fn,e,"f"),B(this,$r,t,"f")})),B(this,Nr,new Promise((e,t)=>{B(this,Bn,e,"f"),B(this,jr,t,"f")})),w(this,Dn,"f").catch(()=>{}),w(this,Nr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},w(this,Ti,"m",yd).bind(this))},0)}_connected(){this.ended||(w(this,Fn,"f").call(this),this._emit("connect"))}get ended(){return w(this,Lr,"f")}get errored(){return w(this,Yn,"f")}get aborted(){return w(this,es,"f")}abort(){this.controller.abort()}on(e,t){return(w(this,gt,"f")[e]||(w(this,gt,"f")[e]=[])).push({listener:t}),this}off(e,t){const r=w(this,gt,"f")[e];if(!r)return this;const s=r.findIndex(a=>a.listener===t);return s>=0&&r.splice(s,1),this}once(e,t){return(w(this,gt,"f")[e]||(w(this,gt,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,r)=>{B(this,sr,!0),e!=="error"&&this.once("error",r),this.once(e,t)})}async done(){B(this,sr,!0),await w(this,Nr,"f")}_emit(e,...t){if(w(this,Lr,"f"))return;e==="end"&&(B(this,Lr,!0),w(this,Bn,"f").call(this));const r=w(this,gt,"f")[e];if(r&&(w(this,gt,"f")[e]=r.filter(s=>!s.once),r.forEach(({listener:s})=>s(...t))),e==="abort"){const s=t[0];!w(this,sr,"f")&&!r?.length&&Promise.reject(s),w(this,$r,"f").call(this,s),w(this,jr,"f").call(this,s),this._emit("end");return}if(e==="error"){const s=t[0];!w(this,sr,"f")&&!r?.length&&Promise.reject(s),w(this,$r,"f").call(this,s),w(this,jr,"f").call(this,s),this._emit("end")}}_emitFinal(){}}Dn=new WeakMap,Fn=new WeakMap,$r=new WeakMap,Nr=new WeakMap,Bn=new WeakMap,jr=new WeakMap,gt=new WeakMap,Lr=new WeakMap,Yn=new WeakMap,es=new WeakMap,sr=new WeakMap,Ti=new WeakSet,yd=function(e){if(B(this,Yn,!0),e instanceof Error&&e.name==="AbortError"&&(e=new qe),e instanceof qe)return B(this,es,!0),this._emit("abort",e);if(e instanceof F)return this._emit("error",e);if(e instanceof Error){const t=new F(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new F(String(e)))};function Ep(n){return typeof n.parse=="function"}var Pe,Ai,ts,Ii,Ri,Pi,_d,bd;const Op=10;class wd extends io{constructor(){super(...arguments),Pe.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),gd(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Qn(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 F("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),w(this,Pe,"m",Ai).call(this)}async finalMessage(){return await this.done(),w(this,Pe,"m",ts).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,Pe,"m",Ii).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,Pe,"m",Ri).call(this)}async totalUsage(){return await this.done(),w(this,Pe,"m",Pi).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=w(this,Pe,"m",ts).call(this);t&&this._emit("finalMessage",t);const r=w(this,Pe,"m",Ai).call(this);r&&this._emit("finalContent",r);const s=w(this,Pe,"m",Ii).call(this);s&&this._emit("finalFunctionToolCall",s);const a=w(this,Pe,"m",Ri).call(this);a!=null&&this._emit("finalFunctionToolCallResult",a),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",w(this,Pe,"m",Pi).call(this))}async _createChatCompletion(e,t,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,Pe,"m",_d).call(this,t);const a=await e.chat.completions.create({...t,stream:!1},{...r,signal:this.controller.signal});return this._connected(),this._addChatCompletion(ao(a,t))}async _runChatCompletion(e,t,r){for(const s of t.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,t,r)}async _runTools(e,t,r){const s="tool",{tool_choice:a="auto",stream:i,...o}=t,u=typeof a!="string"&&a.type==="function"&&a?.function?.name,{maxChatCompletions:c=Op}=r||{},l=t.tools.map(f=>{if(on(f)){if(!f.$callback)throw new F("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),d={};for(const f of l)f.type==="function"&&(d[f.function.name||f.function.function.name]=f.function);const h="tools"in t?l.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(const f of t.messages)this._addMessage(f,!1);for(let f=0;f<c;++f){const m=(await this._createChatCompletion(e,{...o,tool_choice:a,tools:h,messages:[...this.messages]},r)).choices[0]?.message;if(!m)throw new F("missing message in ChatCompletion response");if(!m.tool_calls?.length)return;for(const g of m.tool_calls){if(g.type!=="function")continue;const y=g.id,{name:_,arguments:b}=g.function,v=d[_];if(v){if(u&&u!==_){const x=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(u)} requested. Please try again`;this._addMessage({role:s,tool_call_id:y,content:x});continue}}else{const x=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(d).map(K=>JSON.stringify(K)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:y,content:x});continue}let S;try{S=Ep(v)?await v.parse(b):b}catch(x){const K=x instanceof Error?x.message:String(x);this._addMessage({role:s,tool_call_id:y,content:K});continue}const R=await v.function(S,this),P=w(this,Pe,"m",bd).call(this,R);if(this._addMessage({role:s,tool_call_id:y,content:P}),u)return}}}}Pe=new WeakSet,Ai=function(){return w(this,Pe,"m",ts).call(this).content??null},ts=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Qn(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new F("stream ended without producing a ChatCompletionMessage with role=assistant")},Ii=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Qn(t)&&t?.tool_calls?.length)return t.tool_calls.filter(r=>r.type==="function").at(-1)?.function}},Ri=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(gd(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(r=>r.role==="assistant"&&r.tool_calls?.some(s=>s.type==="function"&&s.id===t.tool_call_id)))return t.content}},Pi=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},_d=function(e){if(e.n!=null&&e.n>1)throw new F("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},bd=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class oo extends wd{static runTools(e,t,r){const s=new oo,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}_addMessage(e,t=!0){super._addMessage(e,t),Qn(e)&&e.content&&this._emit("content",e.content)}}const vd=1,Sd=2,Ed=4,Od=8,xd=16,kd=32,Td=64,Ad=128,Id=256,Rd=Ad|Id,Pd=xd|kd|Rd|Td,Cd=vd|Sd|Pd,$d=Ed|Od,xp=Cd|$d,be={STR:vd,NUM:Sd,ARR:Ed,OBJ:Od,NULL:xd,BOOL:kd,NAN:Td,INFINITY:Ad,MINUS_INFINITY:Id,INF:Rd,SPECIAL:Pd,ATOM:Cd,COLLECTION:$d,ALL:xp};class kp extends Error{}class Tp extends Error{}function Ap(n,e=be.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return Ip(n.trim(),e)}const Ip=(n,e)=>{const t=n.length;let r=0;const s=h=>{throw new kp(`${h} at position ${r}`)},a=h=>{throw new Tp(`${h} at position ${r}`)},i=()=>(d(),r>=t&&s("Unexpected end of input"),n[r]==='"'?o():n[r]==="{"?u():n[r]==="["?c():n.substring(r,r+4)==="null"||be.NULL&e&&t-r<4&&"null".startsWith(n.substring(r))?(r+=4,null):n.substring(r,r+4)==="true"||be.BOOL&e&&t-r<4&&"true".startsWith(n.substring(r))?(r+=4,!0):n.substring(r,r+5)==="false"||be.BOOL&e&&t-r<5&&"false".startsWith(n.substring(r))?(r+=5,!1):n.substring(r,r+8)==="Infinity"||be.INFINITY&e&&t-r<8&&"Infinity".startsWith(n.substring(r))?(r+=8,1/0):n.substring(r,r+9)==="-Infinity"||be.MINUS_INFINITY&e&&1<t-r&&t-r<9&&"-Infinity".startsWith(n.substring(r))?(r+=9,-1/0):n.substring(r,r+3)==="NaN"||be.NAN&e&&t-r<3&&"NaN".startsWith(n.substring(r))?(r+=3,NaN):l()),o=()=>{const h=r;let f=!1;for(r++;r<t&&(n[r]!=='"'||f&&n[r-1]==="\\");)f=n[r]==="\\"?!f:!1,r++;if(n.charAt(r)=='"')try{return JSON.parse(n.substring(h,++r-Number(f)))}catch(p){a(String(p))}else if(be.STR&e)try{return JSON.parse(n.substring(h,r-Number(f))+'"')}catch{return JSON.parse(n.substring(h,n.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},u=()=>{r++,d();const h={};try{for(;n[r]!=="}";){if(d(),r>=t&&be.OBJ&e)return h;const f=o();d(),r++;try{const p=i();Object.defineProperty(h,f,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(be.OBJ&e)return h;throw p}d(),n[r]===","&&r++}}catch{if(be.OBJ&e)return h;s("Expected '}' at end of object")}return r++,h},c=()=>{r++;const h=[];try{for(;n[r]!=="]";)h.push(i()),d(),n[r]===","&&r++}catch{if(be.ARR&e)return h;s("Expected ']' at end of array")}return r++,h},l=()=>{if(r===0){n==="-"&&be.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(be.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}a(String(f))}}const h=r;for(n[r]==="-"&&r++;n[r]&&!",]}".includes(n[r]);)r++;r==t&&!(be.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(n.substring(h,r))}catch{n.substring(h,r)==="-"&&be.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(n.substring(h,n.lastIndexOf("e")))}catch(p){a(String(p))}}},d=()=>{for(;r<t&&`
|
|
10
|
+
\r `.includes(n[r]);)r++};return i()},uu=n=>Ap(n,be.ALL^be.NUM);var fe,mt,Yt,vt,Ys,_n,ea,ta,ra,bn,na,cu;class Vr extends wd{constructor(e){super(),fe.add(this),mt.set(this,void 0),Yt.set(this,void 0),vt.set(this,void 0),B(this,mt,e),B(this,Yt,[])}get currentChatCompletionSnapshot(){return w(this,vt,"f")}static fromReadableStream(e){const t=new Vr(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,r){const s=new Vr(t);return s._run(()=>s._runChatCompletion(e,{...t,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,t,r){super._createChatCompletion;const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,fe,"m",Ys).call(this);const a=await e.chat.completions.create({...t,stream:!0},{...r,signal:this.controller.signal});this._connected();for await(const i of a)w(this,fe,"m",ea).call(this,i);if(a.controller.signal?.aborted)throw new qe;return this._addChatCompletion(w(this,fe,"m",bn).call(this))}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),w(this,fe,"m",Ys).call(this),this._connected();const s=lt.fromReadableStream(e,this.controller);let a;for await(const i of s)a&&a!==i.id&&this._addChatCompletion(w(this,fe,"m",bn).call(this)),w(this,fe,"m",ea).call(this,i),a=i.id;if(s.controller.signal?.aborted)throw new qe;return this._addChatCompletion(w(this,fe,"m",bn).call(this))}[(mt=new WeakMap,Yt=new WeakMap,vt=new WeakMap,fe=new WeakSet,Ys=function(){this.ended||B(this,vt,void 0)},_n=function(t){let r=w(this,Yt,"f")[t.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},w(this,Yt,"f")[t.index]=r,r)},ea=function(t){if(this.ended)return;const r=w(this,fe,"m",cu).call(this,t);this._emit("chunk",t,r);for(const s of t.choices){const a=r.choices[s.index];s.delta.content!=null&&a.message?.role==="assistant"&&a.message?.content&&(this._emit("content",s.delta.content,a.message.content),this._emit("content.delta",{delta:s.delta.content,snapshot:a.message.content,parsed:a.message.parsed})),s.delta.refusal!=null&&a.message?.role==="assistant"&&a.message?.refusal&&this._emit("refusal.delta",{delta:s.delta.refusal,snapshot:a.message.refusal}),s.logprobs?.content!=null&&a.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:s.logprobs?.content,snapshot:a.logprobs?.content??[]}),s.logprobs?.refusal!=null&&a.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:s.logprobs?.refusal,snapshot:a.logprobs?.refusal??[]});const i=w(this,fe,"m",_n).call(this,a);a.finish_reason&&(w(this,fe,"m",ra).call(this,a),i.current_tool_call_index!=null&&w(this,fe,"m",ta).call(this,a,i.current_tool_call_index));for(const o of s.delta.tool_calls??[])i.current_tool_call_index!==o.index&&(w(this,fe,"m",ra).call(this,a),i.current_tool_call_index!=null&&w(this,fe,"m",ta).call(this,a,i.current_tool_call_index)),i.current_tool_call_index=o.index;for(const o of s.delta.tool_calls??[]){const u=a.message.tool_calls?.[o.index];u?.type&&(u?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:u.function?.name,index:o.index,arguments:u.function.arguments,parsed_arguments:u.function.parsed_arguments,arguments_delta:o.function?.arguments??""}):(u?.type,void 0))}}},ta=function(t,r){if(w(this,fe,"m",_n).call(this,t).done_tool_calls.has(r))return;const a=t.message.tool_calls?.[r];if(!a)throw new Error("no tool call snapshot");if(!a.type)throw new Error("tool call snapshot missing `type`");if(a.type==="function"){const i=w(this,mt,"f")?.tools?.find(o=>Xn(o)&&o.function.name===a.function.name);this._emit("tool_calls.function.arguments.done",{name:a.function.name,index:r,arguments:a.function.arguments,parsed_arguments:on(i)?i.$parseRaw(a.function.arguments):i?.function.strict?JSON.parse(a.function.arguments):null})}else a.type},ra=function(t){const r=w(this,fe,"m",_n).call(this,t);if(t.message.content&&!r.content_done){r.content_done=!0;const s=w(this,fe,"m",na).call(this);this._emit("content.done",{content:t.message.content,parsed:s?s.$parseRaw(t.message.content):null})}t.message.refusal&&!r.refusal_done&&(r.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!r.logprobs_content_done&&(r.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!r.logprobs_refusal_done&&(r.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},bn=function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");const t=w(this,vt,"f");if(!t)throw new F("request ended without sending any chunks");return B(this,vt,void 0),B(this,Yt,[]),Rp(t,w(this,mt,"f"))},na=function(){const t=w(this,mt,"f")?.response_format;return so(t)?t:null},cu=function(t){var r,s,a,i;let o=w(this,vt,"f");const{choices:u,...c}=t;o?Object.assign(o,c):o=B(this,vt,{...c,choices:[]});for(const{delta:l,finish_reason:d,index:h,logprobs:f=null,...p}of t.choices){let m=o.choices[h];if(m||(m=o.choices[h]={finish_reason:d,index:h,message:{},logprobs:f,...p}),f)if(!m.logprobs)m.logprobs=Object.assign({},f);else{const{content:R,refusal:P,...x}=f;Object.assign(m.logprobs,x),R&&((r=m.logprobs).content??(r.content=[]),m.logprobs.content.push(...R)),P&&((s=m.logprobs).refusal??(s.refusal=[]),m.logprobs.refusal.push(...P))}if(d&&(m.finish_reason=d,w(this,mt,"f")&&pd(w(this,mt,"f")))){if(d==="length")throw new Kl;if(d==="content_filter")throw new Xl}if(Object.assign(m,p),!l)continue;const{content:g,refusal:y,function_call:_,role:b,tool_calls:v,...S}=l;if(Object.assign(m.message,S),y&&(m.message.refusal=(m.message.refusal||"")+y),b&&(m.message.role=b),_&&(m.message.function_call?(_.name&&(m.message.function_call.name=_.name),_.arguments&&((a=m.message.function_call).arguments??(a.arguments=""),m.message.function_call.arguments+=_.arguments)):m.message.function_call=_),g&&(m.message.content=(m.message.content||"")+g,!m.message.refusal&&w(this,fe,"m",na).call(this)&&(m.message.parsed=uu(m.message.content))),v){m.message.tool_calls||(m.message.tool_calls=[]);for(const{index:R,id:P,type:x,function:K,...Q}of v){const ae=(i=m.message.tool_calls)[R]??(i[R]={});Object.assign(ae,Q),P&&(ae.id=P),x&&(ae.type=x),K&&(ae.function??(ae.function={name:K.name??"",arguments:""})),K?.name&&(ae.function.name=K.name),K?.arguments&&(ae.function.arguments+=K.arguments,vp(w(this,mt,"f"),ae)&&(ae.function.parsed_arguments=uu(ae.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("chunk",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new lt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Rp(n,e){const{id:t,choices:r,created:s,model:a,system_fingerprint:i,...o}=n,u={...o,id:t,choices:r.map(({message:c,finish_reason:l,index:d,logprobs:h,...f})=>{if(!l)throw new F(`missing finish_reason for choice ${d}`);const{content:p=null,function_call:m,tool_calls:g,...y}=c,_=c.role;if(!_)throw new F(`missing role for choice ${d}`);if(m){const{arguments:b,name:v}=m;if(b==null)throw new F(`missing function_call.arguments for choice ${d}`);if(!v)throw new F(`missing function_call.name for choice ${d}`);return{...f,message:{content:p,function_call:{arguments:b,name:v},role:_,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:h}}return g?{...f,index:d,finish_reason:l,logprobs:h,message:{...y,role:_,content:p,refusal:c.refusal??null,tool_calls:g.map((b,v)=>{const{function:S,type:R,id:P,...x}=b,{arguments:K,name:Q,...ae}=S||{};if(P==null)throw new F(`missing choices[${d}].tool_calls[${v}].id
|
|
11
|
+
${wn(n)}`);if(R==null)throw new F(`missing choices[${d}].tool_calls[${v}].type
|
|
12
|
+
${wn(n)}`);if(Q==null)throw new F(`missing choices[${d}].tool_calls[${v}].function.name
|
|
13
|
+
${wn(n)}`);if(K==null)throw new F(`missing choices[${d}].tool_calls[${v}].function.arguments
|
|
14
|
+
${wn(n)}`);return{...x,id:P,type:R,function:{...ae,name:Q,arguments:K}}})}}:{...f,message:{...y,content:p,role:_,refusal:c.refusal??null},finish_reason:l,index:d,logprobs:h}}),created:s,model:a,object:"chat.completion",...i?{system_fingerprint:i}:{}};return _p(u,e)}function wn(n){return JSON.stringify(n)}class rs extends Vr{static fromReadableStream(e){const t=new rs(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,r){const s=new rs(t),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,t,a)),s}}let uo=class extends z{constructor(){super(...arguments),this.messages=new fd(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(T`/chat/completions/${e}`,t)}update(e,t,r){return this._client.post(T`/chat/completions/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/chat/completions",he,{query:e,...t})}delete(e,t){return this._client.delete(T`/chat/completions/${e}`,t)}parse(e,t){return Sp(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(r=>ao(r,e))}runTools(e,t){return e.stream?rs.runTools(this._client,e,t):oo.runTools(this._client,e,t)}stream(e,t){return Vr.createChatCompletion(this._client,e,t)}};uo.Messages=fd;class co extends z{constructor(){super(...arguments),this.completions=new uo(this._client)}}co.Completions=uo;const Nd=Symbol("brand.privateNullableHeaders");function*Pp(n){if(!n)return;if(Nd in n){const{values:r,nulls:s}=n;yield*r.entries();for(const a of s)yield[a,null];return}let e=!1,t;n instanceof Headers?t=n.entries():Wo(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let r of t){const s=r[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");const a=Wo(r[1])?r[1]:[r[1]];let i=!1;for(const o of a)o!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,o])}}const M=n=>{const e=new Headers,t=new Set;for(const r of n){const s=new Set;for(const[a,i]of Pp(r)){const o=a.toLowerCase();s.has(o)||(e.delete(a),s.add(o)),i===null?(e.delete(a),t.add(o)):(e.append(a,i),t.delete(o))}}return{[Nd]:!0,values:e,nulls:t}};class jd extends z{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:M([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Ld extends z{create(e,t){return this._client.post("/audio/transcriptions",Jt({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Md extends z{create(e,t){return this._client.post("/audio/translations",Jt({body:e,...t,__metadata:{model:e.model}},this._client))}}class un extends z{constructor(){super(...arguments),this.transcriptions=new Ld(this._client),this.translations=new Md(this._client),this.speech=new jd(this._client)}}un.Transcriptions=Ld;un.Translations=Md;un.Speech=jd;class Ud extends z{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(T`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",he,{query:e,...t})}cancel(e,t){return this._client.post(T`/batches/${e}/cancel`,t)}}class Dd extends z{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(T`/assistants/${e}`,{...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(T`/assistants/${e}`,{body:t,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",he,{query:e,...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(T`/assistants/${e}`,{...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Fd extends z{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Bd extends z{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}class Ts extends z{constructor(){super(...arguments),this.sessions=new Fd(this._client),this.transcriptionSessions=new Bd(this._client)}}Ts.Sessions=Fd;Ts.TranscriptionSessions=Bd;class zd extends z{create(e,t,r){return this._client.post(T`/threads/${e}/messages`,{body:t,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{thread_id:s}=t;return this._client.get(T`/threads/${s}/messages/${e}`,{...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:s,...a}=t;return this._client.post(T`/threads/${s}/messages/${e}`,{body:a,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(T`/threads/${e}/messages`,he,{query:t,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{thread_id:s}=t;return this._client.delete(T`/threads/${s}/messages/${e}`,{...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class qd extends z{retrieve(e,t,r){const{thread_id:s,run_id:a,...i}=t;return this._client.get(T`/threads/${s}/runs/${a}/steps/${e}`,{query:i,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t,r){const{thread_id:s,...a}=t;return this._client.getAPIList(T`/threads/${s}/runs/${e}/steps`,he,{query:a,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}const Cp=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,r=new Uint8Array(t);for(let s=0;s<t;s++)r[s]=e.charCodeAt(s);return Array.from(new Float32Array(r.buffer))}};var $p={};const er=n=>{if(typeof globalThis.process<"u")return $p?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var xe,zt,Ci,ct,zn,tt,qt,ur,Bt,ns,ze,qn,Zn,qr,Mr,Ur,lu,du,hu,fu,pu,mu,gu;class Zr extends io{constructor(){super(...arguments),xe.add(this),Ci.set(this,[]),ct.set(this,{}),zn.set(this,{}),tt.set(this,void 0),qt.set(this,void 0),ur.set(this,void 0),Bt.set(this,void 0),ns.set(this,void 0),ze.set(this,void 0),qn.set(this,void 0),Zn.set(this,void 0),qr.set(this,void 0)}[(Ci=new WeakMap,ct=new WeakMap,zn=new WeakMap,tt=new WeakMap,qt=new WeakMap,ur=new WeakMap,Bt=new WeakMap,ns=new WeakMap,ze=new WeakMap,qn=new WeakMap,Zn=new WeakMap,qr=new WeakMap,xe=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new zt;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const r=t?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),this._connected();const s=lt.fromReadableStream(e,this.controller);for await(const a of s)w(this,xe,"m",Mr).call(this,a);if(s.controller.signal?.aborted)throw new qe;return this._addRun(w(this,xe,"m",Ur).call(this))}toReadableStream(){return new lt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,r,s){const a=new zt;return a._run(()=>a._runToolAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createToolAssistantStream(e,t,r,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.submitToolOutputs(t,i,{...s,signal:this.controller.signal});this._connected();for await(const u of o)w(this,xe,"m",Mr).call(this,u);if(o.controller.signal?.aborted)throw new qe;return this._addRun(w(this,xe,"m",Ur).call(this))}static createThreadAssistantStream(e,t,r){const s=new zt;return s._run(()=>s._threadAssistantStream(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,t,r,s){const a=new zt;return a._run(()=>a._runAssistantStream(e,t,r,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),a}currentEvent(){return w(this,qn,"f")}currentRun(){return w(this,Zn,"f")}currentMessageSnapshot(){return w(this,tt,"f")}currentRunStepSnapshot(){return w(this,qr,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,ct,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,zn,"f"))}async finalRun(){if(await this.done(),!w(this,qt,"f"))throw Error("Final run was not received.");return w(this,qt,"f")}async _createThreadAssistantStream(e,t,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));const a={...t,stream:!0},i=await e.createAndRun(a,{...r,signal:this.controller.signal});this._connected();for await(const o of i)w(this,xe,"m",Mr).call(this,o);if(i.controller.signal?.aborted)throw new qe;return this._addRun(w(this,xe,"m",Ur).call(this))}async _createAssistantStream(e,t,r,s){const a=s?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort()));const i={...r,stream:!0},o=await e.create(t,i,{...s,signal:this.controller.signal});this._connected();for await(const u of o)w(this,xe,"m",Mr).call(this,u);if(o.controller.signal?.aborted)throw new qe;return this._addRun(w(this,xe,"m",Ur).call(this))}static accumulateDelta(e,t){for(const[r,s]of Object.entries(t)){if(!e.hasOwnProperty(r)){e[r]=s;continue}let a=e[r];if(a==null){e[r]=s;continue}if(r==="index"||r==="type"){e[r]=s;continue}if(typeof a=="string"&&typeof s=="string")a+=s;else if(typeof a=="number"&&typeof s=="number")a+=s;else if(Ks(a)&&Ks(s))a=this.accumulateDelta(a,s);else if(Array.isArray(a)&&Array.isArray(s)){if(a.every(i=>typeof i=="string"||typeof i=="number")){a.push(...s);continue}for(const i of s){if(!Ks(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);const o=i.index;if(o==null)throw console.error(i),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=a[o];u==null?a.push(i):a[o]=this.accumulateDelta(u,i)}continue}else throw Error(`Unhandled record type: ${r}, deltaValue: ${s}, accValue: ${a}`);e[r]=a}return e}_addRun(e){return e}async _threadAssistantStream(e,t,r){return await this._createThreadAssistantStream(t,e,r)}async _runAssistantStream(e,t,r,s){return await this._createAssistantStream(t,e,r,s)}async _runToolAssistantStream(e,t,r,s){return await this._createToolAssistantStream(t,e,r,s)}}zt=Zr,Mr=function(e){if(!this.ended)switch(B(this,qn,e),w(this,xe,"m",hu).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":w(this,xe,"m",gu).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":w(this,xe,"m",du).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":w(this,xe,"m",lu).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Ur=function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");if(!w(this,qt,"f"))throw Error("Final run has not been received");return w(this,qt,"f")},lu=function(e){const[t,r]=w(this,xe,"m",pu).call(this,e,w(this,tt,"f"));B(this,tt,t),w(this,zn,"f")[t.id]=t;for(const s of r){const a=t.content[s.index];a?.type=="text"&&this._emit("textCreated",a.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const s of e.data.delta.content){if(s.type=="text"&&s.text){let a=s.text,i=t.content[s.index];if(i&&i.type=="text")this._emit("textDelta",a,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=w(this,ur,"f")){if(w(this,Bt,"f"))switch(w(this,Bt,"f").type){case"text":this._emit("textDone",w(this,Bt,"f").text,w(this,tt,"f"));break;case"image_file":this._emit("imageFileDone",w(this,Bt,"f").image_file,w(this,tt,"f"));break}B(this,ur,s.index)}B(this,Bt,t.content[s.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,ur,"f")!==void 0){const s=e.data.content[w(this,ur,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,w(this,tt,"f"));break;case"text":this._emit("textDone",s.text,w(this,tt,"f"));break}}w(this,tt,"f")&&this._emit("messageDone",e.data),B(this,tt,void 0)}},du=function(e){const t=w(this,xe,"m",fu).call(this,e);switch(B(this,qr,t),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&&t.step_details.type=="tool_calls")for(const a of r.step_details.tool_calls)a.index==w(this,ns,"f")?this._emit("toolCallDelta",a,t.step_details.tool_calls[a.index]):(w(this,ze,"f")&&this._emit("toolCallDone",w(this,ze,"f")),B(this,ns,a.index),B(this,ze,t.step_details.tool_calls[a.index]),w(this,ze,"f")&&this._emit("toolCallCreated",w(this,ze,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":B(this,qr,void 0),e.data.step_details.type=="tool_calls"&&w(this,ze,"f")&&(this._emit("toolCallDone",w(this,ze,"f")),B(this,ze,void 0)),this._emit("runStepDone",e.data,t);break}},hu=function(e){w(this,Ci,"f").push(e),this._emit("event",e)},fu=function(e){switch(e.event){case"thread.run.step.created":return w(this,ct,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=w(this,ct,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let r=e.data;if(r.delta){const s=zt.accumulateDelta(t,r.delta);w(this,ct,"f")[e.data.id]=s}return w(this,ct,"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":w(this,ct,"f")[e.data.id]=e.data;break}if(w(this,ct,"f")[e.data.id])return w(this,ct,"f")[e.data.id];throw new Error("No snapshot available")},pu=function(e,t){let r=[];switch(e.event){case"thread.message.created":return[e.data,r];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(const a of s.delta.content)if(a.index in t.content){let i=t.content[a.index];t.content[a.index]=w(this,xe,"m",mu).call(this,a,i)}else t.content[a.index]=a,r.push(a);return[t,r];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,r];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},mu=function(e,t){return zt.accumulateDelta(t,e)},gu=function(e){switch(B(this,Zn,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":B(this,qt,e.data),w(this,ze,"f")&&(this._emit("toolCallDone",w(this,ze,"f")),B(this,ze,void 0));break}};let lo=class extends z{constructor(){super(...arguments),this.steps=new qd(this._client)}create(e,t,r){const{include:s,...a}=t;return this._client.post(T`/threads/${e}/runs`,{query:{include:s},body:a,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}retrieve(e,t,r){const{thread_id:s}=t;return this._client.get(T`/threads/${s}/runs/${e}`,{...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{thread_id:s,...a}=t;return this._client.post(T`/threads/${s}/runs/${e}`,{body:a,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(T`/threads/${e}/runs`,he,{query:t,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{thread_id:s}=t;return this._client.post(T`/threads/${s}/runs/${e}/cancel`,{...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const s=await this.create(e,t,r);return await this.poll(s.id,{thread_id:e},r)}createAndStream(e,t,r){return Zr.createAssistantStream(e,this._client.beta.threads.runs,t,r)}async poll(e,t,r){const s=M([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(e,t,{...r,headers:{...r?.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const u=i.headers.get("openai-poll-after-ms");if(u){const c=parseInt(u);isNaN(c)||(o=c)}}await an(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,t,r){return Zr.createAssistantStream(e,this._client.beta.threads.runs,t,r)}submitToolOutputs(e,t,r){const{thread_id:s,...a}=t;return this._client.post(T`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:a,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,r){const s=await this.submitToolOutputs(e,t,r);return await this.poll(s.id,t,r)}submitToolOutputsStream(e,t,r){return Zr.createToolAssistantStream(e,this._client.beta.threads.runs,t,r)}};lo.Steps=qd;class As extends z{constructor(){super(...arguments),this.runs=new lo(this._client),this.messages=new zd(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(T`/threads/${e}`,{...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(T`/threads/${e}`,{body:t,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t){return this._client.delete(T`/threads/${e}`,{...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const r=await this.createAndRun(e,t);return await this.runs.poll(r.id,{thread_id:r.thread_id},t)}createAndRunStream(e,t){return Zr.createThreadAssistantStream(e,this._client.beta.threads,t)}}As.Runs=lo;As.Messages=zd;class cn extends z{constructor(){super(...arguments),this.realtime=new Ts(this._client),this.assistants=new Dd(this._client),this.threads=new As(this._client)}}cn.Realtime=Ts;cn.Assistants=Dd;cn.Threads=As;class Zd extends z{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Hd extends z{retrieve(e,t,r){const{container_id:s}=t;return this._client.get(T`/containers/${s}/files/${e}/content`,{...r,headers:M([{Accept:"application/binary"},r?.headers]),__binaryResponse:!0})}}let ho=class extends z{constructor(){super(...arguments),this.content=new Hd(this._client)}create(e,t,r){return this._client.post(T`/containers/${e}/files`,Jt({body:t,...r},this._client))}retrieve(e,t,r){const{container_id:s}=t;return this._client.get(T`/containers/${s}/files/${e}`,r)}list(e,t={},r){return this._client.getAPIList(T`/containers/${e}/files`,he,{query:t,...r})}delete(e,t,r){const{container_id:s}=t;return this._client.delete(T`/containers/${s}/files/${e}`,{...r,headers:M([{Accept:"*/*"},r?.headers])})}};ho.Content=Hd;class fo extends z{constructor(){super(...arguments),this.files=new ho(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(T`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",he,{query:e,...t})}delete(e,t){return this._client.delete(T`/containers/${e}`,{...t,headers:M([{Accept:"*/*"},t?.headers])})}}fo.Files=ho;class Gd extends z{create(e,t){const r=!!e.encoding_format;let s=r?e.encoding_format:"base64";r&&Oe(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const a=this._client.post("/embeddings",{body:{...e,encoding_format:s},...t});return r?a:(Oe(this._client).debug("embeddings/decoding base64 embeddings from base64"),a._thenUnwrap(i=>(i&&i.data&&i.data.forEach(o=>{const u=o.embedding;o.embedding=Cp(u)}),i)))}}class Jd extends z{retrieve(e,t,r){const{eval_id:s,run_id:a}=t;return this._client.get(T`/evals/${s}/runs/${a}/output_items/${e}`,r)}list(e,t,r){const{eval_id:s,...a}=t;return this._client.getAPIList(T`/evals/${s}/runs/${e}/output_items`,he,{query:a,...r})}}class po extends z{constructor(){super(...arguments),this.outputItems=new Jd(this._client)}create(e,t,r){return this._client.post(T`/evals/${e}/runs`,{body:t,...r})}retrieve(e,t,r){const{eval_id:s}=t;return this._client.get(T`/evals/${s}/runs/${e}`,r)}list(e,t={},r){return this._client.getAPIList(T`/evals/${e}/runs`,he,{query:t,...r})}delete(e,t,r){const{eval_id:s}=t;return this._client.delete(T`/evals/${s}/runs/${e}`,r)}cancel(e,t,r){const{eval_id:s}=t;return this._client.post(T`/evals/${s}/runs/${e}`,r)}}po.OutputItems=Jd;class mo extends z{constructor(){super(...arguments),this.runs=new po(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(T`/evals/${e}`,t)}update(e,t,r){return this._client.post(T`/evals/${e}`,{body:t,...r})}list(e={},t){return this._client.getAPIList("/evals",he,{query:e,...t})}delete(e,t){return this._client.delete(T`/evals/${e}`,t)}}mo.Runs=po;let Wd=class extends z{create(e,t){return this._client.post("/files",Jt({body:e,...t},this._client))}retrieve(e,t){return this._client.get(T`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",he,{query:e,...t})}delete(e,t){return this._client.delete(T`/files/${e}`,t)}content(e,t){return this._client.get(T`/files/${e}/content`,{...t,headers:M([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:r=1800*1e3}={}){const s=new Set(["processed","error","deleted"]),a=Date.now();let i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await an(t),i=await this.retrieve(e),Date.now()-a>r)throw new Es({message:`Giving up on waiting for file ${e} to finish processing after ${r} milliseconds.`});return i}};class Vd extends z{}let Kd=class extends z{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class go extends z{constructor(){super(...arguments),this.graders=new Kd(this._client)}}go.Graders=Kd;class Xd extends z{create(e,t,r){return this._client.getAPIList(T`/fine_tuning/checkpoints/${e}/permissions`,ks,{body:t,method:"post",...r})}retrieve(e,t={},r){return this._client.get(T`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...r})}delete(e,t,r){const{fine_tuned_model_checkpoint:s}=t;return this._client.delete(T`/fine_tuning/checkpoints/${s}/permissions/${e}`,r)}}let yo=class extends z{constructor(){super(...arguments),this.permissions=new Xd(this._client)}};yo.Permissions=Xd;class Qd extends z{list(e,t={},r){return this._client.getAPIList(T`/fine_tuning/jobs/${e}/checkpoints`,he,{query:t,...r})}}class _o extends z{constructor(){super(...arguments),this.checkpoints=new Qd(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(T`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",he,{query:e,...t})}cancel(e,t){return this._client.post(T`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},r){return this._client.getAPIList(T`/fine_tuning/jobs/${e}/events`,he,{query:t,...r})}pause(e,t){return this._client.post(T`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(T`/fine_tuning/jobs/${e}/resume`,t)}}_o.Checkpoints=Qd;class yr extends z{constructor(){super(...arguments),this.methods=new Vd(this._client),this.jobs=new _o(this._client),this.checkpoints=new yo(this._client),this.alpha=new go(this._client)}}yr.Methods=Vd;yr.Jobs=_o;yr.Checkpoints=yo;yr.Alpha=go;class Yd extends z{}class bo extends z{constructor(){super(...arguments),this.graderModels=new Yd(this._client)}}bo.GraderModels=Yd;class eh extends z{createVariation(e,t){return this._client.post("/images/variations",Jt({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",Jt({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class th extends z{retrieve(e,t){return this._client.get(T`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",ks,e)}delete(e,t){return this._client.delete(T`/models/${e}`,t)}}class rh extends z{create(e,t){return this._client.post("/moderations",{body:e,...t})}}function Np(n,e){return!e||!Lp(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(r=>({...r,parsed:null}))}:t)}:nh(n,e)}function nh(n,e){const t=n.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Dp(e,s)};if(s.type==="message"){const a=s.content.map(i=>i.type==="output_text"?{...i,parsed:jp(e,i.text)}:i);return{...s,content:a}}return s}),r=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||$i(r),Object.defineProperty(r,"output_parsed",{enumerable:!0,get(){for(const s of r.output)if(s.type==="message"){for(const a of s.content)if(a.type==="output_text"&&a.parsed!==null)return a.parsed}return null}}),r}function jp(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function Lp(n){return!!so(n.text?.format)}function Mp(n){return n?.$brand==="auto-parseable-tool"}function Up(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function Dp(n,e){const t=Up(n.tools??[],e.name);return{...e,...e,parsed_arguments:Mp(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function $i(n){const e=[];for(const t of n.output)if(t.type==="message")for(const r of t.content)r.type==="output_text"&&e.push(r.text);n.output_text=e.join("")}var tr,vn,St,Sn,yu,_u,bu,wu;class wo extends io{constructor(e){super(),tr.add(this),vn.set(this,void 0),St.set(this,void 0),Sn.set(this,void 0),B(this,vn,e)}static createResponse(e,t,r){const s=new wo(t);return s._run(()=>s._createOrRetrieveResponse(e,t,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,t,r){const s=r?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,tr,"m",yu).call(this);let a,i=null;"response_id"in t?(a=await e.responses.retrieve(t.response_id,{stream:!0},{...r,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):a=await e.responses.create({...t,stream:!0},{...r,signal:this.controller.signal}),this._connected();for await(const o of a)w(this,tr,"m",_u).call(this,o,i);if(a.controller.signal?.aborted)throw new qe;return w(this,tr,"m",bu).call(this)}[(vn=new WeakMap,St=new WeakMap,Sn=new WeakMap,tr=new WeakSet,yu=function(){this.ended||B(this,St,void 0)},_u=function(t,r){if(this.ended)return;const s=(i,o)=>{(r==null||o.sequence_number>r)&&this._emit(i,o)},a=w(this,tr,"m",wu).call(this,t);switch(s("event",t),t.type){case"response.output_text.delta":{const i=a.output[t.output_index];if(!i)throw new F(`missing output at index ${t.output_index}`);if(i.type==="message"){const o=i.content[t.content_index];if(!o)throw new F(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new F(`expected content to be 'output_text', got ${o.type}`);s("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const i=a.output[t.output_index];if(!i)throw new F(`missing output at index ${t.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...t,snapshot:i.arguments});break}default:s(t.type,t);break}},bu=function(){if(this.ended)throw new F("stream has ended, this shouldn't happen");const t=w(this,St,"f");if(!t)throw new F("request ended without sending any events");B(this,St,void 0);const r=Fp(t,w(this,vn,"f"));return B(this,Sn,r),r},wu=function(t){let r=w(this,St,"f");if(!r){if(t.type!=="response.created")throw new F(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return r=B(this,St,t.response),r}switch(t.type){case"response.output_item.added":{r.output.push(t.item);break}case"response.content_part.added":{const s=r.output[t.output_index];if(!s)throw new F(`missing output at index ${t.output_index}`);s.type==="message"&&s.content.push(t.part);break}case"response.output_text.delta":{const s=r.output[t.output_index];if(!s)throw new F(`missing output at index ${t.output_index}`);if(s.type==="message"){const a=s.content[t.content_index];if(!a)throw new F(`missing content at index ${t.content_index}`);if(a.type!=="output_text")throw new F(`expected content to be 'output_text', got ${a.type}`);a.text+=t.delta}break}case"response.function_call_arguments.delta":{const s=r.output[t.output_index];if(!s)throw new F(`missing output at index ${t.output_index}`);s.type==="function_call"&&(s.arguments+=t.delta);break}case"response.completed":{B(this,St,t.response);break}}return r},Symbol.asyncIterator)](){const e=[],t=[];let r=!1;return this.on("event",s=>{const a=t.shift();a?a.resolve(s):e.push(s)}),this.on("end",()=>{r=!0;for(const s of t)s.resolve(void 0);t.length=0}),this.on("abort",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),this.on("error",s=>{r=!0;for(const a of t)a.reject(s);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:r?{value:void 0,done:!0}:new Promise((a,i)=>t.push({resolve:a,reject:i})).then(a=>a?{value:a,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=w(this,Sn,"f");if(!e)throw new F("stream ended without producing a ChatCompletion");return e}}function Fp(n,e){return Np(n,e)}class sh extends z{list(e,t={},r){return this._client.getAPIList(T`/responses/${e}/input_items`,he,{query:t,...r})}}class vo extends z{constructor(){super(...arguments),this.inputItems=new sh(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&$i(r),r))}retrieve(e,t={},r){return this._client.get(T`/responses/${e}`,{query:t,...r,stream:t?.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&$i(s),s))}delete(e,t){return this._client.delete(T`/responses/${e}`,{...t,headers:M([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(r=>nh(r,e))}stream(e,t){return wo.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(T`/responses/${e}/cancel`,t)}}vo.InputItems=sh;class ah extends z{create(e,t,r){return this._client.post(T`/uploads/${e}/parts`,Jt({body:t,...r},this._client))}}class So extends z{constructor(){super(...arguments),this.parts=new ah(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(T`/uploads/${e}/cancel`,t)}complete(e,t,r){return this._client.post(T`/uploads/${e}/complete`,{body:t,...r})}}So.Parts=ah;const Bp=async n=>{const e=await Promise.allSettled(n),t=e.filter(s=>s.status==="rejected");if(t.length){for(const s of t)console.error(s.reason);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const r=[];for(const s of e)s.status==="fulfilled"&&r.push(s.value);return r};class ih extends z{create(e,t,r){return this._client.post(T`/vector_stores/${e}/file_batches`,{body:t,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:s}=t;return this._client.get(T`/vector_stores/${s}/file_batches/${e}`,{...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}cancel(e,t,r){const{vector_store_id:s}=t;return this._client.post(T`/vector_stores/${s}/file_batches/${e}/cancel`,{...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const s=await this.create(e,t);return await this.poll(e,s.id,r)}listFiles(e,t,r){const{vector_store_id:s,...a}=t;return this._client.getAPIList(T`/vector_stores/${s}/file_batches/${e}/files`,he,{query:a,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async poll(e,t,r){const s=M([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:a,response:i}=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse();switch(a.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const u=i.headers.get("openai-poll-after-ms");if(u){const c=parseInt(u);isNaN(c)||(o=c)}}await an(o);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:t,fileIds:r=[]},s){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const a=s?.maxConcurrency??5,i=Math.min(a,t.length),o=this._client,u=t.values(),c=[...r];async function l(h){for(let f of h){const p=await o.files.create({file:f,purpose:"assistants"},s);c.push(p.id)}}const d=Array(i).fill(u).map(l);return await Bp(d),await this.createAndPoll(e,{file_ids:c})}}class oh extends z{create(e,t,r){return this._client.post(T`/vector_stores/${e}/files`,{body:t,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}retrieve(e,t,r){const{vector_store_id:s}=t;return this._client.get(T`/vector_stores/${s}/files/${e}`,{...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}update(e,t,r){const{vector_store_id:s,...a}=t;return this._client.post(T`/vector_stores/${s}/files/${e}`,{body:a,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e,t={},r){return this._client.getAPIList(T`/vector_stores/${e}/files`,he,{query:t,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}delete(e,t,r){const{vector_store_id:s}=t;return this._client.delete(T`/vector_stores/${s}/files/${e}`,{...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}async createAndPoll(e,t,r){const s=await this.create(e,t,r);return await this.poll(e,s.id,r)}async poll(e,t,r){const s=M([r?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":r?.pollIntervalMs?.toString()??void 0}]);for(;;){const a=await this.retrieve(t,{vector_store_id:e},{...r,headers:s}).withResponse(),i=a.data;switch(i.status){case"in_progress":let o=5e3;if(r?.pollIntervalMs)o=r.pollIntervalMs;else{const u=a.response.headers.get("openai-poll-after-ms");if(u){const c=parseInt(u);isNaN(c)||(o=c)}}await an(o);break;case"failed":case"completed":return i}}}async upload(e,t,r){const s=await this._client.files.create({file:t,purpose:"assistants"},r);return this.create(e,{file_id:s.id},r)}async uploadAndPoll(e,t,r){const s=await this.upload(e,t,r);return await this.poll(e,s.id,r)}content(e,t,r){const{vector_store_id:s}=t;return this._client.getAPIList(T`/vector_stores/${s}/files/${e}/content`,ks,{...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}class Is extends z{constructor(){super(...arguments),this.files=new oh(this._client),this.fileBatches=new ih(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(T`/vector_stores/${e}`,{...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,r){return this._client.post(T`/vector_stores/${e}`,{body:t,...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",he,{query:e,...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(T`/vector_stores/${e}`,{...t,headers:M([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,r){return this._client.getAPIList(T`/vector_stores/${e}/search`,ks,{body:t,method:"post",...r,headers:M([{"OpenAI-Beta":"assistants=v2"},r?.headers])})}}Is.Files=oh;Is.FileBatches=ih;var ar,uh,Hn;class ch extends z{constructor(){super(...arguments),ar.add(this)}async unwrap(e,t,r=this._client.webhookSecret,s=300){return await this.verifySignature(e,t,r,s),JSON.parse(e)}async verifySignature(e,t,r=this._client.webhookSecret,s=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");w(this,ar,"m",uh).call(this,r);const a=M([t]).values,i=w(this,ar,"m",Hn).call(this,a,"webhook-signature"),o=w(this,ar,"m",Hn).call(this,a,"webhook-timestamp"),u=w(this,ar,"m",Hn).call(this,a,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new Rr("Invalid webhook timestamp format");const l=Math.floor(Date.now()/1e3);if(l-c>s)throw new Rr("Webhook timestamp is too old");if(c>l+s)throw new Rr("Webhook timestamp is too new");const d=i.split(" ").map(m=>m.startsWith("v1,")?m.substring(3):m),h=r.startsWith("whsec_")?Buffer.from(r.replace("whsec_",""),"base64"):Buffer.from(r,"utf-8"),f=u?`${u}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const m of d)try{const g=Buffer.from(m,"base64");if(await crypto.subtle.verify("HMAC",p,g,new TextEncoder().encode(f)))return}catch{continue}throw new Rr("The given webhook signature does not match the expected signature")}}ar=new WeakSet,uh=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")},Hn=function(e,t){if(!e)throw new Error("Headers are required");const r=e.get(t);if(r==null)throw new Error(`Missing required header: ${t}`);return r};var Ni,Eo,Gn,lh;let X=class{constructor({baseURL:e=er("OPENAI_BASE_URL"),apiKey:t=er("OPENAI_API_KEY"),organization:r=er("OPENAI_ORG_ID")??null,project:s=er("OPENAI_PROJECT_ID")??null,webhookSecret:a=er("OPENAI_WEBHOOK_SECRET")??null,...i}={}){if(Ni.add(this),Gn.set(this,void 0),this.completions=new Zd(this),this.chat=new co(this),this.embeddings=new Gd(this),this.files=new Wd(this),this.images=new eh(this),this.audio=new un(this),this.moderations=new rh(this),this.models=new th(this),this.fineTuning=new yr(this),this.graders=new bo(this),this.vectorStores=new Is(this),this.webhooks=new ch(this),this.beta=new cn(this),this.batches=new Ud(this),this.uploads=new So(this),this.responses=new vo(this),this.evals=new mo(this),this.containers=new fo(this),t===void 0)throw new F("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");const o={apiKey:t,organization:r,project:s,webhookSecret:a,...i,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Ff())throw new F(`It looks like you're running in a browser-like environment.
|
|
15
|
+
|
|
16
|
+
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
|
17
|
+
If you understand the risks and have appropriate mitigations in place,
|
|
18
|
+
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
|
19
|
+
|
|
20
|
+
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
|
21
|
+
|
|
22
|
+
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
|
23
|
+
`);this.baseURL=o.baseURL,this.timeout=o.timeout??Eo.DEFAULT_TIMEOUT,this.logger=o.logger??console;const u="warn";this.logLevel=u,this.logLevel=su(o.logLevel,"ClientOptions.logLevel",this)??su(er("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??u,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??Hf(),B(this,Gn,Jf),this._options=o,this.apiKey=t,this.organization=r,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.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return M([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Yf(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${nr}`}defaultIdempotencyKey(){return`stainless-node-retry-${Bl()}`}makeStatusError(e,t,r,s){return ke.generate(e,t,r,s)}buildURL(e,t,r){const s=!w(this,Ni,"m",lh).call(this)&&r||this.baseURL,a=Nf(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return Lf(i)||(t={...i,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(a.search=this.stringifyQuery(t)),a.toString()}async prepareOptions(e){}async prepareRequest(e,{url:t,options:r}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,r){return this.request(Promise.resolve(r).then(s=>({method:e,path:t,...s})))}request(e,t=null){return new xs(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,r){const s=await e,a=s.maxRetries??this.maxRetries;t==null&&(t=a),await this.prepareOptions(s);const{req:i,url:o,timeout:u}=await this.buildRequest(s,{retryCount:a-t});await this.prepareRequest(i,{url:o,options:s});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),l=r===void 0?"":`, retryOf: ${r}`,d=Date.now();if(Oe(this).debug(`[${c}] sending request`,Ft({retryOfRequestLogID:r,method:s.method,url:o,options:s,headers:i.headers})),s.signal?.aborted)throw new qe;const h=new AbortController,f=await this.fetchWithTimeout(o,i,u,h).catch(Ei),p=Date.now();if(f instanceof Error){const y=`retrying, ${t} attempts remaining`;if(s.signal?.aborted)throw new qe;const _=Si(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return Oe(this).info(`[${c}] connection ${_?"timed out":"failed"} - ${y}`),Oe(this).debug(`[${c}] connection ${_?"timed out":"failed"} (${y})`,Ft({retryOfRequestLogID:r,url:o,durationMs:p-d,message:f.message})),this.retryRequest(s,t,r??c);throw Oe(this).info(`[${c}] connection ${_?"timed out":"failed"} - error; no more retries left`),Oe(this).debug(`[${c}] connection ${_?"timed out":"failed"} (error; no more retries left)`,Ft({retryOfRequestLogID:r,url:o,durationMs:p-d,message:f.message})),_?new Es:new Ss({cause:f})}const m=[...f.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,_])=>", "+y+": "+JSON.stringify(_)).join(""),g=`[${c}${l}${m}] ${i.method} ${o} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${p-d}ms`;if(!f.ok){const y=await this.shouldRetry(f);if(t&&y){const P=`retrying, ${t} attempts remaining`;return await Gf(f.body),Oe(this).info(`${g} - ${P}`),Oe(this).debug(`[${c}] response error (${P})`,Ft({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),this.retryRequest(s,t,r??c,f.headers)}const _=y?"error; no more retries left":"error; not retryable";Oe(this).info(`${g} - ${_}`);const b=await f.text().catch(P=>Ei(P).message),v=Df(b),S=v?void 0:b;throw Oe(this).debug(`[${c}] response error (${_})`,Ft({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,message:S,durationMs:Date.now()-d})),this.makeStatusError(f.status,v,S,f.headers)}return Oe(this).info(g),Oe(this).debug(`[${c}] response start`,Ft({retryOfRequestLogID:r,url:f.url,status:f.status,headers:f.headers,durationMs:p-d})),{response:f,options:s,controller:h,requestLogID:c,retryOfRequestLogID:r,startTime:d}}getAPIList(e,t,r){return this.requestAPIList(t,{method:"get",path:e,...r})}requestAPIList(e,t){const r=this.makeRequest(t,null,void 0);return new up(this,r,e)}async fetchWithTimeout(e,t,r,s){const{signal:a,method:i,...o}=t||{};a&&a.addEventListener("abort",()=>s.abort());const u=setTimeout(()=>s.abort(),r),c=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,l={signal:s.signal,...c?{duplex:"half"}:{},method:"GET",...o};i&&(l.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,l)}finally{clearTimeout(u)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,r,s){let a;const i=s?.get("retry-after-ms");if(i){const u=parseFloat(i);Number.isNaN(u)||(a=u)}const o=s?.get("retry-after");if(o&&!a){const u=parseFloat(o);Number.isNaN(u)?a=Date.parse(o)-Date.now():a=u*1e3}if(!(a&&0<=a&&a<60*1e3)){const u=e.maxRetries??this.maxRetries;a=this.calculateDefaultRetryTimeoutMillis(t,u)}return await an(a),this.makeRequest(e,t-1,r)}calculateDefaultRetryTimeoutMillis(e,t){const a=t-e,i=Math.min(.5*Math.pow(2,a),8),o=1-Math.random()*.25;return i*o*1e3}async buildRequest(e,{retryCount:t=0}={}){const r={...e},{method:s,path:a,query:i,defaultBaseURL:o}=r,u=this.buildURL(a,i,o);"timeout"in r&&Uf("timeout",r.timeout),r.timeout=r.timeout??this.timeout;const{bodyHeaders:c,body:l}=this.buildBody({options:r}),d=await this.buildHeaders({options:e,method:s,bodyHeaders:c,retryCount:t});return{req:{method:s,headers:d,...r.signal&&{signal:r.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...this.fetchOptions??{},...r.fetchOptions??{}},url:u,timeout:r.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:r,retryCount:s}){let a={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),a[this.idempotencyHeader]=e.idempotencyKey);const i=M([a,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Zf(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,r,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const r=M([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&r.values.has("content-type")||e instanceof 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:Yl(e)}:w(this,Gn,"f").call(this,{body:e,headers:r})}};Eo=X,Gn=new WeakMap,Ni=new WeakSet,lh=function(){return this.baseURL!=="https://api.openai.com/v1"};X.OpenAI=Eo;X.DEFAULT_TIMEOUT=6e5;X.OpenAIError=F;X.APIError=ke;X.APIConnectionError=Ss;X.APIConnectionTimeoutError=Es;X.APIUserAbortError=qe;X.NotFoundError=Hl;X.ConflictError=Gl;X.RateLimitError=Wl;X.BadRequestError=zl;X.AuthenticationError=ql;X.InternalServerError=Vl;X.PermissionDeniedError=Zl;X.UnprocessableEntityError=Jl;X.InvalidWebhookSignatureError=Rr;X.toFile=pp;X.Completions=Zd;X.Chat=co;X.Embeddings=Gd;X.Files=Wd;X.Images=eh;X.Audio=un;X.Moderations=rh;X.Models=th;X.FineTuning=yr;X.Graders=bo;X.VectorStores=Is;X.Webhooks=ch;X.Beta=cn;X.Batches=Ud;X.Uploads=So;X.Responses=vo;X.Evals=mo;X.Containers=fo;function vu(n,e=Oo){n=n.trim();const t=n.indexOf("```");if(t===-1)return e(n);let r=n.substring(t+3);r.startsWith(`json
|
|
24
|
+
`)?r=r.substring(5):r.startsWith("json")?r=r.substring(4):r.startsWith(`
|
|
25
|
+
`)&&(r=r.substring(1));const s=r.indexOf("```");let a=r;return s!==-1&&(a=r.substring(0,s)),e(a.trim())}function Oo(n){if(typeof n>"u")return null;try{return JSON.parse(n)}catch{}let e="";const t=[];let r=!1,s=!1;for(let a of n){if(r)a==='"'&&!s?r=!1:a===`
|
|
26
|
+
`&&!s?a="\\n":a==="\\"?s=!s:s=!1;else if(a==='"')r=!0,s=!1;else if(a==="{")t.push("}");else if(a==="[")t.push("]");else if(a==="}"||a==="]")if(t&&t[t.length-1]===a)t.pop();else return null;e+=a}r&&(e+='"');for(let a=t.length-1;a>=0;a-=1)e+=t[a];try{return JSON.parse(e)}catch{return null}}var sa,Su;function zp(){return Su||(Su=1,sa=function(n,e){if(typeof n!="string")throw new TypeError("Expected a string");return e=typeof e>"u"?"_":e,n.replace(/([a-z\d])([A-Z])/g,"$1"+e+"$2").replace(/([A-Z]+)([A-Z][a-z\d]+)/g,"$1"+e+"$2").toLowerCase()}),sa}var qp=zp();const Zp=sn(qp);var En={exports:{}},Eu;function Hp(){if(Eu)return En.exports;Eu=1;const n=/[\p{Lu}]/u,e=/[\p{Ll}]/u,t=/^[\p{Lu}](?![\p{Lu}])/gu,r=/([\p{Alpha}\p{N}_]|$)/u,s=/[_.\- ]+/,a=new RegExp("^"+s.source),i=new RegExp(s.source+r.source,"gu"),o=new RegExp("\\d+"+r.source,"gu"),u=(h,f,p)=>{let m=!1,g=!1,y=!1;for(let _=0;_<h.length;_++){const b=h[_];m&&n.test(b)?(h=h.slice(0,_)+"-"+h.slice(_),m=!1,y=g,g=!0,_++):g&&y&&e.test(b)?(h=h.slice(0,_-1)+"-"+h.slice(_-1),y=g,g=!1,m=!0):(m=f(b)===b&&p(b)!==b,y=g,g=p(b)===b&&f(b)!==b)}return h},c=(h,f)=>(t.lastIndex=0,h.replace(t,p=>f(p))),l=(h,f)=>(i.lastIndex=0,o.lastIndex=0,h.replace(i,(p,m)=>f(m)).replace(o,p=>f(p))),d=(h,f)=>{if(!(typeof h=="string"||Array.isArray(h)))throw new TypeError("Expected the input to be `string | string[]`");if(f={pascalCase:!1,preserveConsecutiveUppercase:!1,...f},Array.isArray(h)?h=h.map(y=>y.trim()).filter(y=>y.length).join("-"):h=h.trim(),h.length===0)return"";const p=f.locale===!1?y=>y.toLowerCase():y=>y.toLocaleLowerCase(f.locale),m=f.locale===!1?y=>y.toUpperCase():y=>y.toLocaleUpperCase(f.locale);return h.length===1?f.pascalCase?m(h):p(h):(h!==p(h)&&(h=u(h,p,m)),h=h.replace(a,""),f.preserveConsecutiveUppercase?h=c(h,p):h=p(h),f.pascalCase&&(h=m(h.charAt(0))+h.slice(1)),l(h,m))};return En.exports=d,En.exports.default=d,En.exports}Hp();function Gp(n,e){return e?.[n]||Zp(n)}function Jp(n,e,t){const r={};for(const s in n)Object.hasOwn(n,s)&&(r[e(s,t)]=n[s]);return r}function Ou(n){return Array.isArray(n)?[...n]:{...n}}function Wp(n,e){const t=Ou(n);for(const[r,s]of Object.entries(e)){const[a,...i]=r.split(".").reverse();let o=t;for(const u of i.reverse()){if(o[u]===void 0)break;o[u]=Ou(o[u]),o=o[u]}o[a]!==void 0&&(o[a]={lc:1,type:"secret",id:[s]})}return t}function dh(n){const e=Object.getPrototypeOf(n);return typeof n.lc_name=="function"&&(typeof e.lc_name!="function"||n.lc_name()!==e.lc_name())?n.lc_name():n.name}class Wt{static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,dh(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...t){Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([r])=>this.lc_serializable_keys?.includes(r))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Wt||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();const e={},t={},r=Object.keys(this.lc_kwargs).reduce((s,a)=>(s[a]=a in this?this[a]:this.lc_kwargs[a],s),{});for(let s=Object.getPrototypeOf(this);s;s=Object.getPrototypeOf(s))Object.assign(e,Reflect.get(s,"lc_aliases",this)),Object.assign(t,Reflect.get(s,"lc_secrets",this)),Object.assign(r,Reflect.get(s,"lc_attributes",this));return Object.keys(t).forEach(s=>{let a=this,i=r;const[o,...u]=s.split(".").reverse();for(const c of u.reverse()){if(!(c in a)||a[c]===void 0)return;(!(c in i)||i[c]===void 0)&&(typeof a[c]=="object"&&a[c]!=null?i[c]={}:Array.isArray(a[c])&&(i[c]=[])),a=a[c],i=i[c]}o in a&&a[o]!==void 0&&(i[o]=i[o]||a[o])}),{lc:1,type:"constructor",id:this.lc_id,kwargs:Jp(Object.keys(t).length?Wp(r,t):r,Gp,e)}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}}function Vt(n){return typeof n=="object"&&n!==null&&"type"in n&&typeof n.type=="string"&&"source_type"in n&&(n.source_type==="url"||n.source_type==="base64"||n.source_type==="text"||n.source_type==="id")}function Vp(n){return Vt(n)&&n.source_type==="url"&&"url"in n&&typeof n.url=="string"}function Kp(n){return Vt(n)&&n.source_type==="base64"&&"data"in n&&typeof n.data=="string"}function Xp(n){if(Vt(n)){if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url}};if(n.source_type==="base64"){if(!n.mime_type)throw new Error("mime_type key is required for base64 data.");return{type:"image_url",image_url:{url:`data:${n.mime_type};base64,${n.data}`}}}}throw new Error("Unsupported source type. Only 'url' and 'base64' are supported.")}function xu(n){const e=n.split(";")[0].split("/");if(e.length!==2)throw new Error(`Invalid mime type: "${n}" - does not match type/subtype format.`);const t=e[0].trim(),r=e[1].trim();if(t===""||r==="")throw new Error(`Invalid mime type: "${n}" - type or subtype is empty.`);const s={};for(const a of n.split(";").slice(1)){const i=a.split("=");if(i.length!==2)throw new Error(`Invalid parameter syntax in mime type: "${n}".`);const o=i[0].trim(),u=i[1].trim();if(o==="")throw new Error(`Invalid parameter syntax in mime type: "${n}".`);s[o]=u}return{type:t,subtype:r,parameters:s}}function ku({dataUrl:n,asTypedArray:e=!1}){const t=n.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/);let r;if(t){r=t[1].toLowerCase();const s=e?Uint8Array.from(atob(t[2]),a=>a.charCodeAt(0)):t[2];return{mime_type:r,data:s}}}function hh(n,e){if(n.type==="text"){if(!e.fromStandardTextBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardTextBlock\` method.`);return e.fromStandardTextBlock(n)}if(n.type==="image"){if(!e.fromStandardImageBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardImageBlock\` method.`);return e.fromStandardImageBlock(n)}if(n.type==="audio"){if(!e.fromStandardAudioBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardAudioBlock\` method.`);return e.fromStandardAudioBlock(n)}if(n.type==="file"){if(!e.fromStandardFileBlock)throw new Error(`Converter for ${e.providerName} does not implement \`fromStandardFileBlock\` method.`);return e.fromStandardFileBlock(n)}throw new Error(`Unable to convert content block type '${n.type}' to provider-specific format: not recognized.`)}function _r(n,e){return typeof n=="string"?n===""?e:typeof e=="string"?n+e:Array.isArray(e)&&e.some(t=>Vt(t))?[{type:"text",source_type:"text",text:n},...e]:[{type:"text",text:n},...e]:Array.isArray(e)?Rs(n,e)??[...n,...e]:e===""?n:Array.isArray(n)&&n.some(t=>Vt(t))?[...n,{type:"file",source_type:"text",text:e}]:[...n,{type:"text",text:e}]}function Qp(n,e){return n==="error"||e==="error"?"error":"success"}function Yp(n,e){function t(r,s){if(typeof r!="object"||r===null||r===void 0)return r;if(s>=e)return Array.isArray(r)?"[Array]":"[Object]";if(Array.isArray(r))return r.map(i=>t(i,s+1));const a={};for(const i of Object.keys(r))a[i]=t(r[i],s+1);return a}return JSON.stringify(t(n,0),null,2)}class Qt extends Wt{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}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(""):""}getType(){return this._getType()}constructor(e,t){typeof e=="string"&&(e={content:e,additional_kwargs:t,response_metadata:{}}),e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{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,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.content=e.content,this.additional_kwargs=e.additional_kwargs,this.response_metadata=e.response_metadata,this.id=e.id}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}}_updateId(e){this.id=e,this.lc_kwargs.id=e}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](e){if(e===null)return this;const t=Yp(this._printableFields,Math.max(4,e));return`${this.constructor.lc_name()} ${t}`}}function Ce(n,e){const t={...n};for(const[r,s]of Object.entries(e))if(t[r]==null)t[r]=s;else{if(s==null)continue;if(typeof t[r]!=typeof s||Array.isArray(t[r])!==Array.isArray(s))throw new Error(`field[${r}] already exists in the message chunk, but with a different type.`);if(typeof t[r]=="string"){if(r==="type")continue;["id","name","output_version","model_provider"].includes(r)?t[r]=s:t[r]+=s}else if(typeof t[r]=="object"&&!Array.isArray(t[r]))t[r]=Ce(t[r],s);else if(Array.isArray(t[r]))t[r]=Rs(t[r],s);else{if(t[r]===s)continue;console.warn(`field[${r}] already exists in this message chunk and value has unsupported type.`)}}return t}function Rs(n,e){if(!(n===void 0&&e===void 0)){if(n===void 0||e===void 0)return n||e;{const t=[...n];for(const r of e)if(typeof r=="object"&&r!==null&&"index"in r&&typeof r.index=="number"){const s=t.findIndex(a=>{const i=typeof a=="object",o="index"in a&&a.index===r.index,u="id"in a&&"id"in r&&a?.id===r?.id,c=!("id"in a)||!a?.id||!("id"in r)||!r?.id;return i&&o&&(u||c)});s!==-1&&typeof t[s]=="object"&&t[s]!==null?t[s]=Ce(t[s],r):t.push(r)}else{if(typeof r=="object"&&r!==null&&"text"in r&&r.text==="")continue;t.push(r)}return t}}}function em(n,e){if(!n&&!e)throw new Error("Cannot merge two undefined objects.");if(!n||!e)return n||e;if(typeof n!=typeof e)throw new Error(`Cannot merge objects of different types.
|
|
27
|
+
Left ${typeof n}
|
|
28
|
+
Right ${typeof e}`);if(typeof n=="string"&&typeof e=="string")return n+e;if(Array.isArray(n)&&Array.isArray(e))return Rs(n,e);if(typeof n=="object"&&typeof e=="object")return Ce(n,e);if(n===e)return n;throw new Error(`Can not merge objects of different types.
|
|
29
|
+
Left ${n}
|
|
30
|
+
Right ${e}`)}class br extends Qt{}function tm(n){return typeof n.role=="string"}function Ps(n){return typeof n?._getType=="function"}function rm(n){return Ps(n)&&typeof n.concat=="function"}class nm extends Qt{static lc_name(){return"ToolMessage"}get lc_aliases(){return{tool_call_id:"tool_call_id"}}constructor(e,t,r){typeof e=="string"&&(e={content:e,name:r,tool_call_id:t}),super(e),Object.defineProperty(this,"lc_direct_tool_output",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status,this.metadata=e.metadata}_getType(){return"tool"}static isInstance(e){return e._getType()==="tool"}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}class xo extends br{constructor(e){super(e),Object.defineProperty(this,"tool_call_id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"artifact",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_id=e.tool_call_id,this.artifact=e.artifact,this.status=e.status}static lc_name(){return"ToolMessageChunk"}_getType(){return"tool"}concat(e){return new xo({content:_r(this.content,e.content),additional_kwargs:Ce(this.additional_kwargs,e.additional_kwargs),response_metadata:Ce(this.response_metadata,e.response_metadata),artifact:em(this.artifact,e.artifact),tool_call_id:this.tool_call_id,id:this.id??e.id,status:Qp(this.status,e.status)})}get _printableFields(){return{...super._printableFields,tool_call_id:this.tool_call_id,artifact:this.artifact}}}function sm(n){const e=[],t=[];for(const r of n)if(r.function){const s=r.function.name;try{const a=JSON.parse(r.function.arguments),i={name:s||"",args:a||{},id:r.id};e.push(i)}catch{t.push({name:s,args:r.function.arguments,id:r.id,error:"Malformed args."})}}else continue;return[e,t]}class Kr extends Qt{get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls"}}constructor(e,t){let r;if(typeof e=="string")r={content:e,tool_calls:[],invalid_tool_calls:[],additional_kwargs:t??{}};else{r=e;const s=r.additional_kwargs?.tool_calls,a=r.tool_calls;s!=null&&s.length>0&&(a===void 0||a.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
|
|
31
|
+
|
|
32
|
+
Please upgrade your packages to versions that set`,"message tool calls. e.g., `yarn add @langchain/anthropic`,","yarn add @langchain/openai`, etc."].join(" "));try{if(s!=null&&a===void 0){const[i,o]=sm(s);r.tool_calls=i??[],r.invalid_tool_calls=o??[]}else r.tool_calls=r.tool_calls??[],r.invalid_tool_calls=r.invalid_tool_calls??[]}catch{r.tool_calls=[],r.invalid_tool_calls=[]}}super(r),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof r!="string"&&(this.tool_calls=r.tool_calls??this.tool_calls,this.invalid_tool_calls=r.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=r.usage_metadata}static lc_name(){return"AIMessage"}_getType(){return"ai"}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}}function ln(n){return n._getType()==="ai"}function Tu(n){return n._getType()==="ai"}class $t extends br{constructor(e){let t;if(typeof e=="string")t={content:e,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(e.tool_call_chunks===void 0)t={...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=e.tool_call_chunks.reduce((i,o)=>{const u=i.findIndex(([c])=>"id"in o&&o.id&&"index"in o&&o.index!==void 0?o.id===c.id&&o.index===c.index:"id"in o&&o.id?o.id===c.id:"index"in o&&o.index!==void 0?o.index===c.index:!1);return u!==-1?i[u].push(o):i.push([o]),i},[]),s=[],a=[];for(const i of r){let o={};const u=i[0]?.name??"",c=i.map(h=>h.args||"").join(""),l=c.length?c:"{}",d=i[0]?.id;try{if(o=Oo(l),!d||o===null||typeof o!="object"||Array.isArray(o))throw new Error("Malformed tool call chunk args.");s.push({name:u,args:o,id:d,type:"tool_call"})}catch{a.push({name:u,args:l,id:d,error:"Malformed args.",type:"invalid_tool_call"})}}t={...e,tool_calls:s,invalid_tool_calls:a,usage_metadata:e.usage_metadata!==void 0?e.usage_metadata:void 0}}super(t),Object.defineProperty(this,"tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"invalid_tool_calls",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tool_call_chunks",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"usage_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.tool_call_chunks=t.tool_call_chunks??this.tool_call_chunks,this.tool_calls=t.tool_calls??this.tool_calls,this.invalid_tool_calls=t.invalid_tool_calls??this.invalid_tool_calls,this.usage_metadata=t.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"}}static lc_name(){return"AIMessageChunk"}_getType(){return"ai"}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 t={content:_r(this.content,e.content),additional_kwargs:Ce(this.additional_kwargs,e.additional_kwargs),response_metadata:Ce(this.response_metadata,e.response_metadata),tool_call_chunks:[],id:this.id??e.id};if(this.tool_call_chunks!==void 0||e.tool_call_chunks!==void 0){const r=Rs(this.tool_call_chunks,e.tool_call_chunks);r!==void 0&&r.length>0&&(t.tool_call_chunks=r)}if(this.usage_metadata!==void 0||e.usage_metadata!==void 0){const r={...(this.usage_metadata?.input_token_details?.audio!==void 0||e.usage_metadata?.input_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.input_token_details?.audio??0)+(e.usage_metadata?.input_token_details?.audio??0)},...(this.usage_metadata?.input_token_details?.cache_read!==void 0||e.usage_metadata?.input_token_details?.cache_read!==void 0)&&{cache_read:(this.usage_metadata?.input_token_details?.cache_read??0)+(e.usage_metadata?.input_token_details?.cache_read??0)},...(this.usage_metadata?.input_token_details?.cache_creation!==void 0||e.usage_metadata?.input_token_details?.cache_creation!==void 0)&&{cache_creation:(this.usage_metadata?.input_token_details?.cache_creation??0)+(e.usage_metadata?.input_token_details?.cache_creation??0)}},s={...(this.usage_metadata?.output_token_details?.audio!==void 0||e.usage_metadata?.output_token_details?.audio!==void 0)&&{audio:(this.usage_metadata?.output_token_details?.audio??0)+(e.usage_metadata?.output_token_details?.audio??0)},...(this.usage_metadata?.output_token_details?.reasoning!==void 0||e.usage_metadata?.output_token_details?.reasoning!==void 0)&&{reasoning:(this.usage_metadata?.output_token_details?.reasoning??0)+(e.usage_metadata?.output_token_details?.reasoning??0)}},a=this.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},i=e.usage_metadata??{input_tokens:0,output_tokens:0,total_tokens:0},o={input_tokens:a.input_tokens+i.input_tokens,output_tokens:a.output_tokens+i.output_tokens,total_tokens:a.total_tokens+i.total_tokens,...Object.keys(r).length>0&&{input_token_details:r},...Object.keys(s).length>0&&{output_token_details:s}};t.usage_metadata=o}return new $t(t)}}class dn extends Qt{static lc_name(){return"ChatMessage"}static _chatMessageClass(){return dn}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}static isInstance(e){return e._getType()==="generic"}get _printableFields(){return{...super._printableFields,role:this.role}}}class Cs extends br{static lc_name(){return"ChatMessageChunk"}constructor(e,t){typeof e=="string"&&(e={content:e,role:t}),super(e),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e.role}_getType(){return"generic"}concat(e){return new Cs({content:_r(this.content,e.content),additional_kwargs:Ce(this.additional_kwargs,e.additional_kwargs),response_metadata:Ce(this.response_metadata,e.response_metadata),role:this.role,id:this.id??e.id})}get _printableFields(){return{...super._printableFields,role:this.role}}}class $s extends br{static lc_name(){return"FunctionMessageChunk"}_getType(){return"function"}concat(e){return new $s({content:_r(this.content,e.content),additional_kwargs:Ce(this.additional_kwargs,e.additional_kwargs),response_metadata:Ce(this.response_metadata,e.response_metadata),name:this.name??"",id:this.id??e.id})}}class Ns extends Qt{static lc_name(){return"HumanMessage"}_getType(){return"human"}constructor(e,t){super(e,t)}}class js extends br{static lc_name(){return"HumanMessageChunk"}_getType(){return"human"}constructor(e,t){super(e,t)}concat(e){return new js({content:_r(this.content,e.content),additional_kwargs:Ce(this.additional_kwargs,e.additional_kwargs),response_metadata:Ce(this.response_metadata,e.response_metadata),id:this.id??e.id})}}class Au extends Qt{static lc_name(){return"SystemMessage"}_getType(){return"system"}constructor(e,t){super(e,t)}}class Xr extends br{static lc_name(){return"SystemMessageChunk"}_getType(){return"system"}constructor(e,t){super(e,t)}concat(e){return new Xr({content:_r(this.content,e.content),additional_kwargs:Ce(this.additional_kwargs,e.additional_kwargs),response_metadata:Ce(this.response_metadata,e.response_metadata),id:this.id??e.id})}}function fh(n,e){return n.lc_error_code=e,n.message=`${n.message}
|
|
33
|
+
|
|
34
|
+
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
|
|
35
|
+
`,n}function ph(n){return!!(n&&typeof n=="object"&&"type"in n&&n.type==="tool_call")}class am extends Error{constructor(e,t){super(e),Object.defineProperty(this,"output",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.output=t}}class im extends Qt{constructor(e){super({...e,content:""}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.id=e.id}_getType(){return"remove"}get _printableFields(){return{...super._printableFields,id:this.id}}}function om(n){return ph(n)?n:typeof n.id=="string"&&n.type==="function"&&typeof n.function=="object"&&n.function!==null&&"arguments"in n.function&&typeof n.function.arguments=="string"&&"name"in n.function&&typeof n.function.name=="string"?{id:n.id,args:JSON.parse(n.function.arguments),name:n.function.name,type:"tool_call"}:n}function um(n){return typeof n=="object"&&n!=null&&n.lc===1&&Array.isArray(n.id)&&n.kwargs!=null&&typeof n.kwargs=="object"}function aa(n){let e,t;if(um(n)){const r=n.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",t=n.kwargs}else{const{type:r,...s}=n;e=r,t=s}if(e==="human"||e==="user")return new Ns(t);if(e==="ai"||e==="assistant"){const{tool_calls:r,...s}=t;if(!Array.isArray(r))return new Kr(t);const a=r.map(om);return new Kr({...s,tool_calls:a})}else{if(e==="system")return new Au(t);if(e==="developer")return new Au({...t,additional_kwargs:{...t.additional_kwargs,__openai_role__:"developer"}});if(e==="tool"&&"tool_call_id"in t)return new nm({...t,content:t.content,tool_call_id:t.tool_call_id,name:t.name});if(e==="remove"&&"id"in t&&typeof t.id=="string")return new im({...t,id:t.id});throw fh(new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.
|
|
36
|
+
|
|
37
|
+
Received: ${JSON.stringify(n,null,2)}`),"MESSAGE_COERCION_FAILURE")}}function Dr(n){if(typeof n=="string")return new Ns(n);if(Ps(n))return n;if(Array.isArray(n)){const[e,t]=n;return aa({type:e,content:t})}else if(tm(n)){const{role:e,...t}=n;return aa({...t,type:e})}else return aa(n)}function mh(n,e="Human",t="AI"){const r=[];for(const s of n){let a;if(s._getType()==="human")a=e;else if(s._getType()==="ai")a=t;else if(s._getType()==="system")a="System";else if(s._getType()==="function")a="Function";else if(s._getType()==="tool")a="Tool";else if(s._getType()==="generic")a=s.role;else throw new Error(`Got unsupported message type: ${s._getType()}`);const i=s.name?`${s.name}, `:"",o=typeof s.content=="string"?s.content:JSON.stringify(s.content,null,2);r.push(`${a}: ${i}${o}`)}return r.join(`
|
|
38
|
+
`)}function cm(n){const e=n._getType();if(e==="human")return new js({...n});if(e==="ai"){let t={...n};return"tool_calls"in t&&(t={...t,tool_call_chunks:t.tool_calls?.map(r=>({...r,type:"tool_call_chunk",index:void 0,args:JSON.stringify(r.args)}))}),new $t({...t})}else{if(e==="system")return new Xr({...n});if(e==="function")return new $s({...n});if(dn.isInstance(n))return new Cs({...n});throw new Error("Unknown message type.")}}var ee;(function(n){n.assertEqual=s=>{};function e(s){}n.assertIs=e;function t(s){throw new Error}n.assertNever=t,n.arrayToEnum=s=>{const a={};for(const i of s)a[i]=i;return a},n.getValidEnumValues=s=>{const a=n.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(const o of a)i[o]=s[o];return n.objectValues(i)},n.objectValues=s=>n.objectKeys(s).map(function(a){return s[a]}),n.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{const a=[];for(const i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},n.find=(s,a)=>{for(const i of s)if(a(i))return i},n.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function r(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}n.joinValues=r,n.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(ee||(ee={}));var Iu;(function(n){n.mergeShapes=(e,t)=>({...e,...t})})(Iu||(Iu={}));const C=ee.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),xt=n=>{switch(typeof n){case"undefined":return C.undefined;case"string":return C.string;case"number":return Number.isNaN(n)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(n)?C.array:n===null?C.null:n.then&&typeof n.then=="function"&&n.catch&&typeof n.catch=="function"?C.promise:typeof Map<"u"&&n instanceof Map?C.map:typeof Set<"u"&&n instanceof Set?C.set:typeof Date<"u"&&n instanceof Date?C.date:C.object;default:return C.unknown}},E=ee.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 wt 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 t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){const t=e||function(a){return a.message},r={_errors:[]},s=a=>{for(const i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)r._errors.push(t(i));else{let o=r,u=0;for(;u<i.path.length;){const c=i.path[u];u===i.path.length-1?(o[c]=o[c]||{_errors:[]},o[c]._errors.push(t(i))):o[c]=o[c]||{_errors:[]},o=o[c],u++}}};return s(this),r}static assert(e){if(!(e instanceof wt))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,ee.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){const t={},r=[];for(const s of this.issues)if(s.path.length>0){const a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else r.push(e(s));return{formErrors:r,fieldErrors:t}}get formErrors(){return this.flatten()}}wt.create=n=>new wt(n);const ji=(n,e)=>{let t;switch(n.code){case E.invalid_type:n.received===C.undefined?t="Required":t=`Expected ${n.expected}, received ${n.received}`;break;case E.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(n.expected,ee.jsonStringifyReplacer)}`;break;case E.unrecognized_keys:t=`Unrecognized key(s) in object: ${ee.joinValues(n.keys,", ")}`;break;case E.invalid_union:t="Invalid input";break;case E.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${ee.joinValues(n.options)}`;break;case E.invalid_enum_value:t=`Invalid enum value. Expected ${ee.joinValues(n.options)}, received '${n.received}'`;break;case E.invalid_arguments:t="Invalid function arguments";break;case E.invalid_return_type:t="Invalid function return type";break;case E.invalid_date:t="Invalid date";break;case E.invalid_string:typeof n.validation=="object"?"includes"in n.validation?(t=`Invalid input: must include "${n.validation.includes}"`,typeof n.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${n.validation.position}`)):"startsWith"in n.validation?t=`Invalid input: must start with "${n.validation.startsWith}"`:"endsWith"in n.validation?t=`Invalid input: must end with "${n.validation.endsWith}"`:ee.assertNever(n.validation):n.validation!=="regex"?t=`Invalid ${n.validation}`:t="Invalid";break;case E.too_small:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at least":"more than"} ${n.minimum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at least":"over"} ${n.minimum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="bigint"?t=`Number must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${n.minimum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly equal to ":n.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(n.minimum))}`:t="Invalid input";break;case E.too_big:n.type==="array"?t=`Array must contain ${n.exact?"exactly":n.inclusive?"at most":"less than"} ${n.maximum} element(s)`:n.type==="string"?t=`String must contain ${n.exact?"exactly":n.inclusive?"at most":"under"} ${n.maximum} character(s)`:n.type==="number"?t=`Number must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="bigint"?t=`BigInt must be ${n.exact?"exactly":n.inclusive?"less than or equal to":"less than"} ${n.maximum}`:n.type==="date"?t=`Date must be ${n.exact?"exactly":n.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(n.maximum))}`:t="Invalid input";break;case E.custom:t="Invalid input";break;case E.invalid_intersection_types:t="Intersection results could not be merged";break;case E.not_multiple_of:t=`Number must be a multiple of ${n.multipleOf}`;break;case E.not_finite:t="Number must be finite";break;default:t=e.defaultError,ee.assertNever(n)}return{message:t}};let lm=ji;function dm(){return lm}const hm=n=>{const{data:e,path:t,errorMaps:r,issueData:s}=n,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="";const u=r.filter(c=>!!c).slice().reverse();for(const c of u)o=c(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}};function A(n,e){const t=dm(),r=hm({issueData:e,data:n.data,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,t,t===ji?void 0:ji].filter(s=>!!s)});n.common.issues.push(r)}class Ze{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){const r=[];for(const s of t){if(s.status==="aborted")return q;s.status==="dirty"&&e.dirty(),r.push(s.value)}return{status:e.value,value:r}}static async mergeObjectAsync(e,t){const r=[];for(const s of t){const a=await s.key,i=await s.value;r.push({key:a,value:i})}return Ze.mergeObjectSync(e,r)}static mergeObjectSync(e,t){const r={};for(const s of t){const{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return q;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(r[a.value]=i.value)}return{status:e.value,value:r}}}const q=Object.freeze({status:"aborted"}),Fr=n=>({status:"dirty",value:n}),We=n=>({status:"valid",value:n}),Ru=n=>n.status==="aborted",Pu=n=>n.status==="dirty",dr=n=>n.status==="valid",ss=n=>typeof Promise<"u"&&n instanceof Promise;var $;(function(n){n.errToObj=e=>typeof e=="string"?{message:e}:e||{},n.toString=e=>typeof e=="string"?e:e?.message})($||($={}));class Nt{constructor(e,t,r,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=r,this._key=s}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 Cu=(n,e)=>{if(dr(e))return{success:!0,data:e.value};if(!n.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;const t=new wt(n.common.issues);return this._error=t,this._error}}};function V(n){if(!n)return{};const{errorMap:e,invalid_type_error:t,required_error:r,description:s}=n;if(e&&(t||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{const{message:u}=n;return i.code==="invalid_enum_value"?{message:u??o.defaultError}:typeof o.data>"u"?{message:u??r??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:u??t??o.defaultError}},description:s}}class Y{get description(){return this._def.description}_getType(e){return xt(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:xt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Ze,ctx:{common:e.parent.common,data:e.data,parsedType:xt(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){const t=this._parse(e);if(ss(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){const t=this._parse(e);return Promise.resolve(t)}parse(e,t){const r=this.safeParse(e,t);if(r.success)return r.data;throw r.error}safeParse(e,t){const r={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xt(e)},s=this._parseSync({data:e,path:r.path,parent:r});return Cu(r,s)}"~validate"(e){const t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xt(e)};if(!this["~standard"].async)try{const r=this._parseSync({data:e,path:[],parent:t});return dr(r)?{value:r.value}:{issues:t.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(r=>dr(r)?{value:r.value}:{issues:t.common.issues})}async parseAsync(e,t){const r=await this.safeParseAsync(e,t);if(r.success)return r.data;throw r.error}async safeParseAsync(e,t){const r={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:xt(e)},s=this._parse({data:e,path:r.path,parent:r}),a=await(ss(s)?s:Promise.resolve(s));return Cu(r,a)}refine(e,t){const r=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{const i=e(s),o=()=>a.addIssue({code:E.custom,...r(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(u=>u?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((r,s)=>e(r)?!0:(s.addIssue(typeof t=="function"?t(r,s):t),!1))}_refinement(e){return new fr({schema:this,typeName:O.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:t=>this["~validate"](t)}}optional(){return Pt.create(this,this._def)}nullable(){return pr.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return ht.create(this)}promise(){return us.create(this,this._def)}or(e){return is.create([this,e],this._def)}and(e){return os.create(this,e,this._def)}transform(e){return new fr({...V(this._def),schema:this,typeName:O.ZodEffects,effect:{type:"transform",transform:e}})}default(e){const t=typeof e=="function"?e:()=>e;return new Ui({...V(this._def),innerType:this,defaultValue:t,typeName:O.ZodDefault})}brand(){return new jm({typeName:O.ZodBranded,type:this,...V(this._def)})}catch(e){const t=typeof e=="function"?e:()=>e;return new Di({...V(this._def),innerType:this,catchValue:t,typeName:O.ZodCatch})}describe(e){const t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ko.create(this,e)}readonly(){return Fi.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}}const fm=/^c[^\s-]{8,}$/i,pm=/^[0-9a-z]+$/,mm=/^[0-9A-HJKMNP-TV-Z]{26}$/i,gm=/^[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,ym=/^[a-z0-9_-]{21}$/i,_m=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,bm=/^[-+]?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)?)??$/,wm=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,vm="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";let ia;const Sm=/^(?:(?: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])$/,Em=/^(?:(?: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])$/,Om=/^(([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]))$/,xm=/^(([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])$/,km=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Tm=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gh="((\\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])))",Am=new RegExp(`^${gh}$`);function yh(n){let e="[0-5]\\d";n.precision?e=`${e}\\.\\d{${n.precision}}`:n.precision==null&&(e=`${e}(\\.\\d+)?`);const t=n.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Im(n){return new RegExp(`^${yh(n)}$`)}function Rm(n){let e=`${gh}T${yh(n)}`;const t=[];return t.push(n.local?"Z?":"Z"),n.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Pm(n,e){return!!((e==="v4"||!e)&&Sm.test(n)||(e==="v6"||!e)&&Om.test(n))}function Cm(n,e){if(!_m.test(n))return!1;try{const[t]=n.split(".");if(!t)return!1;const r=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(r));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function $m(n,e){return!!((e==="v4"||!e)&&Em.test(n)||(e==="v6"||!e)&&xm.test(n))}class At extends Y{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==C.string){const a=this._getOrReturnCtx(e);return A(a,{code:E.invalid_type,expected:C.string,received:a.parsedType}),q}const r=new Ze;let s;for(const a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:E.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:E.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),r.dirty());else if(a.kind==="length"){const i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?A(s,{code:E.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&A(s,{code:E.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),r.dirty())}else if(a.kind==="email")wm.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"email",code:E.invalid_string,message:a.message}),r.dirty());else if(a.kind==="emoji")ia||(ia=new RegExp(vm,"u")),ia.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"emoji",code:E.invalid_string,message:a.message}),r.dirty());else if(a.kind==="uuid")gm.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"uuid",code:E.invalid_string,message:a.message}),r.dirty());else if(a.kind==="nanoid")ym.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"nanoid",code:E.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid")fm.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid",code:E.invalid_string,message:a.message}),r.dirty());else if(a.kind==="cuid2")pm.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cuid2",code:E.invalid_string,message:a.message}),r.dirty());else if(a.kind==="ulid")mm.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ulid",code:E.invalid_string,message:a.message}),r.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),A(s,{validation:"url",code:E.invalid_string,message:a.message}),r.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"regex",code:E.invalid_string,message:a.message}),r.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),A(s,{code:E.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),r.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:E.invalid_string,validation:{startsWith:a.value},message:a.message}),r.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),A(s,{code:E.invalid_string,validation:{endsWith:a.value},message:a.message}),r.dirty()):a.kind==="datetime"?Rm(a).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:E.invalid_string,validation:"datetime",message:a.message}),r.dirty()):a.kind==="date"?Am.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:E.invalid_string,validation:"date",message:a.message}),r.dirty()):a.kind==="time"?Im(a).test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{code:E.invalid_string,validation:"time",message:a.message}),r.dirty()):a.kind==="duration"?bm.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"duration",code:E.invalid_string,message:a.message}),r.dirty()):a.kind==="ip"?Pm(e.data,a.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"ip",code:E.invalid_string,message:a.message}),r.dirty()):a.kind==="jwt"?Cm(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"jwt",code:E.invalid_string,message:a.message}),r.dirty()):a.kind==="cidr"?$m(e.data,a.version)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"cidr",code:E.invalid_string,message:a.message}),r.dirty()):a.kind==="base64"?km.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64",code:E.invalid_string,message:a.message}),r.dirty()):a.kind==="base64url"?Tm.test(e.data)||(s=this._getOrReturnCtx(e,s),A(s,{validation:"base64url",code:E.invalid_string,message:a.message}),r.dirty()):ee.assertNever(a);return{status:r.value,value:e.data}}_regex(e,t,r){return this.refinement(s=>e.test(s),{validation:t,code:E.invalid_string,...$.errToObj(r)})}_addCheck(e){return new At({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...$.errToObj(e)})}url(e){return this._addCheck({kind:"url",...$.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...$.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...$.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...$.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...$.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...$.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...$.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...$.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...$.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...$.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...$.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...$.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?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...$.errToObj(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?.precision>"u"?null:e?.precision,...$.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...$.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...$.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...$.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...$.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...$.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...$.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...$.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...$.errToObj(t)})}nonempty(e){return this.min(1,$.errToObj(e))}trim(){return new At({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new At({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new At({...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 t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}At.create=n=>new At({checks:[],typeName:O.ZodString,coerce:n?.coerce??!1,...V(n)});function Nm(n,e){const t=(n.toString().split(".")[1]||"").length,r=(e.toString().split(".")[1]||"").length,s=t>r?t:r,a=Number.parseInt(n.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}class Qr extends Y{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)!==C.number){const a=this._getOrReturnCtx(e);return A(a,{code:E.invalid_type,expected:C.number,received:a.parsedType}),q}let r;const s=new Ze;for(const a of this._def.checks)a.kind==="int"?ee.isInteger(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{code:E.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),A(r,{code:E.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),A(r,{code:E.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?Nm(e.data,a.value)!==0&&(r=this._getOrReturnCtx(e,r),A(r,{code:E.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(r=this._getOrReturnCtx(e,r),A(r,{code:E.not_finite,message:a.message}),s.dirty()):ee.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,$.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$.toString(t))}setLimit(e,t,r,s){return new Qr({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:$.toString(s)}]})}_addCheck(e){return new Qr({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:$.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:$.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:$.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:$.toString(e)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&ee.isInteger(e.value))}get isFinite(){let e=null,t=null;for(const r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(t===null||r.value>t)&&(t=r.value):r.kind==="max"&&(e===null||r.value<e)&&(e=r.value)}return Number.isFinite(t)&&Number.isFinite(e)}}Qr.create=n=>new Qr({checks:[],typeName:O.ZodNumber,coerce:n?.coerce||!1,...V(n)});class Yr extends Y{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)!==C.bigint)return this._getInvalidInput(e);let r;const s=new Ze;for(const a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(r=this._getOrReturnCtx(e,r),A(r,{code:E.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(r=this._getOrReturnCtx(e,r),A(r,{code:E.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(r=this._getOrReturnCtx(e,r),A(r,{code:E.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):ee.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){const t=this._getOrReturnCtx(e);return A(t,{code:E.invalid_type,expected:C.bigint,received:t.parsedType}),q}gte(e,t){return this.setLimit("min",e,!0,$.toString(t))}gt(e,t){return this.setLimit("min",e,!1,$.toString(t))}lte(e,t){return this.setLimit("max",e,!0,$.toString(t))}lt(e,t){return this.setLimit("max",e,!1,$.toString(t))}setLimit(e,t,r,s){return new Yr({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:r,message:$.toString(s)}]})}_addCheck(e){return new Yr({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:$.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:$.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:$.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:$.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:$.toString(t)})}get minValue(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}}Yr.create=n=>new Yr({checks:[],typeName:O.ZodBigInt,coerce:n?.coerce??!1,...V(n)});class $u extends Y{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==C.boolean){const r=this._getOrReturnCtx(e);return A(r,{code:E.invalid_type,expected:C.boolean,received:r.parsedType}),q}return We(e.data)}}$u.create=n=>new $u({typeName:O.ZodBoolean,coerce:n?.coerce||!1,...V(n)});class as extends Y{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==C.date){const a=this._getOrReturnCtx(e);return A(a,{code:E.invalid_type,expected:C.date,received:a.parsedType}),q}if(Number.isNaN(e.data.getTime())){const a=this._getOrReturnCtx(e);return A(a,{code:E.invalid_date}),q}const r=new Ze;let s;for(const a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:E.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),r.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),A(s,{code:E.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),r.dirty()):ee.assertNever(a);return{status:r.value,value:new Date(e.data.getTime())}}_addCheck(e){return new as({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:$.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:$.toString(t)})}get minDate(){let e=null;for(const t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(const t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}}as.create=n=>new as({checks:[],coerce:n?.coerce||!1,typeName:O.ZodDate,...V(n)});class Nu extends Y{_parse(e){if(this._getType(e)!==C.symbol){const r=this._getOrReturnCtx(e);return A(r,{code:E.invalid_type,expected:C.symbol,received:r.parsedType}),q}return We(e.data)}}Nu.create=n=>new Nu({typeName:O.ZodSymbol,...V(n)});class ju extends Y{_parse(e){if(this._getType(e)!==C.undefined){const r=this._getOrReturnCtx(e);return A(r,{code:E.invalid_type,expected:C.undefined,received:r.parsedType}),q}return We(e.data)}}ju.create=n=>new ju({typeName:O.ZodUndefined,...V(n)});class Lu extends Y{_parse(e){if(this._getType(e)!==C.null){const r=this._getOrReturnCtx(e);return A(r,{code:E.invalid_type,expected:C.null,received:r.parsedType}),q}return We(e.data)}}Lu.create=n=>new Lu({typeName:O.ZodNull,...V(n)});class Li extends Y{constructor(){super(...arguments),this._any=!0}_parse(e){return We(e.data)}}Li.create=n=>new Li({typeName:O.ZodAny,...V(n)});class Mu extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(e){return We(e.data)}}Mu.create=n=>new Mu({typeName:O.ZodUnknown,...V(n)});class jt extends Y{_parse(e){const t=this._getOrReturnCtx(e);return A(t,{code:E.invalid_type,expected:C.never,received:t.parsedType}),q}}jt.create=n=>new jt({typeName:O.ZodNever,...V(n)});class Uu extends Y{_parse(e){if(this._getType(e)!==C.undefined){const r=this._getOrReturnCtx(e);return A(r,{code:E.invalid_type,expected:C.void,received:r.parsedType}),q}return We(e.data)}}Uu.create=n=>new Uu({typeName:O.ZodVoid,...V(n)});class ht extends Y{_parse(e){const{ctx:t,status:r}=this._processInputParams(e),s=this._def;if(t.parsedType!==C.array)return A(t,{code:E.invalid_type,expected:C.array,received:t.parsedType}),q;if(s.exactLength!==null){const i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(A(t,{code:i?E.too_big:E.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),r.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(A(t,{code:E.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),r.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(A(t,{code:E.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),r.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new Nt(t,i,t.path,o)))).then(i=>Ze.mergeArray(r,i));const a=[...t.data].map((i,o)=>s.type._parseSync(new Nt(t,i,t.path,o)));return Ze.mergeArray(r,a)}get element(){return this._def.type}min(e,t){return new ht({...this._def,minLength:{value:e,message:$.toString(t)}})}max(e,t){return new ht({...this._def,maxLength:{value:e,message:$.toString(t)}})}length(e,t){return new ht({...this._def,exactLength:{value:e,message:$.toString(t)}})}nonempty(e){return this.min(1,e)}}ht.create=(n,e)=>new ht({type:n,minLength:null,maxLength:null,exactLength:null,typeName:O.ZodArray,...V(e)});function ir(n){if(n instanceof le){const e={};for(const t in n.shape){const r=n.shape[t];e[t]=Pt.create(ir(r))}return new le({...n._def,shape:()=>e})}else return n instanceof ht?new ht({...n._def,type:ir(n.element)}):n instanceof Pt?Pt.create(ir(n.unwrap())):n instanceof pr?pr.create(ir(n.unwrap())):n instanceof Kt?Kt.create(n.items.map(e=>ir(e))):n}class le extends Y{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(),t=ee.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==C.object){const c=this._getOrReturnCtx(e);return A(c,{code:E.invalid_type,expected:C.object,received:c.parsedType}),q}const{status:r,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof jt&&this._def.unknownKeys==="strip"))for(const c in s.data)i.includes(c)||o.push(c);const u=[];for(const c of i){const l=a[c],d=s.data[c];u.push({key:{status:"valid",value:c},value:l._parse(new Nt(s,d,s.path,c)),alwaysSet:c in s.data})}if(this._def.catchall instanceof jt){const c=this._def.unknownKeys;if(c==="passthrough")for(const l of o)u.push({key:{status:"valid",value:l},value:{status:"valid",value:s.data[l]}});else if(c==="strict")o.length>0&&(A(s,{code:E.unrecognized_keys,keys:o}),r.dirty());else if(c!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{const c=this._def.catchall;for(const l of o){const d=s.data[l];u.push({key:{status:"valid",value:l},value:c._parse(new Nt(s,d,s.path,l)),alwaysSet:l in s.data})}}return s.common.async?Promise.resolve().then(async()=>{const c=[];for(const l of u){const d=await l.key,h=await l.value;c.push({key:d,value:h,alwaysSet:l.alwaysSet})}return c}).then(c=>Ze.mergeObjectSync(r,c)):Ze.mergeObjectSync(r,u)}get shape(){return this._def.shape()}strict(e){return $.errToObj,new le({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,r)=>{const s=this._def.errorMap?.(t,r).message??r.defaultError;return t.code==="unrecognized_keys"?{message:$.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new le({...this._def,unknownKeys:"strip"})}passthrough(){return new le({...this._def,unknownKeys:"passthrough"})}extend(e){return new le({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new le({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:O.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new le({...this._def,catchall:e})}pick(e){const t={};for(const r of ee.objectKeys(e))e[r]&&this.shape[r]&&(t[r]=this.shape[r]);return new le({...this._def,shape:()=>t})}omit(e){const t={};for(const r of ee.objectKeys(this.shape))e[r]||(t[r]=this.shape[r]);return new le({...this._def,shape:()=>t})}deepPartial(){return ir(this)}partial(e){const t={};for(const r of ee.objectKeys(this.shape)){const s=this.shape[r];e&&!e[r]?t[r]=s:t[r]=s.optional()}return new le({...this._def,shape:()=>t})}required(e){const t={};for(const r of ee.objectKeys(this.shape))if(e&&!e[r])t[r]=this.shape[r];else{let a=this.shape[r];for(;a instanceof Pt;)a=a._def.innerType;t[r]=a}return new le({...this._def,shape:()=>t})}keyof(){return _h(ee.objectKeys(this.shape))}}le.create=(n,e)=>new le({shape:()=>n,unknownKeys:"strip",catchall:jt.create(),typeName:O.ZodObject,...V(e)});le.strictCreate=(n,e)=>new le({shape:()=>n,unknownKeys:"strict",catchall:jt.create(),typeName:O.ZodObject,...V(e)});le.lazycreate=(n,e)=>new le({shape:n,unknownKeys:"strip",catchall:jt.create(),typeName:O.ZodObject,...V(e)});class is extends Y{_parse(e){const{ctx:t}=this._processInputParams(e),r=this._def.options;function s(a){for(const o of a)if(o.result.status==="valid")return o.result;for(const o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;const i=a.map(o=>new wt(o.ctx.common.issues));return A(t,{code:E.invalid_union,unionErrors:i}),q}if(t.common.async)return Promise.all(r.map(async a=>{const i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a;const i=[];for(const u of r){const c={...t,common:{...t.common,issues:[]},parent:null},l=u._parseSync({data:t.data,path:t.path,parent:c});if(l.status==="valid")return l;l.status==="dirty"&&!a&&(a={result:l,ctx:c}),c.common.issues.length&&i.push(c.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;const o=i.map(u=>new wt(u));return A(t,{code:E.invalid_union,unionErrors:o}),q}}get options(){return this._def.options}}is.create=(n,e)=>new is({options:n,typeName:O.ZodUnion,...V(e)});function Mi(n,e){const t=xt(n),r=xt(e);if(n===e)return{valid:!0,data:n};if(t===C.object&&r===C.object){const s=ee.objectKeys(e),a=ee.objectKeys(n).filter(o=>s.indexOf(o)!==-1),i={...n,...e};for(const o of a){const u=Mi(n[o],e[o]);if(!u.valid)return{valid:!1};i[o]=u.data}return{valid:!0,data:i}}else if(t===C.array&&r===C.array){if(n.length!==e.length)return{valid:!1};const s=[];for(let a=0;a<n.length;a++){const i=n[a],o=e[a],u=Mi(i,o);if(!u.valid)return{valid:!1};s.push(u.data)}return{valid:!0,data:s}}else return t===C.date&&r===C.date&&+n==+e?{valid:!0,data:n}:{valid:!1}}class os extends Y{_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=(a,i)=>{if(Ru(a)||Ru(i))return q;const o=Mi(a.value,i.value);return o.valid?((Pu(a)||Pu(i))&&t.dirty(),{status:t.value,value:o.data}):(A(r,{code:E.invalid_intersection_types}),q)};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(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}}os.create=(n,e,t)=>new os({left:n,right:e,typeName:O.ZodIntersection,...V(t)});class Kt extends Y{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.array)return A(r,{code:E.invalid_type,expected:C.array,received:r.parsedType}),q;if(r.data.length<this._def.items.length)return A(r,{code:E.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),q;!this._def.rest&&r.data.length>this._def.items.length&&(A(r,{code:E.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());const a=[...r.data].map((i,o)=>{const u=this._def.items[o]||this._def.rest;return u?u._parse(new Nt(r,i,r.path,o)):null}).filter(i=>!!i);return r.common.async?Promise.all(a).then(i=>Ze.mergeArray(t,i)):Ze.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new Kt({...this._def,rest:e})}}Kt.create=(n,e)=>{if(!Array.isArray(n))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Kt({items:n,typeName:O.ZodTuple,rest:null,...V(e)})};class Du extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.map)return A(r,{code:E.invalid_type,expected:C.map,received:r.parsedType}),q;const s=this._def.keyType,a=this._def.valueType,i=[...r.data.entries()].map(([o,u],c)=>({key:s._parse(new Nt(r,o,r.path,[c,"key"])),value:a._parse(new Nt(r,u,r.path,[c,"value"]))}));if(r.common.async){const o=new Map;return Promise.resolve().then(async()=>{for(const u of i){const c=await u.key,l=await u.value;if(c.status==="aborted"||l.status==="aborted")return q;(c.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(c.value,l.value)}return{status:t.value,value:o}})}else{const o=new Map;for(const u of i){const c=u.key,l=u.value;if(c.status==="aborted"||l.status==="aborted")return q;(c.status==="dirty"||l.status==="dirty")&&t.dirty(),o.set(c.value,l.value)}return{status:t.value,value:o}}}}Du.create=(n,e,t)=>new Du({valueType:e,keyType:n,typeName:O.ZodMap,...V(t)});class en extends Y{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.parsedType!==C.set)return A(r,{code:E.invalid_type,expected:C.set,received:r.parsedType}),q;const s=this._def;s.minSize!==null&&r.data.size<s.minSize.value&&(A(r,{code:E.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&r.data.size>s.maxSize.value&&(A(r,{code:E.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());const a=this._def.valueType;function i(u){const c=new Set;for(const l of u){if(l.status==="aborted")return q;l.status==="dirty"&&t.dirty(),c.add(l.value)}return{status:t.value,value:c}}const o=[...r.data.values()].map((u,c)=>a._parse(new Nt(r,u,r.path,c)));return r.common.async?Promise.all(o).then(u=>i(u)):i(o)}min(e,t){return new en({...this._def,minSize:{value:e,message:$.toString(t)}})}max(e,t){return new en({...this._def,maxSize:{value:e,message:$.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}}en.create=(n,e)=>new en({valueType:n,minSize:null,maxSize:null,typeName:O.ZodSet,...V(e)});class Fu extends Y{get schema(){return this._def.getter()}_parse(e){const{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}}Fu.create=(n,e)=>new Fu({getter:n,typeName:O.ZodLazy,...V(e)});class Bu extends Y{_parse(e){if(e.data!==this._def.value){const t=this._getOrReturnCtx(e);return A(t,{received:t.data,code:E.invalid_literal,expected:this._def.value}),q}return{status:"valid",value:e.data}}get value(){return this._def.value}}Bu.create=(n,e)=>new Bu({value:n,typeName:O.ZodLiteral,...V(e)});function _h(n,e){return new hr({values:n,typeName:O.ZodEnum,...V(e)})}class hr extends Y{_parse(e){if(typeof e.data!="string"){const t=this._getOrReturnCtx(e),r=this._def.values;return A(t,{expected:ee.joinValues(r),received:t.parsedType,code:E.invalid_type}),q}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){const t=this._getOrReturnCtx(e),r=this._def.values;return A(t,{received:t.data,code:E.invalid_enum_value,options:r}),q}return We(e.data)}get options(){return this._def.values}get enum(){const e={};for(const t of this._def.values)e[t]=t;return e}get Values(){const e={};for(const t of this._def.values)e[t]=t;return e}get Enum(){const e={};for(const t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return hr.create(e,{...this._def,...t})}exclude(e,t=this._def){return hr.create(this.options.filter(r=>!e.includes(r)),{...this._def,...t})}}hr.create=_h;class zu extends Y{_parse(e){const t=ee.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(e);if(r.parsedType!==C.string&&r.parsedType!==C.number){const s=ee.objectValues(t);return A(r,{expected:ee.joinValues(s),received:r.parsedType,code:E.invalid_type}),q}if(this._cache||(this._cache=new Set(ee.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){const s=ee.objectValues(t);return A(r,{received:r.data,code:E.invalid_enum_value,options:s}),q}return We(e.data)}get enum(){return this._def.values}}zu.create=(n,e)=>new zu({values:n,typeName:O.ZodNativeEnum,...V(e)});class us extends Y{unwrap(){return this._def.type}_parse(e){const{ctx:t}=this._processInputParams(e);if(t.parsedType!==C.promise&&t.common.async===!1)return A(t,{code:E.invalid_type,expected:C.promise,received:t.parsedType}),q;const r=t.parsedType===C.promise?t.data:Promise.resolve(t.data);return We(r.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}}us.create=(n,e)=>new us({type:n,typeName:O.ZodPromise,...V(e)});class fr extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===O.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){const{status:t,ctx:r}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{A(r,i),i.fatal?t.abort():t.dirty()},get path(){return r.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){const i=s.transform(r.data,a);if(r.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return q;const u=await this._def.schema._parseAsync({data:o,path:r.path,parent:r});return u.status==="aborted"?q:u.status==="dirty"||t.value==="dirty"?Fr(u.value):u});{if(t.value==="aborted")return q;const o=this._def.schema._parseSync({data:i,path:r.path,parent:r});return o.status==="aborted"?q:o.status==="dirty"||t.value==="dirty"?Fr(o.value):o}}if(s.type==="refinement"){const i=o=>{const u=s.refinement(o,a);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"?q:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(o=>o.status==="aborted"?q:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(r.common.async===!1){const i=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!dr(i))return q;const o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(i=>dr(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):q);ee.assertNever(s)}}fr.create=(n,e,t)=>new fr({schema:n,typeName:O.ZodEffects,effect:e,...V(t)});fr.createWithPreprocess=(n,e,t)=>new fr({schema:e,effect:{type:"preprocess",transform:n},typeName:O.ZodEffects,...V(t)});class Pt extends Y{_parse(e){return this._getType(e)===C.undefined?We(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}Pt.create=(n,e)=>new Pt({innerType:n,typeName:O.ZodOptional,...V(e)});class pr extends Y{_parse(e){return this._getType(e)===C.null?We(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}}pr.create=(n,e)=>new pr({innerType:n,typeName:O.ZodNullable,...V(e)});class Ui extends Y{_parse(e){const{ctx:t}=this._processInputParams(e);let r=t.data;return t.parsedType===C.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:t.path,parent:t})}removeDefault(){return this._def.innerType}}Ui.create=(n,e)=>new Ui({innerType:n,typeName:O.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...V(e)});class Di extends Y{_parse(e){const{ctx:t}=this._processInputParams(e),r={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return ss(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new wt(r.common.issues)},input:r.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new wt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}}Di.create=(n,e)=>new Di({innerType:n,typeName:O.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...V(e)});class qu extends Y{_parse(e){if(this._getType(e)!==C.nan){const r=this._getOrReturnCtx(e);return A(r,{code:E.invalid_type,expected:C.nan,received:r.parsedType}),q}return{status:"valid",value:e.data}}}qu.create=n=>new qu({typeName:O.ZodNaN,...V(n)});class jm extends Y{_parse(e){const{ctx:t}=this._processInputParams(e),r=t.data;return this._def.type._parse({data:r,path:t.path,parent:t})}unwrap(){return this._def.type}}class ko extends Y{_parse(e){const{status:t,ctx:r}=this._processInputParams(e);if(r.common.async)return(async()=>{const a=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return a.status==="aborted"?q:a.status==="dirty"?(t.dirty(),Fr(a.value)):this._def.out._parseAsync({data:a.value,path:r.path,parent:r})})();{const s=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?q:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:r.path,parent:r})}}static create(e,t){return new ko({in:e,out:t,typeName:O.ZodPipeline})}}class Fi extends Y{_parse(e){const t=this._def.innerType._parse(e),r=s=>(dr(s)&&(s.value=Object.freeze(s.value)),s);return ss(t)?t.then(s=>r(s)):r(t)}unwrap(){return this._def.innerType}}Fi.create=(n,e)=>new Fi({innerType:n,typeName:O.ZodReadonly,...V(e)});var O;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(O||(O={}));const bh=At.create,Zu=Li.create;jt.create;ht.create;const wh=le.create;is.create;os.create;Kt.create;hr.create;us.create;Pt.create;pr.create;var kr={exports:{}},oa={},ua,Hu;function Lm(){if(Hu)return ua;Hu=1;function n(e,t){typeof t=="boolean"&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}return ua=n,n.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},n.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},n.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=new Date().getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var r=this._timeouts.shift();if(r===void 0)if(this._cachedTimeouts)this._errors.splice(0,this._errors.length-1),r=this._cachedTimeouts.slice(-1);else return!1;var s=this;return this._timer=setTimeout(function(){s._attempts++,s._operationTimeoutCb&&(s._timeout=setTimeout(function(){s._operationTimeoutCb(s._attempts)},s._operationTimeout),s._options.unref&&s._timeout.unref()),s._fn(s._attempts)},r),this._options.unref&&this._timer.unref(),!0},n.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var r=this;this._operationTimeoutCb&&(this._timeout=setTimeout(function(){r._operationTimeoutCb()},r._operationTimeout)),this._operationStart=new Date().getTime(),this._fn(this._attempts)},n.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},n.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},n.prototype.start=n.prototype.try,n.prototype.errors=function(){return this._errors},n.prototype.attempts=function(){return this._attempts},n.prototype.mainError=function(){if(this._errors.length===0)return null;for(var e={},t=null,r=0,s=0;s<this._errors.length;s++){var a=this._errors[s],i=a.message,o=(e[i]||0)+1;e[i]=o,o>=r&&(t=a,r=o)}return t},ua}var Gu;function Mm(){return Gu||(Gu=1,(function(n){var e=Lm();n.operation=function(t){var r=n.timeouts(t);return new e(r,{forever:t&&(t.forever||t.retries===1/0),unref:t&&t.unref,maxRetryTime:t&&t.maxRetryTime})},n.timeouts=function(t){if(t instanceof Array)return[].concat(t);var r={retries:10,factor:2,minTimeout:1*1e3,maxTimeout:1/0,randomize:!1};for(var s in t)r[s]=t[s];if(r.minTimeout>r.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var a=[],i=0;i<r.retries;i++)a.push(this.createTimeout(i,r));return t&&t.forever&&!a.length&&a.push(this.createTimeout(i,r)),a.sort(function(o,u){return o-u}),a},n.createTimeout=function(t,r){var s=r.randomize?Math.random()+1:1,a=Math.round(s*Math.max(r.minTimeout,1)*Math.pow(r.factor,t));return a=Math.min(a,r.maxTimeout),a},n.wrap=function(t,r,s){if(r instanceof Array&&(s=r,r=null),!s){s=[];for(var a in t)typeof t[a]=="function"&&s.push(a)}for(var i=0;i<s.length;i++){var o=s[i],u=t[o];t[o]=(function(l){var d=n.operation(r),h=Array.prototype.slice.call(arguments,1),f=h.pop();h.push(function(p){d.retry(p)||(p&&(arguments[0]=d.mainError()),f.apply(this,arguments))}),d.attempt(function(){l.apply(t,h)})}).bind(t,u),t[o].options=r}}})(oa)),oa}var ca,Ju;function Um(){return Ju||(Ju=1,ca=Mm()),ca}var Wu;function Dm(){if(Wu)return kr.exports;Wu=1;const n=Um(),e=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class t extends Error{constructor(o){super(),o instanceof Error?(this.originalError=o,{message:o}=o):(this.originalError=new Error(o),this.originalError.stack=this.stack),this.name="AbortError",this.message=o}}const r=(i,o,u)=>{const c=u.retries-(o-1);return i.attemptNumber=o,i.retriesLeft=c,i},s=i=>e.includes(i),a=(i,o)=>new Promise((u,c)=>{o={onFailedAttempt:()=>{},retries:10,...o};const l=n.operation(o);l.attempt(async d=>{try{u(await i(d))}catch(h){if(!(h instanceof Error)){c(new TypeError(`Non-error was thrown: "${h}". You should only throw errors.`));return}if(h instanceof t)l.stop(),c(h.originalError);else if(h instanceof TypeError&&!s(h.message))l.stop(),c(h);else{r(h,d,o);try{await o.onFailedAttempt(h)}catch(f){c(f);return}l.retry(h)||c(l.mainError())}}})});return kr.exports=a,kr.exports.default=a,kr.exports.AbortError=t,kr.exports}var Fm=Dm();const cs=sn(Fm),Bm=/^(?:[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 Jn(n){return typeof n=="string"&&Bm.test(n)}var Se=[];for(var la=0;la<256;++la)Se.push((la+256).toString(16).slice(1));function zm(n,e=0){return(Se[n[e+0]]+Se[n[e+1]]+Se[n[e+2]]+Se[n[e+3]]+"-"+Se[n[e+4]]+Se[n[e+5]]+"-"+Se[n[e+6]]+Se[n[e+7]]+"-"+Se[n[e+8]]+Se[n[e+9]]+"-"+Se[n[e+10]]+Se[n[e+11]]+Se[n[e+12]]+Se[n[e+13]]+Se[n[e+14]]+Se[n[e+15]]).toLowerCase()}var On,qm=new Uint8Array(16);function Zm(){if(!On&&(On=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!On))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return On(qm)}var Hm=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Vu={randomUUID:Hm};function yt(n,e,t){if(Vu.randomUUID&&!n)return Vu.randomUUID();n=n||{};var r=n.random||(n.rng||Zm)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,zm(r)}let Gm=class{getStore(){}run(e,t){return t()}};const da=Symbol.for("ls:tracing_async_local_storage"),Jm=new Gm;let Wm=class{getInstance(){return globalThis[da]??Jm}initializeGlobalInstance(e){globalThis[da]===void 0&&(globalThis[da]=e)}};const Vm=new Wm;function Km(n=!1){const e=Vm.getInstance().getStore();if(!n&&e===void 0)throw new Error(`Could not get the current run tree.
|
|
39
|
+
|
|
40
|
+
Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}function To(n){return typeof n=="function"&&"langsmith:traceable"in n}/*!
|
|
41
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
42
|
+
* (c) 2017-2022 Joachim Wester
|
|
43
|
+
* MIT licensed
|
|
44
|
+
*/const Xm=Object.prototype.hasOwnProperty;function Bi(n,e){return Xm.call(n,e)}function zi(n){if(Array.isArray(n)){const t=new Array(n.length);for(let r=0;r<t.length;r++)t[r]=""+r;return t}if(Object.keys)return Object.keys(n);let e=[];for(let t in n)Bi(n,t)&&e.push(t);return e}function dt(n){switch(typeof n){case"object":return JSON.parse(JSON.stringify(n));case"undefined":return null;default:return n}}function qi(n){let e=0;const t=n.length;let r;for(;e<t;){if(r=n.charCodeAt(e),r>=48&&r<=57){e++;continue}return!1}return!0}function rr(n){return n.indexOf("/")===-1&&n.indexOf("~")===-1?n:n.replace(/~/g,"~0").replace(/\//g,"~1")}function Qm(n){return n.replace(/~1/g,"/").replace(/~0/g,"~")}function Zi(n){if(n===void 0)return!0;if(n){if(Array.isArray(n)){for(let t=0,r=n.length;t<r;t++)if(Zi(n[t]))return!0}else if(typeof n=="object"){const t=zi(n),r=t.length;for(var e=0;e<r;e++)if(Zi(n[t[e]]))return!0}}return!1}function Ku(n,e){const t=[n];for(const r in e){const s=typeof e[r]=="object"?JSON.stringify(e[r],null,2):e[r];typeof s<"u"&&t.push(`${r}: ${s}`)}return t.join(`
|
|
45
|
+
`)}class Ym extends Error{constructor(e,t,r,s,a){super(Ku(e,{name:t,index:r,operation:s,tree:a})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.setPrototypeOf(this,new.target.prototype),this.message=Ku(e,{name:t,index:r,operation:s,tree:a})}}const de=Ym,cr={add:function(n,e,t){return n[e]=this.value,{newDocument:t}},remove:function(n,e,t){var r=n[e];return delete n[e],{newDocument:t,removed:r}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:function(n,e,t){let r=Hi(t,this.path);r&&(r=dt(r));const s=Hr(t,{op:"remove",path:this.from}).removed;return Hr(t,{op:"add",path:this.path,value:s}),{newDocument:t,removed:r}},copy:function(n,e,t){const r=Hi(t,this.from);return Hr(t,{op:"add",path:this.path,value:dt(r)}),{newDocument:t}},test:function(n,e,t){return{newDocument:t,test:ds(n[e],this.value)}},_get:function(n,e,t){return this.value=n[e],{newDocument:t}}};var eg={add:function(n,e,t){return qi(e)?n.splice(e,0,this.value):n[e]=this.value,{newDocument:t,index:e}},remove:function(n,e,t){var r=n.splice(e,1);return{newDocument:t,removed:r[0]}},replace:function(n,e,t){var r=n[e];return n[e]=this.value,{newDocument:t,removed:r}},move:cr.move,copy:cr.copy,test:cr.test,_get:cr._get};function Hi(n,e){if(e=="")return n;var t={op:"_get",path:e};return Hr(n,t),t.value}function Hr(n,e,t=!1,r=!0,s=!0,a=0){if(t&&(typeof t=="function"?t(e,0,n,e.path):Gi(e,0)),e.path===""){let i={newDocument:n};if(e.op==="add")return i.newDocument=e.value,i;if(e.op==="replace")return i.newDocument=e.value,i.removed=n,i;if(e.op==="move"||e.op==="copy")return i.newDocument=Hi(n,e.from),e.op==="move"&&(i.removed=n),i;if(e.op==="test"){if(i.test=ds(n,e.value),i.test===!1)throw new de("Test operation failed","TEST_OPERATION_FAILED",a,e,n);return i.newDocument=n,i}else{if(e.op==="remove")return i.removed=n,i.newDocument=null,i;if(e.op==="_get")return e.value=n,i;if(t)throw new de("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",a,e,n);return i}}else{r||(n=dt(n));const o=(e.path||"").split("/");let u=n,c=1,l=o.length,d,h,f;for(typeof t=="function"?f=t:f=Gi;;){if(h=o[c],h&&h.indexOf("~")!=-1&&(h=Qm(h)),s&&(h=="__proto__"||h=="prototype"&&c>0&&o[c-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(t&&d===void 0&&(u[h]===void 0?d=o.slice(0,c).join("/"):c==l-1&&(d=e.path),d!==void 0&&f(e,0,n,d)),c++,Array.isArray(u)){if(h==="-")h=u.length;else{if(t&&!qi(h))throw new de("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",a,e,n);qi(h)&&(h=~~h)}if(c>=l){if(t&&e.op==="add"&&h>u.length)throw new de("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",a,e,n);const p=eg[e.op].call(e,u,h,n);if(p.test===!1)throw new de("Test operation failed","TEST_OPERATION_FAILED",a,e,n);return p}}else if(c>=l){const p=cr[e.op].call(e,u,h,n);if(p.test===!1)throw new de("Test operation failed","TEST_OPERATION_FAILED",a,e,n);return p}if(u=u[h],t&&c<l&&(!u||typeof u!="object"))throw new de("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",a,e,n)}}}function ls(n,e,t,r=!0,s=!0){if(t&&!Array.isArray(e))throw new de("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");r||(n=dt(n));const a=new Array(e.length);for(let i=0,o=e.length;i<o;i++)a[i]=Hr(n,e[i],t,!0,s,i),n=a[i].newDocument;return a.newDocument=n,a}function Gi(n,e,t,r){if(typeof n!="object"||n===null||Array.isArray(n))throw new de("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,n,t);if(cr[n.op]){if(typeof n.path!="string")throw new de("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,n,t);if(n.path.indexOf("/")!==0&&n.path.length>0)throw new de('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,n,t);if((n.op==="move"||n.op==="copy")&&typeof n.from!="string")throw new de("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&n.value===void 0)throw new de("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,n,t);if((n.op==="add"||n.op==="replace"||n.op==="test")&&Zi(n.value))throw new de("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,n,t);if(t){if(n.op=="add"){var s=n.path.split("/").length,a=r.split("/").length;if(s!==a+1&&s!==a)throw new de("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,n,t)}else if(n.op==="replace"||n.op==="remove"||n.op==="_get"){if(n.path!==r)throw new de("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,n,t)}else if(n.op==="move"||n.op==="copy"){var i={op:"_get",path:n.from,value:void 0},o=tg([i],t);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new de("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,n,t)}}}else throw new de("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,n,t)}function tg(n,e,t){try{if(!Array.isArray(n))throw new de("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)ls(dt(e),dt(n),t||!0);else{t=t||Gi;for(var r=0;r<n.length;r++)t(n[r],r,e,void 0)}}catch(s){if(s instanceof de)return s;throw s}}function ds(n,e){if(n===e)return!0;if(n&&e&&typeof n=="object"&&typeof e=="object"){var t=Array.isArray(n),r=Array.isArray(e),s,a,i;if(t&&r){if(a=n.length,a!=e.length)return!1;for(s=a;s--!==0;)if(!ds(n[s],e[s]))return!1;return!0}if(t!=r)return!1;var o=Object.keys(n);if(a=o.length,a!==Object.keys(e).length)return!1;for(s=a;s--!==0;)if(!e.hasOwnProperty(o[s]))return!1;for(s=a;s--!==0;)if(i=o[s],!ds(n[i],e[i]))return!1;return!0}return n!==n&&e!==e}/*!
|
|
46
|
+
* https://github.com/Starcounter-Jack/JSON-Patch
|
|
47
|
+
* (c) 2013-2021 Joachim Wester
|
|
48
|
+
* MIT license
|
|
49
|
+
*/function vh(n,e,t,r,s){if(e!==n){typeof e.toJSON=="function"&&(e=e.toJSON());for(var a=zi(e),i=zi(n),o=!1,u=i.length-1;u>=0;u--){var c=i[u],l=n[c];if(Bi(e,c)&&!(e[c]===void 0&&l!==void 0&&Array.isArray(e)===!1)){var d=e[c];typeof l=="object"&&l!=null&&typeof d=="object"&&d!=null&&Array.isArray(l)===Array.isArray(d)?vh(l,d,t,r+"/"+rr(c),s):l!==d&&(s&&t.push({op:"test",path:r+"/"+rr(c),value:dt(l)}),t.push({op:"replace",path:r+"/"+rr(c),value:dt(d)}))}else Array.isArray(n)===Array.isArray(e)?(s&&t.push({op:"test",path:r+"/"+rr(c),value:dt(l)}),t.push({op:"remove",path:r+"/"+rr(c)}),o=!0):(s&&t.push({op:"test",path:r,value:n}),t.push({op:"replace",path:r,value:e}))}if(!(!o&&a.length==i.length))for(var u=0;u<a.length;u++){var c=a[u];!Bi(n,c)&&e[c]!==void 0&&t.push({op:"add",path:r+"/"+rr(c),value:dt(e[c])})}}}function rg(n,e,t=!1){var r=[];return vh(n,e,r,"",t),r}const ng=/^(?:[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 sg(n){return typeof n=="string"&&ng.test(n)}function ag(n){if(!sg(n))throw TypeError("Invalid UUID");var e,t=new Uint8Array(16);return t[0]=(e=parseInt(n.slice(0,8),16))>>>24,t[1]=e>>>16&255,t[2]=e>>>8&255,t[3]=e&255,t[4]=(e=parseInt(n.slice(9,13),16))>>>8,t[5]=e&255,t[6]=(e=parseInt(n.slice(14,18),16))>>>8,t[7]=e&255,t[8]=(e=parseInt(n.slice(19,23),16))>>>8,t[9]=e&255,t[10]=(e=parseInt(n.slice(24,36),16))/1099511627776&255,t[11]=e/4294967296&255,t[12]=e>>>24&255,t[13]=e>>>16&255,t[14]=e>>>8&255,t[15]=e&255,t}var Ee=[];for(var ha=0;ha<256;++ha)Ee.push((ha+256).toString(16).slice(1));function Sh(n,e=0){return(Ee[n[e+0]]+Ee[n[e+1]]+Ee[n[e+2]]+Ee[n[e+3]]+"-"+Ee[n[e+4]]+Ee[n[e+5]]+"-"+Ee[n[e+6]]+Ee[n[e+7]]+"-"+Ee[n[e+8]]+Ee[n[e+9]]+"-"+Ee[n[e+10]]+Ee[n[e+11]]+Ee[n[e+12]]+Ee[n[e+13]]+Ee[n[e+14]]+Ee[n[e+15]]).toLowerCase()}var xn,ig=new Uint8Array(16);function og(){if(!xn&&(xn=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!xn))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return xn(ig)}function ug(n){n=unescape(encodeURIComponent(n));for(var e=[],t=0;t<n.length;++t)e.push(n.charCodeAt(t));return e}var cg="6ba7b810-9dad-11d1-80b4-00c04fd430c8",lg="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function dg(n,e,t){function r(s,a,i,o){var u;if(typeof s=="string"&&(s=ug(s)),typeof a=="string"&&(a=ag(a)),((u=a)===null||u===void 0?void 0:u.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");var c=new Uint8Array(16+s.length);if(c.set(a),c.set(s,a.length),c=t(c),c[6]=c[6]&15|e,c[8]=c[8]&63|128,i){o=o||0;for(var l=0;l<16;++l)i[o+l]=c[l];return i}return Sh(c)}try{r.name=n}catch{}return r.DNS=cg,r.URL=lg,r}var hg=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto);const Xu={randomUUID:hg};function or(n,e,t){if(Xu.randomUUID&&!n)return Xu.randomUUID();n=n||{};var r=n.random||(n.rng||og)();return r[6]=r[6]&15|64,r[8]=r[8]&63|128,Sh(r)}function fg(n,e,t,r){switch(n){case 0:return e&t^~e&r;case 1:return e^t^r;case 2:return e&t^e&r^t&r;case 3:return e^t^r}}function fa(n,e){return n<<e|n>>>32-e}function pg(n){var e=[1518500249,1859775393,2400959708,3395469782],t=[1732584193,4023233417,2562383102,271733878,3285377520];if(typeof n=="string"){var r=unescape(encodeURIComponent(n));n=[];for(var s=0;s<r.length;++s)n.push(r.charCodeAt(s))}else Array.isArray(n)||(n=Array.prototype.slice.call(n));n.push(128);for(var a=n.length/4+2,i=Math.ceil(a/16),o=new Array(i),u=0;u<i;++u){for(var c=new Uint32Array(16),l=0;l<16;++l)c[l]=n[u*64+l*4]<<24|n[u*64+l*4+1]<<16|n[u*64+l*4+2]<<8|n[u*64+l*4+3];o[u]=c}o[i-1][14]=(n.length-1)*8/Math.pow(2,32),o[i-1][14]=Math.floor(o[i-1][14]),o[i-1][15]=(n.length-1)*8&4294967295;for(var d=0;d<i;++d){for(var h=new Uint32Array(80),f=0;f<16;++f)h[f]=o[d][f];for(var p=16;p<80;++p)h[p]=fa(h[p-3]^h[p-8]^h[p-14]^h[p-16],1);for(var m=t[0],g=t[1],y=t[2],_=t[3],b=t[4],v=0;v<80;++v){var S=Math.floor(v/20),R=fa(m,5)+fg(S,g,y,_)+b+e[S]+h[v]>>>0;b=_,_=y,y=fa(g,30)>>>0,g=m,m=R}t[0]=t[0]+m>>>0,t[1]=t[1]+g>>>0,t[2]=t[2]+y>>>0,t[3]=t[3]+_>>>0,t[4]=t[4]+b>>>0}return[t[0]>>24&255,t[0]>>16&255,t[0]>>8&255,t[0]&255,t[1]>>24&255,t[1]>>16&255,t[1]>>8&255,t[1]&255,t[2]>>24&255,t[2]>>16&255,t[2]>>8&255,t[2]&255,t[3]>>24&255,t[3]>>16&255,t[3]>>8&255,t[3]&255,t[4]>>24&255,t[4]>>16&255,t[4]>>8&255,t[4]&255]}var Qu=dg("v5",80,pg);const mg="gen_ai.operation.name",gg="gen_ai.system",Yu="gen_ai.request.model",yg="gen_ai.response.model",ec="gen_ai.usage.input_tokens",tc="gen_ai.usage.output_tokens",rc="gen_ai.usage.total_tokens",_g="gen_ai.request.max_tokens",bg="gen_ai.request.temperature",wg="gen_ai.request.top_p",vg="gen_ai.request.frequency_penalty",Sg="gen_ai.request.presence_penalty",Eg="gen_ai.response.finish_reasons",Og="gen_ai.prompt",xg="gen_ai.completion",kg="gen_ai.request.extra_query",Tg="gen_ai.request.extra_body",Ag="gen_ai.serialized.name",Ig="gen_ai.serialized.signature",Rg="gen_ai.serialized.doc",Pg="gen_ai.response.id",Cg="gen_ai.response.service_tier",$g="gen_ai.response.system_fingerprint",Ng="gen_ai.usage.input_token_details",jg="gen_ai.usage.output_token_details",Lg="langsmith.trace.session_id",Mg="langsmith.trace.session_name",Ug="langsmith.span.kind",Dg="langsmith.trace.name",Fg="langsmith.metadata",nc="langsmith.span.tags",Bg="langsmith.request.streaming",zg="langsmith.request.headers",qg=(...n)=>fetch(...n),Eh=Symbol.for("ls:fetch_implementation"),Zg=()=>{const n=globalThis[Eh];return n?typeof n=="function"&&"Headers"in n&&"Request"in n&&"Response"in n:!1},Hg=n=>async(...e)=>{if(n||Me("DEBUG")==="true"){const[r,s]=e;console.log(`→ ${s?.method||"GET"} ${r}`)}const t=await(globalThis[Eh]??qg)(...e);return(n||Me("DEBUG")==="true")&&console.log(`← ${t.status} ${t.statusText} ${t.url}`),t},Oh=()=>Me("PROJECT")??ft("LANGCHAIN_SESSION")??"default",xh="0.3.73";var Ji={};let ut;const Gg=()=>typeof window<"u"&&typeof window.document<"u",Jg=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",Wg=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),kh=()=>typeof Deno<"u",Vg=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!kh(),Th=()=>ut||(typeof Bun<"u"?ut="bun":Gg()?ut="browser":Vg()?ut="node":Jg()?ut="webworker":Wg()?ut="jsdom":kh()?ut="deno":ut="other",ut);let pa;function Ah(){if(pa===void 0){const n=Th(),e=Xg();pa={library:"langsmith",runtime:n,sdk:"langsmith-js",sdk_version:xh,...e}}return pa}function Ih(){const n=Kg(),e={},t=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(const[r,s]of Object.entries(n))typeof s=="string"&&!t.includes(r)&&!r.toLowerCase().includes("key")&&!r.toLowerCase().includes("secret")&&!r.toLowerCase().includes("token")&&(r==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[r]=s);return e}function Kg(){const n={};try{if(typeof process<"u"&&Ji)for(const[e,t]of Object.entries(Ji))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&t!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof t=="string"?n[e]=t.slice(0,2)+"*".repeat(t.length-4)+t.slice(-2):n[e]=t)}catch{}return n}function ft(n){try{return typeof process<"u"?Ji?.[n]:void 0}catch{return}}function Me(n){return ft(`LANGSMITH_${n}`)||ft(`LANGCHAIN_${n}`)}let ma;function Xg(){if(ma!==void 0)return ma;const n=["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 t of n){const r=ft(t);r!==void 0&&(e[t]=r)}return ma=e,e}function Rh(){return ft("OTEL_ENABLED")==="true"||Me("OTEL_ENABLED")==="true"}class Qg{constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...t){!this.hasWarned&&Rh()&&(console.warn('You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let r;if(t.length===1&&typeof t[0]=="function"?r=t[0]:t.length===2&&typeof t[1]=="function"?r=t[1]:t.length===3&&typeof t[2]=="function"&&(r=t[2]),typeof r=="function")return r()}}class Yg{constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new Qg})}getTracer(e,t){return this.mockTracer}getActiveSpan(){}setSpan(e,t){return e}getSpan(e){}setSpanContext(e,t){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}}class ey{active(){return{}}with(e,t){return t()}}const ga=Symbol.for("ls:otel_trace"),ya=Symbol.for("ls:otel_context"),sc=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),ty=new Yg,ry=new ey;class ny{getTraceInstance(){return globalThis[ga]??ty}getContextInstance(){return globalThis[ya]??ry}initializeGlobalInstances(e){globalThis[ga]===void 0&&(globalThis[ga]=e.trace),globalThis[ya]===void 0&&(globalThis[ya]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[sc]=e}getDefaultOTLPTracerComponents(){return globalThis[sc]??void 0}}const Ao=new ny;function Ph(){return Ao.getTraceInstance()}function sy(){return Ao.getContextInstance()}function ay(){return Ao.getDefaultOTLPTracerComponents()}const iy={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function oy(n){return iy[n]||n}class uy{constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,t){for(const r of e)try{if(!r.run)continue;if(r.operation==="post"){const s=this.createSpanForRun(r,r.run,t.get(r.id));s&&!r.run.end_time&&this.spans.set(r.id,s)}else this.updateSpanForRun(r,r.run)}catch(s){console.error(`Error processing operation ${r.id}:`,s)}}createSpanForRun(e,t,r){const s=r&&Ph().getSpan(r);if(s)try{return this.finishSpanSetup(s,t,e)}catch(a){console.error(`Failed to create span for run ${e.id}:`,a);return}}finishSpanSetup(e,t,r){return this.setSpanAttributes(e,t,r),t.error?(e.setStatus({code:2}),e.recordException(new Error(t.error))):e.setStatus({code:1}),t.end_time&&e.end(new Date(t.end_time)),e}updateSpanForRun(e,t){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,t,e),t.error?(r.setStatus({code:2}),r.recordException(new Error(t.error))):r.setStatus({code:1});const s=t.end_time;s&&(r.end(new Date(s)),this.spans.delete(e.id))}catch(r){console.error(`Failed to update span for run ${e.id}:`,r)}}extractModelName(e){if(e.extra?.metadata){const t=e.extra.metadata;if(t.ls_model_name)return t.ls_model_name;if(t.invocation_params){const r=t.invocation_params;if(r.model)return r.model;if(r.model_name)return r.model_name}}}setSpanAttributes(e,t,r){if("run_type"in t&&t.run_type){e.setAttribute(Ug,t.run_type);const o=oy(t.run_type||"chain");e.setAttribute(mg,o)}"name"in t&&t.name&&e.setAttribute(Dg,t.name),"session_id"in t&&t.session_id&&e.setAttribute(Lg,t.session_id),"session_name"in t&&t.session_name&&e.setAttribute(Mg,t.session_name),this.setGenAiSystem(e,t);const s=this.extractModelName(t);s&&e.setAttribute(Yu,s),"prompt_tokens"in t&&typeof t.prompt_tokens=="number"&&e.setAttribute(ec,t.prompt_tokens),"completion_tokens"in t&&typeof t.completion_tokens=="number"&&e.setAttribute(tc,t.completion_tokens),"total_tokens"in t&&typeof t.total_tokens=="number"&&e.setAttribute(rc,t.total_tokens),this.setInvocationParameters(e,t);const a=t.extra?.metadata||{};for(const[o,u]of Object.entries(a))u!=null&&e.setAttribute(`${Fg}.${o}`,String(u));const i=t.tags;if(i&&Array.isArray(i)?e.setAttribute(nc,i.join(", ")):i&&e.setAttribute(nc,String(i)),"serialized"in t&&typeof t.serialized=="object"){const o=t.serialized;o.name&&e.setAttribute(Ag,String(o.name)),o.signature&&e.setAttribute(Ig,String(o.signature)),o.doc&&e.setAttribute(Rg,String(o.doc))}this.setIOAttributes(e,r)}setGenAiSystem(e,t){let r="langchain";const s=this.extractModelName(t);if(s){const a=s.toLowerCase();a.includes("anthropic")||a.startsWith("claude")?r="anthropic":a.includes("bedrock")?r="aws.bedrock":a.includes("azure")&&a.includes("openai")?r="az.ai.openai":a.includes("azure")&&a.includes("inference")?r="az.ai.inference":a.includes("cohere")?r="cohere":a.includes("deepseek")?r="deepseek":a.includes("gemini")?r="gemini":a.includes("groq")?r="groq":a.includes("watson")||a.includes("ibm")?r="ibm.watsonx.ai":a.includes("mistral")?r="mistral_ai":a.includes("gpt")||a.includes("openai")?r="openai":a.includes("perplexity")||a.includes("sonar")?r="perplexity":a.includes("vertex")?r="vertex_ai":(a.includes("xai")||a.includes("grok"))&&(r="xai")}e.setAttribute(gg,r)}setInvocationParameters(e,t){if(!t.extra?.metadata?.invocation_params)return;const r=t.extra.metadata.invocation_params;r.max_tokens!==void 0&&e.setAttribute(_g,r.max_tokens),r.temperature!==void 0&&e.setAttribute(bg,r.temperature),r.top_p!==void 0&&e.setAttribute(wg,r.top_p),r.frequency_penalty!==void 0&&e.setAttribute(vg,r.frequency_penalty),r.presence_penalty!==void 0&&e.setAttribute(Sg,r.presence_penalty)}setIOAttributes(e,t){if(t.run.inputs)try{const r=t.run.inputs;typeof r=="object"&&r!==null&&(r.model&&Array.isArray(r.messages)&&e.setAttribute(Yu,r.model),r.stream!==void 0&&e.setAttribute(Bg,r.stream),r.extra_headers&&e.setAttribute(zg,JSON.stringify(r.extra_headers)),r.extra_query&&e.setAttribute(kg,JSON.stringify(r.extra_query)),r.extra_body&&e.setAttribute(Tg,JSON.stringify(r.extra_body))),e.setAttribute(Og,JSON.stringify(r))}catch(r){console.debug(`Failed to process inputs for run ${t.id}`,r)}if(t.run.outputs)try{const r=t.run.outputs,s=this.getUnifiedRunTokens(r);if(s&&(e.setAttribute(ec,s[0]),e.setAttribute(tc,s[1]),e.setAttribute(rc,s[0]+s[1])),r&&typeof r=="object"){if(r.model&&e.setAttribute(yg,String(r.model)),r.id&&e.setAttribute(Pg,r.id),r.choices&&Array.isArray(r.choices)){const a=r.choices.map(i=>i.finish_reason).filter(i=>i).map(String);a.length>0&&e.setAttribute(Eg,a.join(", "))}if(r.service_tier&&e.setAttribute(Cg,r.service_tier),r.system_fingerprint&&e.setAttribute($g,r.system_fingerprint),r.usage_metadata&&typeof r.usage_metadata=="object"){const a=r.usage_metadata;a.input_token_details&&e.setAttribute(Ng,JSON.stringify(a.input_token_details)),a.output_token_details&&e.setAttribute(jg,JSON.stringify(a.output_token_details))}}e.setAttribute(xg,JSON.stringify(r))}catch(r){console.debug(`Failed to process outputs for run ${t.id}`,r)}}getUnifiedRunTokens(e){if(!e)return null;let t=this.extractUnifiedRunTokens(e.usage_metadata);if(t)return t;const r=Object.keys(e);for(const i of r){const o=e[i];if(!(!o||typeof o!="object")&&(t=this.extractUnifiedRunTokens(o.usage_metadata),t||o.lc===1&&o.kwargs&&typeof o.kwargs=="object"&&(t=this.extractUnifiedRunTokens(o.kwargs.usage_metadata),t)))return t}const s=e.generations||[];if(!Array.isArray(s))return null;const a=Array.isArray(s[0])?s.flat():s;for(const i of a)if(typeof i=="object"&&i.message&&typeof i.message=="object"&&i.message.kwargs&&typeof i.message.kwargs=="object"&&(t=this.extractUnifiedRunTokens(i.message.kwargs.usage_metadata),t))return t;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]}}var kn={},_a={exports:{}},ac;function cy(){return ac||(ac=1,(function(n){var e=Object.prototype.hasOwnProperty,t="~";function r(){}Object.create&&(r.prototype=Object.create(null),new r().__proto__||(t=!1));function s(u,c,l){this.fn=u,this.context=c,this.once=l||!1}function a(u,c,l,d,h){if(typeof l!="function")throw new TypeError("The listener must be a function");var f=new s(l,d||u,h),p=t?t+c:c;return u._events[p]?u._events[p].fn?u._events[p]=[u._events[p],f]:u._events[p].push(f):(u._events[p]=f,u._eventsCount++),u}function i(u,c){--u._eventsCount===0?u._events=new r:delete u._events[c]}function o(){this._events=new r,this._eventsCount=0}o.prototype.eventNames=function(){var c=[],l,d;if(this._eventsCount===0)return c;for(d in l=this._events)e.call(l,d)&&c.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?c.concat(Object.getOwnPropertySymbols(l)):c},o.prototype.listeners=function(c){var l=t?t+c:c,d=this._events[l];if(!d)return[];if(d.fn)return[d.fn];for(var h=0,f=d.length,p=new Array(f);h<f;h++)p[h]=d[h].fn;return p},o.prototype.listenerCount=function(c){var l=t?t+c:c,d=this._events[l];return d?d.fn?1:d.length:0},o.prototype.emit=function(c,l,d,h,f,p){var m=t?t+c:c;if(!this._events[m])return!1;var g=this._events[m],y=arguments.length,_,b;if(g.fn){switch(g.once&&this.removeListener(c,g.fn,void 0,!0),y){case 1:return g.fn.call(g.context),!0;case 2:return g.fn.call(g.context,l),!0;case 3:return g.fn.call(g.context,l,d),!0;case 4:return g.fn.call(g.context,l,d,h),!0;case 5:return g.fn.call(g.context,l,d,h,f),!0;case 6:return g.fn.call(g.context,l,d,h,f,p),!0}for(b=1,_=new Array(y-1);b<y;b++)_[b-1]=arguments[b];g.fn.apply(g.context,_)}else{var v=g.length,S;for(b=0;b<v;b++)switch(g[b].once&&this.removeListener(c,g[b].fn,void 0,!0),y){case 1:g[b].fn.call(g[b].context);break;case 2:g[b].fn.call(g[b].context,l);break;case 3:g[b].fn.call(g[b].context,l,d);break;case 4:g[b].fn.call(g[b].context,l,d,h);break;default:if(!_)for(S=1,_=new Array(y-1);S<y;S++)_[S-1]=arguments[S];g[b].fn.apply(g[b].context,_)}}return!0},o.prototype.on=function(c,l,d){return a(this,c,l,d,!1)},o.prototype.once=function(c,l,d){return a(this,c,l,d,!0)},o.prototype.removeListener=function(c,l,d,h){var f=t?t+c:c;if(!this._events[f])return this;if(!l)return i(this,f),this;var p=this._events[f];if(p.fn)p.fn===l&&(!h||p.once)&&(!d||p.context===d)&&i(this,f);else{for(var m=0,g=[],y=p.length;m<y;m++)(p[m].fn!==l||h&&!p[m].once||d&&p[m].context!==d)&&g.push(p[m]);g.length?this._events[f]=g.length===1?g[0]:g:i(this,f)}return this},o.prototype.removeAllListeners=function(c){var l;return c?(l=t?t+c:c,this._events[l]&&i(this,l)):(this._events=new r,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=t,o.EventEmitter=o,n.exports=o})(_a)),_a.exports}var Tr={exports:{}},ba,ic;function ly(){return ic||(ic=1,ba=(n,e)=>(e=e||(()=>{}),n.then(t=>new Promise(r=>{r(e())}).then(()=>t),t=>new Promise(r=>{r(e())}).then(()=>{throw t})))),ba}var oc;function dy(){if(oc)return Tr.exports;oc=1;const n=ly();class e extends Error{constructor(s){super(s),this.name="TimeoutError"}}const t=(r,s,a)=>new Promise((i,o)=>{if(typeof s!="number"||s<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(s===1/0){i(r);return}const u=setTimeout(()=>{if(typeof a=="function"){try{i(a())}catch(d){o(d)}return}const c=typeof a=="string"?a:`Promise timed out after ${s} milliseconds`,l=a instanceof Error?a:new e(c);typeof r.cancel=="function"&&r.cancel(),o(l)},s);n(r.then(i,o),()=>{clearTimeout(u)})});return Tr.exports=t,Tr.exports.default=t,Tr.exports.TimeoutError=e,Tr.exports}var Tn={},An={},uc;function hy(){if(uc)return An;uc=1,Object.defineProperty(An,"__esModule",{value:!0});function n(e,t,r){let s=0,a=e.length;for(;a>0;){const i=a/2|0;let o=s+i;r(e[o],t)<=0?(s=++o,a-=i+1):a=i}return s}return An.default=n,An}var cc;function fy(){if(cc)return Tn;cc=1,Object.defineProperty(Tn,"__esModule",{value:!0});const n=hy();class e{constructor(){this._queue=[]}enqueue(r,s){s=Object.assign({priority:0},s);const a={priority:s.priority,run:r};if(this.size&&this._queue[this.size-1].priority>=s.priority){this._queue.push(a);return}const i=n.default(this._queue,a,(o,u)=>u.priority-o.priority);this._queue.splice(i,0,a)}dequeue(){const r=this._queue.shift();return r?.run}filter(r){return this._queue.filter(s=>s.priority===r.priority).map(s=>s.run)}get size(){return this._queue.length}}return Tn.default=e,Tn}var lc;function py(){if(lc)return kn;lc=1,Object.defineProperty(kn,"__esModule",{value:!0});const n=cy(),e=dy(),t=fy(),r=()=>{},s=new e.TimeoutError;class a extends n{constructor(o){var u,c,l,d;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=r,this._resolveIdle=r,o=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:t.default},o),!(typeof o.intervalCap=="number"&&o.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(c=(u=o.intervalCap)===null||u===void 0?void 0:u.toString())!==null&&c!==void 0?c:""}\` (${typeof o.intervalCap})`);if(o.interval===void 0||!(Number.isFinite(o.interval)&&o.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(d=(l=o.interval)===null||l===void 0?void 0:l.toString())!==null&&d!==void 0?d:""}\` (${typeof o.interval})`);this._carryoverConcurrencyCount=o.carryoverConcurrencyCount,this._isIntervalIgnored=o.intervalCap===1/0||o.interval===0,this._intervalCap=o.intervalCap,this._interval=o.interval,this._queue=new o.queueClass,this._queueClass=o.queueClass,this.concurrency=o.concurrency,this._timeout=o.timeout,this._throwOnTimeout=o.throwOnTimeout===!0,this._isPaused=o.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=r,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=r,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const o=Date.now();if(this._intervalId===void 0){const u=this._intervalEnd-o;if(u<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},u)),!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 o=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const u=this._queue.dequeue();return u?(this.emit("active"),u(),o&&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(o){if(!(typeof o=="number"&&o>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${o}\` (${typeof o})`);this._concurrency=o,this._processQueue()}async add(o,u={}){return new Promise((c,l)=>{const d=async()=>{this._pendingCount++,this._intervalCount++;try{const h=this._timeout===void 0&&u.timeout===void 0?o():e.default(Promise.resolve(o()),u.timeout===void 0?this._timeout:u.timeout,()=>{(u.throwOnTimeout===void 0?this._throwOnTimeout:u.throwOnTimeout)&&l(s)});c(await h)}catch(h){l(h)}this._next()};this._queue.enqueue(d,u),this._tryToStartAnother(),this.emit("add")})}async addAll(o,u){return Promise.all(o.map(async c=>this.add(c,u)))}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(o=>{const u=this._resolveEmpty;this._resolveEmpty=()=>{u(),o()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(o=>{const u=this._resolveIdle;this._resolveIdle=()=>{u(),o()}})}get size(){return this._queue.size}sizeBy(o){return this._queue.filter(o).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(o){this._timeout=o}}return kn.default=a,kn}var my=py();const bt=sn(my),gy=[429,500,502,503,504];let dc=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,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,"default"in bt?this.queue=new bt.default({concurrency:this.maxConcurrency}):this.queue=new bt({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...t){const r=this.onFailedResponseHook;return this.queue.add(()=>cs(()=>e(...t).catch(s=>{throw s instanceof Error?s:new Error(s)}),{async onFailedAttempt(s){if(s.message.startsWith("Cancel")||s.message.startsWith("TimeoutError")||s.name==="TimeoutError"||s.message.startsWith("AbortError")||s?.code==="ECONNABORTED")throw s;const a=s?.response;if(r&&await r(a))return;const i=a?.status??s?.status;if(i&&!gy.includes(+i))throw s},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((s,a)=>{e.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(t,...r)}};function hc(n){return typeof n?._getType=="function"}function fc(n){const e={type:n._getType(),data:{content:n.content}};return n?.additional_kwargs&&Object.keys(n.additional_kwargs).length>0&&(e.data.additional_kwargs={...n.additional_kwargs}),e}const yy=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function Z(n,e){if(!yy.test(n)){const t=e!==void 0?`Invalid UUID for ${e}: ${n}`:`Invalid UUID: ${n}`;throw new Error(t)}return n}const pc={};function Ch(n){pc[n]||(console.warn(n),pc[n]=!0)}var In={exports:{}},wa,mc;function Ls(){if(mc)return wa;mc=1;const n="2.0.0",e=256,t=Number.MAX_SAFE_INTEGER||9007199254740991,r=16,s=e-6;return wa={MAX_LENGTH:e,MAX_SAFE_COMPONENT_LENGTH:r,MAX_SAFE_BUILD_LENGTH:s,MAX_SAFE_INTEGER:t,RELEASE_TYPES:["major","premajor","minor","preminor","patch","prepatch","prerelease"],SEMVER_SPEC_VERSION:n,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2},wa}var va,gc;function Ms(){if(gc)return va;gc=1;var n={};return va=typeof process=="object"&&n&&n.NODE_DEBUG&&/\bsemver\b/i.test(n.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{},va}var yc;function hn(){return yc||(yc=1,(function(n,e){const{MAX_SAFE_COMPONENT_LENGTH:t,MAX_SAFE_BUILD_LENGTH:r,MAX_LENGTH:s}=Ls(),a=Ms();e=n.exports={};const i=e.re=[],o=e.safeRe=[],u=e.src=[],c=e.safeSrc=[],l=e.t={};let d=0;const h="[a-zA-Z0-9-]",f=[["\\s",1],["\\d",s],[h,r]],p=g=>{for(const[y,_]of f)g=g.split(`${y}*`).join(`${y}{0,${_}}`).split(`${y}+`).join(`${y}{1,${_}}`);return g},m=(g,y,_)=>{const b=p(y),v=d++;a(g,v,y),l[g]=v,u[v]=y,c[v]=b,i[v]=new RegExp(y,_?"g":void 0),o[v]=new RegExp(b,_?"g":void 0)};m("NUMERICIDENTIFIER","0|[1-9]\\d*"),m("NUMERICIDENTIFIERLOOSE","\\d+"),m("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${h}*`),m("MAINVERSION",`(${u[l.NUMERICIDENTIFIER]})\\.(${u[l.NUMERICIDENTIFIER]})\\.(${u[l.NUMERICIDENTIFIER]})`),m("MAINVERSIONLOOSE",`(${u[l.NUMERICIDENTIFIERLOOSE]})\\.(${u[l.NUMERICIDENTIFIERLOOSE]})\\.(${u[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASEIDENTIFIER",`(?:${u[l.NONNUMERICIDENTIFIER]}|${u[l.NUMERICIDENTIFIER]})`),m("PRERELEASEIDENTIFIERLOOSE",`(?:${u[l.NONNUMERICIDENTIFIER]}|${u[l.NUMERICIDENTIFIERLOOSE]})`),m("PRERELEASE",`(?:-(${u[l.PRERELEASEIDENTIFIER]}(?:\\.${u[l.PRERELEASEIDENTIFIER]})*))`),m("PRERELEASELOOSE",`(?:-?(${u[l.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${u[l.PRERELEASEIDENTIFIERLOOSE]})*))`),m("BUILDIDENTIFIER",`${h}+`),m("BUILD",`(?:\\+(${u[l.BUILDIDENTIFIER]}(?:\\.${u[l.BUILDIDENTIFIER]})*))`),m("FULLPLAIN",`v?${u[l.MAINVERSION]}${u[l.PRERELEASE]}?${u[l.BUILD]}?`),m("FULL",`^${u[l.FULLPLAIN]}$`),m("LOOSEPLAIN",`[v=\\s]*${u[l.MAINVERSIONLOOSE]}${u[l.PRERELEASELOOSE]}?${u[l.BUILD]}?`),m("LOOSE",`^${u[l.LOOSEPLAIN]}$`),m("GTLT","((?:<|>)?=?)"),m("XRANGEIDENTIFIERLOOSE",`${u[l.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`),m("XRANGEIDENTIFIER",`${u[l.NUMERICIDENTIFIER]}|x|X|\\*`),m("XRANGEPLAIN",`[v=\\s]*(${u[l.XRANGEIDENTIFIER]})(?:\\.(${u[l.XRANGEIDENTIFIER]})(?:\\.(${u[l.XRANGEIDENTIFIER]})(?:${u[l.PRERELEASE]})?${u[l.BUILD]}?)?)?`),m("XRANGEPLAINLOOSE",`[v=\\s]*(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:\\.(${u[l.XRANGEIDENTIFIERLOOSE]})(?:${u[l.PRERELEASELOOSE]})?${u[l.BUILD]}?)?)?`),m("XRANGE",`^${u[l.GTLT]}\\s*${u[l.XRANGEPLAIN]}$`),m("XRANGELOOSE",`^${u[l.GTLT]}\\s*${u[l.XRANGEPLAINLOOSE]}$`),m("COERCEPLAIN",`(^|[^\\d])(\\d{1,${t}})(?:\\.(\\d{1,${t}}))?(?:\\.(\\d{1,${t}}))?`),m("COERCE",`${u[l.COERCEPLAIN]}(?:$|[^\\d])`),m("COERCEFULL",u[l.COERCEPLAIN]+`(?:${u[l.PRERELEASE]})?(?:${u[l.BUILD]})?(?:$|[^\\d])`),m("COERCERTL",u[l.COERCE],!0),m("COERCERTLFULL",u[l.COERCEFULL],!0),m("LONETILDE","(?:~>?)"),m("TILDETRIM",`(\\s*)${u[l.LONETILDE]}\\s+`,!0),e.tildeTrimReplace="$1~",m("TILDE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAIN]}$`),m("TILDELOOSE",`^${u[l.LONETILDE]}${u[l.XRANGEPLAINLOOSE]}$`),m("LONECARET","(?:\\^)"),m("CARETTRIM",`(\\s*)${u[l.LONECARET]}\\s+`,!0),e.caretTrimReplace="$1^",m("CARET",`^${u[l.LONECARET]}${u[l.XRANGEPLAIN]}$`),m("CARETLOOSE",`^${u[l.LONECARET]}${u[l.XRANGEPLAINLOOSE]}$`),m("COMPARATORLOOSE",`^${u[l.GTLT]}\\s*(${u[l.LOOSEPLAIN]})$|^$`),m("COMPARATOR",`^${u[l.GTLT]}\\s*(${u[l.FULLPLAIN]})$|^$`),m("COMPARATORTRIM",`(\\s*)${u[l.GTLT]}\\s*(${u[l.LOOSEPLAIN]}|${u[l.XRANGEPLAIN]})`,!0),e.comparatorTrimReplace="$1$2$3",m("HYPHENRANGE",`^\\s*(${u[l.XRANGEPLAIN]})\\s+-\\s+(${u[l.XRANGEPLAIN]})\\s*$`),m("HYPHENRANGELOOSE",`^\\s*(${u[l.XRANGEPLAINLOOSE]})\\s+-\\s+(${u[l.XRANGEPLAINLOOSE]})\\s*$`),m("STAR","(<|>)?=?\\s*\\*"),m("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$"),m("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")})(In,In.exports)),In.exports}var Sa,_c;function Io(){if(_c)return Sa;_c=1;const n=Object.freeze({loose:!0}),e=Object.freeze({});return Sa=r=>r?typeof r!="object"?n:r:e,Sa}var Ea,bc;function $h(){if(bc)return Ea;bc=1;const n=/^[0-9]+$/,e=(r,s)=>{if(typeof r=="number"&&typeof s=="number")return r===s?0:r<s?-1:1;const a=n.test(r),i=n.test(s);return a&&i&&(r=+r,s=+s),r===s?0:a&&!i?-1:i&&!a?1:r<s?-1:1};return Ea={compareIdentifiers:e,rcompareIdentifiers:(r,s)=>e(s,r)},Ea}var Oa,wc;function $e(){if(wc)return Oa;wc=1;const n=Ms(),{MAX_LENGTH:e,MAX_SAFE_INTEGER:t}=Ls(),{safeRe:r,t:s}=hn(),a=Io(),{compareIdentifiers:i}=$h();class o{constructor(c,l){if(l=a(l),c instanceof o){if(c.loose===!!l.loose&&c.includePrerelease===!!l.includePrerelease)return c;c=c.version}else if(typeof c!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof c}".`);if(c.length>e)throw new TypeError(`version is longer than ${e} characters`);n("SemVer",c,l),this.options=l,this.loose=!!l.loose,this.includePrerelease=!!l.includePrerelease;const d=c.trim().match(l.loose?r[s.LOOSE]:r[s.FULL]);if(!d)throw new TypeError(`Invalid Version: ${c}`);if(this.raw=c,this.major=+d[1],this.minor=+d[2],this.patch=+d[3],this.major>t||this.major<0)throw new TypeError("Invalid major version");if(this.minor>t||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>t||this.patch<0)throw new TypeError("Invalid patch version");d[4]?this.prerelease=d[4].split(".").map(h=>{if(/^[0-9]+$/.test(h)){const f=+h;if(f>=0&&f<t)return f}return h}):this.prerelease=[],this.build=d[5]?d[5].split("."):[],this.format()}format(){return this.version=`${this.major}.${this.minor}.${this.patch}`,this.prerelease.length&&(this.version+=`-${this.prerelease.join(".")}`),this.version}toString(){return this.version}compare(c){if(n("SemVer.compare",this.version,this.options,c),!(c instanceof o)){if(typeof c=="string"&&c===this.version)return 0;c=new o(c,this.options)}return c.version===this.version?0:this.compareMain(c)||this.comparePre(c)}compareMain(c){return c instanceof o||(c=new o(c,this.options)),this.major<c.major?-1:this.major>c.major?1:this.minor<c.minor?-1:this.minor>c.minor?1:this.patch<c.patch?-1:this.patch>c.patch?1:0}comparePre(c){if(c instanceof o||(c=new o(c,this.options)),this.prerelease.length&&!c.prerelease.length)return-1;if(!this.prerelease.length&&c.prerelease.length)return 1;if(!this.prerelease.length&&!c.prerelease.length)return 0;let l=0;do{const d=this.prerelease[l],h=c.prerelease[l];if(n("prerelease compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}compareBuild(c){c instanceof o||(c=new o(c,this.options));let l=0;do{const d=this.build[l],h=c.build[l];if(n("build compare",l,d,h),d===void 0&&h===void 0)return 0;if(h===void 0)return 1;if(d===void 0)return-1;if(d===h)continue;return i(d,h)}while(++l)}inc(c,l,d){if(c.startsWith("pre")){if(!l&&d===!1)throw new Error("invalid increment argument: identifier is empty");if(l){const h=`-${l}`.match(this.options.loose?r[s.PRERELEASELOOSE]:r[s.PRERELEASE]);if(!h||h[1]!==l)throw new Error(`invalid identifier: ${l}`)}}switch(c){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",l,d);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",l,d);break;case"prepatch":this.prerelease.length=0,this.inc("patch",l,d),this.inc("pre",l,d);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",l,d),this.inc("pre",l,d);break;case"release":if(this.prerelease.length===0)throw new Error(`version ${this.raw} is not a prerelease`);this.prerelease.length=0;break;case"major":(this.minor!==0||this.patch!==0||this.prerelease.length===0)&&this.major++,this.minor=0,this.patch=0,this.prerelease=[];break;case"minor":(this.patch!==0||this.prerelease.length===0)&&this.minor++,this.patch=0,this.prerelease=[];break;case"patch":this.prerelease.length===0&&this.patch++,this.prerelease=[];break;case"pre":{const h=Number(d)?1:0;if(this.prerelease.length===0)this.prerelease=[h];else{let f=this.prerelease.length;for(;--f>=0;)typeof this.prerelease[f]=="number"&&(this.prerelease[f]++,f=-2);if(f===-1){if(l===this.prerelease.join(".")&&d===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(h)}}if(l){let f=[l,h];d===!1&&(f=[l]),i(this.prerelease[0],l)===0?isNaN(this.prerelease[1])&&(this.prerelease=f):this.prerelease=f}break}default:throw new Error(`invalid increment argument: ${c}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}}return Oa=o,Oa}var xa,vc;function wr(){if(vc)return xa;vc=1;const n=$e();return xa=(t,r,s=!1)=>{if(t instanceof n)return t;try{return new n(t,r)}catch(a){if(!s)return null;throw a}},xa}var ka,Sc;function _y(){if(Sc)return ka;Sc=1;const n=wr();return ka=(t,r)=>{const s=n(t,r);return s?s.version:null},ka}var Ta,Ec;function by(){if(Ec)return Ta;Ec=1;const n=wr();return Ta=(t,r)=>{const s=n(t.trim().replace(/^[=v]+/,""),r);return s?s.version:null},Ta}var Aa,Oc;function wy(){if(Oc)return Aa;Oc=1;const n=$e();return Aa=(t,r,s,a,i)=>{typeof s=="string"&&(i=a,a=s,s=void 0);try{return new n(t instanceof n?t.version:t,s).inc(r,a,i).version}catch{return null}},Aa}var Ia,xc;function vy(){if(xc)return Ia;xc=1;const n=wr();return Ia=(t,r)=>{const s=n(t,null,!0),a=n(r,null,!0),i=s.compare(a);if(i===0)return null;const o=i>0,u=o?s:a,c=o?a:s,l=!!u.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(u)===0)return c.minor&&!c.patch?"minor":"patch"}const h=l?"pre":"";return s.major!==a.major?h+"major":s.minor!==a.minor?h+"minor":s.patch!==a.patch?h+"patch":"prerelease"},Ia}var Ra,kc;function Sy(){if(kc)return Ra;kc=1;const n=$e();return Ra=(t,r)=>new n(t,r).major,Ra}var Pa,Tc;function Ey(){if(Tc)return Pa;Tc=1;const n=$e();return Pa=(t,r)=>new n(t,r).minor,Pa}var Ca,Ac;function Oy(){if(Ac)return Ca;Ac=1;const n=$e();return Ca=(t,r)=>new n(t,r).patch,Ca}var $a,Ic;function xy(){if(Ic)return $a;Ic=1;const n=wr();return $a=(t,r)=>{const s=n(t,r);return s&&s.prerelease.length?s.prerelease:null},$a}var Na,Rc;function st(){if(Rc)return Na;Rc=1;const n=$e();return Na=(t,r,s)=>new n(t,s).compare(new n(r,s)),Na}var ja,Pc;function ky(){if(Pc)return ja;Pc=1;const n=st();return ja=(t,r,s)=>n(r,t,s),ja}var La,Cc;function Ty(){if(Cc)return La;Cc=1;const n=st();return La=(t,r)=>n(t,r,!0),La}var Ma,$c;function Ro(){if($c)return Ma;$c=1;const n=$e();return Ma=(t,r,s)=>{const a=new n(t,s),i=new n(r,s);return a.compare(i)||a.compareBuild(i)},Ma}var Ua,Nc;function Ay(){if(Nc)return Ua;Nc=1;const n=Ro();return Ua=(t,r)=>t.sort((s,a)=>n(s,a,r)),Ua}var Da,jc;function Iy(){if(jc)return Da;jc=1;const n=Ro();return Da=(t,r)=>t.sort((s,a)=>n(a,s,r)),Da}var Fa,Lc;function Us(){if(Lc)return Fa;Lc=1;const n=st();return Fa=(t,r,s)=>n(t,r,s)>0,Fa}var Ba,Mc;function Po(){if(Mc)return Ba;Mc=1;const n=st();return Ba=(t,r,s)=>n(t,r,s)<0,Ba}var za,Uc;function Nh(){if(Uc)return za;Uc=1;const n=st();return za=(t,r,s)=>n(t,r,s)===0,za}var qa,Dc;function jh(){if(Dc)return qa;Dc=1;const n=st();return qa=(t,r,s)=>n(t,r,s)!==0,qa}var Za,Fc;function Co(){if(Fc)return Za;Fc=1;const n=st();return Za=(t,r,s)=>n(t,r,s)>=0,Za}var Ha,Bc;function $o(){if(Bc)return Ha;Bc=1;const n=st();return Ha=(t,r,s)=>n(t,r,s)<=0,Ha}var Ga,zc;function Lh(){if(zc)return Ga;zc=1;const n=Nh(),e=jh(),t=Us(),r=Co(),s=Po(),a=$o();return Ga=(o,u,c,l)=>{switch(u){case"===":return typeof o=="object"&&(o=o.version),typeof c=="object"&&(c=c.version),o===c;case"!==":return typeof o=="object"&&(o=o.version),typeof c=="object"&&(c=c.version),o!==c;case"":case"=":case"==":return n(o,c,l);case"!=":return e(o,c,l);case">":return t(o,c,l);case">=":return r(o,c,l);case"<":return s(o,c,l);case"<=":return a(o,c,l);default:throw new TypeError(`Invalid operator: ${u}`)}},Ga}var Ja,qc;function Ry(){if(qc)return Ja;qc=1;const n=$e(),e=wr(),{safeRe:t,t:r}=hn();return Ja=(a,i)=>{if(a instanceof n)return a;if(typeof a=="number"&&(a=String(a)),typeof a!="string")return null;i=i||{};let o=null;if(!i.rtl)o=a.match(i.includePrerelease?t[r.COERCEFULL]:t[r.COERCE]);else{const f=i.includePrerelease?t[r.COERCERTLFULL]:t[r.COERCERTL];let p;for(;(p=f.exec(a))&&(!o||o.index+o[0].length!==a.length);)(!o||p.index+p[0].length!==o.index+o[0].length)&&(o=p),f.lastIndex=p.index+p[1].length+p[2].length;f.lastIndex=-1}if(o===null)return null;const u=o[2],c=o[3]||"0",l=o[4]||"0",d=i.includePrerelease&&o[5]?`-${o[5]}`:"",h=i.includePrerelease&&o[6]?`+${o[6]}`:"";return e(`${u}.${c}.${l}${d}${h}`,i)},Ja}var Wa,Zc;function Py(){if(Zc)return Wa;Zc=1;class n{constructor(){this.max=1e3,this.map=new Map}get(t){const r=this.map.get(t);if(r!==void 0)return this.map.delete(t),this.map.set(t,r),r}delete(t){return this.map.delete(t)}set(t,r){if(!this.delete(t)&&r!==void 0){if(this.map.size>=this.max){const a=this.map.keys().next().value;this.delete(a)}this.map.set(t,r)}return this}}return Wa=n,Wa}var Va,Hc;function at(){if(Hc)return Va;Hc=1;const n=/\s+/g;class e{constructor(k,U){if(U=s(U),k instanceof e)return k.loose===!!U.loose&&k.includePrerelease===!!U.includePrerelease?k:new e(k.raw,U);if(k instanceof a)return this.raw=k.value,this.set=[[k]],this.formatted=void 0,this;if(this.options=U,this.loose=!!U.loose,this.includePrerelease=!!U.includePrerelease,this.raw=k.trim().replace(n," "),this.set=this.raw.split("||").map(j=>this.parseRange(j.trim())).filter(j=>j.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){const j=this.set[0];if(this.set=this.set.filter(D=>!m(D[0])),this.set.length===0)this.set=[j];else if(this.set.length>1){for(const D of this.set)if(D.length===1&&g(D[0])){this.set=[D];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let k=0;k<this.set.length;k++){k>0&&(this.formatted+="||");const U=this.set[k];for(let j=0;j<U.length;j++)j>0&&(this.formatted+=" "),this.formatted+=U[j].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(k){const j=((this.options.includePrerelease&&f)|(this.options.loose&&p))+":"+k,D=r.get(j);if(D)return D;const L=this.options.loose,H=L?u[c.HYPHENRANGELOOSE]:u[c.HYPHENRANGE];k=k.replace(H,Ve(this.options.includePrerelease)),i("hyphen replace",k),k=k.replace(u[c.COMPARATORTRIM],l),i("comparator trim",k),k=k.replace(u[c.TILDETRIM],d),i("tilde trim",k),k=k.replace(u[c.CARETTRIM],h),i("caret trim",k);let re=k.split(" ").map(ce=>_(ce,this.options)).join(" ").split(/\s+/).map(ce=>ae(ce,this.options));L&&(re=re.filter(ce=>(i("loose invalid filter",ce,this.options),!!ce.match(u[c.COMPARATORLOOSE])))),i("range list",re);const W=new Map,ue=re.map(ce=>new a(ce,this.options));for(const ce of ue){if(m(ce))return[ce];W.set(ce.value,ce)}W.size>1&&W.has("")&&W.delete("");const Ae=[...W.values()];return r.set(j,Ae),Ae}intersects(k,U){if(!(k instanceof e))throw new TypeError("a Range is required");return this.set.some(j=>y(j,U)&&k.set.some(D=>y(D,U)&&j.every(L=>D.every(H=>L.intersects(H,U)))))}test(k){if(!k)return!1;if(typeof k=="string")try{k=new o(k,this.options)}catch{return!1}for(let U=0;U<this.set.length;U++)if(Ut(this.set[U],k,this.options))return!0;return!1}}Va=e;const t=Py(),r=new t,s=Io(),a=Ds(),i=Ms(),o=$e(),{safeRe:u,t:c,comparatorTrimReplace:l,tildeTrimReplace:d,caretTrimReplace:h}=hn(),{FLAG_INCLUDE_PRERELEASE:f,FLAG_LOOSE:p}=Ls(),m=I=>I.value==="<0.0.0-0",g=I=>I.value==="",y=(I,k)=>{let U=!0;const j=I.slice();let D=j.pop();for(;U&&j.length;)U=j.every(L=>D.intersects(L,k)),D=j.pop();return U},_=(I,k)=>(I=I.replace(u[c.BUILD],""),i("comp",I,k),I=R(I,k),i("caret",I),I=v(I,k),i("tildes",I),I=x(I,k),i("xrange",I),I=Q(I,k),i("stars",I),I),b=I=>!I||I.toLowerCase()==="x"||I==="*",v=(I,k)=>I.trim().split(/\s+/).map(U=>S(U,k)).join(" "),S=(I,k)=>{const U=k.loose?u[c.TILDELOOSE]:u[c.TILDE];return I.replace(U,(j,D,L,H,re)=>{i("tilde",I,j,D,L,H,re);let W;return b(D)?W="":b(L)?W=`>=${D}.0.0 <${+D+1}.0.0-0`:b(H)?W=`>=${D}.${L}.0 <${D}.${+L+1}.0-0`:re?(i("replaceTilde pr",re),W=`>=${D}.${L}.${H}-${re} <${D}.${+L+1}.0-0`):W=`>=${D}.${L}.${H} <${D}.${+L+1}.0-0`,i("tilde return",W),W})},R=(I,k)=>I.trim().split(/\s+/).map(U=>P(U,k)).join(" "),P=(I,k)=>{i("caret",I,k);const U=k.loose?u[c.CARETLOOSE]:u[c.CARET],j=k.includePrerelease?"-0":"";return I.replace(U,(D,L,H,re,W)=>{i("caret",I,D,L,H,re,W);let ue;return b(L)?ue="":b(H)?ue=`>=${L}.0.0${j} <${+L+1}.0.0-0`:b(re)?L==="0"?ue=`>=${L}.${H}.0${j} <${L}.${+H+1}.0-0`:ue=`>=${L}.${H}.0${j} <${+L+1}.0.0-0`:W?(i("replaceCaret pr",W),L==="0"?H==="0"?ue=`>=${L}.${H}.${re}-${W} <${L}.${H}.${+re+1}-0`:ue=`>=${L}.${H}.${re}-${W} <${L}.${+H+1}.0-0`:ue=`>=${L}.${H}.${re}-${W} <${+L+1}.0.0-0`):(i("no pr"),L==="0"?H==="0"?ue=`>=${L}.${H}.${re}${j} <${L}.${H}.${+re+1}-0`:ue=`>=${L}.${H}.${re}${j} <${L}.${+H+1}.0-0`:ue=`>=${L}.${H}.${re} <${+L+1}.0.0-0`),i("caret return",ue),ue})},x=(I,k)=>(i("replaceXRanges",I,k),I.split(/\s+/).map(U=>K(U,k)).join(" ")),K=(I,k)=>{I=I.trim();const U=k.loose?u[c.XRANGELOOSE]:u[c.XRANGE];return I.replace(U,(j,D,L,H,re,W)=>{i("xRange",I,j,D,L,H,re,W);const ue=b(L),Ae=ue||b(H),ce=Ae||b(re),Or=ce;return D==="="&&Or&&(D=""),W=k.includePrerelease?"-0":"",ue?D===">"||D==="<"?j="<0.0.0-0":j="*":D&&Or?(Ae&&(H=0),re=0,D===">"?(D=">=",Ae?(L=+L+1,H=0,re=0):(H=+H+1,re=0)):D==="<="&&(D="<",Ae?L=+L+1:H=+H+1),D==="<"&&(W="-0"),j=`${D+L}.${H}.${re}${W}`):Ae?j=`>=${L}.0.0${W} <${+L+1}.0.0-0`:ce&&(j=`>=${L}.${H}.0${W} <${L}.${+H+1}.0-0`),i("xRange return",j),j})},Q=(I,k)=>(i("replaceStars",I,k),I.trim().replace(u[c.STAR],"")),ae=(I,k)=>(i("replaceGTE0",I,k),I.trim().replace(u[k.includePrerelease?c.GTE0PRE:c.GTE0],"")),Ve=I=>(k,U,j,D,L,H,re,W,ue,Ae,ce,Or)=>(b(j)?U="":b(D)?U=`>=${j}.0.0${I?"-0":""}`:b(L)?U=`>=${j}.${D}.0${I?"-0":""}`:H?U=`>=${U}`:U=`>=${U}${I?"-0":""}`,b(ue)?W="":b(Ae)?W=`<${+ue+1}.0.0-0`:b(ce)?W=`<${ue}.${+Ae+1}.0-0`:Or?W=`<=${ue}.${Ae}.${ce}-${Or}`:I?W=`<${ue}.${Ae}.${+ce+1}-0`:W=`<=${W}`,`${U} ${W}`.trim()),Ut=(I,k,U)=>{for(let j=0;j<I.length;j++)if(!I[j].test(k))return!1;if(k.prerelease.length&&!U.includePrerelease){for(let j=0;j<I.length;j++)if(i(I[j].semver),I[j].semver!==a.ANY&&I[j].semver.prerelease.length>0){const D=I[j].semver;if(D.major===k.major&&D.minor===k.minor&&D.patch===k.patch)return!0}return!1}return!0};return Va}var Ka,Gc;function Ds(){if(Gc)return Ka;Gc=1;const n=Symbol("SemVer ANY");class e{static get ANY(){return n}constructor(l,d){if(d=t(d),l instanceof e){if(l.loose===!!d.loose)return l;l=l.value}l=l.trim().split(/\s+/).join(" "),i("comparator",l,d),this.options=d,this.loose=!!d.loose,this.parse(l),this.semver===n?this.value="":this.value=this.operator+this.semver.version,i("comp",this)}parse(l){const d=this.options.loose?r[s.COMPARATORLOOSE]:r[s.COMPARATOR],h=l.match(d);if(!h)throw new TypeError(`Invalid comparator: ${l}`);this.operator=h[1]!==void 0?h[1]:"",this.operator==="="&&(this.operator=""),h[2]?this.semver=new o(h[2],this.options.loose):this.semver=n}toString(){return this.value}test(l){if(i("Comparator.test",l,this.options.loose),this.semver===n||l===n)return!0;if(typeof l=="string")try{l=new o(l,this.options)}catch{return!1}return a(l,this.operator,this.semver,this.options)}intersects(l,d){if(!(l instanceof e))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new u(l.value,d).test(this.value):l.operator===""?l.value===""?!0:new u(this.value,d).test(l.semver):(d=t(d),d.includePrerelease&&(this.value==="<0.0.0-0"||l.value==="<0.0.0-0")||!d.includePrerelease&&(this.value.startsWith("<0.0.0")||l.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&l.operator.startsWith(">")||this.operator.startsWith("<")&&l.operator.startsWith("<")||this.semver.version===l.semver.version&&this.operator.includes("=")&&l.operator.includes("=")||a(this.semver,"<",l.semver,d)&&this.operator.startsWith(">")&&l.operator.startsWith("<")||a(this.semver,">",l.semver,d)&&this.operator.startsWith("<")&&l.operator.startsWith(">")))}}Ka=e;const t=Io(),{safeRe:r,t:s}=hn(),a=Lh(),i=Ms(),o=$e(),u=at();return Ka}var Xa,Jc;function Fs(){if(Jc)return Xa;Jc=1;const n=at();return Xa=(t,r,s)=>{try{r=new n(r,s)}catch{return!1}return r.test(t)},Xa}var Qa,Wc;function Cy(){if(Wc)return Qa;Wc=1;const n=at();return Qa=(t,r)=>new n(t,r).set.map(s=>s.map(a=>a.value).join(" ").trim().split(" ")),Qa}var Ya,Vc;function $y(){if(Vc)return Ya;Vc=1;const n=$e(),e=at();return Ya=(r,s,a)=>{let i=null,o=null,u=null;try{u=new e(s,a)}catch{return null}return r.forEach(c=>{u.test(c)&&(!i||o.compare(c)===-1)&&(i=c,o=new n(i,a))}),i},Ya}var ei,Kc;function Ny(){if(Kc)return ei;Kc=1;const n=$e(),e=at();return ei=(r,s,a)=>{let i=null,o=null,u=null;try{u=new e(s,a)}catch{return null}return r.forEach(c=>{u.test(c)&&(!i||o.compare(c)===1)&&(i=c,o=new n(i,a))}),i},ei}var ti,Xc;function jy(){if(Xc)return ti;Xc=1;const n=$e(),e=at(),t=Us();return ti=(s,a)=>{s=new e(s,a);let i=new n("0.0.0");if(s.test(i)||(i=new n("0.0.0-0"),s.test(i)))return i;i=null;for(let o=0;o<s.set.length;++o){const u=s.set[o];let c=null;u.forEach(l=>{const d=new n(l.semver.version);switch(l.operator){case">":d.prerelease.length===0?d.patch++:d.prerelease.push(0),d.raw=d.format();case"":case">=":(!c||t(d,c))&&(c=d);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${l.operator}`)}}),c&&(!i||t(i,c))&&(i=c)}return i&&s.test(i)?i:null},ti}var ri,Qc;function Ly(){if(Qc)return ri;Qc=1;const n=at();return ri=(t,r)=>{try{return new n(t,r).range||"*"}catch{return null}},ri}var ni,Yc;function No(){if(Yc)return ni;Yc=1;const n=$e(),e=Ds(),{ANY:t}=e,r=at(),s=Fs(),a=Us(),i=Po(),o=$o(),u=Co();return ni=(l,d,h,f)=>{l=new n(l,f),d=new r(d,f);let p,m,g,y,_;switch(h){case">":p=a,m=o,g=i,y=">",_=">=";break;case"<":p=i,m=u,g=a,y="<",_="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(s(l,d,f))return!1;for(let b=0;b<d.set.length;++b){const v=d.set[b];let S=null,R=null;if(v.forEach(P=>{P.semver===t&&(P=new e(">=0.0.0")),S=S||P,R=R||P,p(P.semver,S.semver,f)?S=P:g(P.semver,R.semver,f)&&(R=P)}),S.operator===y||S.operator===_||(!R.operator||R.operator===y)&&m(l,R.semver))return!1;if(R.operator===_&&g(l,R.semver))return!1}return!0},ni}var si,el;function My(){if(el)return si;el=1;const n=No();return si=(t,r,s)=>n(t,r,">",s),si}var ai,tl;function Uy(){if(tl)return ai;tl=1;const n=No();return ai=(t,r,s)=>n(t,r,"<",s),ai}var ii,rl;function Dy(){if(rl)return ii;rl=1;const n=at();return ii=(t,r,s)=>(t=new n(t,s),r=new n(r,s),t.intersects(r,s)),ii}var oi,nl;function Fy(){if(nl)return oi;nl=1;const n=Fs(),e=st();return oi=(t,r,s)=>{const a=[];let i=null,o=null;const u=t.sort((h,f)=>e(h,f,s));for(const h of u)n(h,r,s)?(o=h,i||(i=h)):(o&&a.push([i,o]),o=null,i=null);i&&a.push([i,null]);const c=[];for(const[h,f]of a)h===f?c.push(h):!f&&h===u[0]?c.push("*"):f?h===u[0]?c.push(`<=${f}`):c.push(`${h} - ${f}`):c.push(`>=${h}`);const l=c.join(" || "),d=typeof r.raw=="string"?r.raw:String(r);return l.length<d.length?l:r},oi}var ui,sl;function By(){if(sl)return ui;sl=1;const n=at(),e=Ds(),{ANY:t}=e,r=Fs(),s=st(),a=(d,h,f={})=>{if(d===h)return!0;d=new n(d,f),h=new n(h,f);let p=!1;e:for(const m of d.set){for(const g of h.set){const y=u(m,g,f);if(p=p||y!==null,y)continue e}if(p)return!1}return!0},i=[new e(">=0.0.0-0")],o=[new e(">=0.0.0")],u=(d,h,f)=>{if(d===h)return!0;if(d.length===1&&d[0].semver===t){if(h.length===1&&h[0].semver===t)return!0;f.includePrerelease?d=i:d=o}if(h.length===1&&h[0].semver===t){if(f.includePrerelease)return!0;h=o}const p=new Set;let m,g;for(const x of d)x.operator===">"||x.operator===">="?m=c(m,x,f):x.operator==="<"||x.operator==="<="?g=l(g,x,f):p.add(x.semver);if(p.size>1)return null;let y;if(m&&g){if(y=s(m.semver,g.semver,f),y>0)return null;if(y===0&&(m.operator!==">="||g.operator!=="<="))return null}for(const x of p){if(m&&!r(x,String(m),f)||g&&!r(x,String(g),f))return null;for(const K of h)if(!r(x,String(K),f))return!1;return!0}let _,b,v,S,R=g&&!f.includePrerelease&&g.semver.prerelease.length?g.semver:!1,P=m&&!f.includePrerelease&&m.semver.prerelease.length?m.semver:!1;R&&R.prerelease.length===1&&g.operator==="<"&&R.prerelease[0]===0&&(R=!1);for(const x of h){if(S=S||x.operator===">"||x.operator===">=",v=v||x.operator==="<"||x.operator==="<=",m){if(P&&x.semver.prerelease&&x.semver.prerelease.length&&x.semver.major===P.major&&x.semver.minor===P.minor&&x.semver.patch===P.patch&&(P=!1),x.operator===">"||x.operator===">="){if(_=c(m,x,f),_===x&&_!==m)return!1}else if(m.operator===">="&&!r(m.semver,String(x),f))return!1}if(g){if(R&&x.semver.prerelease&&x.semver.prerelease.length&&x.semver.major===R.major&&x.semver.minor===R.minor&&x.semver.patch===R.patch&&(R=!1),x.operator==="<"||x.operator==="<="){if(b=l(g,x,f),b===x&&b!==g)return!1}else if(g.operator==="<="&&!r(g.semver,String(x),f))return!1}if(!x.operator&&(g||m)&&y!==0)return!1}return!(m&&v&&!g&&y!==0||g&&S&&!m&&y!==0||P||R)},c=(d,h,f)=>{if(!d)return h;const p=s(d.semver,h.semver,f);return p>0?d:p<0||h.operator===">"&&d.operator===">="?h:d},l=(d,h,f)=>{if(!d)return h;const p=s(d.semver,h.semver,f);return p<0?d:p>0||h.operator==="<"&&d.operator==="<="?h:d};return ui=a,ui}var ci,al;function zy(){if(al)return ci;al=1;const n=hn(),e=Ls(),t=$e(),r=$h(),s=wr(),a=_y(),i=by(),o=wy(),u=vy(),c=Sy(),l=Ey(),d=Oy(),h=xy(),f=st(),p=ky(),m=Ty(),g=Ro(),y=Ay(),_=Iy(),b=Us(),v=Po(),S=Nh(),R=jh(),P=Co(),x=$o(),K=Lh(),Q=Ry(),ae=Ds(),Ve=at(),Ut=Fs(),I=Cy(),k=$y(),U=Ny(),j=jy(),D=Ly(),L=No(),H=My(),re=Uy(),W=Dy(),ue=Fy(),Ae=By();return ci={parse:s,valid:a,clean:i,inc:o,diff:u,major:c,minor:l,patch:d,prerelease:h,compare:f,rcompare:p,compareLoose:m,compareBuild:g,sort:y,rsort:_,gt:b,lt:v,eq:S,neq:R,gte:P,lte:x,cmp:K,coerce:Q,Comparator:ae,Range:Ve,satisfies:Ut,toComparators:I,maxSatisfying:k,minSatisfying:U,minVersion:j,validRange:D,outside:L,gtr:H,ltr:re,intersects:W,simplifyRange:ue,subset:Ae,SemVer:t,re:n.re,src:n.src,tokens:n.t,SEMVER_SPEC_VERSION:e.SEMVER_SPEC_VERSION,RELEASE_TYPES:e.RELEASE_TYPES,compareIdentifiers:r.compareIdentifiers,rcompareIdentifiers:r.rcompareIdentifiers},ci}zy();function Et(n){if(!n||n.split("/").length>2||n.startsWith("/")||n.endsWith("/")||n.split(":").length>2)throw new Error(`Invalid identifier format: ${n}`);const[e,t]=n.split(":"),r=t||"latest";if(e.includes("/")){const[s,a]=e.split("/",2);if(!s||!a)throw new Error(`Invalid identifier format: ${n}`);return[s,a,r]}else{if(!e)throw new Error(`Invalid identifier format: ${n}`);return["-",e,r]}}class qy 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}}async function N(n,e,t){let r;if(n.ok){t&&(r=await n.text());return}if(n.status===403)try{(await n.json())?.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(`${n.status} ${n.statusText}`);throw o.status=n?.status,o}if(r===void 0)try{r=await n.text()}catch{r=""}const s=`Failed to ${e}. Received status [${n.status}]: ${n.statusText}. Message: ${r}`;if(n.status===409)throw new qy(s);const a=new Error(s);throw a.status=n.status,a}const Mh="ERR_CONFLICTING_ENDPOINTS";class Zy 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:Mh}),this.name="ConflictingEndpointsError"}}function Hy(n){return typeof n=="object"&&n!==null&&n.code===Mh}var il="[...]",Gy={result:"[Circular]"},hs=[],lr=[];const Jy=new TextEncoder;function Wy(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}function Rn(n){return Jy.encode(n)}function Uh(n){if(n&&typeof n=="object"&&n!==null){if(n instanceof Map)return Object.fromEntries(n);if(n instanceof Set)return Array.from(n);if(n instanceof Date)return n.toISOString();if(n instanceof RegExp)return n.toString();if(n instanceof Error)return{name:n.name,message:n.message}}else if(typeof n=="bigint")return n.toString();return n}function Vy(n){return function(e,t){return Uh(t)}}function Be(n,e,t,r,s){try{const a=JSON.stringify(n,Vy(t),r);return Rn(a)}catch(a){if(!a.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
|
|
50
|
+
Context: ${e}`:""}`),Rn("[Unserializable]");Me("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
|
|
51
|
+
Context: ${e}`:""}`),typeof s>"u"&&(s=Wy()),Wi(n,"",0,[],void 0,0,s);let i;try{lr.length===0?i=JSON.stringify(n,t,r):i=JSON.stringify(n,Ky(t),r)}catch{return Rn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;hs.length!==0;){const o=hs.pop();o.length===4?Object.defineProperty(o[0],o[1],o[3]):o[0][o[1]]=o[2]}}return Rn(i)}}function li(n,e,t,r){var s=Object.getOwnPropertyDescriptor(r,t);s.get!==void 0?s.configurable?(Object.defineProperty(r,t,{value:n}),hs.push([r,t,e,s])):lr.push([e,t,n]):(r[t]=n,hs.push([r,t,e]))}function Wi(n,e,t,r,s,a,i){a+=1;var o;if(typeof n=="object"&&n!==null){for(o=0;o<r.length;o++)if(r[o]===n){li(Gy,n,e,s);return}if(typeof i.depthLimit<"u"&&a>i.depthLimit){li(il,n,e,s);return}if(typeof i.edgesLimit<"u"&&t+1>i.edgesLimit){li(il,n,e,s);return}if(r.push(n),Array.isArray(n))for(o=0;o<n.length;o++)Wi(n[o],o,o,r,n,a,i);else{n=Uh(n);var u=Object.keys(n);for(o=0;o<u.length;o++){var c=u[o];Wi(n[c],c,o,r,n,a,i)}}r.pop()}}function Ky(n){return n=typeof n<"u"?n:function(e,t){return t},function(e,t){if(lr.length>0)for(var r=0;r<lr.length;r++){var s=lr[r];if(s[1]===e&&s[0]===t){t=s[2],lr.splice(r,1);break}}return n.call(this,e,t)}}function ol(n,e){const t=Ah(),r=e??Ih(),s=n.extra??{},a=s.metadata;return n.extra={...s,runtime:{...t,...s?.runtime},metadata:{...r,...r.revision_id||"revision_id"in n&&n.revision_id?{revision_id:("revision_id"in n?n.revision_id:void 0)??r.revision_id}:{},...a}},n}const Xy=n=>{const e=n?.toString()??Me("TRACING_SAMPLING_RATE");if(e===void 0)return;const t=parseFloat(e);if(t<0||t>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${t}`);return t},Qy=n=>{const t=n.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return t==="localhost"||t==="127.0.0.1"||t==="::1"};async function Yy(n){const e=[];for await(const t of n)e.push(t);return e}function Pn(n){if(n!==void 0)return n.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}const e_=async n=>{if(n?.status===429){const e=parseInt(n.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(t=>setTimeout(t,e)),!0}return!1};function ul(n){return typeof n=="number"?Number(n.toFixed(4)):n}class t_{constructor(){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0})}peek(){return this.items[0]}push(e){let t;const r=new Promise(a=>{t=a}),s=Be(e.item,`Serializing run with id: ${e.item.id}`).length;return this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:t,itemPromise:r,size:s}),this.sizeBytes+=s,r}pop({upToSizeBytes:e,upToSize:t}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");const r=[];let s=0;for(;s+(this.peek()?.size??0)<e&&this.items.length>0&&r.length<t;){const a=this.items.shift();a&&(r.push(a),s+=a.size,this.sizeBytes-=a.size)}if(r.length===0&&this.items.length>0){const a=this.items.shift();r.push(a),s+=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})),()=>r.forEach(a=>a.itemPromiseResolve())]}}const r_=24*1024*1024,n_=1e4,s_=100,cl="https://api.smith.langchain.com";class tn{get _fetch(){return this.fetchImplementation||Hg(this.debug)}constructor(e={}){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,"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:new t_}),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,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:ft("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,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),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,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:ft("LANGSMITH_DEBUG")==="true"});const t=tn.getDefaultClientConfig();if(this.tracingSampleRate=Xy(e.tracingSamplingRate),this.apiUrl=Pn(e.apiUrl??t.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Pn(e.apiKey??t.apiKey),this.webUrl=Pn(e.webUrl??t.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Pn(e.workspaceId??Me("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new dc({...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.batchIngestCaller=new dc({maxRetries:2,maxConcurrency:this.traceBatchConcurrency,...e.callerOptions??{},onFailedResponseHook:e_,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??t.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??t.hideOutputs,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Rh()&&(this.langSmithToOTELTranslator=new uy),this.cachedLSEnvVarsForMetadata=Ih()}static getDefaultClientConfig(){const e=Me("API_KEY"),t=Me("ENDPOINT")??cl,r=Me("HIDE_INPUTS")==="true",s=Me("HIDE_OUTPUTS")==="true";return{apiUrl:t,apiKey:e,webUrl:void 0,hideInputs:r,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:Qy(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("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){const e={"User-Agent":`langsmith-js/${xh}`};return this.apiKey&&(e["x-api-key"]=`${this.apiKey}`),this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}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 prepareRunCreateOrUpdateInputs(e){const t={...e};return t.inputs!==void 0&&(t.inputs=await this.processInputs(t.inputs)),t.outputs!==void 0&&(t.outputs=await this.processOutputs(t.outputs)),t}async _getResponse(e,t){const r=t?.toString()??"",s=`${this.apiUrl}${e}?${r}`;return await this.caller.call(async()=>{const i=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(i,`fetch ${e}`),i})}async _get(e,t){return(await this._getResponse(e,t)).json()}async*_getPaginated(e,t=new URLSearchParams,r){let s=Number(t.get("offset"))||0;const a=Number(t.get("limit"))||100;for(;;){t.set("offset",String(s)),t.set("limit",String(a));const i=`${this.apiUrl}${e}?${t}`,o=await this.caller.call(async()=>{const c=await this._fetch(i,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(c,`fetch ${e}`),c}),u=r?r(await o.json()):await o.json();if(u.length===0||(yield u,u.length<a))break;s+=u.length}}async*_getCursorPaginatedList(e,t=null,r="POST",s="runs"){const a=t?{...t}:{};for(;;){const i=JSON.stringify(a),u=await(await this.caller.call(async()=>{const l=await this._fetch(`${this.apiUrl}${e}`,{method:r,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await N(l,`fetch ${e}`),l})).json();if(!u||!u[s])break;yield u[s];const c=u.cursors;if(!c||!c.next)break;a.cursor=c.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,t=!1){if(this.tracingSampleRate===void 0)return e;if(t){const r=[];for(const s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):r.push(s);return r}else{const r=[];for(const s of e){const a=s.trace_id??s.id;this.filteredPostUuids.has(a)||(s.id===a?this._shouldSample()?r.push(s):this.filteredPostUuids.add(a):r.push(s))}return r}}async _getBatchSizeLimitBytes(){const e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e.batch_ingest_config?.size_limit_bytes??r_}async _getBatchSizeLimit(){const e=await this._ensureServerInfo();return this.batchSizeLimit??e.batch_ingest_config?.size_limit??s_}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t}){const r=[];for(;this.autoBatchQueue.items.length>0;){const[s,a]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:t});if(!s.length){a();break}const i=s.reduce((c,l)=>{const d=l.apiUrl??this.apiUrl,h=l.apiKey??this.apiKey,p=l.apiKey===this.apiKey&&l.apiUrl===this.apiUrl?"default":`${d}|${h}`;return c[p]||(c[p]=[]),c[p].push(l),c},{}),o=[];for(const[c,l]of Object.entries(i)){const d=this._processBatch(l,{apiUrl:c==="default"?void 0:c.split("|")[0],apiKey:c==="default"?void 0:c.split("|")[1]});o.push(d)}const u=Promise.all(o).finally(a);r.push(u)}return Promise.all(r)}async _processBatch(e,t){if(e.length)try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{const r={runCreates:e.filter(a=>a.action==="create").map(a=>a.item),runUpdates:e.filter(a=>a.action==="update").map(a=>a.item)},s=await this._ensureServerInfo();if(s?.batch_ingest_config?.use_multipart_endpoint){const a=s?.instance_flags?.gzip_body_enabled;await this.multipartIngestRuns(r,{...t,useGzip:a})}else await this.batchIngestRuns(r,t)}}catch(r){console.error("Error exporting batch:",r)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){const t=new Map,r=[];for(const s of e)s.item.id&&s.otelContext&&(t.set(s.item.id,s.otelContext),s.action==="create"?r.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):r.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(r,t)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=ol(e.item,this.cachedLSEnvVarsForMetadata);const t=this.autoBatchQueue.push(e);if(this.manualFlushMode)return t;const r=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>r||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:r,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),t}async _getServerInfo(){const t=await(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(n_),...this.fetchOptions});return await N(r,"get server info"),r})).json();return this.debug&&console.log(`
|
|
52
|
+
=== LangSmith Server Configuration ===
|
|
53
|
+
`+JSON.stringify(t,null,2)+`
|
|
54
|
+
`),t}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(),t=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:t})}_cloneCurrentOTELContext(){const e=Ph(),t=sy();if(this.langSmithToOTELTranslator!==void 0){const r=e.getActiveSpan();if(r)return e.setSpan(t.active(),r)}}async createRun(e,t){if(!this._filterForSampling([e]).length)return;const r={...this.headers,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;const a=await this.prepareRunCreateOrUpdateInputs({session_name:s,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&a.trace_id!==void 0&&a.dotted_order!==void 0){const u=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:a,otelContext:u,apiKey:t?.apiKey,apiUrl:t?.apiUrl}).catch(console.error);return}const i=ol(a,this.cachedLSEnvVarsForMetadata);t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),t?.workspaceId!==void 0&&(r["x-tenant-id"]=t.workspaceId);const o=Be(i,`Creating run with id: ${i.id}`);await this.caller.call(async()=>{const u=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await N(u,"create run",!0),u})}async batchIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;let s=await Promise.all(e?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]),a=await Promise.all(t?.map(u=>this.prepareRunCreateOrUpdateInputs(u))??[]);if(s.length>0&&a.length>0){const u=s.reduce((l,d)=>(d.id&&(l[d.id]=d),l),{}),c=[];for(const l of a)l.id!==void 0&&u[l.id]?u[l.id]={...u[l.id],...l}:c.push(l);s=Object.values(u),a=c}const i={post:s,patch:a};if(!i.post.length&&!i.patch.length)return;const o={post:[],patch:[]};for(const u of["post","patch"]){const c=u,l=i[c].reverse();let d=l.pop();for(;d!==void 0;)o[c].push(d),d=l.pop()}if(o.post.length>0||o.patch.length>0){const u=o.post.map(c=>c.id).concat(o.patch.map(c=>c.id)).join(",");await this._postBatchIngestRuns(Be(o,`Ingesting runs with ids: ${u}`),r)}}async _postBatchIngestRuns(e,t){const r={...this.headers,"Content-Type":"application/json",Accept:"application/json"};t?.apiKey!==void 0&&(r["x-api-key"]=t.apiKey),await this.batchIngestCaller.call(async()=>{const s=await this._fetch(`${t?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:r,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await N(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:t},r){if(e===void 0&&t===void 0)return;const s={};let a=[];for(const d of e??[]){const h=await this.prepareRunCreateOrUpdateInputs(d);h.id!==void 0&&h.attachments!==void 0&&(s[h.id]=h.attachments),delete h.attachments,a.push(h)}let i=[];for(const d of t??[])i.push(await this.prepareRunCreateOrUpdateInputs(d));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 creating a run');if(i.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(a.length>0&&i.length>0){const d=a.reduce((f,p)=>(p.id&&(f[p.id]=p),f),{}),h=[];for(const f of i)f.id!==void 0&&d[f.id]?d[f.id]={...d[f.id],...f}:h.push(f);a=Object.values(d),i=h}if(a.length===0&&i.length===0)return;const c=[],l=[];for(const[d,h]of[["post",a],["patch",i]])for(const f of h){const{inputs:p,outputs:m,events:g,extra:y,error:_,serialized:b,attachments:v,...S}=f,R={inputs:p,outputs:m,events:g,extra:y,error:_,serialized:b},P=Be(S,`Serializing for multipart ingestion of run with id: ${S.id}`);l.push({name:`${d}.${S.id}`,payload:new Blob([P],{type:`application/json; length=${P.length}`})});for(const[x,K]of Object.entries(R)){if(K===void 0)continue;const Q=Be(K,`Serializing ${x} for multipart ingestion of run with id: ${S.id}`);l.push({name:`${d}.${S.id}.${x}`,payload:new Blob([Q],{type:`application/json; length=${Q.length}`})})}if(S.id!==void 0){const x=s[S.id];if(x){delete s[S.id];for(const[K,Q]of Object.entries(x)){let ae,Ve;if(Array.isArray(Q)?[ae,Ve]=Q:(ae=Q.mimeType,Ve=Q.data),K.includes(".")){console.warn(`Skipping attachment '${K}' for run ${S.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}l.push({name:`attachment.${S.id}.${K}`,payload:new Blob([Ve],{type:`${ae}; length=${Ve.byteLength}`})})}}}c.push(`trace=${S.trace_id},id=${S.id}`)}await this._sendMultipartRequest(l,c.join("; "),r)}async _createNodeFetchBody(e,t){const r=[];for(const i of e)r.push(new Blob([`--${t}\r
|
|
55
|
+
`])),r.push(new Blob([`Content-Disposition: form-data; name="${i.name}"\r
|
|
56
|
+
`,`Content-Type: ${i.payload.type}\r
|
|
57
|
+
\r
|
|
58
|
+
`])),r.push(i.payload),r.push(new Blob([`\r
|
|
59
|
+
`]));return r.push(new Blob([`--${t}--\r
|
|
60
|
+
`])),await new Blob(r).arrayBuffer()}async _createMultipartStream(e,t){const r=new TextEncoder;return new ReadableStream({async start(a){const i=async o=>{typeof o=="string"?a.enqueue(r.encode(o)):a.enqueue(o)};for(const o of e){await i(`--${t}\r
|
|
61
|
+
`),await i(`Content-Disposition: form-data; name="${o.name}"\r
|
|
62
|
+
`),await i(`Content-Type: ${o.payload.type}\r
|
|
63
|
+
\r
|
|
64
|
+
`);const c=o.payload.stream().getReader();try{let l;for(;!(l=await c.read()).done;)a.enqueue(l.value)}finally{c.releaseLock()}await i(`\r
|
|
65
|
+
`)}await i(`--${t}--\r
|
|
66
|
+
`),a.close()}})}async _sendMultipartRequest(e,t,r){const s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),a=Zg(),i=()=>this._createNodeFetchBody(e,s),o=()=>this._createMultipartStream(e,s),u=async c=>this.batchIngestCaller.call(async()=>{const l=await c(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};r?.apiKey!==void 0&&(d["x-api-key"]=r.apiKey);let h=l;r?.useGzip&&typeof l=="object"&&"pipeThrough"in l&&(h=l.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");const f=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:h,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(f,"Failed to send multipart request",!0),f});try{let c,l=!1;!a&&!this.multipartStreamingDisabled&&Th()!=="bun"?(l=!0,c=await u(o)):c=await u(i),(!this.multipartStreamingDisabled||l)&&c.status===422&&(r?.apiUrl??this.apiUrl)!==cl&&(console.warn(`Streaming multipart upload to ${r?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${t}".`),this.multipartStreamingDisabled=!0,c=await u(i))}catch(c){console.warn(`${c.message.trim()}
|
|
67
|
+
|
|
68
|
+
Context: ${t}`)}}async updateRun(e,t,r){Z(e),t.inputs&&(t.inputs=await this.processInputs(t.inputs)),t.outputs&&(t.outputs=await this.processOutputs(t.outputs));const s={...t,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){const o=this._cloneCurrentOTELContext();if(t.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:o,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}const a={...this.headers,"Content-Type":"application/json"};r?.apiKey!==void 0&&(a["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(a["x-tenant-id"]=r.workspaceId);const i=Be(t,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{const o=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:a,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await N(o,"update run",!0),o})}async readRun(e,{loadChildRuns:t}={loadChildRuns:!1}){Z(e);let r=await this._get(`/runs/${e}`);return t&&(r=await this._loadChildRuns(r)),r}async getRunUrl({runId:e,run:t,projectOpts:r}){if(t!==void 0){let s;t.session_id?s=t.session_id:r?.projectName?s=(await this.readProject({projectName:r?.projectName})).id:r?.projectId?s=r?.projectId:s=(await this.readProject({projectName:Me("PROJECT")||"default"})).id;const a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${s}/r/${t.id}?poll=true`}else if(e!==void 0){const s=await this.readRun(e);if(!s.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${s.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){const t=await Yy(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),r={},s={};t.sort((a,i)=>(a?.dotted_order??"").localeCompare(i?.dotted_order??""));for(const a of t){if(a.parent_run_id===null||a.parent_run_id===void 0)throw new Error(`Child run ${a.id} has no parent`);a.dotted_order?.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),s[a.id]=a)}e.child_runs=r[e.id]||[];for(const a in r)a!==e.id&&(s[a].child_runs=r[a]);return e}async*listRuns(e){const{projectId:t,projectName:r,parentRunId:s,traceId:a,referenceExampleId:i,startTime:o,executionOrder:u,isRoot:c,runType:l,error:d,id:h,query:f,filter:p,traceFilter:m,treeFilter:g,limit:y,select:_,order:b}=e;let v=[];if(t&&(v=Array.isArray(t)?t:[t]),r){const x=Array.isArray(r)?r:[r],K=await Promise.all(x.map(Q=>this.readProject({projectName:Q}).then(ae=>ae.id)));v.push(...K)}const S=["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"],R={session:v.length?v:null,run_type:l,reference_example:i,query:f,filter:p,trace_filter:m,tree_filter:g,execution_order:u,parent_run:s,start_time:o?o.toISOString():null,error:d,id:h,limit:y,trace:a,select:_||S,is_root:c,order:b};let P=0;for await(const x of this._getCursorPaginatedList("/runs/query",R))if(y){if(P>=y)break;if(x.length+P>y){yield*x.slice(0,y-P);break}P+=x.length,yield*x}else yield*x}async*listGroupRuns(e){const{projectId:t,projectName:r,groupBy:s,filter:a,startTime:i,endTime:o,limit:u,offset:c}=e,d={session_id:t||(await this.readProject({projectName:r})).id,group_by:s,filter:a,start_time:i?i.toISOString():null,end_time:o?o.toISOString():null,limit:Number(u)||100};let h=Number(c)||0;const f="/runs/group",p=`${this.apiUrl}${f}`;for(;;){const m={...d,offset:h},g=Object.fromEntries(Object.entries(m).filter(([R,P])=>P!==void 0)),y=JSON.stringify(g),b=await(await this.caller.call(async()=>{const R=await this._fetch(p,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:y});return await N(R,`Failed to fetch ${f}`),R})).json(),{groups:v,total:S}=b;if(v.length===0)break;for(const R of v)yield R;if(h+=v.length,h>=S)break}}async getRunStats({id:e,trace:t,parentRun:r,runType:s,projectNames:a,projectIds:i,referenceExampleIds:o,startTime:u,endTime:c,error:l,query:d,filter:h,traceFilter:f,treeFilter:p,isRoot:m,dataSourceType:g}){let y=i||[];a&&(y=[...i||[],...await Promise.all(a.map(P=>this.readProject({projectName:P}).then(x=>x.id)))]);const b=Object.fromEntries(Object.entries({id:e,trace:t,parent_run:r,run_type:s,session:y,reference_example:o,start_time:u,end_time:c,error:l,query:d,filter:h,trace_filter:f,tree_filter:p,is_root:m,data_source_type:g}).filter(([P,x])=>x!==void 0)),v=JSON.stringify(b);return await(await this.caller.call(async()=>{const P=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await N(P,"get run stats"),P})).json()}async shareRun(e,{shareId:t}={}){const r={run_id:e,share_token:t||or()};Z(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await N(o,"share run"),o})).json();if(i===null||!("share_token"in i))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${i.share_token}/r`}async unshareRun(e){Z(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(t,"unshare run",!0),t})}async readRunSharedLink(e){Z(e);const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(s,"read run shared link"),s})).json();if(!(r===null||!("share_token"in r)))return`${this.getHostUrl()}/public/${r.share_token}/r`}async listSharedRuns(e,{runIds:t}={}){const r=new URLSearchParams({share_token:e});if(t!==void 0)for(const i of t)r.append("id",i);return Z(e),await(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/public/${e}/runs${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(i,"list shared runs"),i})).json()}async readDatasetSharedSchema(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id),Z(e);const s=await(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(a,"read dataset shared schema"),a})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,t){if(!e&&!t)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:t})).id);const r={dataset_id:e};Z(e);const s=JSON.stringify(r),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:s});return await N(o,"share dataset"),o})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async unshareDataset(e){Z(e),await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(t,"unshare dataset",!0),t})}async readSharedDataset(e){return Z(e),await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(s,"read shared dataset"),s})).json()}async listSharedExamples(e,t){const r={};t?.exampleIds&&(r.id=t.exampleIds);const s=new URLSearchParams;Object.entries(r).forEach(([o,u])=>{Array.isArray(u)?u.forEach(c=>s.append(o,c)):s.append(o,u)});const a=await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/public/${e}/examples?${s.toString()}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(o,"list shared examples"),o}),i=await a.json();if(!a.ok)throw"detail"in i?new Error(`Failed to list shared examples.
|
|
69
|
+
Status: ${a.status}
|
|
70
|
+
Message: ${Array.isArray(i.detail)?i.detail.join(`
|
|
71
|
+
`):"Unspecified error"}`):new Error(`Failed to list shared examples: ${a.status} ${a.statusText}`);return i.map(o=>({...o,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:t=null,metadata:r=null,upsert:s=!1,projectExtra:a=null,referenceDatasetId:i=null}){const o=s?"?upsert=true":"",u=`${this.apiUrl}/sessions${o}`,c=a||{};r&&(c.metadata=r);const l={name:e,extra:c,description:t};i!==null&&(l.reference_dataset_id=i);const d=JSON.stringify(l);return await(await this.caller.call(async()=>{const p=await this._fetch(u,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:d});return await N(p,"create project"),p})).json()}async updateProject(e,{name:t=null,description:r=null,metadata:s=null,projectExtra:a=null,endTime:i=null}){const o=`${this.apiUrl}/sessions/${e}`;let u=a;s&&(u={...u||{},metadata:s});const c=JSON.stringify({name:t,extra:u,description:r,end_time:i?new Date(i).toISOString():null});return await(await this.caller.call(async()=>{const h=await this._fetch(o,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await N(h,"update project"),h})).json()}async hasProject({projectId:e,projectName:t}){let r="/sessions";const s=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Z(e),r+=`/${e}`;else if(t!==void 0)s.append("name",t);else throw new Error("Must provide projectName or projectId");const a=await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${r}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(i,"has project"),i});try{const i=await a.json();return a.ok?Array.isArray(i)?i.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:t,includeStats:r}){let s="/sessions";const a=new URLSearchParams;if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)Z(e),s+=`/${e}`;else if(t!==void 0)a.append("name",t);else throw new Error("Must provide projectName or projectId");r!==void 0&&a.append("include_stats",r.toString());const i=await this._get(s,a);let o;if(Array.isArray(i)){if(i.length===0)throw new Error(`Project[id=${e}, name=${t}] not found`);o=i[0]}else o=i;return o}async getProjectUrl({projectId:e,projectName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either projectName or projectId");const r=await this.readProject({projectId:e,projectName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${r.id}`}async getDatasetUrl({datasetId:e,datasetName:t}){if(e===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");const r=await this.readDataset({datasetId:e,datasetName:t}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${r.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;const e=new URLSearchParams({limit:"1"});for await(const t of this._getPaginated("/sessions",e))return this._tenantId=t[0].tenant_id,t[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:t,nameContains:r,referenceDatasetId:s,referenceDatasetName:a,includeStats:i,datasetVersion:o,referenceFree:u,metadata:c}={}){const l=new URLSearchParams;if(e!==void 0)for(const d of e)l.append("id",d);if(t!==void 0&&l.append("name",t),r!==void 0&&l.append("name_contains",r),s!==void 0)l.append("reference_dataset",s);else if(a!==void 0){const d=await this.readDataset({datasetName:a});l.append("reference_dataset",d.id)}i!==void 0&&l.append("include_stats",i.toString()),o!==void 0&&l.append("dataset_version",o),u!==void 0&&l.append("reference_free",u.toString()),c!==void 0&&l.append("metadata",JSON.stringify(c));for await(const d of this._getPaginated("/sessions",l))yield*d}async deleteProject({projectId:e,projectName:t}){let r;if(e===void 0&&t===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&t!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?r=(await this.readProject({projectName:t})).id:r=e,Z(r),await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/sessions/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(s,`delete session ${r} (${t})`,!0),s})}async uploadCsv({csvFile:e,fileName:t,inputKeys:r,outputKeys:s,description:a,dataType:i,name:o}){const u=`${this.apiUrl}/datasets/upload`,c=new FormData;return c.append("file",e,t),r.forEach(h=>{c.append("input_keys",h)}),s.forEach(h=>{c.append("output_keys",h)}),a&&c.append("description",a),i&&c.append("data_type",i),o&&c.append("name",o),await(await this.caller.call(async()=>{const h=await this._fetch(u,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await N(h,"upload CSV"),h})).json()}async createDataset(e,{description:t,dataType:r,inputsSchema:s,outputsSchema:a,metadata:i}={}){const o={name:e,description:t,extra:i?{metadata:i}:void 0};r&&(o.data_type=r),s&&(o.inputs_schema_definition=s),a&&(o.outputs_schema_definition=a);const u=JSON.stringify(o);return await(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await N(d,"create dataset"),d})).json()}async readDataset({datasetId:e,datasetName:t}){let r="/datasets";const s=new URLSearchParams({limit:"1"});if(e&&t)throw new Error("Must provide either datasetName or datasetId, not both");if(e)Z(e),r+=`/${e}`;else if(t)s.append("name",t);else throw new Error("Must provide datasetName or datasetId");const a=await this._get(r,s);let i;if(Array.isArray(a)){if(a.length===0)throw new Error(`Dataset[id=${e}, name=${t}] not found`);i=a[0]}else i=a;return i}async hasDataset({datasetId:e,datasetName:t}){try{return await this.readDataset({datasetId:e,datasetName:t}),!0}catch(r){if(r instanceof Error&&r.message.toLocaleLowerCase().includes("not found"))return!1;throw r}}async diffDatasetVersions({datasetId:e,datasetName:t,fromVersion:r,toVersion:s}){let a=e;if(a===void 0&&t===void 0)throw new Error("Must provide either datasetName or datasetId");if(a!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");a===void 0&&(a=(await this.readDataset({datasetName:t})).id);const i=new URLSearchParams({from_version:typeof r=="string"?r:r.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${a}/versions/diff`,i)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:t}){const r="/datasets";if(e===void 0)if(t!==void 0)e=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${r}/${e}/openai_ft`)).text()).trim().split(`
|
|
72
|
+
`).map(o=>JSON.parse(o))}async*listDatasets({limit:e=100,offset:t=0,datasetIds:r,datasetName:s,datasetNameContains:a,metadata:i}={}){const o="/datasets",u=new URLSearchParams({limit:e.toString(),offset:t.toString()});if(r!==void 0)for(const c of r)u.append("id",c);s!==void 0&&u.append("name",s),a!==void 0&&u.append("name_contains",a),i!==void 0&&u.append("metadata",JSON.stringify(i));for await(const c of this._getPaginated(o,u))yield*c}async updateDataset(e){const{datasetId:t,datasetName:r,...s}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const a=t??(await this.readDataset({datasetName:r})).id;Z(a);const i=JSON.stringify(s);return await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${a}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await N(u,"update dataset"),u})).json()}async updateDatasetTag(e){const{datasetId:t,datasetName:r,asOf:s,tag:a}=e;if(!t&&!r)throw new Error("Must provide either datasetName or datasetId");const i=t??(await this.readDataset({datasetName:r})).id;Z(i);const o=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:a});await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${i}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await N(u,"update dataset tags",!0),u})}async deleteDataset({datasetId:e,datasetName:t}){let r="/datasets",s=e;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(t!==void 0&&(s=(await this.readDataset({datasetName:t})).id),s!==void 0)Z(s),r+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{const a=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(a,`delete ${r}`,!0),a})}async indexDataset({datasetId:e,datasetName:t,tag:r}){let s=e;if(!s&&!t)throw new Error("Must provide either datasetName or datasetId");if(s&&t)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:t})).id),Z(s);const i=JSON.stringify({tag:r});await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${s}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await N(u,"index dataset"),u})).json()}async similarExamples(e,t,r,{filter:s}={}){const a={limit:r,inputs:e};s!==void 0&&(a.filter=s),Z(t);const i=JSON.stringify(a);return(await(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${t}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:i});return await N(c,"fetch similar examples"),c})).json()).examples}async createExample(e,t,r){if(ll(e)&&(t!==void 0||r!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=t?r?.datasetId:e.dataset_id;const a=t?r?.datasetName:e.dataset_name;if(s===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:a})).id);const i=(t?r?.createdAt:e.created_at)||new Date;let o;ll(e)?o=e:o={inputs:e,outputs:t,created_at:i?.toISOString(),id:r?.exampleId,metadata:r?.metadata,split:r?.split,source_run_id:r?.sourceRunId,use_source_run_io:r?.useSourceRunIO,use_source_run_attachments:r?.useSourceRunAttachments,attachments:r?.attachments};const u=await this._uploadExamplesMultipart(s,[o]);return await this.readExample(u.example_ids?.[0]??or())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];const _=e;let b=_[0].dataset_id;const v=_[0].dataset_name;if(b===void 0&&v===void 0)throw new Error("Must provide either datasetName or datasetId");if(b!==void 0&&v!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");b===void 0&&(b=(await this.readDataset({datasetName:v})).id);const S=await this._uploadExamplesMultipart(b,_);return await Promise.all(S.example_ids.map(P=>this.readExample(P)))}const{inputs:t,outputs:r,metadata:s,splits:a,sourceRunIds:i,useSourceRunIOs:o,useSourceRunAttachments:u,attachments:c,exampleIds:l,datasetId:d,datasetName:h}=e;if(t===void 0)throw new Error("Must provide inputs when using legacy parameters");let f=d;const p=h;if(f===void 0&&p===void 0)throw new Error("Must provide either datasetName or datasetId");if(f!==void 0&&p!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");f===void 0&&(f=(await this.readDataset({datasetName:p})).id);const m=t.map((_,b)=>({dataset_id:f,inputs:_,outputs:r?.[b],metadata:s?.[b],split:a?.[b],id:l?.[b],attachments:c?.[b],source_run_id:i?.[b],use_source_run_io:o?.[b],use_source_run_attachments:u?.[b]})),g=await this._uploadExamplesMultipart(f,m);return await Promise.all(g.example_ids.map(_=>this.readExample(_)))}async createLLMExample(e,t,r){return this.createExample({input:e},{output:t},r)}async createChatExample(e,t,r){const s=e.map(i=>hc(i)?fc(i):i),a=hc(t)?fc(t):t;return this.createExample({input:s},{output:a},r)}async readExample(e){Z(e);const t=`/examples/${e}`,r=await this._get(t),{attachment_urls:s,...a}=r,i=a;return s&&(i.attachments=Object.entries(s).reduce((o,[u,c])=>(o[u.slice(11)]={presigned_url:c.presigned_url,mime_type:c.mime_type},o),{})),i}async*listExamples({datasetId:e,datasetName:t,exampleIds:r,asOf:s,splits:a,inlineS3Urls:i,metadata:o,limit:u,offset:c,filter:l,includeAttachments:d}={}){let h;if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)h=e;else if(t!==void 0)h=(await this.readDataset({datasetName:t})).id;else throw new Error("Must provide a datasetName or datasetId");const f=new URLSearchParams({dataset:h}),p=s?typeof s=="string"?s:s?.toISOString():void 0;p&&f.append("as_of",p);const m=i??!0;if(f.append("inline_s3_urls",m.toString()),r!==void 0)for(const y of r)f.append("id",y);if(a!==void 0)for(const y of a)f.append("splits",y);if(o!==void 0){const y=JSON.stringify(o);f.append("metadata",y)}u!==void 0&&f.append("limit",u.toString()),c!==void 0&&f.append("offset",c.toString()),l!==void 0&&f.append("filter",l),d===!0&&["attachment_urls","outputs","metadata"].forEach(y=>f.append("select",y));let g=0;for await(const y of this._getPaginated("/examples",f)){for(const _ of y){const{attachment_urls:b,...v}=_,S=v;b&&(S.attachments=Object.entries(b).reduce((R,[P,x])=>(R[P.slice(11)]={presigned_url:x.presigned_url,mime_type:x.mime_type||void 0},R),{})),yield S,g++}if(u!==void 0&&g>=u)break}}async deleteExample(e){Z(e);const t=`/examples/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(r,`delete ${t}`,!0),r})}async updateExample(e,t){let r;t?r=e:r=e.id,Z(r);let s;t?s={id:r,...t}:s=e;let a;return s.dataset_id!==void 0?a=s.dataset_id:a=(await this.readExample(r)).dataset_id,this._updateExamplesMultipart(a,[s])}async updateExamples(e){let t;return e[0].dataset_id===void 0?t=(await this.readExample(e[0].id)).dataset_id:t=e[0].dataset_id,this._updateExamplesMultipart(t,e)}async readDatasetVersion({datasetId:e,datasetName:t,asOf:r,tag:s}){let a;if(e?a=e:a=(await this.readDataset({datasetName:t})).id,Z(a),r&&s||!r&&!s)throw new Error("Exactly one of asOf and tag must be specified.");const i=new URLSearchParams;return r!==void 0&&i.append("as_of",typeof r=="string"?r:r.toISOString()),s!==void 0&&i.append("tag",s),await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/datasets/${a}/version?${i.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(u,"read dataset version"),u})).json()}async listDatasetSplits({datasetId:e,datasetName:t,asOf:r}){let s;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:t})).id:s=e,Z(s);const a=new URLSearchParams,i=r?typeof r=="string"?r:r?.toISOString():void 0;return i&&a.append("as_of",i),await this._get(`/datasets/${s}/splits`,a)}async updateDatasetSplits({datasetId:e,datasetName:t,splitName:r,exampleIds:s,remove:a=!1}){let i;if(e===void 0&&t===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&t!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:t})).id:i=e,Z(i);const o={split_name:r,examples:s.map(c=>(Z(c),c)),remove:a},u=JSON.stringify(o);await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/datasets/${i}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await N(c,"update dataset splits",!0),c})}async evaluateRun(e,t,{sourceInfo:r,loadChildRuns:s,referenceExample:a}={loadChildRuns:!1}){Ch("This method is deprecated and will be removed in future LangSmith versions, use `evaluate` from `langsmith/evaluation` instead.");let i;if(typeof e=="string")i=await this.readRun(e,{loadChildRuns:s});else if(typeof e=="object"&&"id"in e)i=e;else throw new Error(`Invalid run type: ${typeof e}`);i.reference_example_id!==null&&i.reference_example_id!==void 0&&(a=await this.readExample(i.reference_example_id));const o=await t.evaluateRun(i,a),[u,c]=await this._logEvaluationFeedback(o,i,r);return c[0]}async createFeedback(e,t,{score:r,value:s,correction:a,comment:i,sourceInfo:o,feedbackSourceType:u="api",sourceRunId:c,feedbackId:l,feedbackConfig:d,projectId:h,comparativeExperimentId:f}){if(!e&&!h)throw new Error("One of runId or projectId must be provided");if(e&&h)throw new Error("Only one of runId or projectId can be provided");const p={type:u??"api",metadata:o??{}};c!==void 0&&p?.metadata!==void 0&&!p.metadata.__run&&(p.metadata.__run={run_id:c}),p?.metadata!==void 0&&p.metadata.__run?.run_id!==void 0&&Z(p.metadata.__run.run_id);const m={id:l??or(),run_id:e,key:t,score:ul(r),value:s,correction:a,comment:i,feedback_source:p,comparative_experiment_id:f,feedbackConfig:d,session_id:h},g=JSON.stringify(m),y=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{const _=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await N(_,"create feedback",!0),_}),m}async updateFeedback(e,{score:t,value:r,correction:s,comment:a}){const i={};t!=null&&(i.score=ul(t)),r!=null&&(i.value=r),s!=null&&(i.correction=s),a!=null&&(i.comment=a),Z(e);const o=JSON.stringify(i);await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await N(u,"update feedback",!0),u})}async readFeedback(e){Z(e);const t=`/feedback/${e}`;return await this._get(t)}async deleteFeedback(e){Z(e);const t=`/feedback/${e}`;await this.caller.call(async()=>{const r=await this._fetch(this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(r,`delete ${t}`,!0),r})}async*listFeedback({runIds:e,feedbackKeys:t,feedbackSourceTypes:r}={}){const s=new URLSearchParams;if(e)for(const a of e)Z(a),s.append("run",a);if(t)for(const a of t)s.append("key",a);if(r)for(const a of r)s.append("source",a);for await(const a of this._getPaginated("/feedback",s))yield*a}async createPresignedFeedbackToken(e,t,{expiration:r,feedbackConfig:s}={}){const a={run_id:e,feedback_key:t,feedback_config:s};r?typeof r=="string"?a.expires_at=r:(r?.hours||r?.minutes||r?.days)&&(a.expires_in=r):a.expires_in={hours:3};const i=JSON.stringify(a);return await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await N(u,"create presigned feedback token"),u})).json()}async createComparativeExperiment({name:e,experimentIds:t,referenceDatasetId:r,createdAt:s,description:a,metadata:i,id:o}){if(t.length===0)throw new Error("At least one experiment is required");if(r||(r=(await this.readProject({projectId:t[0]})).reference_dataset_id),!r==null)throw new Error("A reference dataset is required");const u={id:o,name:e,experiment_ids:t,reference_dataset_id:r,description:a,created_at:(s??new Date)?.toISOString(),extra:{}};i&&(u.extra.metadata=i);const c=JSON.stringify(u);return(await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await N(d,"create comparative experiment"),d})).json()}async*listPresignedFeedbackTokens(e){Z(e);const t=new URLSearchParams({run_id:e});for await(const r of this._getPaginated("/feedback/tokens",t))yield*r}_selectEvalResults(e){let t;return"results"in e?t=e.results:Array.isArray(e)?t=e:t=[e],t}async _logEvaluationFeedback(e,t,r){const s=this._selectEvalResults(e),a=[];for(const i of s){let o=r||{};i.evaluatorInfo&&(o={...i.evaluatorInfo,...o});let u=null;i.targetRunId?u=i.targetRunId:t&&(u=t.id),a.push(await this.createFeedback(u,i.key,{score:i.score,value:i.value,comment:i.comment,correction:i.correction,sourceInfo:o,sourceRunId:i.sourceRunId,feedbackConfig:i.feedbackConfig,feedbackSourceType:"model"}))}return[s,a]}async logEvaluationFeedback(e,t,r){const[s]=await this._logEvaluationFeedback(e,t,r);return s}async*listAnnotationQueues(e={}){const{queueIds:t,name:r,nameContains:s,limit:a}=e,i=new URLSearchParams;t&&t.forEach((u,c)=>{Z(u,`queueIds[${c}]`),i.append("ids",u)}),r&&i.append("name",r),s&&i.append("name_contains",s),i.append("limit",(a!==void 0?Math.min(a,100):100).toString());let o=0;for await(const u of this._getPaginated("/annotation-queues",i))if(yield*u,o++,a!==void 0&&o>=a)break}async createAnnotationQueue(e){const{name:t,description:r,queueId:s,rubricInstructions:a}=e,i={name:t,description:r,id:s||or(),rubric_instructions:a},o=JSON.stringify(Object.fromEntries(Object.entries(i).filter(([c,l])=>l!==void 0)));return(await this.caller.call(async()=>{const c=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await N(c,"create annotation queue"),c})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${Z(e,"queueId")}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(r,"read annotation queue"),r})).json()}async updateAnnotationQueue(e,t){const{name:r,description:s,rubricInstructions:a}=t,i=JSON.stringify({name:r,description:s,rubric_instructions:a});await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/annotation-queues/${Z(e,"queueId")}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await N(o,"update annotation queue",!0),o})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{const t=await this._fetch(`${this.apiUrl}/annotation-queues/${Z(e,"queueId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(t,"delete annotation queue",!0),t})}async addRunsToAnnotationQueue(e,t){const r=JSON.stringify(t.map((s,a)=>Z(s,`runIds[${a}]`).toString()));await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/annotation-queues/${Z(e,"queueId")}/runs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await N(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,t){const r=`/annotation-queues/${Z(e,"queueId")}/run`;return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${r}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(a,"get run from annotation queue"),a})).json()}async deleteRunFromAnnotationQueue(e,t){await this.caller.call(async()=>{const r=await this._fetch(`${this.apiUrl}/annotation-queues/${Z(e,"queueId")}/runs/${Z(t,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(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/${Z(e,"queueId")}/size`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(r,"get size from annotation queue"),r})).json()}async _currentTenantIsOwner(e){const t=await this._getSettings();return e=="-"||t.tenant_handle===e}async _ownerConflictError(e,t){const r=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
|
|
73
|
+
|
|
74
|
+
Current tenant: ${r.tenant_handle}
|
|
75
|
+
|
|
76
|
+
Requested tenant: ${t}`)}async _getLatestCommitHash(e){const r=await(await this.caller.call(async()=>{const s=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(s,"get latest commit hash"),s})).json();if(r.commits.length!==0)return r.commits[0].commit_hash}async _likeOrUnlikePrompt(e,t){const[r,s,a]=Et(e),i=JSON.stringify({like:t});return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/likes/${r}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await N(u,`${t?"like":"unlike"} prompt`),u})).json()}async _getPromptUrl(e){const[t,r,s]=Et(e);if(await this._currentTenantIsOwner(t)){const a=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${r}/${s.substring(0,8)}?organizationId=${a.id}`:`${this.getHostUrl()}/prompts/${r}?organizationId=${a.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${t}/${r}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${t}/${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){for await(const t of this._getPaginated(`/commits/${e}/`,new URLSearchParams,r=>r.commits))yield*t}async*listPrompts(e){const t=new URLSearchParams;t.append("sort_field",e?.sortField??"updated_at"),t.append("sort_direction","desc"),t.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&t.append("is_public",e.isPublic.toString()),e?.query&&t.append("query",e.query);for await(const r of this._getPaginated("/repos",t,s=>s.repos))yield*r}async getPrompt(e){const[t,r,s]=Et(e),i=await(await this.caller.call(async()=>{const o=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return o?.status===404?null:(await N(o,"get prompt"),o)}))?.json();return i?.repo?i.repo:null}async createPrompt(e,t){const r=await this._getSettings();if(t?.isPublic&&!r.tenant_handle)throw new Error(`Cannot create a public prompt without first
|
|
77
|
+
|
|
78
|
+
creating a LangChain Hub handle.
|
|
79
|
+
You can add a handle by creating a public prompt at:
|
|
80
|
+
|
|
81
|
+
https://smith.langchain.com/prompts`);const[s,a,i]=Et(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);const o={repo_handle:a,...t?.description&&{description:t.description},...t?.readme&&{readme:t.readme},...t?.tags&&{tags:t.tags},is_public:!!t?.isPublic},u=JSON.stringify(o),c=await this.caller.call(async()=>{const d=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await N(d,"create prompt"),d}),{repo:l}=await c.json();return l}async createCommit(e,t,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[s,a,i]=Et(e),o=r?.parentCommitHash==="latest"||!r?.parentCommitHash?await this._getLatestCommitHash(`${s}/${a}`):r?.parentCommitHash,u={manifest:JSON.parse(JSON.stringify(t)),parent_commit:o},c=JSON.stringify(u),d=await(await this.caller.call(async()=>{const h=await this._fetch(`${this.apiUrl}/commits/${s}/${a}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await N(h,"create commit"),h})).json();return this._getPromptUrl(`${s}/${a}${d.commit_hash?`:${d.commit_hash}`:""}`)}async updateExamplesMultipart(e,t=[]){return this._updateExamplesMultipart(e,t)}async _updateExamplesMultipart(e,t=[]){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 i of t){const o=i.id,u={...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split}},c=Be(u,`Serializing body for example with id: ${o}`),l=new Blob([c],{type:"application/json"});if(r.append(o,l),i.inputs){const d=Be(i.inputs,`Serializing inputs for example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.inputs`,h)}if(i.outputs){const d=Be(i.outputs,`Serializing outputs whle updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.outputs`,h)}if(i.attachments)for(const[d,h]of Object.entries(i.attachments)){let f,p;Array.isArray(h)?[f,p]=h:(f=h.mimeType,p=h.data);const m=new Blob([p],{type:`${f}; length=${p.byteLength}`});r.append(`${o}.attachment.${d}`,m)}if(i.attachments_operations){const d=Be(i.attachments_operations,`Serializing attachments while updating example with id: ${o}`),h=new Blob([d],{type:"application/json"});r.append(`${o}.attachments_operations`,h)}}const s=e??t[0]?.dataset_id;return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await N(i,"update examples"),i})).json()}async uploadExamplesMultipart(e,t=[]){return this._uploadExamplesMultipart(e,t)}async _uploadExamplesMultipart(e,t=[]){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 a of t){const i=(a.id??or()).toString(),o={created_at:a.created_at,...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split},...a.source_run_id&&{source_run_id:a.source_run_id},...a.use_source_run_io&&{use_source_run_io:a.use_source_run_io},...a.use_source_run_attachments&&{use_source_run_attachments:a.use_source_run_attachments}},u=Be(o,`Serializing body for uploaded example with id: ${i}`),c=new Blob([u],{type:"application/json"});if(r.append(i,c),a.inputs){const l=Be(a.inputs,`Serializing inputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.inputs`,d)}if(a.outputs){const l=Be(a.outputs,`Serializing outputs for uploaded example with id: ${i}`),d=new Blob([l],{type:"application/json"});r.append(`${i}.outputs`,d)}if(a.attachments)for(const[l,d]of Object.entries(a.attachments)){let h,f;Array.isArray(d)?[h,f]=d:(h=d.mimeType,f=d.data);const p=new Blob([f],{type:`${h}; length=${f.byteLength}`});r.append(`${i}.attachment.${l}`,p)}}return(await this.caller.call(async()=>{const a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:r});return await N(a,"upload examples"),a})).json()}async updatePrompt(e,t){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");const[r,s]=Et(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("update a prompt",r);const a={};if(t?.description!==void 0&&(a.description=t.description),t?.readme!==void 0&&(a.readme=t.readme),t?.tags!==void 0&&(a.tags=t.tags),t?.isPublic!==void 0&&(a.is_public=t.isPublic),t?.isArchived!==void 0&&(a.is_archived=t.isArchived),Object.keys(a).length===0)throw new Error("No valid update options provided");const i=JSON.stringify(a);return(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/repos/${r}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await N(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[t,r,s]=Et(e);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("delete a prompt",t);return(await this.caller.call(async()=>{const i=await this._fetch(`${this.apiUrl}/repos/${t}/${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(i,"delete prompt"),i})).json()}async pullPromptCommit(e,t){const[r,s,a]=Et(e),o=await(await this.caller.call(async()=>{const u=await this._fetch(`${this.apiUrl}/commits/${r}/${s}/${a}${t?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await N(u,"pull prompt commit"),u})).json();return{owner:r,repo:s,commit_hash:o.commit_hash,manifest:o.manifest,examples:o.examples}}async _pullPrompt(e,t){const r=await this.pullPromptCommit(e,{includeModel:t?.includeModel});return JSON.stringify(r.manifest)}async pushPrompt(e,t){return await this.promptExists(e)?t&&Object.keys(t).some(s=>s!=="object")&&await this.updatePrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}):await this.createPrompt(e,{description:t?.description,readme:t?.readme,tags:t?.tags,isPublic:t?.isPublic}),t?.object?await this.createCommit(e,t?.object,{parentCommitHash:t?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,t={}){const{sourceApiUrl:r=this.apiUrl,datasetName:s}=t,[a,i]=this.parseTokenOrUrl(e,r),o=new tn({apiUrl:a,apiKey:"placeholder"}),u=await o.readSharedDataset(i),c=s||u.name;try{if(await this.hasDataset({datasetId:c})){console.log(`Dataset ${c} already exists in your tenant. Skipping.`);return}}catch{}const l=await o.listSharedExamples(i),d=await this.createDataset(c,{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:l.map(h=>h.inputs),outputs:l.flatMap(h=>h.outputs?[h.outputs]:[]),datasetId:d.id})}catch(h){throw console.error(`An error occurred while creating dataset ${c}. You should delete it manually.`),h}}parseTokenOrUrl(e,t,r=2,s="dataset"){try{return Z(e),[t,e]}catch{}try{const i=new URL(e).pathname.split("/").filter(o=>o!=="");if(i.length>=r){const o=i[i.length-r];return[t,o]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}async awaitPendingTraceBatches(){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();await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await ay()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}}function ll(n){return"dataset_id"in n||"dataset_name"in n}const a_=n=>!!["TRACING_V2","TRACING"].find(t=>Me(t)==="true"),di=Symbol.for("lc:context_variables");function i_(n){return n.replace(/[-:.]/g,"")}function Dh(n,e,t=1){const r=t.toFixed(0).slice(0,3).padStart(3,"0"),s=`${new Date(n).toISOString().slice(0,-1)}${r}Z`;return{dottedOrder:i_(s)+e,microsecondPrecisionDatestring:s}}class fs{constructor(e,t,r,s){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=t,this.project_name=r,this.replicas=s}static fromHeader(e){const t=e.split(",");let r={},s=[],a,i;for(const o of t){const[u,c]=o.split("="),l=decodeURIComponent(c);u==="langsmith-metadata"?r=JSON.parse(l):u==="langsmith-tags"?s=l.split(","):u==="langsmith-project"?a=l:u==="langsmith-replicas"&&(i=JSON.parse(l))}return new fs(r,s,a,i)}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 je{constructor(e){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,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),o_(e)){Object.assign(this,{...e});return}const t=je.getDefaultConfig(),{metadata:r,...s}=e,a=s.client??je.getSharedClient(),i={...r,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:i},Object.assign(this,{...t,...s,client:a}),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=h_(this.replicas),this.execution_order??=1,this.child_execution_order??=1,!this.dotted_order){const{dottedOrder:o,microsecondPrecisionDatestring:u}=Dh(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+o:this.dotted_order=o,this._serialized_start_time=u}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){return{id:or(),run_type:"chain",project_name:Oh(),child_runs:[],api_url:ft("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:ft("LANGCHAIN_API_KEY"),caller_options:{},start_time:Date.now(),serialized:{},inputs:{},extra:{}}}static getSharedClient(){return je.sharedClient||(je.sharedClient=new tn),je.sharedClient}createChild(e){const t=this.child_execution_order+1,r=new je({...e,parent_run:this,project_name:this.project_name,replicas:this.replicas,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:t,child_execution_order:t});di in this&&(r[di]=this[di]);const s=Symbol.for("lc:child_config"),a=e.extra?.[s]??this.extra[s];if(c_(a)){const u={...a},c=u_(u.callbacks)?u.callbacks.copy?.():void 0;c&&(Object.assign(c,{_parentRunId:r.id}),c.handlers?.find(Fh)?.updateFromRunTree?.(r),u.callbacks=c),r.extra[s]=u}const i=new Set;let o=this;for(;o!=null&&!i.has(o.id);)i.add(o.id),o.child_execution_order=Math.max(o.child_execution_order,t),o=o.parent_run;return this.child_runs.push(r),r}async end(e,t,r=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??t,this.end_time=this.end_time??r,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,t,r=!0){const s=e.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),t))for(const[o,u]of Object.entries(t))s.runtime[o]||(s.runtime[o]=u);let a,i;return r?(i=e.parent_run?.id??e.parent_run_id,a=[]):(a=e.child_runs.map(o=>this._convertToCreate(o,t,r)),i=void 0),{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:s,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:a,parent_run_id:i,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_remapForProject(e,t,r=!0){const s=this._convertToCreate(this,t,r);if(e===this.project_name)return s;const a=d=>Qu(`${d}:${e}`,Qu.DNS),i=a(s.id),o=s.trace_id?a(s.trace_id):void 0,u=s.parent_run_id?a(s.parent_run_id):void 0;let c;if(s.dotted_order){const d=l_(s.dotted_order),h=[];for(let p=0;p<d.length-1;p++){const[m,g]=d[p],y=a(g);h.push(m.toISOString().replace(/[-:]/g,"").replace(".","")+y)}const[f]=d[d.length-1];h.push(f.toISOString().replace(/[-:]/g,"").replace(".","")+i),c=h.join(".")}else c=void 0;return{...s,id:i,trace_id:o,parent_run_id:u,dotted_order:c,session_name:e}}async postRun(e=!0){try{const t=Ah();if(this.replicas&&this.replicas.length>0)for(const{projectName:r,apiKey:s,apiUrl:a,workspaceId:i}of this.replicas){const o=this._remapForProject(r??this.project_name,t,!0);await this.client.createRun(o,{apiKey:s,apiUrl:a,workspaceId:i})}else{const r=this._convertToCreate(this,t,e);await this.client.createRun(r)}if(!e){Ch("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)}}catch(t){console.error(`Error in postRun for run ${this.id}:`,t)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(const{projectName:t,apiKey:r,apiUrl:s,workspaceId:a,updates:i}of this.replicas){const o=this._remapForProject(t??this.project_name),u={id:o.id,outputs:o.outputs,error:o.error,parent_run_id:o.parent_run_id,session_name:o.session_name,reference_example_id:o.reference_example_id,end_time:o.end_time,dotted_order:o.dotted_order,trace_id:o.trace_id,events:o.events,tags:o.tags,extra:o.extra,attachments:this.attachments,...i};e?.excludeInputs||(u.inputs=o.inputs),await this.client.updateRun(o.id,u,{apiKey:r,apiUrl:s,workspaceId:a})}else try{const t={end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id:this.parent_run?.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?.excludeInputs||(t.inputs=this.inputs),await this.client.updateRun(this.id,t)}catch(t){console.error(`Error in patchRun for run ${this.id}`,t)}}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,t){const r=e?.callbacks;let s,a,i,o=a_();if(r){const c=r?.getParentRunId?.()??"",l=r?.handlers?.find(d=>d?.name=="langchain_tracer");s=l?.getRun?.(c),a=l?.projectName,i=l?.client,o=o||!!l}return s?new je({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:i,tracingEnabled:o,project_name:a,tags:[...new Set((s?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...s?.extra?.metadata,...e?.metadata}}}).createChild(t):new je({...t,client:i,tracingEnabled:o,project_name:a})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,t){const r="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=r["langsmith-trace"];if(!s||typeof s!="string")return;const a=s.trim(),i=a.split(".").map(c=>{const[l,d]=c.split("Z");return{strTime:l,time:Date.parse(l+"Z"),uuid:d}}),o=i[0].uuid,u={...t,name:t?.name??"parent",run_type:t?.run_type??"chain",start_time:t?.start_time??Date.now(),id:i.at(-1)?.uuid,trace_id:o,dotted_order:a};if(r.baggage&&typeof r.baggage=="string"){const c=fs.fromHeader(r.baggage);u.metadata=c.metadata,u.tags=c.tags,u.project_name=c.project_name,u.replicas=c.replicas}return new je(u)}toHeaders(e){const t={"langsmith-trace":this.dotted_order,baggage:new fs(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(const[r,s]of Object.entries(t))e.set(r,s);return t}}Object.defineProperty(je,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function o_(n){return n!=null&&typeof n.createChild=="function"&&typeof n.postRun=="function"}function Fh(n){return typeof n=="object"&&n!=null&&typeof n.name=="string"&&n.name==="langchain_tracer"}function dl(n){return Array.isArray(n)&&n.some(e=>Fh(e))}function u_(n){return typeof n=="object"&&n!=null&&Array.isArray(n.handlers)}function c_(n){return n!=null&&typeof n.callbacks=="object"&&(dl(n.callbacks?.handlers)||dl(n.callbacks))}function l_(n){return n.split(".").map(t=>{const r=t.slice(0,-36),s=t.slice(-36),a=parseInt(r.slice(0,4)),i=parseInt(r.slice(4,6))-1,o=parseInt(r.slice(6,8)),u=parseInt(r.slice(9,11)),c=parseInt(r.slice(11,13)),l=parseInt(r.slice(13,15)),d=parseInt(r.slice(15,21));return[new Date(a,i,o,u,c,l,d/1e3),s]})}function d_(){const n=ft("LANGSMITH_RUNS_ENDPOINTS");if(!n)return[];try{const e=JSON.parse(n);if(Array.isArray(e)){const t=[];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}t.push({apiUrl:r.api_url.replace(/\/$/,""),apiKey:r.api_key})}return t}else if(typeof e=="object"&&e!==null){f_(e);const t=[];for(const[r,s]of Object.entries(e)){const a=r.replace(/\/$/,"");if(typeof s=="string")t.push({apiUrl:a,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${r}: expected string, got ${typeof s}`);continue}}return t}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(Hy(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 h_(n){return n?n.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):d_()}function f_(n){if(Object.keys(n).length>0&&Me("ENDPOINT"))throw new Zy}var p_={};const m_=()=>typeof window<"u"&&typeof window.document<"u",g_=()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope",y_=()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),jo=()=>typeof Deno<"u",__=()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!jo(),b_=()=>{let n;return m_()?n="browser":__()?n="node":g_()?n="webworker":y_()?n="jsdom":jo()?n="deno":n="other",n};let hi;function w_(){return hi===void 0&&(hi={library:"langchain-js",runtime:b_()}),hi}function Ct(n){try{return typeof process<"u"?p_?.[n]:jo()?Deno?.env.get(n):void 0}catch{return}}class v_{}function S_(n){return"lc_prefer_streaming"in n&&n.lc_prefer_streaming}class fn extends v_{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,dh(this.constructor)]}constructor(e){super(),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreRetriever",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreCustomEvent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"raiseError",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"awaitHandlers",{enumerable:!0,configurable:!0,writable:!0,value:Ct("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))}copy(){return new this.constructor(this)}toJSON(){return Wt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Wt.prototype.toJSONNotImplemented.call(this)}static fromMethods(e){class t extends fn{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:yt()}),Object.assign(this,e)}}return new t}}const E_=n=>{const e=n;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},O_=n=>{if(n)return n.events=n.events??[],n.child_runs=n.child_runs??[],n};function Vi(n,e){if(n)return new je({...n,start_time:n._serialized_start_time??n.start_time,parent_run:Vi(e),child_runs:n.child_runs.map(t=>Vi(t)).filter(t=>t!==void 0),extra:{...n.extra,runtime:w_()},tracingEnabled:!1})}function fi(n,e){return n&&!Array.isArray(n)&&typeof n=="object"?n:{[e]:n}}function Ar(n){return typeof n._addRunToRunMap=="function"}class pn extends fn{constructor(e){super(...arguments),Object.defineProperty(this,"runMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"runTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!1})}copy(){return this}getRunById(e){if(e!==void 0)return this.usesRunTreeMap?O_(this.runTreeMap.get(e)):this.runMap.get(e)}stringifyError(e){return e instanceof Error?e.message+(e?.stack?`
|
|
82
|
+
|
|
83
|
+
${e.stack}`:""):typeof e=="string"?e:`${e}`}_addChildRun(e,t){e.child_runs.push(t)}_addRunToRunMap(e){const{dottedOrder:t,microsecondPrecisionDatestring:r}=Dh(new Date(e.start_time).getTime(),e.id,e.execution_order),s={...e},a=this.getRunById(s.parent_run_id);if(s.parent_run_id!==void 0?a&&(this._addChildRun(a,s),a.child_execution_order=Math.max(a.child_execution_order,s.child_execution_order),s.trace_id=a.trace_id,a.dotted_order!==void 0&&(s.dotted_order=[a.dotted_order,t].join("."),s._serialized_start_time=r)):(s.trace_id=s.id,s.dotted_order=t,s._serialized_start_time=r),this.usesRunTreeMap){const i=Vi(s,a);i!==void 0&&this.runTreeMap.set(s.id,i)}else this.runMap.set(s.id,s);return s}async _endTrace(e){const t=e.parent_run_id!==void 0&&this.getRunById(e.parent_run_id);t?t.child_execution_order=Math.max(t.child_execution_order,e.child_execution_order):await this.persistRun(e),await this.onRunUpdate?.(e),this.usesRunTreeMap?this.runTreeMap.delete(e.id):this.runMap.delete(e.id)}_getExecutionOrder(e){const t=e!==void 0&&this.getRunById(e);return t?t.child_execution_order+1:1}_createRunForLLMStart(e,t,r,s,a,i,o,u){const c=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,h={id:r,name:u??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{prompts:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(h)}async handleLLMStart(e,t,r,s,a,i,o,u){const c=this.getRunById(r)??this._createRunForLLMStart(e,t,r,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}_createRunForChatModelStart(e,t,r,s,a,i,o,u){const c=this._getExecutionOrder(s),l=Date.now(),d=o?{...a,metadata:o}:a,h={id:r,name:u??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{messages:t},execution_order:c,child_runs:[],child_execution_order:c,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(h)}async handleChatModelStart(e,t,r,s,a,i,o,u){const c=this.getRunById(r)??this._createRunForChatModelStart(e,t,r,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onLLMStart?.(c),c}async handleLLMEnd(e,t,r,s,a){const i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=e,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(e,t,r,s,a){const i=this.getRunById(t);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...a},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(e,t,r,s,a,i,o,u){const c=this._getExecutionOrder(s),l=Date.now(),d={id:r,name:u??e.id[e.id.length-1],parent_run_id:s,start_time:l,serialized:e,events:[{name:"start",time:new Date(l).toISOString()}],inputs:t,execution_order:c,child_execution_order:c,run_type:o??"chain",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(d)}async handleChainStart(e,t,r,s,a,i,o,u){const c=this.getRunById(r)??this._createRunForChainStart(e,t,r,s,a,i,o,u);return await this.onRunCreate?.(c),await this.onChainStart?.(c),c}async handleChainEnd(e,t,r,s,a){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=fi(e,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=fi(a.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(e,t,r,s,a){const i=this.getRunById(t);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(e),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),a?.inputs!==void 0&&(i.inputs=fi(a.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(e,t,r,s,a,i,o){const u=this._getExecutionOrder(s),c=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{input:t},execution_order:u,child_execution_order:u,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleToolStart(e,t,r,s,a,i,o){const u=this.getRunById(r)??this._createRunForToolStart(e,t,r,s,a,i,o);return await this.onRunCreate?.(u),await this.onToolStart?.(u),u}async handleToolEnd(e,t){const r=this.getRunById(t);if(!r||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 this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(e,t){const r=this.getRunById(t);if(!r||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 this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(e,t){const r=this.getRunById(t);if(!r||r?.run_type!=="chain")return;const s=r;s.actions=s.actions||[],s.actions.push(e),s.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentAction?.(r)}async handleAgentEnd(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:e}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(e,t,r,s,a,i,o){const u=this._getExecutionOrder(s),c=Date.now(),l={id:r,name:o??e.id[e.id.length-1],parent_run_id:s,start_time:c,serialized:e,events:[{name:"start",time:new Date(c).toISOString()}],inputs:{query:t},execution_order:u,child_execution_order:u,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:a||[]};return this._addRunToRunMap(l)}async handleRetrieverStart(e,t,r,s,a,i,o){const u=this.getRunById(r)??this._createRunForRetrieverStart(e,t,r,s,a,i,o);return await this.onRunCreate?.(u),await this.onRetrieverStart?.(u),u}async handleRetrieverEnd(e,t){const r=this.getRunById(t);if(!r||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 this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(e,t){const r=this.getRunById(t);if(!r||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 this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(e,t){const r=this.getRunById(t);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:e}}),await this.onText?.(r))}async handleLLMNewToken(e,t,r,s,a,i){const o=this.getRunById(r);if(!o||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:t,chunk:i?.chunk}}),await this.onLLMNewToken?.(o,e,{chunk:i?.chunk}),o}}var Wn={exports:{}};Wn.exports;var hl;function x_(){return hl||(hl=1,(function(n){const t=(a=0)=>i=>`\x1B[${38+a};5;${i}m`,r=(a=0)=>(i,o,u)=>`\x1B[${38+a};2;${i};${o};${u}m`;function s(){const a=new Map,i={modifier:{reset:[0,0],bold:[1,22],dim:[2,22],italic:[3,23],underline:[4,24],overline:[53,55],inverse:[7,27],hidden:[8,28],strikethrough:[9,29]},color:{black:[30,39],red:[31,39],green:[32,39],yellow:[33,39],blue:[34,39],magenta:[35,39],cyan:[36,39],white:[37,39],blackBright:[90,39],redBright:[91,39],greenBright:[92,39],yellowBright:[93,39],blueBright:[94,39],magentaBright:[95,39],cyanBright:[96,39],whiteBright:[97,39]},bgColor:{bgBlack:[40,49],bgRed:[41,49],bgGreen:[42,49],bgYellow:[43,49],bgBlue:[44,49],bgMagenta:[45,49],bgCyan:[46,49],bgWhite:[47,49],bgBlackBright:[100,49],bgRedBright:[101,49],bgGreenBright:[102,49],bgYellowBright:[103,49],bgBlueBright:[104,49],bgMagentaBright:[105,49],bgCyanBright:[106,49],bgWhiteBright:[107,49]}};i.color.gray=i.color.blackBright,i.bgColor.bgGray=i.bgColor.bgBlackBright,i.color.grey=i.color.blackBright,i.bgColor.bgGrey=i.bgColor.bgBlackBright;for(const[o,u]of Object.entries(i)){for(const[c,l]of Object.entries(u))i[c]={open:`\x1B[${l[0]}m`,close:`\x1B[${l[1]}m`},u[c]=i[c],a.set(l[0],l[1]);Object.defineProperty(i,o,{value:u,enumerable:!1})}return Object.defineProperty(i,"codes",{value:a,enumerable:!1}),i.color.close="\x1B[39m",i.bgColor.close="\x1B[49m",i.color.ansi256=t(),i.color.ansi16m=r(),i.bgColor.ansi256=t(10),i.bgColor.ansi16m=r(10),Object.defineProperties(i,{rgbToAnsi256:{value:(o,u,c)=>o===u&&u===c?o<8?16:o>248?231:Math.round((o-8)/247*24)+232:16+36*Math.round(o/255*5)+6*Math.round(u/255*5)+Math.round(c/255*5),enumerable:!1},hexToRgb:{value:o=>{const u=/(?<colorString>[a-f\d]{6}|[a-f\d]{3})/i.exec(o.toString(16));if(!u)return[0,0,0];let{colorString:c}=u.groups;c.length===3&&(c=c.split("").map(d=>d+d).join(""));const l=Number.parseInt(c,16);return[l>>16&255,l>>8&255,l&255]},enumerable:!1},hexToAnsi256:{value:o=>i.rgbToAnsi256(...i.hexToRgb(o)),enumerable:!1}}),i}Object.defineProperty(n,"exports",{enumerable:!0,get:s})})(Wn)),Wn.exports}var k_=x_();const Bh=sn(k_);function Ie(n,e){return`${n.open}${e}${n.close}`}function Je(n,e){try{return JSON.stringify(n,null,2)}catch{return e}}function fl(n){return typeof n=="string"?n.trim():n==null?n:Je(n,n.toString())}function Ot(n){if(!n.end_time)return"";const e=n.end_time-n.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}const{color:Ne}=Bh;class pl extends pn{constructor(){super(...arguments),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"console_callback_handler"})}persistRun(e){return Promise.resolve()}getParents(e){const t=[];let r=e;for(;r.parent_run_id;){const s=this.runMap.get(r.parent_run_id);if(s)t.push(s),r=s;else break}return t}getBreadcrumbs(e){const r=[...this.getParents(e).reverse(),e].map((s,a,i)=>{const o=`${s.execution_order}:${s.run_type}:${s.name}`;return a===i.length-1?Ie(Bh.bold,o):o}).join(" > ");return Ie(Ne.grey,r)}onChainStart(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.green,"[chain/start]")} [${t}] Entering Chain run with input: ${Je(e.inputs,"[inputs]")}`)}onChainEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.cyan,"[chain/end]")} [${t}] [${Ot(e)}] Exiting Chain run with output: ${Je(e.outputs,"[outputs]")}`)}onChainError(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.red,"[chain/error]")} [${t}] [${Ot(e)}] Chain run errored with error: ${Je(e.error,"[error]")}`)}onLLMStart(e){const t=this.getBreadcrumbs(e),r="prompts"in e.inputs?{prompts:e.inputs.prompts.map(s=>s.trim())}:e.inputs;console.log(`${Ie(Ne.green,"[llm/start]")} [${t}] Entering LLM run with input: ${Je(r,"[inputs]")}`)}onLLMEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.cyan,"[llm/end]")} [${t}] [${Ot(e)}] Exiting LLM run with output: ${Je(e.outputs,"[response]")}`)}onLLMError(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.red,"[llm/error]")} [${t}] [${Ot(e)}] LLM run errored with error: ${Je(e.error,"[error]")}`)}onToolStart(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.green,"[tool/start]")} [${t}] Entering Tool run with input: "${fl(e.inputs.input)}"`)}onToolEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.cyan,"[tool/end]")} [${t}] [${Ot(e)}] Exiting Tool run with output: "${fl(e.outputs?.output)}"`)}onToolError(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.red,"[tool/error]")} [${t}] [${Ot(e)}] Tool run errored with error: ${Je(e.error,"[error]")}`)}onRetrieverStart(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.green,"[retriever/start]")} [${t}] Entering Retriever run with input: ${Je(e.inputs,"[inputs]")}`)}onRetrieverEnd(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.cyan,"[retriever/end]")} [${t}] [${Ot(e)}] Exiting Retriever run with output: ${Je(e.outputs,"[outputs]")}`)}onRetrieverError(e){const t=this.getBreadcrumbs(e);console.log(`${Ie(Ne.red,"[retriever/error]")} [${t}] [${Ot(e)}] Retriever run errored with error: ${Je(e.error,"[error]")}`)}onAgentAction(e){const t=e,r=this.getBreadcrumbs(e);console.log(`${Ie(Ne.blue,"[agent/action]")} [${r}] Agent selected action: ${Je(t.actions[t.actions.length-1],"[action]")}`)}}let pi;const T_=()=>{if(pi===void 0){const n=Ct("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{};pi=new tn(n)}return pi};class Gr extends pn{constructor(e={}){super(e),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{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,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"usesRunTreeMap",{enumerable:!0,configurable:!0,writable:!0,value:!0});const{exampleId:t,projectName:r,client:s,replicas:a}=e;this.projectName=r??Oh(),this.replicas=a,this.exampleId=t,this.client=s??T_();const i=Gr.getTraceableRunTree();i&&this.updateFromRunTree(i)}async persistRun(e){}async onRunCreate(e){await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){await this.getRunTreeWithTracingConfig(e.id)?.patchRun()}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let t=e;const r=new Set;for(;t.parent_run&&!(r.has(t.id)||(r.add(t.id),!t.parent_run));)t=t.parent_run;r.clear();const s=[t];for(;s.length>0;){const a=s.shift();!a||r.has(a.id)||(r.add(a.id),this.runTreeMap.set(a.id,a),a.child_runs&&s.push(...a.child_runs))}this.client=e.client??this.client,this.replicas=e.replicas??this.replicas,this.projectName=e.project_name??this.projectName,this.exampleId=e.reference_example_id??this.exampleId}getRunTreeWithTracingConfig(e){const t=this.runTreeMap.get(e);if(t)return new je({...t,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Km(!0)}catch{return}}}const zh=Symbol.for("ls:tracing_async_local_storage"),Vn=Symbol.for("lc:context_variables"),A_=n=>{globalThis[zh]=n},rn=()=>globalThis[zh];let Jr;function I_(){const n="default"in bt?bt.default:bt;return new n({autoStart:!0,concurrency:1})}function R_(){return typeof Jr>"u"&&(Jr=I_()),Jr}async function ye(n,e){if(e===!0){const t=rn();t!==void 0?await t.run(void 0,async()=>n()):await n()}else Jr=R_(),Jr.add(async()=>{const t=rn();t!==void 0?await t.run(void 0,async()=>n()):await n()})}const P_=n=>!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(t=>Ct(t)==="true");function qh(n){const e=rn();return e===void 0?void 0:e.getStore()?.[Vn]?.[n]}const C_=Symbol("lc:configure_hooks"),$_=()=>qh(C_)||[];class N_{setHandler(e){return this.setHandlers([e])}}class Bs{constructor(e,t,r,s,a,i,o,u){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:s}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:i}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:o}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:u})}get parentRunId(){return this._parentRunId}async handleText(e){await Promise.all(this.handlers.map(t=>ye(async()=>{try{await t.handleText?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleText: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleCustomEvent(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ye(async()=>{try{await i.handleCustomEvent?.(e,t,this.runId,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}}class j_ extends Bs{getChild(e){const t=new Ue(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleRetrieverEnd(e){await Promise.all(this.handlers.map(t=>ye(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetriever`),t.raiseError)throw r}},t.awaitHandlers)))}async handleRetrieverError(e){await Promise.all(this.handlers.map(t=>ye(async()=>{if(!t.ignoreRetriever)try{await t.handleRetrieverError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleRetrieverError: ${r}`),t.raiseError)throw e}},t.awaitHandlers)))}}class ml extends Bs{async handleLLMNewToken(e,t,r,s,a,i){await Promise.all(this.handlers.map(o=>ye(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(e,t??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(u){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${u}`),o.raiseError)throw u}},o.awaitHandlers)))}async handleLLMError(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ye(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleLLMEnd(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ye(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}}class L_ extends Bs{getChild(e){const t=new Ue(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleChainError(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ye(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleChainEnd(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ye(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(e,this.runId,this._parentRunId,this.tags,a)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}async handleAgentAction(e){await Promise.all(this.handlers.map(t=>ye(async()=>{if(!t.ignoreAgent)try{await t.handleAgentAction?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentAction: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleAgentEnd(e){await Promise.all(this.handlers.map(t=>ye(async()=>{if(!t.ignoreAgent)try{await t.handleAgentEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleAgentEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}}class M_ extends Bs{getChild(e){const t=new Ue(this.runId);return t.setHandlers(this.inheritableHandlers),t.addTags(this.inheritableTags),t.addMetadata(this.inheritableMetadata),e&&t.addTags([e],!1),t}async handleToolError(e){await Promise.all(this.handlers.map(t=>ye(async()=>{if(!t.ignoreAgent)try{await t.handleToolError?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolError: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}async handleToolEnd(e){await Promise.all(this.handlers.map(t=>ye(async()=>{if(!t.ignoreAgent)try{await t.handleToolEnd?.(e,this.runId,this._parentRunId,this.tags)}catch(r){if((t.raiseError?console.error:console.warn)(`Error in handler ${t.constructor.name}, handleToolEnd: ${r}`),t.raiseError)throw r}},t.awaitHandlers)))}}class Ue extends N_{constructor(e,t){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"callback_manager"}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=t?.handlers??this.handlers,this.inheritableHandlers=t?.inheritableHandlers??this.inheritableHandlers,this.tags=t?.tags??this.tags,this.inheritableTags=t?.inheritableTags??this.inheritableTags,this.metadata=t?.metadata??this.metadata,this.inheritableMetadata=t?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,t,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{const d=l===0&&r?r:yt();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return Ar(h)&&h._createRunForLLMStart(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u),ye(async()=>{try{await h.handleLLMStart?.(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u)}catch(f){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${f}`),h.raiseError)throw f}},h.awaitHandlers)})),new ml(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,t,r=void 0,s=void 0,a=void 0,i=void 0,o=void 0,u=void 0){return Promise.all(t.map(async(c,l)=>{const d=l===0&&r?r:yt();return await Promise.all(this.handlers.map(h=>{if(!h.ignoreLLM)return Ar(h)&&h._createRunForChatModelStart(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u),ye(async()=>{try{if(h.handleChatModelStart)await h.handleChatModelStart?.(e,[c],d,this._parentRunId,a,this.tags,this.metadata,u);else if(h.handleLLMStart){const f=mh(c);await h.handleLLMStart?.(e,[f],d,this._parentRunId,a,this.tags,this.metadata,u)}}catch(f){if((h.raiseError?console.error:console.warn)(`Error in handler ${h.constructor.name}, handleLLMStart: ${f}`),h.raiseError)throw f}},h.awaitHandlers)})),new ml(d,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,t,r=yt(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreChain)return Ar(u)&&u._createRunForChainStart(e,t,r,this._parentRunId,this.tags,this.metadata,s,o),ye(async()=>{try{await u.handleChainStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,s,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleChainStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new L_(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,t,r=yt(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return Ar(u)&&u._createRunForToolStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),ye(async()=>{try{await u.handleToolStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new M_(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,t,r=yt(),s=void 0,a=void 0,i=void 0,o=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreRetriever)return Ar(u)&&u._createRunForRetrieverStart(e,t,r,this._parentRunId,this.tags,this.metadata,o),ye(async()=>{try{await u.handleRetrieverStart?.(e,t,r,this._parentRunId,this.tags,this.metadata,o)}catch(c){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleRetrieverStart: ${c}`),u.raiseError)throw c}},u.awaitHandlers)})),new j_(r,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,t,r,s,a){await Promise.all(this.handlers.map(i=>ye(async()=>{if(!i.ignoreCustomEvent)try{await i.handleCustomEvent?.(e,t,r,this.tags,this.metadata)}catch(o){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${o}`),i.raiseError)throw o}},i.awaitHandlers)))}addHandler(e,t=!0){this.handlers.push(e),t&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(t=>t!==e),this.inheritableHandlers=this.inheritableHandlers.filter(t=>t!==e)}setHandlers(e,t=!0){this.handlers=[],this.inheritableHandlers=[];for(const r of e)this.addHandler(r,t)}addTags(e,t=!0){this.removeTags(e),this.tags.push(...e),t&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(t=>!e.includes(t)),this.inheritableTags=this.inheritableTags.filter(t=>!e.includes(t))}addMetadata(e,t=!0){this.metadata={...this.metadata,...e},t&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(const t of Object.keys(e))delete this.metadata[t],delete this.inheritableMetadata[t]}copy(e=[],t=!0){const r=new Ue(this._parentRunId);for(const s of this.handlers){const a=this.inheritableHandlers.includes(s);r.addHandler(s,a)}for(const s of this.tags){const a=this.inheritableTags.includes(s);r.addTags([s],a)}for(const s of Object.keys(this.metadata)){const a=Object.keys(this.inheritableMetadata).includes(s);r.addMetadata({[s]:this.metadata[s]},a)}for(const s of e)r.handlers.filter(a=>a.name==="console_callback_handler").some(a=>a.name===s.name)||r.addHandler(s,t);return r}static fromHandlers(e){class t extends fn{constructor(){super(),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:yt()}),Object.assign(this,e)}}const r=new this;return r.addHandler(new t),r}static configure(e,t,r,s,a,i,o){return this._configureSync(e,t,r,s,a,i,o)}static _configureSync(e,t,r,s,a,i,o){let u;(e||t)&&(Array.isArray(e)||!e?(u=new Ue,u.setHandlers(e?.map(ps)??[],!0)):u=e,u=u.copy(Array.isArray(t)?t.map(ps):t?.handlers,!1));const c=Ct("LANGCHAIN_VERBOSE")==="true"||o?.verbose,l=Gr.getTraceableRunTree()?.tracingEnabled||P_(),d=l||(Ct("LANGCHAIN_TRACING")??!1);if(c||d){if(u||(u=new Ue),c&&!u.handlers.some(h=>h.name===pl.prototype.name)){const h=new pl;u.addHandler(h,!0)}if(d&&!u.handlers.some(h=>h.name==="langchain_tracer")&&l){const h=new Gr;u.addHandler(h,!0)}if(l){const h=Gr.getTraceableRunTree();h&&u._parentRunId===void 0&&(u._parentRunId=h.id,u.handlers.find(p=>p.name==="langchain_tracer")?.updateFromRunTree(h))}}for(const{contextVar:h,inheritable:f=!0,handlerClass:p,envVar:m}of $_()){const g=m&&Ct(m)==="true"&&p;let y;const _=h!==void 0?qh(h):void 0;_&&E_(_)?y=_:g&&(y=new p({})),y!==void 0&&(u||(u=new Ue),u.handlers.some(b=>b.name===y.name)||u.addHandler(y,f))}return(r||s)&&u&&(u.addTags(r??[]),u.addTags(s??[],!1)),(a||i)&&u&&(u.addMetadata(a??{}),u.addMetadata(i??{},!1)),u}}function ps(n){return"name"in n?n:fn.fromMethods(n)}class U_{getStore(){}run(e,t){return t()}enterWith(e){}}const D_=new U_,gl=Symbol.for("lc:child_config");class F_{getInstance(){return rn()??D_}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[gl]}runWithConfig(e,t,r){const s=Ue._configureSync(e?.callbacks,void 0,e?.tags,void 0,e?.metadata),a=this.getInstance(),i=a.getStore(),o=s?.getParentRunId(),u=s?.handlers?.find(l=>l?.name==="langchain_tracer");let c;return u&&o?c=u.getRunTreeWithTracingConfig(o):r||(c=new je({name:"<runnable_lambda>",tracingEnabled:!1})),c&&(c.extra={...c.extra,[gl]:e}),i!==void 0&&i[Vn]!==void 0&&(c===void 0&&(c={}),c[Vn]=i[Vn]),a.run(c,t)}initializeGlobalInstance(e){rn()===void 0&&A_(e)}}const Lt=new F_,mi=25;async function rt(n){return Ue._configureSync(n?.callbacks,void 0,n?.tags,void 0,n?.metadata)}function yl(...n){const e={};for(const t of n.filter(r=>!!r))for(const r of Object.keys(t))if(r==="metadata")e[r]={...e[r],...t[r]};else if(r==="tags"){const s=e[r]??[];e[r]=[...new Set(s.concat(t[r]??[]))]}else if(r==="configurable")e[r]={...e[r],...t[r]};else if(r==="timeout")e.timeout===void 0?e.timeout=t.timeout:t.timeout!==void 0&&(e.timeout=Math.min(e.timeout,t.timeout));else if(r==="signal")e.signal===void 0?e.signal=t.signal:t.signal!==void 0&&("any"in AbortSignal?e.signal=AbortSignal.any([e.signal,t.signal]):e.signal=t.signal);else if(r==="callbacks"){const s=e.callbacks,a=t.callbacks;if(Array.isArray(a))if(!s)e.callbacks=a;else if(Array.isArray(s))e.callbacks=s.concat(a);else{const i=s.copy();for(const o of a)i.addHandler(ps(o),!0);e.callbacks=i}else if(a)if(!s)e.callbacks=a;else if(Array.isArray(s)){const i=a.copy();for(const o of s)i.addHandler(ps(o),!0);e.callbacks=i}else e.callbacks=new Ue(a._parentRunId,{handlers:s.handlers.concat(a.handlers),inheritableHandlers:s.inheritableHandlers.concat(a.inheritableHandlers),tags:Array.from(new Set(s.tags.concat(a.tags))),inheritableTags:Array.from(new Set(s.inheritableTags.concat(a.inheritableTags))),metadata:{...s.metadata,...a.metadata}})}else{const s=r;e[s]=t[s]??e[s]}return e}const B_=new Set(["string","number","boolean"]);function ne(n){const e=Lt.getRunnableConfig();let t={tags:[],metadata:{},recursionLimit:25,runId:void 0};if(e){const{runId:r,runName:s,...a}=e;t=Object.entries(a).reduce((i,[o,u])=>(u!==void 0&&(i[o]=u),i),t)}if(n&&(t=Object.entries(n).reduce((r,[s,a])=>(a!==void 0&&(r[s]=a),r),t)),t?.configurable)for(const r of Object.keys(t.configurable))B_.has(typeof t.configurable[r])&&!t.metadata?.[r]&&(t.metadata||(t.metadata={}),t.metadata[r]=t.configurable[r]);if(t.timeout!==void 0){if(t.timeout<=0)throw new Error("Timeout must be a positive number");const r=AbortSignal.timeout(t.timeout);t.signal!==void 0?"any"in AbortSignal&&(t.signal=AbortSignal.any([t.signal,r])):t.signal=r,delete t.timeout}return t}function Te(n={},{callbacks:e,maxConcurrency:t,recursionLimit:r,runName:s,configurable:a,runId:i}={}){const o=ne(n);return e!==void 0&&(delete o.runName,o.callbacks=e),r!==void 0&&(o.recursionLimit=r),t!==void 0&&(o.maxConcurrency=t),s!==void 0&&(o.runName=s),a!==void 0&&(o.configurable={...o.configurable,...a}),i!==void 0&&delete o.runId,o}function mr(n){return n?{configurable:n.configurable,recursionLimit:n.recursionLimit,callbacks:n.callbacks,tags:n.tags,metadata:n.metadata,maxConcurrency:n.maxConcurrency,timeout:n.timeout,signal:n.signal}:void 0}async function Mt(n,e){if(e===void 0)return n;let t;return Promise.race([n.catch(r=>{if(!e?.aborted)throw r}),new Promise((r,s)=>{t=()=>{s(new Error("Aborted"))},e.addEventListener("abort",t),e.aborted&&s(new Error("Aborted"))})]).finally(()=>e.removeEventListener("abort",t))}class He extends ReadableStream{constructor(){super(...arguments),Object.defineProperty(this,"reader",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}ensureReader(){this.reader||(this.reader=this.getReader())}async next(){this.ensureReader();try{const e=await this.reader.read();return e.done?(this.reader.releaseLock(),{done:!0,value:void 0}):{done:!1,value:e.value}}catch(e){throw this.reader.releaseLock(),e}}async return(){if(this.ensureReader(),this.locked){const e=this.reader.cancel();this.reader.releaseLock(),await e}return{done:!0,value:void 0}}async throw(e){if(this.ensureReader(),this.locked){const t=this.reader.cancel();this.reader.releaseLock(),await t}throw e}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}static fromReadableStream(e){const t=e.getReader();return new He({start(r){return s();function s(){return t.read().then(({done:a,value:i})=>{if(a){r.close();return}return r.enqueue(i),s()})}},cancel(){t.releaseLock()}})}static fromAsyncGenerator(e){return new He({async pull(t){const{value:r,done:s}=await e.next();s&&t.close(),t.enqueue(r)},async cancel(t){await e.return(t)}})}}function Zh(n,e=2){const t=Array.from({length:e},()=>[]);return t.map(async function*(s){for(;;)if(s.length===0){const a=await n.next();for(const i of t)i.push(a)}else{if(s[0].done)return;yield s.shift().value}})}function zs(n,e){if(Array.isArray(n)&&Array.isArray(e))return n.concat(e);if(typeof n=="string"&&typeof e=="string")return n+e;if(typeof n=="number"&&typeof e=="number")return n+e;if("concat"in n&&typeof n.concat=="function")return n.concat(e);if(typeof n=="object"&&typeof e=="object"){const t={...n};for(const[r,s]of Object.entries(e))r in t&&!Array.isArray(t[r])?t[r]=zs(t[r],s):t[r]=s;return t}else throw new Error(`Cannot concat ${typeof n} and ${typeof e}`)}class vr{constructor(e){Object.defineProperty(this,"generator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"setup",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"signal",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResult",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"firstResultUsed",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.generator=e.generator,this.config=e.config,this.signal=e.signal??this.config?.signal,this.setup=new Promise((t,r)=>{Lt.runWithConfig(mr(e.config),async()=>{this.firstResult=e.generator.next(),e.startSetup?this.firstResult.then(e.startSetup).then(t,r):this.firstResult.then(s=>t(void 0),r)},!0)})}async next(...e){return this.signal?.throwIfAborted(),this.firstResultUsed?Lt.runWithConfig(mr(this.config),this.signal?async()=>Mt(this.generator.next(...e),this.signal):async()=>this.generator.next(...e),!0):(this.firstResultUsed=!0,this.firstResult)}async return(e){return this.generator.return(e)}async throw(e){return this.generator.throw(e)}[Symbol.asyncIterator](){return this}async[Symbol.asyncDispose](){await this.return()}}async function z_(n,e,t,r,...s){const a=new vr({generator:e,startSetup:t,signal:r}),i=await a.setup;return{output:n(a,i,...s),setup:i}}class kt{constructor(e){Object.defineProperty(this,"ops",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.ops=e.ops??[]}concat(e){const t=this.ops.concat(e.ops),r=ls({},t);return new nn({ops:t,state:r[r.length-1].newDocument})}}class nn extends kt{constructor(e){super(e),Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.state=e.state}concat(e){const t=this.ops.concat(e.ops),r=ls(this.state,e.ops);return new nn({ops:t,state:r[r.length-1].newDocument})}static fromRunLogPatch(e){const t=ls({},e.ops);return new nn({ops:e.ops,state:t[t.length-1].newDocument})}}const q_=n=>n.name==="log_stream_tracer";async function _l(n,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:t}=n;if(["retriever","llm","prompt"].includes(n.run_type))return t;if(!(Object.keys(t).length===1&&t?.input===""))return t.input}async function bl(n,e){const{outputs:t}=n;return e==="original"||["retriever","llm","prompt"].includes(n.run_type)?t:t!==void 0&&Object.keys(t).length===1&&t?.output!==void 0?t.output:t}function Z_(n){return n!==void 0&&n.message!==void 0}class wl extends pn{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_schemaFormat",{enumerable:!0,configurable:!0,writable:!0,value:"original"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"keyMapByRunId",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"counterMapByRunName",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"log_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this._schemaFormat=e?._schemaFormat??this._schemaFormat,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=He.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){if(e.id===this.rootId)return!1;const t=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||t.find(s=>this.includeTags?.includes(s))!==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&&t.every(s=>!this.excludeTags?.includes(s))),r}async*tapOutputIterable(e,t){for await(const r of t){if(e!==this.rootId){const s=this.keyMapByRunId[e];s&&await this.writer.write(new kt({ops:[{op:"add",path:`/logs/${s}/streamed_output/-`,value:r}]}))}yield r}}async onRunCreate(e){if(this.rootId===void 0&&(this.rootId=e.id,await this.writer.write(new kt({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 t=this.counterMapByRunName[e.name];this.keyMapByRunId[e.id]=t===1?e.name:`${e.name}:${t}`;const r={id:e.id,name:e.name,type:e.run_type,tags:e.tags??[],metadata:e.extra?.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 _l(e,this._schemaFormat)),await this.writer.write(new kt({ops:[{op:"add",path:`/logs/${this.keyMapByRunId[e.id]}`,value:r}]}))}async onRunUpdate(e){try{const t=this.keyMapByRunId[e.id];if(t===void 0)return;const r=[];this._schemaFormat==="streaming_events"&&r.push({op:"replace",path:`/logs/${t}/inputs`,value:await _l(e,this._schemaFormat)}),r.push({op:"add",path:`/logs/${t}/final_output`,value:await bl(e,this._schemaFormat)}),e.end_time!==void 0&&r.push({op:"add",path:`/logs/${t}/end_time`,value:new Date(e.end_time).toISOString()});const s=new kt({ops:r});await this.writer.write(s)}finally{if(e.id===this.rootId){const t=new kt({ops:[{op:"replace",path:"/final_output",value:await bl(e,this._schemaFormat)}]});await this.writer.write(t),this.autoClose&&await this.writer.close()}}}async onLLMNewToken(e,t,r){const s=this.keyMapByRunId[e.id];if(s===void 0)return;const a=e.inputs.messages!==void 0;let i;a?Z_(r?.chunk)?i=r?.chunk:i=new $t({id:`run-${e.id}`,content:t}):i=t;const o=new kt({ops:[{op:"add",path:`/logs/${s}/streamed_output_str/-`,value:t},{op:"add",path:`/logs/${s}/streamed_output/-`,value:i}]});await this.writer.write(o)}}const vl="__run";class gr{constructor(e){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"generationInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=e.text,this.generationInfo=e.generationInfo}concat(e){return new gr({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo}})}}class Xt extends gr{constructor(e){super(e),Object.defineProperty(this,"message",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.message=e.message}concat(e){return new Xt({text:this.text+e.text,generationInfo:{...this.generationInfo,...e.generationInfo},message:this.message.concat(e.message)})}}function Cn({name:n,serialized:e}){return n!==void 0?n:e?.name!==void 0?e.name:e?.id!==void 0&&Array.isArray(e?.id)?e.id[e.id.length-1]:"Unnamed"}const H_=n=>n.name==="event_stream_tracer";class G_ extends pn{constructor(e){super({_awaitHandler:!0,...e}),Object.defineProperty(this,"autoClose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"runInfoMap",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"tappedPromises",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"transformStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"writer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"receiveStream",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"event_stream_tracer"}),Object.defineProperty(this,"lc_prefer_streaming",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.autoClose=e?.autoClose??!0,this.includeNames=e?.includeNames,this.includeTypes=e?.includeTypes,this.includeTags=e?.includeTags,this.excludeNames=e?.excludeNames,this.excludeTypes=e?.excludeTypes,this.excludeTags=e?.excludeTags,this.transformStream=new TransformStream,this.writer=this.transformStream.writable.getWriter(),this.receiveStream=He.fromReadableStream(this.transformStream.readable)}[Symbol.asyncIterator](){return this.receiveStream}async persistRun(e){}_includeRun(e){const t=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||t.find(s=>this.includeTags?.includes(s))!==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&&t.every(s=>!this.excludeTags?.includes(s))),r}async*tapOutputIterable(e,t){const r=await t.next();if(r.done)return;const s=this.runInfoMap.get(e);if(s===void 0){yield r.value;return}function a(o,u){return o==="llm"&&typeof u=="string"?new gr({text:u}):u}let i=this.tappedPromises.get(e);if(i===void 0){let o;i=new Promise(u=>{o=u}),this.tappedPromises.set(e,i);try{const u={event:`on_${s.runType}_stream`,run_id:e,name:s.name,tags:s.tags,metadata:s.metadata,data:{}};await this.send({...u,data:{chunk:a(s.runType,r.value)}},s),yield r.value;for await(const c of t)s.runType!=="tool"&&s.runType!=="retriever"&&await this.send({...u,data:{chunk:a(s.runType,c)}},s),yield c}finally{o()}}else{yield r.value;for await(const o of t)yield o}}async send(e,t){this._includeRun(t)&&await this.writer.write(e)}async sendEndEvent(e,t){const r=this.tappedPromises.get(e.run_id);r!==void 0?r.then(()=>{this.send(e,t)}):await this.send(e,t)}async onLLMStart(e){const t=Cn(e),r=e.inputs.messages!==void 0?"chat_model":"llm",s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:r,inputs:e.inputs};this.runInfoMap.set(e.id,s);const a=`on_${r}_start`;await this.send({event:a,data:{input:e.inputs},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onLLMNewToken(e,t,r){const s=this.runInfoMap.get(e.id);let a,i;if(s===void 0)throw new Error(`onLLMNewToken: Run ID ${e.id} not found in run map.`);if(this.runInfoMap.size!==1){if(s.runType==="chat_model")i="on_chat_model_stream",r?.chunk===void 0?a=new $t({content:t,id:`run-${e.id}`}):a=r.chunk.message;else if(s.runType==="llm")i="on_llm_stream",r?.chunk===void 0?a=new gr({text:t}):a=r.chunk;else throw new Error(`Unexpected run type ${s.runType}`);await this.send({event:i,data:{chunk:a},run_id:e.id,name:s.name,tags:s.tags,metadata:s.metadata},s)}}async onLLMEnd(e){const t=this.runInfoMap.get(e.id);this.runInfoMap.delete(e.id);let r;if(t===void 0)throw new Error(`onLLMEnd: Run ID ${e.id} not found in run map.`);const s=e.outputs?.generations;let a;if(t.runType==="chat_model"){for(const i of s??[]){if(a!==void 0)break;a=i[0]?.message}r="on_chat_model_end"}else if(t.runType==="llm")a={generations:s?.map(i=>i.map(o=>({text:o.text,generationInfo:o.generationInfo}))),llmOutput:e.outputs?.llmOutput??{}},r="on_llm_end";else throw new Error(`onLLMEnd: Unexpected run type: ${t.runType}`);await this.sendEndEvent({event:r,data:{output:a,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onChainStart(e){const t=Cn(e),r=e.run_type??"chain",s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:e.run_type};let a={};e.inputs.input===""&&Object.keys(e.inputs).length===1?(a={},s.inputs={}):e.inputs.input!==void 0?(a.input=e.inputs.input,s.inputs=e.inputs.input):(a.input=e.inputs,s.inputs=e.inputs),this.runInfoMap.set(e.id,s),await this.send({event:`on_${r}_start`,data:a,name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onChainEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onChainEnd: Run ID ${e.id} not found in run map.`);const r=`on_${e.run_type}_end`,s=e.inputs??t.inputs??{},i={output:e.outputs?.output??e.outputs,input:s};s.input&&Object.keys(s).length===1&&(i.input=s.input,t.inputs=s.input),await this.sendEndEvent({event:r,data:i,run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata??{}},t)}async onToolStart(e){const t=Cn(e),r={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"tool",inputs:e.inputs??{}};this.runInfoMap.set(e.id,r),await this.send({event:"on_tool_start",data:{input:e.inputs??{}},name:t,run_id:e.id,tags:e.tags??[],metadata:e.extra?.metadata??{}},r)}async onToolEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onToolEnd: Run ID ${e.id} not found in run map.`);if(t.inputs===void 0)throw new Error(`onToolEnd: Run ID ${e.id} is a tool call, and is expected to have traced inputs.`);const r=e.outputs?.output===void 0?e.outputs:e.outputs.output;await this.sendEndEvent({event:"on_tool_end",data:{output:r,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async onRetrieverStart(e){const t=Cn(e),s={tags:e.tags??[],metadata:e.extra?.metadata??{},name:t,runType:"retriever",inputs:{query:e.inputs.query}};this.runInfoMap.set(e.id,s),await this.send({event:"on_retriever_start",data:{input:{query:e.inputs.query}},name:t,tags:e.tags??[],run_id:e.id,metadata:e.extra?.metadata??{}},s)}async onRetrieverEnd(e){const t=this.runInfoMap.get(e.id);if(this.runInfoMap.delete(e.id),t===void 0)throw new Error(`onRetrieverEnd: Run ID ${e.id} not found in run map.`);await this.sendEndEvent({event:"on_retriever_end",data:{output:e.outputs?.documents??e.outputs,input:t.inputs},run_id:e.id,name:t.name,tags:t.tags,metadata:t.metadata},t)}async handleCustomEvent(e,t,r){const s=this.runInfoMap.get(r);if(s===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:s.tags,metadata:s.metadata,data:t},s)}async finish(){const e=[...this.tappedPromises.values()];Promise.all(e).finally(()=>{this.writer.close()})}}const J_=[400,401,402,403,404,405,406,407,409],W_=n=>{if(n.message.startsWith("Cancel")||n.message.startsWith("AbortError")||n.name==="AbortError"||n?.code==="ECONNABORTED")throw n;const e=n?.response?.status??n?.status;if(e&&J_.includes(+e))throw n;if(n?.error?.code==="insufficient_quota"){const t=new Error(n?.message);throw t.name="InsufficientQuotaError",t}};class Lo{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,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.onFailedAttempt=e.onFailedAttempt??W_;const t="default"in bt?bt.default:bt;this.queue=new t({concurrency:this.maxConcurrency})}call(e,...t){return this.queue.add(()=>cs(()=>e(...t).catch(r=>{throw r instanceof Error?r:new Error(r)}),{onFailedAttempt:this.onFailedAttempt,retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0})}callWithOptions(e,t,...r){return e.signal?Promise.race([this.call(t,...r),new Promise((s,a)=>{e.signal?.addEventListener("abort",()=>{a(new Error("AbortError"))})})]):this.call(t,...r)}fetch(...e){return this.call(()=>fetch(...e).then(t=>t.ok?t:Promise.reject(t)))}}class Hh extends pn{constructor({config:e,onStart:t,onEnd:r,onError:s}){super({_awaitHandler:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"RootListenersTracer"}),Object.defineProperty(this,"rootId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnStart",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnEnd",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"argOnError",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.config=e,this.argOnStart=t,this.argOnEnd=r,this.argOnError=s}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 Mo(n){return n?n.lc_runnable:!1}class V_{constructor(e){Object.defineProperty(this,"includeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"includeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeNames",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTypes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"excludeTags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.includeNames=e.includeNames,this.includeTypes=e.includeTypes,this.includeTags=e.includeTags,this.excludeNames=e.excludeNames,this.excludeTypes=e.excludeTypes,this.excludeTags=e.excludeTags}includeEvent(e,t){let r=this.includeNames===void 0&&this.includeTypes===void 0&&this.includeTags===void 0;const s=e.tags??[];return this.includeNames!==void 0&&(r=r||this.includeNames.includes(e.name)),this.includeTypes!==void 0&&(r=r||this.includeTypes.includes(t)),this.includeTags!==void 0&&(r=r||s.some(a=>this.includeTags?.includes(a))),this.excludeNames!==void 0&&(r=r&&!this.excludeNames.includes(e.name)),this.excludeTypes!==void 0&&(r=r&&!this.excludeTypes.includes(t)),this.excludeTags!==void 0&&(r=r&&s.every(a=>!this.excludeTags?.includes(a))),r}}function gi(n){return n.replace(/[^a-zA-Z-_0-9]/g,"_")}const K_=["*","_","`"];function X_(n){let e="";for(const[t,r]of Object.entries(n))e+=` classDef ${t} ${r};
|
|
84
|
+
`;return e}function Q_(n,e,t){const{firstNode:r,lastNode:s,nodeColors:a,withStyles:i=!0,curveStyle:o="linear",wrapLabelNWords:u=9}=t??{};let c=i?`%%{init: {'flowchart': {'curve': '${o}'}}}%%
|
|
85
|
+
graph TD;
|
|
86
|
+
`:`graph TD;
|
|
87
|
+
`;if(i){const f="default",p={[f]:"{0}({1})"};r!==void 0&&(p[r]="{0}([{1}]):::first"),s!==void 0&&(p[s]="{0}([{1}]):::last");for(const[m,g]of Object.entries(n)){const y=g.name.split(":").pop()??"";let b=K_.some(S=>y.startsWith(S)&&y.endsWith(S))?`<p>${y}</p>`:y;Object.keys(g.metadata??{}).length&&(b+=`<hr/><small><em>${Object.entries(g.metadata??{}).map(([S,R])=>`${S} = ${R}`).join(`
|
|
88
|
+
`)}</em></small>`);const v=(p[m]??p[f]).replace("{0}",gi(m)).replace("{1}",b);c+=` ${v}
|
|
89
|
+
`}}const l={};for(const f of e){const p=f.source.split(":"),m=f.target.split(":"),g=p.filter((y,_)=>y===m[_]).join(":");l[g]||(l[g]=[]),l[g].push(f)}const d=new Set;function h(f,p){const m=f.length===1&&f[0].source===f[0].target;if(p&&!m){const g=p.split(":").pop();if(d.has(g))throw new Error(`Found duplicate subgraph '${g}' -- 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(g),c+=` subgraph ${g}
|
|
90
|
+
`}for(const g of f){const{source:y,target:_,data:b,conditional:v}=g;let S="";if(b!==void 0){let R=b;const P=R.split(" ");P.length>u&&(R=Array.from({length:Math.ceil(P.length/u)},(x,K)=>P.slice(K*u,(K+1)*u).join(" ")).join(" <br> ")),S=v?` -. ${R} .-> `:` -- ${R} --> `}else S=v?" -.-> ":" --> ";c+=` ${gi(y)}${S}${gi(_)};
|
|
91
|
+
`}for(const g in l)g.startsWith(`${p}:`)&&g!==p&&h(l[g],g);p&&!m&&(c+=` end
|
|
92
|
+
`)}h(l[""]??[],"");for(const f in l)!f.includes(":")&&f!==""&&h(l[f],f);return i&&(c+=X_(a??{})),c}async function Y_(n,e){return eb(n,{...e,imageType:"png"})}async function eb(n,e){let t=e?.backgroundColor??"white";const r=e?.imageType,s=btoa(n);t!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(t)||(t=`!${t}`));const a=`https://mermaid.ink/img/${s}?bgColor=${t}&type=${r}`,i=await fetch(a);if(!i.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${i.status}`,`Status text: ${i.statusText}`].join(`
|
|
93
|
+
`));return await i.blob()}function qs(n,e,t){function r(o,u){var c;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(c=o._zod).traits??(c.traits=new Set),o._zod.traits.add(n),e(o,u);for(const l in i.prototype)l in o||Object.defineProperty(o,l,{value:i.prototype[l].bind(o)});o._zod.constr=i,o._zod.def=u}const s=t?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:n});function i(o){var u;const c=t?.Parent?new a:this;r(c,o),(u=c._zod).deferred??(u.deferred=[]);for(const l of c._zod.deferred)l();return c}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>t?.Parent&&o instanceof t.Parent?!0:o?._zod?.traits?.has(n)}),Object.defineProperty(i,"name",{value:n}),i}let ms=class extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}};const tb={};function Zs(n){return tb}function rb(n){const e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function nb(n,e){return typeof e=="bigint"?e.toString():e}const Gh=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};function gs(n,e,t){const r=new n._zod.constr(e??n._zod.def);return(!e||t?.parent)&&(r._zod.parent=n),r}function sb(n){return{}}function yi(n,e=0){for(let t=e;t<n.issues.length;t++)if(n.issues[t]?.continue!==!0)return!0;return!1}function $n(n){return typeof n=="string"?n:n?.message}function Hs(n,e,t){const r={...n,path:n.path??[]};if(!n.message){const s=$n(n.inst?._zod.def?.error?.(n))??$n(e?.error?.(n))??$n(t.customError?.(n))??$n(t.localeError?.(n))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}const Jh=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(e,nb,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},ab=qs("$ZodError",Jh),Gs=qs("$ZodError",Jh,{Parent:Error}),ib=n=>(e,t,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise)throw new ms;if(i.issues.length){const o=new(s?.Err??n)(i.issues.map(u=>Hs(u,a,Zs())));throw Gh(o,s?.callee),o}return i.value},ob=ib(Gs),ub=n=>async(e,t,r,s)=>{const a=r?Object.assign(r,{async:!0}):{async:!0};let i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise&&(i=await i),i.issues.length){const o=new(s?.Err??n)(i.issues.map(u=>Hs(u,a,Zs())));throw Gh(o,s?.callee),o}return i.value},cb=ub(Gs),lb=n=>(e,t,r)=>{const s=r?{...r,async:!1}:{async:!1},a=e._zod.run({value:t,issues:[]},s);if(a instanceof Promise)throw new ms;return a.issues.length?{success:!1,error:new(n??ab)(a.issues.map(i=>Hs(i,s,Zs())))}:{success:!0,data:a.value}},db=lb(Gs),hb=n=>async(e,t,r)=>{const s=r?Object.assign(r,{async:!0}):{async:!0};let a=e._zod.run({value:t,issues:[]},s);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new n(a.issues.map(i=>Hs(i,s,Zs())))}:{success:!0,data:a.value}},fb=hb(Gs),pb={major:4,minor:0,patch:0},mb=qs("$ZodType",(n,e)=>{var t;n??(n={}),n._zod.def=e,n._zod.bag=n._zod.bag||{},n._zod.version=pb;const r=[...n._zod.def.checks??[]];n._zod.traits.has("$ZodCheck")&&r.unshift(n);for(const s of r)for(const a of s._zod.onattach)a(n);if(r.length===0)(t=n._zod).deferred??(t.deferred=[]),n._zod.deferred?.push(()=>{n._zod.run=n._zod.parse});else{const s=(a,i,o)=>{let u=yi(a),c;for(const l of i){if(l._zod.def.when){if(!l._zod.def.when(a))continue}else if(u)continue;const d=a.issues.length,h=l._zod.check(a);if(h instanceof Promise&&o?.async===!1)throw new ms;if(c||h instanceof Promise)c=(c??Promise.resolve()).then(async()=>{await h,a.issues.length!==d&&(u||(u=yi(a,d)))});else{if(a.issues.length===d)continue;u||(u=yi(a,d))}}return c?c.then(()=>a):a};n._zod.run=(a,i)=>{const o=n._zod.parse(a,i);if(o instanceof Promise){if(i.async===!1)throw new ms;return o.then(u=>s(u,r,i))}return s(o,r,i)}}n["~standard"]={validate:s=>{try{const a=db(n,s);return a.success?{value:a.data}:{issues:a.error?.issues}}catch{return fb(n,s).then(i=>i.success?{value:i.data}:{issues:i.error?.issues})}},vendor:"zod",version:1}}),gb=qs("$ZodNever",(n,e)=>{mb.init(n,e),n._zod.parse=(t,r)=>(t.issues.push({expected:"never",code:"invalid_type",input:t.value,inst:n}),t)});let Wh=class{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}};function yb(){return new Wh}const It=yb();function _b(n,e){return new n({type:"never",...sb()})}let Sl=class{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??It,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);const u=e._zod.toJSONSchema?.();if(u)o.schema=u;else{const d={...t,schemaPath:[...t.schemaPath,e],path:t.path},h=e._zod.parent;if(h)o.ref=h,this.process(h,d),this.seen.get(h).isParent=!0;else{const f=o.schema;switch(s.type){case"string":{const p=f;p.type="string";const{minimum:m,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof g=="number"&&(p.maxLength=g),y&&(p.format=a[y]??y,p.format===""&&delete p.format),b&&(p.contentEncoding=b),_&&_.size>0){const v=[..._];v.length===1?p.pattern=v[0].source:v.length>1&&(o.schema.allOf=[...v.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{const p=f,{minimum:m,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:v}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof v=="number"&&(p.exclusiveMinimum=v),typeof m=="number"&&(p.minimum=m,typeof v=="number"&&(v>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof b=="number"&&(p.exclusiveMaximum=b),typeof g=="number"&&(p.maximum=g,typeof b=="number"&&(b<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{const p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=f,{minimum:m,maximum:g}=e._zod.bag;typeof m=="number"&&(p.minItems=m),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...d,path:[...d.path,"items"]});break}case"object":{const p=f;p.type="object",p.properties={};const m=s.shape;for(const _ in m)p.properties[_]=this.process(m[_],{...d,path:[...d.path,"properties",_]});const g=new Set(Object.keys(m)),y=new Set([...g].filter(_=>{const b=s.shape[_]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));y.size>0&&(p.required=Array.from(y)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=f;p.anyOf=s.options.map((m,g)=>this.process(m,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{const p=f,m=this.process(s.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(s.right,{...d,path:[...d.path,"allOf",1]}),y=b=>"allOf"in b&&Object.keys(b).length===1,_=[...y(m)?m.allOf:[m],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{const p=f;p.type="array";const m=s.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?p.prefixItems=m:p.items=m,s.rest){const _=this.process(s.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}s.rest&&(p.items=this.process(s.rest,{...d,path:[...d.path,"items"]}));const{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{const p=f;p.type="object",p.propertyNames=this.process(s.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(s.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const p=f,m=rb(s.entries);m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),p.enum=m;break}case"literal":{const p=f,m=[];for(const g of s.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");m.push(Number(g))}else m.push(g);if(m.length!==0)if(m.length===1){const g=m[0];p.type=g===null?"null":typeof g,p.const=g}else m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),m.every(g=>typeof g=="boolean")&&(p.type="string"),m.every(g=>g===null)&&(p.type="null"),p.enum=m;break}case"file":{const p=f,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(m.minLength=g),y!==void 0&&(m.maxLength=y),_?_.length===1?(m.contentMediaType=_[0],Object.assign(p,m)):p.anyOf=_.map(b=>({...m,contentMediaType:b})):Object.assign(p,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(s.innerType,d);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"success":{const p=f;p.type="boolean";break}case"default":{this.process(s.innerType,d),o.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,d),o.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,d),o.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=f,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=m.source;break}case"pipe":{const p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,d),o.ref=p;break}case"readonly":{this.process(s.innerType,d),o.ref=s.innerType,f.readOnly=!0;break}case"promise":{this.process(s.innerType,d),o.ref=s.innerType;break}case"optional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"lazy":{const p=e._zod.innerType;this.process(p,d),o.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),this.io==="input"&&pe(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){const r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const m=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(m)return{ref:g(m)};const y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===s)return{ref:"#"};const f=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:h,defId:f}=a(l);d.def={...d.schema},f&&(d.defId=f);const p=d.schema;for(const m in p)delete p[m];p.$ref=h};if(r.cycles==="throw")for(const l of this.seen.entries()){const d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
94
|
+
|
|
95
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const l of this.seen.entries()){const d=l[1];if(e===l[0]){i(l);continue}if(r.external){const f=r.external.registry.get(l[0])?.id;if(e!==l[0]&&f){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}const o=(l,d)=>{const h=this.seen.get(l),f=h.def??h.schema,p={...f};if(h.ref===null)return;const m=h.ref;if(h.ref=null,m){o(m,d);const g=this.seen.get(m).schema;g.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}h.isParent||this.override({zodSchema:l,jsonSchema:f,path:h.path??[]})};for(const l of[...this.seen.entries()].reverse())o(l[0],{target:this.target});const u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");u.$id=r.external.uri(l)}Object.assign(u,s.def);const c=r.external?.defs??{};for(const l of this.seen.entries()){const d=l[1];d.def&&d.defId&&(c[d.defId]=d.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?u.$defs=c:u.definitions=c);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}};function El(n,e){if(n instanceof Wh){const r=new Sl(e),s={};for(const o of n._idmap.entries()){const[u,c]=o;r.process(c)}const a={},i={registry:n,uri:e?.uri,defs:s};for(const o of n._idmap.entries()){const[u,c]=o;a[u]=r.emit(c,{...e,external:i})}if(Object.keys(s).length>0){const o=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[o]:s}}return{schemas:a}}const t=new Sl(e);return t.process(n),t.emit(n,e)}function pe(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const s=n._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return pe(s.element,t);case"object":{for(const a in s.shape)if(pe(s.shape[a],t))return!0;return!1}case"union":{for(const a of s.options)if(pe(a,t))return!0;return!1}case"intersection":return pe(s.left,t)||pe(s.right,t);case"tuple":{for(const a of s.items)if(pe(a,t))return!0;return!!(s.rest&&pe(s.rest,t))}case"record":return pe(s.keyType,t)||pe(s.valueType,t);case"map":return pe(s.keyType,t)||pe(s.valueType,t);case"set":return pe(s.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return pe(s.innerType,t);case"lazy":return pe(s.getter(),t);case"default":return pe(s.innerType,t);case"prefault":return pe(s.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return pe(s.in,t)||pe(s.out,t);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const bb=Symbol("Let zodToJsonSchema decide on which parser to use"),wb={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"},vb=n=>({...wb,...n}),Sb=n=>{const e=vb(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:t,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[s._def,{def:s._def,path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function Vh(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function ie(n,e,t,r,s){n[e]=t,Vh(n,e,r,s)}const Kh=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")};function Ge(n){if(n.target!=="openAi")return{};const e=[...n.basePath,n.definitionPath,n.openAiAnyTypeName];return n.flags.hasReferencedOpenAiAnyType=!0,{$ref:n.$refStrategy==="relative"?Kh(e,n.currentPath):e.join("/")}}function Eb(n,e){const t={type:"array"};return n.type?._def&&n.type?._def?.typeName!==O.ZodAny&&(t.items=se(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&ie(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&ie(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(ie(t,"minItems",n.exactLength.value,n.exactLength.message,e),ie(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function Ob(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?ie(t,"minimum",r.value,r.message,e):ie(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),ie(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ie(t,"maximum",r.value,r.message,e):ie(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),ie(t,"maximum",r.value,r.message,e));break;case"multipleOf":ie(t,"multipleOf",r.value,r.message,e);break}return t}function xb(){return{type:"boolean"}}function Xh(n,e){return se(n.type._def,e)}const kb=(n,e)=>se(n.innerType._def,e);function Qh(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>Qh(n,e,s))};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 Tb(n,e)}}const Tb=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const r of n.checks)switch(r.kind){case"min":ie(t,"minimum",r.value,r.message,e);break;case"max":ie(t,"maximum",r.value,r.message,e);break}return t};function Ab(n,e){return{...se(n.innerType._def,e),default:n.defaultValue()}}function Ib(n,e){return e.effectStrategy==="input"?se(n.schema._def,e):Ge(e)}function Rb(n){return{type:"string",enum:Array.from(n.values)}}const Pb=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function Cb(n,e){const t=[se(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),se(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(a=>{if(Pb(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...u}=a;i=u}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function $b(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let _i;const Ke={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:()=>(_i===void 0&&(_i=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),_i),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Yh(n,e){const t={type:"string"};if(n.checks)for(const r of n.checks)switch(r.kind){case"min":ie(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e);break;case"max":ie(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Xe(t,"email",r.message,e);break;case"format:idn-email":Xe(t,"idn-email",r.message,e);break;case"pattern:zod":Re(t,Ke.email,r.message,e);break}break;case"url":Xe(t,"uri",r.message,e);break;case"uuid":Xe(t,"uuid",r.message,e);break;case"regex":Re(t,r.regex,r.message,e);break;case"cuid":Re(t,Ke.cuid,r.message,e);break;case"cuid2":Re(t,Ke.cuid2,r.message,e);break;case"startsWith":Re(t,RegExp(`^${bi(r.value,e)}`),r.message,e);break;case"endsWith":Re(t,RegExp(`${bi(r.value,e)}$`),r.message,e);break;case"datetime":Xe(t,"date-time",r.message,e);break;case"date":Xe(t,"date",r.message,e);break;case"time":Xe(t,"time",r.message,e);break;case"duration":Xe(t,"duration",r.message,e);break;case"length":ie(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,r.value):r.value,r.message,e),ie(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,r.value):r.value,r.message,e);break;case"includes":{Re(t,RegExp(bi(r.value,e)),r.message,e);break}case"ip":{r.version!=="v6"&&Xe(t,"ipv4",r.message,e),r.version!=="v4"&&Xe(t,"ipv6",r.message,e);break}case"base64url":Re(t,Ke.base64url,r.message,e);break;case"jwt":Re(t,Ke.jwt,r.message,e);break;case"cidr":{r.version!=="v6"&&Re(t,Ke.ipv4Cidr,r.message,e),r.version!=="v4"&&Re(t,Ke.ipv6Cidr,r.message,e);break}case"emoji":Re(t,Ke.emoji(),r.message,e);break;case"ulid":{Re(t,Ke.ulid,r.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Xe(t,"binary",r.message,e);break}case"contentEncoding:base64":{ie(t,"contentEncoding","base64",r.message,e);break}case"pattern:zod":{Re(t,Ke.base64,r.message,e);break}}break}case"nanoid":Re(t,Ke.nanoid,r.message,e)}return t}function bi(n,e){return e.patternStrategy==="escape"?jb(n):n}const Nb=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function jb(n){let e="";for(let t=0;t<n.length;t++)Nb.has(n[t])||(e+="\\"),e+=n[t];return e}function Xe(n,e,t,r){n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):ie(n,"format",e,t,r)}function Re(n,e,t,r){n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:Ol(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):ie(n,"pattern",Ol(e,r),t,r)}function Ol(n,e){if(!e.applyRegexFlags||!n.flags)return n.source;const t={i:n.flags.includes("i"),m:n.flags.includes("m"),s:n.flags.includes("s")},r=t.i?n.source.toLowerCase():n.source;let s="",a=!1,i=!1,o=!1;for(let u=0;u<r.length;u++){if(a){s+=r[u],a=!1;continue}if(t.i){if(i){if(r[u].match(/[a-z]/)){o?(s+=r[u],s+=`${r[u-2]}-${r[u]}`.toUpperCase(),o=!1):r[u+1]==="-"&&r[u+2]?.match(/[a-z]/)?(s+=r[u],o=!0):s+=`${r[u]}${r[u].toUpperCase()}`;continue}}else if(r[u].match(/[a-z]/)){s+=`[${r[u]}${r[u].toUpperCase()}]`;continue}}if(t.m){if(r[u]==="^"){s+=`(^|(?<=[\r
|
|
96
|
+
]))`;continue}else if(r[u]==="$"){s+=`($|(?=[\r
|
|
97
|
+
]))`;continue}}if(t.s&&r[u]==="."){s+=i?`${r[u]}\r
|
|
98
|
+
`:`[${r[u]}\r
|
|
99
|
+
]`;continue}s+=r[u],r[u]==="\\"?a=!0:i&&r[u]==="]"?i=!1:!i&&r[u]==="["&&(i=!0)}try{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 ef(n,e){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"&&n.keyType?._def.typeName===O.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:se(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??Ge(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};const t={type:"object",additionalProperties:se(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===O.ZodString&&n.keyType._def.checks?.length){const{type:r,...s}=Yh(n.keyType._def,e);return{...t,propertyNames:s}}else{if(n.keyType?._def.typeName===O.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};if(n.keyType?._def.typeName===O.ZodBranded&&n.keyType._def.type._def.typeName===O.ZodString&&n.keyType._def.type._def.checks?.length){const{type:r,...s}=Xh(n.keyType._def,e);return{...t,propertyNames:s}}}return t}function Lb(n,e){if(e.mapStrategy==="record")return ef(n,e);const t=se(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||Ge(e),r=se(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||Ge(e);return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function Mb(n){const e=n.values,r=Object.keys(n.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function Ub(n){return n.target==="openAi"?void 0:{not:Ge({...n,currentPath:[...n.currentPath,"not"]})}}function Db(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ys={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Fb(n,e){if(e.target==="openApi3")return xl(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in ys&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((s,a)=>{const i=ys[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=t.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return xl(n,e)}const xl=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>se(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function Bb(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"?{type:ys[n.innerType._def.typeName],nullable:!0}:{type:[ys[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=se(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const t=se(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function zb(n,e){const t={type:"number"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"int":t.type="integer",Vh(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?ie(t,"minimum",r.value,r.message,e):ie(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),ie(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?ie(t,"maximum",r.value,r.message,e):ie(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),ie(t,"maximum",r.value,r.message,e));break;case"multipleOf":ie(t,"multipleOf",r.value,r.message,e);break}return t}function qb(n,e){const t=e.target==="openAi",r={type:"object",properties:{}},s=[],a=n.shape();for(const o in a){let u=a[o];if(u===void 0||u._def===void 0)continue;let c=Hb(u);c&&t&&(u._def.typeName==="ZodOptional"&&(u=u._def.innerType),u.isNullable()||(u=u.nullable()),c=!1);const l=se(u._def,{...e,currentPath:[...e.currentPath,"properties",o],propertyPath:[...e.currentPath,"properties",o]});l!==void 0&&(r.properties[o]=l,c||s.push(o))}s.length&&(r.required=s);const i=Zb(n,e);return i!==void 0&&(r.additionalProperties=i),r}function Zb(n,e){if(n.catchall._def.typeName!=="ZodNever")return se(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(n.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function Hb(n){try{return n.isOptional()}catch{return!0}}const Gb=(n,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return se(n.innerType._def,e);const t=se(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:Ge(e)},t]}:Ge(e)},Jb=(n,e)=>{if(e.pipeStrategy==="input")return se(n.in._def,e);if(e.pipeStrategy==="output")return se(n.out._def,e);const t=se(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=se(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function Wb(n,e){return se(n.type._def,e)}function Vb(n,e){const r={type:"array",uniqueItems:!0,items:se(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&ie(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&ie(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function Kb(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>se(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:se(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>se(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Xb(n){return{not:Ge(n)}}function Qb(n){return Ge(n)}const Yb=(n,e)=>se(n.innerType._def,e),ew=(n,e,t)=>{switch(e){case O.ZodString:return Yh(n,t);case O.ZodNumber:return zb(n,t);case O.ZodObject:return qb(n,t);case O.ZodBigInt:return Ob(n,t);case O.ZodBoolean:return xb();case O.ZodDate:return Qh(n,t);case O.ZodUndefined:return Xb(t);case O.ZodNull:return Db(t);case O.ZodArray:return Eb(n,t);case O.ZodUnion:case O.ZodDiscriminatedUnion:return Fb(n,t);case O.ZodIntersection:return Cb(n,t);case O.ZodTuple:return Kb(n,t);case O.ZodRecord:return ef(n,t);case O.ZodLiteral:return $b(n,t);case O.ZodEnum:return Rb(n);case O.ZodNativeEnum:return Mb(n);case O.ZodNullable:return Bb(n,t);case O.ZodOptional:return Gb(n,t);case O.ZodMap:return Lb(n,t);case O.ZodSet:return Vb(n,t);case O.ZodLazy:return()=>n.getter()._def;case O.ZodPromise:return Wb(n,t);case O.ZodNaN:case O.ZodNever:return Ub(t);case O.ZodEffects:return Ib(n,t);case O.ZodAny:return Ge(t);case O.ZodUnknown:return Qb(t);case O.ZodDefault:return Ab(n,t);case O.ZodBranded:return Xh(n,t);case O.ZodReadonly:return Yb(n,t);case O.ZodCatch:return kb(n,t);case O.ZodPipeline:return Jb(n,t);case O.ZodFunction:case O.ZodVoid:case O.ZodSymbol:return;default:return(r=>{})()}};function se(n,e,t=!1){const r=e.seen.get(n);if(e.override){const o=e.override?.(n,e,r,t);if(o!==bb)return o}if(r&&!t){const o=tw(r,e);if(o!==void 0)return o}const s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);const a=ew(n,n.typeName,e),i=typeof a=="function"?se(a(),e):a;if(i&&rw(n,e,i),e.postProcess){const o=e.postProcess(i,n,e);return s.jsonSchema=i,o}return s.jsonSchema=i,i}const tw=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"relative":return{$ref:Kh(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((t,r)=>e.currentPath[r]===t)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),Ge(e)):e.$refStrategy==="seen"?Ge(e):void 0}},rw=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),nw=(n,e)=>{const t=Sb(e);let r;const s=e?.name,a=se(n._def,t,!1)??Ge(t);t.flags.hasReferencedOpenAiAnyType&&(r||(r={}),r[t.openAiAnyTypeName]||(r[t.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:t.$refStrategy==="relative"?"1":[...t.basePath,t.definitionPath,t.openAiAnyTypeName].join("/")}}));const i=s===void 0?r?{...a,[t.definitionPath]:r}:a:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,s].join("/"),[t.definitionPath]:{...r,[s]:a}};return t.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(t.target==="jsonSchema2019-09"||t.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),t.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};function Ki(n,e){const t=typeof n;if(t!==typeof e)return!1;if(Array.isArray(n)){if(!Array.isArray(e))return!1;const r=n.length;if(r!==e.length)return!1;for(let s=0;s<r;s++)if(!Ki(n[s],e[s]))return!1;return!0}if(t==="object"){if(!n||!e)return n===e;const r=Object.keys(n),s=Object.keys(e);if(r.length!==s.length)return!1;for(const i of r)if(!Ki(n[i],e[i]))return!1;return!0}return n===e}function it(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_zod"in e))return!1;const t=e._zod;return typeof t=="object"&&t!==null&&"def"in t}function pt(n){if(typeof n!="object"||n===null)return!1;const e=n;if(!("_def"in e)||"_zod"in e)return!1;const t=e._def;return typeof t=="object"&&t!=null&&"typeName"in t}function Zt(n){return!n||typeof n!="object"||Array.isArray(n)?!1:!!(it(n)||pt(n))}async function sw(n,e){if(it(n))try{return{success:!0,data:await cb(n,e)}}catch(t){return{success:!1,error:t}}if(pt(n))return n.safeParse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}async function tf(n,e){if(it(n))return ob(n,e);if(pt(n))return n.parse(e);throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Uo(n){if(it(n))return It.get(n)?.description;if(pt(n)||"description"in n&&typeof n.description=="string")return n.description}function aw(n){return Zt(n)?pt(n)?n._def.typeName==="ZodString":it(n)?n._zod.def.type==="string":!1:!1}function Wr(n){return it(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="object":!1}function rf(n){return it(n)?typeof n=="object"&&n!==null&&"_zod"in n&&typeof n._zod=="object"&&n._zod!==null&&"def"in n._zod&&typeof n._zod.def=="object"&&n._zod.def!==null&&"type"in n._zod.def&&n._zod.def.type==="array":!1}function Xi(n,e=!1){if(pt(n))return n.strict();if(Wr(n)){const t=n._zod.def.shape;if(e)for(const[a,i]of Object.entries(n._zod.def.shape)){if(Wr(i)){const u=Xi(i,e);t[a]=u}else if(rf(i)){let u=i._zod.def.element;Wr(u)&&(u=Xi(u,e)),t[a]=gs(i,{...i._zod.def,element:u})}else t[a]=i;const o=It.get(i);o&&It.add(t[a],o)}const r=gs(n,{...n._zod.def,shape:t,catchall:_b(gb)}),s=It.get(n);return s&&It.add(r,s),r}throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject")}function iw(n){return pt(n)&&"typeName"in n._def&&n._def.typeName==="ZodEffects"}function ow(n){return it(n)&&n._zod.def.type==="pipe"}function Br(n,e=!1){if(pt(n))return iw(n)?Br(n._def.schema,e):n;if(it(n)){let t=n;if(ow(n)&&(t=Br(n._zod.def.in,e)),e){if(Wr(t)){const s=t._zod.def.shape;for(const[a,i]of Object.entries(t._zod.def.shape))s[a]=Br(i,e);t=gs(t,{...t._zod.def,shape:s})}else if(rf(t)){const s=Br(t._zod.def.element,e);t=gs(t,{...t._zod.def,element:s})}}const r=It.get(n);return r&&It.add(t,r),t}throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType")}function Rt(n){if(it(n)){const e=Br(n,!0);if(Wr(e)){const t=Xi(e,!0);return El(t)}else return El(n)}return pt(n)?nw(n):n}function uw(n,e){if(n!==void 0&&!Jn(n))return n;if(Mo(e))try{let t=e.getName();return t=t.startsWith("Runnable")?t.slice(8):t,t}catch{return e.getName()}else return e.name??"UnknownSchema"}function cw(n){return Mo(n.data)?{type:"runnable",data:{id:n.data.lc_id,name:n.data.getName()}}:{type:"schema",data:{...Rt(n.data.schema),title:n.data.name}}}class Js{constructor(e){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=e?.nodes??this.nodes,this.edges=e?.edges??this.edges}toJSON(){const e={};return Object.values(this.nodes).forEach((t,r)=>{e[t.id]=Jn(t.id)?r:t.id}),{nodes:Object.values(this.nodes).map(t=>({id:e[t.id],...cw(t)})),edges:this.edges.map(t=>{const r={source:e[t.source],target:e[t.target]};return typeof t.data<"u"&&(r.data=t.data),typeof t.conditional<"u"&&(r.conditional=t.conditional),r})}}addNode(e,t,r){if(t!==void 0&&this.nodes[t]!==void 0)throw new Error(`Node with id ${t} already exists`);const s=t??yt(),a={id:s,data:e,name:uw(t,e),metadata:r};return this.nodes[s]=a,a}removeNode(e){delete this.nodes[e.id],this.edges=this.edges.filter(t=>t.source!==e.id&&t.target!==e.id)}addEdge(e,t,r,s){if(this.nodes[e.id]===void 0)throw new Error(`Source node ${e.id} not in graph`);if(this.nodes[t.id]===void 0)throw new Error(`Target node ${t.id} not in graph`);const a={source:e.id,target:t.id,data:r,conditional:s};return this.edges.push(a),a}firstNode(){return kl(this)}lastNode(){return Tl(this)}extend(e,t=""){let r=t;Object.values(e.nodes).map(c=>c.id).every(Jn)&&(r="");const a=c=>r?`${r}:${c}`:c;Object.entries(e.nodes).forEach(([c,l])=>{this.nodes[a(c)]={...l,id:a(c)}});const i=e.edges.map(c=>({...c,source:a(c.source),target:a(c.target)}));this.edges=[...this.edges,...i];const o=e.firstNode(),u=e.lastNode();return[o?{id:a(o.id),data:o.data}:void 0,u?{id:a(u.id),data:u.data}:void 0]}trimFirstNode(){const e=this.firstNode();e&&kl(this,[e.id])&&this.removeNode(e)}trimLastNode(){const e=this.lastNode();e&&Tl(this,[e.id])&&this.removeNode(e)}reid(){const e=Object.fromEntries(Object.values(this.nodes).map(s=>[s.id,s.name])),t=new Map;Object.values(e).forEach(s=>{t.set(s,(t.get(s)||0)+1)});const r=s=>{const a=e[s];return Jn(s)&&t.get(a)===1?a:s};return new Js({nodes:Object.fromEntries(Object.entries(this.nodes).map(([s,a])=>[r(s),{...a,id:r(s)}])),edges:this.edges.map(s=>({...s,source:r(s.source),target:r(s.target)}))})}drawMermaid(e){const{withStyles:t,curveStyle:r,nodeColors:s={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:a}=e??{},i=this.reid(),o=i.firstNode(),u=i.lastNode();return Q_(i.nodes,i.edges,{firstNode:o?.id,lastNode:u?.id,withStyles:t,curveStyle:r,nodeColors:s,wrapLabelNWords:a})}async drawMermaidPng(e){const t=this.drawMermaid(e);return Y_(t,{backgroundColor:e?.backgroundColor})}}function kl(n,e=[]){const t=new Set(n.edges.filter(s=>!e.includes(s.source)).map(s=>s.target)),r=[];for(const s of Object.values(n.nodes))!e.includes(s.id)&&!t.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function Tl(n,e=[]){const t=new Set(n.edges.filter(s=>!e.includes(s.target)).map(s=>s.source)),r=[];for(const s of Object.values(n.nodes))!e.includes(s.id)&&!t.has(s.id)&&r.push(s);return r.length===1?r[0]:void 0}function lw(n){const e=new TextEncoder,t=new ReadableStream({async start(r){for await(const s of n)r.enqueue(e.encode(`event: data
|
|
100
|
+
data: ${JSON.stringify(s)}
|
|
101
|
+
|
|
102
|
+
`));r.enqueue(e.encode(`event: end
|
|
103
|
+
|
|
104
|
+
`)),r.close()}});return He.fromReadableStream(t)}function Al(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.iterator]=="function"&&typeof n.next=="function"}const dw=n=>n!=null&&typeof n=="object"&&"next"in n&&typeof n.next=="function";function Qi(n){return typeof n=="object"&&n!==null&&typeof n[Symbol.asyncIterator]=="function"}function*Il(n,e){for(;;){const{value:t,done:r}=Lt.runWithConfig(mr(n),e.next.bind(e),!0);if(r)break;yield t}}async function*Yi(n,e){const t=e[Symbol.asyncIterator]();for(;;){const{value:r,done:s}=await Lt.runWithConfig(mr(n),t.next.bind(e),!0);if(s)break;yield r}}function we(n,e){return n&&!Array.isArray(n)&&!(n instanceof Date)&&typeof n=="object"?n:{[e]:n}}class ve extends Wt{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(e){const t=this.name??this.constructor.lc_name()??this.constructor.name;return e?`${t}${e}`:t}bind(e){return new Gt({bound:this,kwargs:e,config:{}})}map(){return new _s({bound:this})}withRetry(e){return new nf({bound:this,kwargs:{},config:{},maxAttemptNumber:e?.stopAfterAttempt,...e})}withConfig(e){return new Gt({bound:this,config:e,kwargs:{}})}withFallbacks(e){const t=Array.isArray(e)?e:e.fallbacks;return new fw({runnable:this,fallbacks:t})}_getOptionsList(e,t=0){if(Array.isArray(e)&&e.length!==t)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${e.length} options for ${t} inputs`);if(Array.isArray(e))return e.map(ne);if(t>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(([s])=>s!=="runId"));return Array.from({length:t},(s,a)=>ne(a===0?e:r))}return Array.from({length:t},()=>ne(e))}async batch(e,t,r){const s=this._getOptionsList(t??{},e.length),a=s[0]?.maxConcurrency??r?.maxConcurrency,i=new Lo({maxConcurrency:a,onFailedAttempt:u=>{throw u}}),o=e.map((u,c)=>i.call(async()=>{try{return await this.invoke(u,s[c])}catch(l){if(r?.returnExceptions)return l;throw l}}));return Promise.all(o)}async*_streamIterator(e,t){yield this.invoke(e,t)}async stream(e,t){const r=ne(t),s=new vr({generator:this._streamIterator(e,r),config:r});return await s.setup,He.fromAsyncGenerator(s)}_separateRunnableConfigFromCallOptions(e){let t;e===void 0?t=ne(e):t=ne({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,[t,r]}async _callWithConfig(e,t,r){const s=ne(r),i=await(await rt(s))?.handleChainStart(this.toJSON(),we(t,"input"),s.runId,s?.runType,void 0,void 0,s?.runName??this.getName());delete s.runId;let o;try{const u=e.call(this,t,s,i);o=await Mt(u,r?.signal)}catch(u){throw await i?.handleChainError(u),u}return await i?.handleChainEnd(we(o,"output")),o}async _batchWithConfig(e,t,r,s){const a=this._getOptionsList(r??{},t.length),i=await Promise.all(a.map(rt)),o=await Promise.all(i.map(async(c,l)=>{const d=await c?.handleChainStart(this.toJSON(),we(t[l],"input"),a[l].runId,a[l].runType,void 0,void 0,a[l].runName??this.getName());return delete a[l].runId,d}));let u;try{const c=e.call(this,t,a,o,s);u=await Mt(c,a?.[0]?.signal)}catch(c){throw await Promise.all(o.map(l=>l?.handleChainError(c))),c}return await Promise.all(o.map(c=>c?.handleChainEnd(we(u,"output")))),u}_concatOutputChunks(e,t){return zs(e,t)}async*_transformStreamWithConfig(e,t,r){let s,a=!0,i,o=!0;const u=ne(r),c=await rt(u),l=this;async function*d(){for await(const f of e){if(a)if(s===void 0)s=f;else try{s=l._concatOutputChunks(s,f)}catch{s=void 0,a=!1}yield f}}let h;try{const f=await z_(t.bind(this),d(),async()=>c?.handleChainStart(this.toJSON(),{input:""},u.runId,u.runType,void 0,void 0,u.runName??this.getName()),r?.signal,u);delete u.runId,h=f.setup;const p=h?.handlers.find(H_);let m=f.output;p!==void 0&&h!==void 0&&(m=p.tapOutputIterable(h.runId,m));const g=h?.handlers.find(q_);g!==void 0&&h!==void 0&&(m=g.tapOutputIterable(h.runId,m));for await(const y of m)if(yield y,o)if(i===void 0)i=y;else try{i=this._concatOutputChunks(i,y)}catch{i=void 0,o=!1}}catch(f){throw await h?.handleChainError(f,void 0,void 0,void 0,{inputs:we(s,"input")}),f}await h?.handleChainEnd(i??{},void 0,void 0,void 0,{inputs:we(s,"input")})}getGraph(e){const t=new Js,r=t.addNode({name:`${this.getName()}Input`,schema:Zu()}),s=t.addNode(this),a=t.addNode({name:`${this.getName()}Output`,schema:Zu()});return t.addEdge(r,s),t.addEdge(s,a),t}pipe(e){return new _t({first:this,last:Ht(e)})}pick(e){return this.pipe(new pw(e))}assign(e){return this.pipe(new sf(new Sr({steps:e})))}async*transform(e,t){let r;for await(const s of e)r===void 0?r=s:r=this._concatOutputChunks(r,s);yield*this._streamIterator(r,ne(t))}async*streamLog(e,t,r){const s=new wl({...r,autoClose:!1,_schemaFormat:"original"}),a=ne(t);yield*this._streamLog(e,s,a)}async*_streamLog(e,t,r){const{callbacks:s}=r;if(s===void 0)r.callbacks=[t];else if(Array.isArray(s))r.callbacks=s.concat([t]);else{const u=s.copy();u.addHandler(t,!0),r.callbacks=u}const a=this.stream(e,r);async function i(){try{const u=await a;for await(const c of u){const l=new kt({ops:[{op:"add",path:"/streamed_output/-",value:c}]});await t.writer.write(l)}}finally{await t.writer.close()}}const o=i();try{for await(const u of t)yield u}finally{await o}}streamEvents(e,t,r){let s;if(t.version==="v1")s=this._streamEventsV1(e,t,r);else if(t.version==="v2")s=this._streamEventsV2(e,t,r);else throw new Error('Only versions "v1" and "v2" of the schema are currently supported.');return t.encoding==="text/event-stream"?lw(s):He.fromAsyncGenerator(s)}async*_streamEventsV2(e,t,r){const s=new G_({...r,autoClose:!1}),a=ne(t),i=a.runId??yt();a.runId=i;const o=a.callbacks;if(o===void 0)a.callbacks=[s];else if(Array.isArray(o))a.callbacks=o.concat(s);else{const p=o.copy();p.addHandler(s,!0),a.callbacks=p}const u=new AbortController,c=this;async function l(){let p,m=null;try{t?.signal?"any"in AbortSignal?p=AbortSignal.any([u.signal,t.signal]):(p=t.signal,m=()=>{u.abort()},t.signal.addEventListener("abort",m,{once:!0})):p=u.signal;const g=await c.stream(e,{...a,signal:p}),y=s.tapOutputIterable(i,g);for await(const _ of y)if(u.signal.aborted)break}finally{await s.finish(),p&&m&&p.removeEventListener("abort",m)}}const d=l();let h=!1,f;try{for await(const p of s){if(!h){p.data.input=e,h=!0,f=p.run_id,yield p;continue}p.run_id===f&&p.event.endsWith("_end")&&p.data?.input&&delete p.data.input,yield p}}finally{u.abort(),await d}}async*_streamEventsV1(e,t,r){let s,a=!1;const i=ne(t),o=i.tags??[],u=i.metadata??{},c=i.runName??this.getName(),l=new wl({...r,autoClose:!1,_schemaFormat:"streaming_events"}),d=new V_({...r}),h=this._streamLog(e,l,i);for await(const p of h){if(s?s=s.concat(p):s=nn.fromRunLogPatch(p),s.state===void 0)throw new Error('Internal error: "streamEvents" state is missing. Please open a bug report.');if(!a){a=!0;const _={...s.state},b={run_id:_.id,event:`on_${_.type}_start`,name:c,tags:o,metadata:u,data:{input:e}};d.includeEvent(b,_.type)&&(yield b)}const m=p.ops.filter(_=>_.path.startsWith("/logs/")).map(_=>_.path.split("/")[2]),g=[...new Set(m)];for(const _ of g){let b,v={};const S=s.state.logs[_];if(S.end_time===void 0?S.streamed_output.length>0?b="stream":b="start":b="end",b==="start")S.inputs!==void 0&&(v.input=S.inputs);else if(b==="end")S.inputs!==void 0&&(v.input=S.inputs),v.output=S.final_output;else if(b==="stream"){const R=S.streamed_output.length;if(R!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${R} instead. Encountered in: "${S.name}"`);v={chunk:S.streamed_output[0]},S.streamed_output=[]}yield{event:`on_${S.type}_${b}`,name:S.name,run_id:S.id,tags:S.tags,metadata:S.metadata,data:v}}const{state:y}=s;if(y.streamed_output.length>0){const _=y.streamed_output.length;if(_!==1)throw new Error(`Expected exactly one chunk of streamed output, got ${_} instead. Encountered in: "${y.name}"`);const b={chunk:y.streamed_output[0]};y.streamed_output=[];const v={event:`on_${y.type}_stream`,run_id:y.id,tags:o,metadata:u,name:c,data:b};d.includeEvent(v,y.type)&&(yield v)}}const f=s?.state;if(f!==void 0){const p={event:`on_${f.type}_end`,name:c,run_id:f.id,tags:o,metadata:u,data:{output:f.final_output}};d.includeEvent(p,f.type)&&(yield p)}}static isRunnable(e){return Mo(e)}withListeners({onStart:e,onEnd:t,onError:r}){return new Gt({bound:this,config:{},configFactories:[s=>({callbacks:[new Hh({config:s,onStart:e,onEnd:t,onError:r})]})]})}asTool(e){return mw(this,e)}}class Gt extends ve{static lc_name(){return"RunnableBinding"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"config",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"configFactories",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound,this.kwargs=e.kwargs,this.config=e.config,this.configFactories=e.configFactories}getName(e){return this.bound.getName(e)}async _mergeConfig(...e){const t=yl(this.config,...e);return yl(t,...this.configFactories?await Promise.all(this.configFactories.map(async r=>await r(t))):[])}bind(e){return new this.constructor({bound:this.bound,kwargs:{...this.kwargs,...e},config:this.config})}withConfig(e){return new this.constructor({bound:this.bound,kwargs:this.kwargs,config:{...this.config,...e}})}withRetry(e){return new nf({bound:this.bound,kwargs:this.kwargs,config:this.config,maxAttemptNumber:e?.stopAfterAttempt,...e})}async invoke(e,t){return this.bound.invoke(e,await this._mergeConfig(ne(t),this.kwargs))}async batch(e,t,r){const s=Array.isArray(t)?await Promise.all(t.map(async a=>this._mergeConfig(ne(a),this.kwargs))):await this._mergeConfig(ne(t),this.kwargs);return this.bound.batch(e,s,r)}_concatOutputChunks(e,t){return this.bound._concatOutputChunks(e,t)}async*_streamIterator(e,t){yield*this.bound._streamIterator(e,await this._mergeConfig(ne(t),this.kwargs))}async stream(e,t){return this.bound.stream(e,await this._mergeConfig(ne(t),this.kwargs))}async*transform(e,t){yield*this.bound.transform(e,await this._mergeConfig(ne(t),this.kwargs))}streamEvents(e,t,r){const s=this,a=async function*(){yield*s.bound.streamEvents(e,{...await s._mergeConfig(ne(t),s.kwargs),version:t.version},r)};return He.fromAsyncGenerator(a())}static isRunnableBinding(e){return e.bound&&ve.isRunnable(e.bound)}withListeners({onStart:e,onEnd:t,onError:r}){return new Gt({bound:this.bound,kwargs:this.kwargs,config:this.config,configFactories:[s=>({callbacks:[new Hh({config:s,onStart:e,onEnd:t,onError:r})]})]})}}class _s extends ve{static lc_name(){return"RunnableEach"}constructor(e){super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"bound",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.bound=e.bound}bind(e){return new _s({bound:this.bound.bind(e)})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _invoke(e,t,r){return this.bound.batch(e,Te(t,{callbacks:r?.getChild()}))}withListeners({onStart:e,onEnd:t,onError:r}){return new _s({bound:this.bound.withListeners({onStart:e,onEnd:t,onError:r})})}}class nf extends Gt{static lc_name(){return"RunnableRetry"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"maxAttemptNumber",{enumerable:!0,configurable:!0,writable:!0,value:3}),Object.defineProperty(this,"onFailedAttempt",{enumerable:!0,configurable:!0,writable:!0,value:()=>{}}),this.maxAttemptNumber=e.maxAttemptNumber??this.maxAttemptNumber,this.onFailedAttempt=e.onFailedAttempt??this.onFailedAttempt}_patchConfigForRetry(e,t,r){const s=e>1?`retry:attempt:${e}`:void 0;return Te(t,{callbacks:r?.getChild(s)})}async _invoke(e,t,r){return cs(s=>super.invoke(e,this._patchConfigForRetry(s,t,r)),{onFailedAttempt:s=>this.onFailedAttempt(s,e),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async _batch(e,t,r,s){const a={};try{await cs(async i=>{const o=e.map((h,f)=>f).filter(h=>a[h.toString()]===void 0||a[h.toString()]instanceof Error),u=o.map(h=>e[h]),c=o.map(h=>this._patchConfigForRetry(i,t?.[h],r?.[h])),l=await super.batch(u,c,{...s,returnExceptions:!0});let d;for(let h=0;h<l.length;h+=1){const f=l[h],p=o[h];f instanceof Error&&d===void 0&&(d=f,d.input=u[h]),a[p.toString()]=f}if(d)throw d;return l},{onFailedAttempt:i=>this.onFailedAttempt(i,i.input),retries:Math.max(this.maxAttemptNumber-1,0),randomize:!0})}catch(i){if(s?.returnExceptions!==!0)throw i}return Object.keys(a).sort((i,o)=>parseInt(i,10)-parseInt(o,10)).map(i=>a[parseInt(i,10)])}async batch(e,t,r){return this._batchWithConfig(this._batch.bind(this),e,t,r)}}class _t extends ve{static lc_name(){return"RunnableSequence"}constructor(e){super(e),Object.defineProperty(this,"first",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"middle",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"last",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitSequenceTags",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),this.first=e.first,this.middle=e.middle??this.middle,this.last=e.last,this.name=e.name,this.omitSequenceTags=e.omitSequenceTags??this.omitSequenceTags}get steps(){return[this.first,...this.middle,this.last]}async invoke(e,t){const r=ne(t),a=await(await rt(r))?.handleChainStart(this.toJSON(),we(e,"input"),r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;let i=e,o;try{const u=[this.first,...this.middle];for(let c=0;c<u.length;c+=1){const d=u[c].invoke(i,Te(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${c+1}`)}));i=await Mt(d,t?.signal)}if(t?.signal?.aborted)throw new Error("Aborted");o=await this.last.invoke(i,Te(r,{callbacks:a?.getChild(this.omitSequenceTags?void 0:`seq:step:${this.steps.length}`)}))}catch(u){throw await a?.handleChainError(u),u}return await a?.handleChainEnd(we(o,"output")),o}async batch(e,t,r){const s=this._getOptionsList(t??{},e.length),a=await Promise.all(s.map(rt)),i=await Promise.all(a.map(async(u,c)=>{const l=await u?.handleChainStart(this.toJSON(),we(e[c],"input"),s[c].runId,void 0,void 0,void 0,s[c].runName);return delete s[c].runId,l}));let o=e;try{for(let u=0;u<this.steps.length;u+=1){const l=this.steps[u].batch(o,i.map((d,h)=>{const f=d?.getChild(this.omitSequenceTags?void 0:`seq:step:${u+1}`);return Te(s[h],{callbacks:f})}),r);o=await Mt(l,s[0]?.signal)}}catch(u){throw await Promise.all(i.map(c=>c?.handleChainError(u))),u}return await Promise.all(i.map(u=>u?.handleChainEnd(we(o,"output")))),o}_concatOutputChunks(e,t){return this.last._concatOutputChunks(e,t)}async*_streamIterator(e,t){const r=await rt(t),{runId:s,...a}=t??{},i=await r?.handleChainStart(this.toJSON(),we(e,"input"),s,void 0,void 0,void 0,a?.runName),o=[this.first,...this.middle,this.last];let u=!0,c;async function*l(){yield e}try{let d=o[0].transform(l(),Te(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:"seq:step:1")}));for(let h=1;h<o.length;h+=1)d=await o[h].transform(d,Te(a,{callbacks:i?.getChild(this.omitSequenceTags?void 0:`seq:step:${h+1}`)}));for await(const h of d)if(t?.signal?.throwIfAborted(),yield h,u)if(c===void 0)c=h;else try{c=this._concatOutputChunks(c,h)}catch{c=void 0,u=!1}}catch(d){throw await i?.handleChainError(d),d}await i?.handleChainEnd(we(c,"output"))}getGraph(e){const t=new Js;let r=null;return this.steps.forEach((s,a)=>{const i=s.getGraph(e);a!==0&&i.trimFirstNode(),a!==this.steps.length-1&&i.trimLastNode(),t.extend(i);const o=i.firstNode();if(!o)throw new Error(`Runnable ${s} has no first node`);r&&t.addEdge(r,o),r=i.lastNode()}),t}pipe(e){return _t.isRunnableSequence(e)?new _t({first:this.first,middle:this.middle.concat([this.last,e.first,...e.middle]),last:e.last,name:this.name??e.name}):new _t({first:this.first,middle:[...this.middle,this.last],last:Ht(e),name:this.name})}static isRunnableSequence(e){return Array.isArray(e.middle)&&ve.isRunnable(e)}static from([e,...t],r){let s={};return typeof r=="string"?s.name=r:r!==void 0&&(s=r),new _t({...s,first:Ht(e),middle:t.slice(0,-1).map(Ht),last:Ht(t[t.length-1])})}}class Sr extends ve{static lc_name(){return"RunnableMap"}getStepsKeys(){return Object.keys(this.steps)}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"steps",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.steps={};for(const[t,r]of Object.entries(e.steps))this.steps[t]=Ht(r)}static from(e){return new Sr({steps:e})}async invoke(e,t){const r=ne(t),a=await(await rt(r))?.handleChainStart(this.toJSON(),{input:e},r.runId,void 0,void 0,void 0,r?.runName);delete r.runId;const i={};try{const o=Object.entries(this.steps).map(async([u,c])=>{i[u]=await c.invoke(e,Te(r,{callbacks:a?.getChild(`map:key:${u}`)}))});await Mt(Promise.all(o),t?.signal)}catch(o){throw await a?.handleChainError(o),o}return await a?.handleChainEnd(i),i}async*_transform(e,t,r){const s={...this.steps},a=Zh(e,Object.keys(s).length),i=new Map(Object.entries(s).map(([o,u],c)=>{const l=u.transform(a[c],Te(r,{callbacks:t?.getChild(`map:key:${o}`)}));return[o,l.next().then(d=>({key:o,gen:l,result:d}))]}));for(;i.size;){const o=Promise.race(i.values()),{key:u,result:c,gen:l}=await Mt(o,r?.signal);i.delete(u),c.done||(yield{[u]:c.value},i.set(u,l.next().then(d=>({key:u,gen:l,result:d}))))}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=ne(t),a=new vr({generator:this.transform(r(),s),config:s});return await a.setup,He.fromAsyncGenerator(a)}}class Do extends ve{constructor(e){if(super(e),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),!To(e.func))throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function");this.func=e.func}async invoke(e,t){const[r]=this._getOptionsList(t??{},1),s=await rt(r),a=this.func(Te(r,{callbacks:s}),e);return Mt(a,r?.signal)}async*_streamIterator(e,t){const[r]=this._getOptionsList(t??{},1),s=await this.invoke(e,t);if(Qi(s)){for await(const a of s)r?.signal?.throwIfAborted(),yield a;return}if(dw(s)){for(;;){r?.signal?.throwIfAborted();const a=s.next();if(a.done)break;yield a.value}return}yield s}static from(e){return new Do({func:e})}}function hw(n){if(To(n))throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen.")}class Er extends ve{static lc_name(){return"RunnableLambda"}constructor(e){if(To(e.func))return Do.from(e.func);super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),hw(e.func),this.func=e.func}static from(e){return new Er({func:e})}async _invoke(e,t,r){return new Promise((s,a)=>{const i=Te(t,{callbacks:r?.getChild(),recursionLimit:(t?.recursionLimit??mi)-1});Lt.runWithConfig(mr(i),async()=>{try{let o=await this.func(e,{...i});if(o&&ve.isRunnable(o)){if(t?.recursionLimit===0)throw new Error("Recursion limit reached.");o=await o.invoke(e,{...i,recursionLimit:(i.recursionLimit??mi)-1})}else if(Qi(o)){let u;for await(const c of Yi(i,o))if(t?.signal?.throwIfAborted(),u===void 0)u=c;else try{u=this._concatOutputChunks(u,c)}catch{u=c}o=u}else if(Al(o)){let u;for(const c of Il(i,o))if(t?.signal?.throwIfAborted(),u===void 0)u=c;else try{u=this._concatOutputChunks(u,c)}catch{u=c}o=u}s(o)}catch(o){a(o)}})})}async invoke(e,t){return this._callWithConfig(this._invoke.bind(this),e,t)}async*_transform(e,t,r){let s;for await(const o of e)if(s===void 0)s=o;else try{s=this._concatOutputChunks(s,o)}catch{s=o}const a=Te(r,{callbacks:t?.getChild(),recursionLimit:(r?.recursionLimit??mi)-1}),i=await new Promise((o,u)=>{Lt.runWithConfig(mr(a),async()=>{try{const c=await this.func(s,{...a,config:a});o(c)}catch(c){u(c)}})});if(i&&ve.isRunnable(i)){if(r?.recursionLimit===0)throw new Error("Recursion limit reached.");const o=await i.stream(s,a);for await(const u of o)yield u}else if(Qi(i))for await(const o of Yi(a,i))r?.signal?.throwIfAborted(),yield o;else if(Al(i))for(const o of Il(a,i))r?.signal?.throwIfAborted(),yield o;else yield i}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=ne(t),a=new vr({generator:this.transform(r(),s),config:s});return await a.setup,He.fromAsyncGenerator(a)}}class fw extends ve{static lc_name(){return"RunnableWithFallbacks"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"runnable",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fallbacks",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.runnable=e.runnable,this.fallbacks=e.fallbacks}*runnables(){yield this.runnable;for(const e of this.fallbacks)yield e}async invoke(e,t){const r=ne(t),s=await rt(r),{runId:a,...i}=r,o=await s?.handleChainStart(this.toJSON(),we(e,"input"),a,void 0,void 0,void 0,i?.runName),u=Te(i,{callbacks:o?.getChild()});return await Lt.runWithConfig(u,async()=>{let l;for(const d of this.runnables()){r?.signal?.throwIfAborted();try{const h=await d.invoke(e,u);return await o?.handleChainEnd(we(h,"output")),h}catch(h){l===void 0&&(l=h)}}throw l===void 0?new Error("No error stored at end of fallback."):(await o?.handleChainError(l),l)})}async*_streamIterator(e,t){const r=ne(t),s=await rt(r),{runId:a,...i}=r,o=await s?.handleChainStart(this.toJSON(),we(e,"input"),a,void 0,void 0,void 0,i?.runName);let u,c;for(const d of this.runnables()){r?.signal?.throwIfAborted();const h=Te(i,{callbacks:o?.getChild()});try{const f=await d.stream(e,h);c=Yi(h,f);break}catch(f){u===void 0&&(u=f)}}if(c===void 0){const d=u??new Error("No error stored at end of fallback.");throw await o?.handleChainError(d),d}let l;try{for await(const d of c){yield d;try{l=l===void 0?l:this._concatOutputChunks(l,d)}catch{l=void 0}}}catch(d){throw await o?.handleChainError(d),d}await o?.handleChainEnd(we(l,"output"))}async batch(e,t,r){if(r?.returnExceptions)throw new Error("Not implemented.");const s=this._getOptionsList(t??{},e.length),a=await Promise.all(s.map(u=>rt(u))),i=await Promise.all(a.map(async(u,c)=>{const l=await u?.handleChainStart(this.toJSON(),we(e[c],"input"),s[c].runId,void 0,void 0,void 0,s[c].runName);return delete s[c].runId,l}));let o;for(const u of this.runnables()){s[0].signal?.throwIfAborted();try{const c=await u.batch(e,i.map((l,d)=>Te(s[d],{callbacks:l?.getChild()})),r);return await Promise.all(i.map((l,d)=>l?.handleChainEnd(we(c[d],"output")))),c}catch(c){o===void 0&&(o=c)}}throw o?(await Promise.all(i.map(u=>u?.handleChainError(o))),o):new Error("No error stored at end of fallbacks.")}}function Ht(n){if(typeof n=="function")return new Er({func:n});if(ve.isRunnable(n))return n;if(!Array.isArray(n)&&typeof n=="object"){const e={};for(const[t,r]of Object.entries(n))e[t]=Ht(r);return new Sr({steps:e})}else throw new Error(`Expected a Runnable, function or object.
|
|
105
|
+
Instead got an unsupported type.`)}class sf extends ve{static lc_name(){return"RunnableAssign"}constructor(e){e instanceof Sr&&(e={mapper:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=e.mapper}async invoke(e,t){const r=await this.mapper.invoke(e,t);return{...e,...r}}async*_transform(e,t,r){const s=this.mapper.getStepsKeys(),[a,i]=Zh(e),o=this.mapper.transform(i,Te(r,{callbacks:t?.getChild()})),u=o.next();for await(const c of a){if(typeof c!="object"||Array.isArray(c))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof c}`);const l=Object.fromEntries(Object.entries(c).filter(([d])=>!s.includes(d)));Object.keys(l).length>0&&(yield l)}yield(await u).value;for await(const c of o)yield c}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=ne(t),a=new vr({generator:this.transform(r(),s),config:s});return await a.setup,He.fromAsyncGenerator(a)}}class pw extends ve{static lc_name(){return"RunnablePick"}constructor(e){(typeof e=="string"||Array.isArray(e))&&(e={keys:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=e.keys}async _pick(e){if(typeof this.keys=="string")return e[this.keys];{const t=this.keys.map(r=>[r,e[r]]).filter(r=>r[1]!==void 0);return t.length===0?void 0:Object.fromEntries(t)}}async invoke(e,t){return this._callWithConfig(this._pick.bind(this),e,t)}async*_transform(e){for await(const t of e){const r=await this._pick(t);r!==void 0&&(yield r)}}transform(e,t){return this._transformStreamWithConfig(e,this._transform.bind(this),t)}async stream(e,t){async function*r(){yield e}const s=ne(t),a=new vr({generator:this.transform(r(),s),config:s});return await a.setup,He.fromAsyncGenerator(a)}}class Rl extends Gt{constructor(e){const t=_t.from([Er.from(async r=>{let s;if(ph(r))try{s=await tf(this.schema,r.args)}catch{throw new am("Received tool input did not match expected schema",JSON.stringify(r.args))}else s=r;return s}).withConfig({runName:`${e.name}:parse_input`}),e.bound]).withConfig({runName:e.name});super({bound:t,config:e.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=e.name,this.description=e.description,this.schema=e.schema}static lc_name(){return"RunnableToolLike"}}function mw(n,e){const t=e.name??n.getName(),r=e.description??Uo(e.schema);return aw(e.schema)?new Rl({name:t,description:r,schema:wh({input:bh()}).transform(s=>s.input),bound:n}):new Rl({name:t,description:r,schema:e.schema,bound:n})}/*
|
|
106
|
+
* [js-sha1]{@link https://github.com/emn178/js-sha1}
|
|
107
|
+
*
|
|
108
|
+
* @version 0.6.0
|
|
109
|
+
* @author Chen, Yi-Cyuan [emn178@gmail.com]
|
|
110
|
+
* @copyright Chen, Yi-Cyuan 2014-2017
|
|
111
|
+
* @license MIT
|
|
112
|
+
*/var gw=typeof window=="object"?window:{},J="0123456789abcdef".split(""),yw=[-2147483648,8388608,32768,128],Qe=[24,16,8,0],_e=[];function nt(n){n?(_e[0]=_e[16]=_e[1]=_e[2]=_e[3]=_e[4]=_e[5]=_e[6]=_e[7]=_e[8]=_e[9]=_e[10]=_e[11]=_e[12]=_e[13]=_e[14]=_e[15]=0,this.blocks=_e):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],this.h0=1732584193,this.h1=4023233417,this.h2=2562383102,this.h3=271733878,this.h4=3285377520,this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0}nt.prototype.update=function(n){if(!this.finalized){var e=typeof n!="string";e&&n.constructor===gw.ArrayBuffer&&(n=new Uint8Array(n));for(var t,r=0,s,a=n.length||0,i=this.blocks;r<a;){if(this.hashed&&(this.hashed=!1,i[0]=this.block,i[16]=i[1]=i[2]=i[3]=i[4]=i[5]=i[6]=i[7]=i[8]=i[9]=i[10]=i[11]=i[12]=i[13]=i[14]=i[15]=0),e)for(s=this.start;r<a&&s<64;++r)i[s>>2]|=n[r]<<Qe[s++&3];else for(s=this.start;r<a&&s<64;++r)t=n.charCodeAt(r),t<128?i[s>>2]|=t<<Qe[s++&3]:t<2048?(i[s>>2]|=(192|t>>6)<<Qe[s++&3],i[s>>2]|=(128|t&63)<<Qe[s++&3]):t<55296||t>=57344?(i[s>>2]|=(224|t>>12)<<Qe[s++&3],i[s>>2]|=(128|t>>6&63)<<Qe[s++&3],i[s>>2]|=(128|t&63)<<Qe[s++&3]):(t=65536+((t&1023)<<10|n.charCodeAt(++r)&1023),i[s>>2]|=(240|t>>18)<<Qe[s++&3],i[s>>2]|=(128|t>>12&63)<<Qe[s++&3],i[s>>2]|=(128|t>>6&63)<<Qe[s++&3],i[s>>2]|=(128|t&63)<<Qe[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=i[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}};nt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var n=this.blocks,e=this.lastByteIndex;n[16]=this.block,n[e>>2]|=yw[e&3],this.block=n[16],e>=56&&(this.hashed||this.hash(),n[0]=this.block,n[16]=n[1]=n[2]=n[3]=n[4]=n[5]=n[6]=n[7]=n[8]=n[9]=n[10]=n[11]=n[12]=n[13]=n[14]=n[15]=0),n[14]=this.hBytes<<3|this.bytes>>>29,n[15]=this.bytes<<3,this.hash()}};nt.prototype.hash=function(){var n=this.h0,e=this.h1,t=this.h2,r=this.h3,s=this.h4,a,i,o,u=this.blocks;for(i=16;i<80;++i)o=u[i-3]^u[i-8]^u[i-14]^u[i-16],u[i]=o<<1|o>>>31;for(i=0;i<20;i+=5)a=e&t|~e&r,o=n<<5|n>>>27,s=o+a+s+1518500249+u[i]<<0,e=e<<30|e>>>2,a=n&e|~n&t,o=s<<5|s>>>27,r=o+a+r+1518500249+u[i+1]<<0,n=n<<30|n>>>2,a=s&n|~s&e,o=r<<5|r>>>27,t=o+a+t+1518500249+u[i+2]<<0,s=s<<30|s>>>2,a=r&s|~r&n,o=t<<5|t>>>27,e=o+a+e+1518500249+u[i+3]<<0,r=r<<30|r>>>2,a=t&r|~t&s,o=e<<5|e>>>27,n=o+a+n+1518500249+u[i+4]<<0,t=t<<30|t>>>2;for(;i<40;i+=5)a=e^t^r,o=n<<5|n>>>27,s=o+a+s+1859775393+u[i]<<0,e=e<<30|e>>>2,a=n^e^t,o=s<<5|s>>>27,r=o+a+r+1859775393+u[i+1]<<0,n=n<<30|n>>>2,a=s^n^e,o=r<<5|r>>>27,t=o+a+t+1859775393+u[i+2]<<0,s=s<<30|s>>>2,a=r^s^n,o=t<<5|t>>>27,e=o+a+e+1859775393+u[i+3]<<0,r=r<<30|r>>>2,a=t^r^s,o=e<<5|e>>>27,n=o+a+n+1859775393+u[i+4]<<0,t=t<<30|t>>>2;for(;i<60;i+=5)a=e&t|e&r|t&r,o=n<<5|n>>>27,s=o+a+s-1894007588+u[i]<<0,e=e<<30|e>>>2,a=n&e|n&t|e&t,o=s<<5|s>>>27,r=o+a+r-1894007588+u[i+1]<<0,n=n<<30|n>>>2,a=s&n|s&e|n&e,o=r<<5|r>>>27,t=o+a+t-1894007588+u[i+2]<<0,s=s<<30|s>>>2,a=r&s|r&n|s&n,o=t<<5|t>>>27,e=o+a+e-1894007588+u[i+3]<<0,r=r<<30|r>>>2,a=t&r|t&s|r&s,o=e<<5|e>>>27,n=o+a+n-1894007588+u[i+4]<<0,t=t<<30|t>>>2;for(;i<80;i+=5)a=e^t^r,o=n<<5|n>>>27,s=o+a+s-899497514+u[i]<<0,e=e<<30|e>>>2,a=n^e^t,o=s<<5|s>>>27,r=o+a+r-899497514+u[i+1]<<0,n=n<<30|n>>>2,a=s^n^e,o=r<<5|r>>>27,t=o+a+t-899497514+u[i+2]<<0,s=s<<30|s>>>2,a=r^s^n,o=t<<5|t>>>27,e=o+a+e-899497514+u[i+3]<<0,r=r<<30|r>>>2,a=t^r^s,o=e<<5|e>>>27,n=o+a+n-899497514+u[i+4]<<0,t=t<<30|t>>>2;this.h0=this.h0+n<<0,this.h1=this.h1+e<<0,this.h2=this.h2+t<<0,this.h3=this.h3+r<<0,this.h4=this.h4+s<<0};nt.prototype.hex=function(){this.finalize();var n=this.h0,e=this.h1,t=this.h2,r=this.h3,s=this.h4;return 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[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[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[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[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]};nt.prototype.toString=nt.prototype.hex;nt.prototype.digest=function(){this.finalize();var n=this.h0,e=this.h1,t=this.h2,r=this.h3,s=this.h4;return[n>>24&255,n>>16&255,n>>8&255,n&255,e>>24&255,e>>16&255,e>>8&255,e&255,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24&255,r>>16&255,r>>8&255,r&255,s>>24&255,s>>16&255,s>>8&255,s&255]};nt.prototype.array=nt.prototype.digest;nt.prototype.arrayBuffer=function(){this.finalize();var n=new ArrayBuffer(20),e=new DataView(n);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),n};let Pl=!1;const _w=n=>(Pl||(console.warn(["The default method for hashing keys is insecure and will be replaced in a future version,","but hasn't been replaced yet as to not break existing caches. It's recommended that you use","a more secure hashing algorithm to avoid cache poisoning.","","See this page for more information:","|","└> https://js.langchain.com/docs/troubleshooting/warnings/insecure-cache-algorithm"].join(`
|
|
113
|
+
`)),Pl=!0),new nt(!0).update(n).hex()),bw=(...n)=>_w(n.join("_"));class ww{constructor(){Object.defineProperty(this,"keyEncoder",{enumerable:!0,configurable:!0,writable:!0,value:bw})}makeDefaultKeyEncoder(e){this.keyEncoder=e}}const vw=new Map;class Fo extends ww{constructor(e){super(),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.cache=e??new Map}lookup(e,t){return Promise.resolve(this.cache.get(this.keyEncoder(e,t))??null)}async update(e,t,r){this.cache.set(this.keyEncoder(e,t),r)}static global(){return new Fo(vw)}}class af extends Wt{}class Sw extends af{static lc_name(){return"StringPromptValue"}constructor(e){super({value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.value=e}toString(){return this.value}toChatMessages(){return[new Ns(this.value)]}}class Ew extends af{static lc_name(){return"ChatPromptValue"}constructor(e){Array.isArray(e)&&(e={messages:e}),super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","prompt_values"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"messages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.messages=e.messages}toString(){return mh(this.messages)}toChatMessages(){return this.messages}}var Ir={},Cl;function Ow(){if(Cl)return Ir;Cl=1,Ir.byteLength=o,Ir.toByteArray=c,Ir.fromByteArray=h;for(var n=[],e=[],t=typeof Uint8Array<"u"?Uint8Array:Array,r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",s=0,a=r.length;s<a;++s)n[s]=r[s],e[r.charCodeAt(s)]=s;e[45]=62,e[95]=63;function i(f){var p=f.length;if(p%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var m=f.indexOf("=");m===-1&&(m=p);var g=m===p?0:4-m%4;return[m,g]}function o(f){var p=i(f),m=p[0],g=p[1];return(m+g)*3/4-g}function u(f,p,m){return(p+m)*3/4-m}function c(f){var p,m=i(f),g=m[0],y=m[1],_=new t(u(f,g,y)),b=0,v=y>0?g-4:g,S;for(S=0;S<v;S+=4)p=e[f.charCodeAt(S)]<<18|e[f.charCodeAt(S+1)]<<12|e[f.charCodeAt(S+2)]<<6|e[f.charCodeAt(S+3)],_[b++]=p>>16&255,_[b++]=p>>8&255,_[b++]=p&255;return y===2&&(p=e[f.charCodeAt(S)]<<2|e[f.charCodeAt(S+1)]>>4,_[b++]=p&255),y===1&&(p=e[f.charCodeAt(S)]<<10|e[f.charCodeAt(S+1)]<<4|e[f.charCodeAt(S+2)]>>2,_[b++]=p>>8&255,_[b++]=p&255),_}function l(f){return n[f>>18&63]+n[f>>12&63]+n[f>>6&63]+n[f&63]}function d(f,p,m){for(var g,y=[],_=p;_<m;_+=3)g=(f[_]<<16&16711680)+(f[_+1]<<8&65280)+(f[_+2]&255),y.push(l(g));return y.join("")}function h(f){for(var p,m=f.length,g=m%3,y=[],_=16383,b=0,v=m-g;b<v;b+=_)y.push(d(f,b,b+_>v?v:b+_));return g===1?(p=f[m-1],y.push(n[p>>2]+n[p<<4&63]+"==")):g===2&&(p=(f[m-2]<<8)+f[m-1],y.push(n[p>>10]+n[p>>4&63]+n[p<<2&63]+"=")),y.join("")}return Ir}var xw=Ow();const kw=sn(xw);var Tw=Object.defineProperty,Aw=(n,e,t)=>e in n?Tw(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,Iw=(n,e,t)=>(Aw(n,e+"",t),t);function Rw(n,e){let t=Array.from({length:n.length},(r,s)=>({start:s,end:s+1}));for(;t.length>1;){let r=null;for(let s=0;s<t.length-1;s++){const a=n.slice(t[s].start,t[s+1].end),i=e.get(a.join(","));i!=null&&(r==null||i<r[0])&&(r=[i,s])}if(r!=null){const s=r[1];t[s]={start:t[s].start,end:t[s+1].end},t.splice(s+1,1)}else break}return t}function Pw(n,e){return n.length===1?[e.get(n.join(","))]:Rw(n,e).map(t=>e.get(n.slice(t.start,t.end).join(","))).filter(t=>t!=null)}function Cw(n){return n.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var eo=class{specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(n,e){this.patStr=n.pat_str;const t=n.bpe_ranks.split(`
|
|
114
|
+
`).filter(Boolean).reduce((r,s)=>{const[a,i,...o]=s.split(" "),u=Number.parseInt(i,10);return o.forEach((c,l)=>r[c]=u+l),r},{});for(const[r,s]of Object.entries(t)){const a=kw.toByteArray(r);this.rankMap.set(a.join(","),s),this.textMap.set(s,a)}this.specialTokens={...n.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((r,[s,a])=>(r[a]=this.textEncoder.encode(s),r),{})}encode(n,e=[],t="all"){const r=new RegExp(this.patStr,"ug"),s=eo.specialTokenRegex(Object.keys(this.specialTokens)),a=[],i=new Set(e==="all"?Object.keys(this.specialTokens):e),o=new Set(t==="all"?Object.keys(this.specialTokens).filter(c=>!i.has(c)):t);if(o.size>0){const c=eo.specialTokenRegex([...o]),l=n.match(c);if(l!=null)throw new Error(`The text contains a special token that is not allowed: ${l[0]}`)}let u=0;for(;;){let c=null,l=u;for(;s.lastIndex=l,c=s.exec(n),!(c==null||i.has(c[0]));)l=c.index+1;const d=c?.index??n.length;for(const f of n.substring(u,d).matchAll(r)){const p=this.textEncoder.encode(f[0]),m=this.rankMap.get(p.join(","));if(m!=null){a.push(m);continue}a.push(...Pw(p,this.rankMap))}if(c==null)break;let h=this.specialTokens[c[0]];a.push(h),u=c.index+c[0].length}return a}decode(n){const e=[];let t=0;for(let a=0;a<n.length;++a){const i=n[a],o=this.textMap.get(i)??this.inverseSpecialTokens[i];o!=null&&(e.push(o),t+=o.length)}const r=new Uint8Array(t);let s=0;for(const a of e)r.set(a,s),s+=a.length;return this.textDecoder.decode(r)}},of=eo;Iw(of,"specialTokenRegex",n=>new RegExp(n.map(e=>Cw(e)).join("|"),"g"));function $w(n){switch(n){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 Nn={},Nw=new Lo({});async function jw(n){return n in Nn||(Nn[n]=Nw.fetch(`https://tiktoken.pages.dev/js/${n}.json`).then(e=>e.json()).then(e=>new of(e)).catch(e=>{throw delete Nn[n],e})),await Nn[n]}async function Lw(n){return jw($w(n))}const Mw=n=>n.startsWith("gpt-3.5-turbo-16k")?"gpt-3.5-turbo-16k":n.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":n.startsWith("gpt-4-32k")?"gpt-4-32k":n.startsWith("gpt-4-")?"gpt-4":n.startsWith("gpt-4o")?"gpt-4o":n;function uf(n){return typeof n!="object"||!n?!1:!!("type"in n&&n.type==="function"&&"function"in n&&typeof n.function=="object"&&n.function&&"name"in n.function&&"parameters"in n.function)}const Uw=()=>!1;class Dw extends ve{get lc_attributes(){return{callbacks:void 0,verbose:void 0}}constructor(e){super(e),Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbacks",{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,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=e.verbose??Uw(),this.callbacks=e.callbacks,this.tags=e.tags??[],this.metadata=e.metadata??{}}}class Fw extends Dw{get callKeys(){return["stop","timeout","signal","tags","metadata","callbacks"]}constructor({callbacks:e,callbackManager:t,...r}){const{cache:s,...a}=r;super({callbacks:e??t,...a}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),typeof s=="object"?this.cache=s:s?this.cache=Fo.global():this.cache=void 0,this.caller=new Lo(r??{})}async getNumTokens(e){let t;typeof e=="string"?t=e:t=e.map(s=>typeof s=="string"?s:s.type==="text"&&"text"in s?s.text:"").join("");let r=Math.ceil(t.length/4);if(!this._encoding)try{this._encoding=await Lw("modelName"in this?Mw(this.modelName):"gpt2")}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}if(this._encoding)try{r=this._encoding.encode(t).length}catch(s){console.warn("Failed to calculate number of tokens, falling back to approximate count",s)}return r}static _convertInputToPromptValue(e){return typeof e=="string"?new Sw(e):Array.isArray(e)?new Ew(e.map(Dr)):e}_identifyingParams(){return{}}_getSerializedCacheKeyParametersForCall({config:e,...t}){const r={...this._identifyingParams(),...t,_type:this._llmType(),_model:this._modelType()};return Object.entries(r).filter(([i,o])=>o!==void 0).map(([i,o])=>`${i}:${JSON.stringify(o)}`).sort().join(",")}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(e){throw new Error("Use .toJSON() instead")}}class bs extends ve{static lc_name(){return"RunnablePassthrough"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"func",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),e&&(this.func=e.func)}async invoke(e,t){const r=ne(t);return this.func&&await this.func(e,r),this._callWithConfig(s=>Promise.resolve(s),e,r)}async*transform(e,t){const r=ne(t);let s,a=!0;for await(const i of this._transformStreamWithConfig(e,o=>o,r))if(yield i,a)if(s===void 0)s=i;else try{s=zs(s,i)}catch{s=void 0,a=!1}this.func&&s!==void 0&&await this.func(s,r)}static assign(e){return new sf(new Sr({steps:e}))}}function wi(n){const e=[];for(const t of n){let r=t;if(Array.isArray(t.content))for(let s=0;s<t.content.length;s++){const a=t.content[s];(Vp(a)||Kp(a))&&r===t&&(r=new t.constructor({...r,content:[...t.content.slice(0,s),Xp(a),...t.content.slice(s+1)]}))}e.push(r)}return e}class Tt extends Fw{constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","chat_models",this._llmType()]}),Object.defineProperty(this,"disableStreaming",{enumerable:!0,configurable:!0,writable:!0,value:!1})}_separateRunnableConfigFromCallOptionsCompat(e){const[t,r]=super._separateRunnableConfigFromCallOptions(e);return r.signal=t.signal,[t,r]}async invoke(e,t){const r=Tt._convertInputToPromptValue(e);return(await this.generatePrompt([r],t,t?.callbacks)).generations[0][0].message}async*_streamResponseChunks(e,t,r){throw new Error("Not implemented.")}async*_streamIterator(e,t){if(this._streamResponseChunks===Tt.prototype._streamResponseChunks||this.disableStreaming)yield this.invoke(e,t);else{const s=Tt._convertInputToPromptValue(e).toChatMessages(),[a,i]=this._separateRunnableConfigFromCallOptionsCompat(t),o={...a.metadata,...this.getLsParams(i)},u=await Ue.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),c={options:i,invocation_params:this?.invocationParams(i),batch_size:1},l=await u?.handleChatModelStart(this.toJSON(),[wi(s)],a.runId,void 0,c,void 0,void 0,a.runName);let d,h;try{for await(const f of this._streamResponseChunks(s,i,l?.[0])){if(f.message.id==null){const p=l?.at(0)?.runId;p!=null&&f.message._updateId(`run-${p}`)}f.message.response_metadata={...f.generationInfo,...f.message.response_metadata},yield f.message,d?d=d.concat(f):d=f,Tu(f.message)&&f.message.usage_metadata!==void 0&&(h={tokenUsage:{promptTokens:f.message.usage_metadata.input_tokens,completionTokens:f.message.usage_metadata.output_tokens,totalTokens:f.message.usage_metadata.total_tokens}})}}catch(f){throw await Promise.all((l??[]).map(p=>p?.handleLLMError(f))),f}await Promise.all((l??[]).map(f=>f?.handleLLMEnd({generations:[[d]],llmOutput:h})))}}getLsParams(e){const t=this.getName().startsWith("Chat")?this.getName().replace("Chat",""):this.getName();return{ls_model_type:"chat",ls_stop:e.stop,ls_provider:t}}async _generateUncached(e,t,r,s){const a=e.map(d=>d.map(Dr));let i;if(s!==void 0&&s.length===a.length)i=s;else{const d={...r.metadata,...this.getLsParams(t)},h=await Ue.configure(r.callbacks,this.callbacks,r.tags,this.tags,d,this.metadata,{verbose:this.verbose}),f={options:t,invocation_params:this?.invocationParams(t),batch_size:1};i=await h?.handleChatModelStart(this.toJSON(),a.map(wi),r.runId,void 0,f,void 0,void 0,r.runName)}const o=[],u=[];if(!!i?.[0].handlers.find(S_)&&!this.disableStreaming&&a.length===1&&this._streamResponseChunks!==Tt.prototype._streamResponseChunks)try{const d=await this._streamResponseChunks(a[0],t,i?.[0]);let h,f;for await(const p of d){if(p.message.id==null){const m=i?.at(0)?.runId;m!=null&&p.message._updateId(`run-${m}`)}h===void 0?h=p:h=zs(h,p),Tu(p.message)&&p.message.usage_metadata!==void 0&&(f={tokenUsage:{promptTokens:p.message.usage_metadata.input_tokens,completionTokens:p.message.usage_metadata.output_tokens,totalTokens:p.message.usage_metadata.total_tokens}})}if(h===void 0)throw new Error("Received empty response from chat model call.");o.push([h]),await i?.[0].handleLLMEnd({generations:o,llmOutput:f})}catch(d){throw await i?.[0].handleLLMError(d),d}else{const d=await Promise.allSettled(a.map((h,f)=>this._generate(h,{...t,promptIndex:f},i?.[f])));await Promise.all(d.map(async(h,f)=>{if(h.status==="fulfilled"){const p=h.value;for(const m of p.generations){if(m.message.id==null){const g=i?.at(0)?.runId;g!=null&&m.message._updateId(`run-${g}`)}m.message.response_metadata={...m.generationInfo,...m.message.response_metadata}}return p.generations.length===1&&(p.generations[0].message.response_metadata={...p.llmOutput,...p.generations[0].message.response_metadata}),o[f]=p.generations,u[f]=p.llmOutput,i?.[f]?.handleLLMEnd({generations:[p.generations],llmOutput:p.llmOutput})}else return await i?.[f]?.handleLLMError(h.reason),Promise.reject(h.reason)}))}const l={generations:o,llmOutput:u.length?this._combineLLMOutput?.(...u):void 0};return Object.defineProperty(l,vl,{value:i?{runIds:i?.map(d=>d.runId)}:void 0,configurable:!0}),l}async _generateCached({messages:e,cache:t,llmStringKey:r,parsedOptions:s,handledOptions:a}){const i=e.map(g=>g.map(Dr)),o={...a.metadata,...this.getLsParams(s)},u=await Ue.configure(a.callbacks,this.callbacks,a.tags,this.tags,o,this.metadata,{verbose:this.verbose}),c={options:s,invocation_params:this?.invocationParams(s),batch_size:1},l=await u?.handleChatModelStart(this.toJSON(),i.map(wi),a.runId,void 0,c,void 0,void 0,a.runName),d=[],f=(await Promise.allSettled(i.map(async(g,y)=>{const _=Tt._convertInputToPromptValue(g).toString(),b=await t.lookup(_,r);return b==null&&d.push(y),b}))).map((g,y)=>({result:g,runManager:l?.[y]})).filter(({result:g})=>g.status==="fulfilled"&&g.value!=null||g.status==="rejected"),p=[];await Promise.all(f.map(async({result:g,runManager:y},_)=>{if(g.status==="fulfilled"){const b=g.value;return p[_]=b.map(v=>("message"in v&&Ps(v.message)&&ln(v.message)&&(v.message.usage_metadata={input_tokens:0,output_tokens:0,total_tokens:0}),v.generationInfo={...v.generationInfo,tokenUsage:{}},v)),b.length&&await y?.handleLLMNewToken(b[0].text),y?.handleLLMEnd({generations:[b]},void 0,void 0,void 0,{cached:!0})}else return await y?.handleLLMError(g.reason,void 0,void 0,void 0,{cached:!0}),Promise.reject(g.reason)}));const m={generations:p,missingPromptIndices:d,startedRunManagers:l};return Object.defineProperty(m,vl,{value:l?{runIds:l?.map(g=>g.runId)}:void 0,configurable:!0}),m}async generate(e,t,r){let s;Array.isArray(t)?s={stop:t}:s=t;const a=e.map(p=>p.map(Dr)),[i,o]=this._separateRunnableConfigFromCallOptionsCompat(s);if(i.callbacks=i.callbacks??r,!this.cache)return this._generateUncached(a,o,i);const{cache:u}=this,c=this._getSerializedCacheKeyParametersForCall(o),{generations:l,missingPromptIndices:d,startedRunManagers:h}=await this._generateCached({messages:a,cache:u,llmStringKey:c,parsedOptions:o,handledOptions:i});let f={};if(d.length>0){const p=await this._generateUncached(d.map(m=>a[m]),o,i,h!==void 0?d.map(m=>h?.[m]):void 0);await Promise.all(p.generations.map(async(m,g)=>{const y=d[g];l[y]=m;const _=Tt._convertInputToPromptValue(a[y]).toString();return u.update(_,c,m)})),f=p.llmOutput??{}}return{generations:l,llmOutput:f}}invocationParams(e){return{}}_modelType(){return"base_chat_model"}serialize(){return{...this.invocationParams(),_type:this._llmType(),_model:this._modelType()}}async generatePrompt(e,t,r){const s=e.map(a=>a.toChatMessages());return this.generate(s,t,r)}async call(e,t,r){return(await this.generate([e.map(Dr)],t,r)).generations[0][0].message}async callPrompt(e,t,r){const s=e.toChatMessages();return this.call(s,t,r)}async predictMessages(e,t,r){return this.call(e,t,r)}async predict(e,t,r){const s=new Ns(e),a=await this.call([s],t,r);if(typeof a.content!="string")throw new Error("Cannot use predict when output is not a string.");return a.content}withStructuredOutput(e,t){if(typeof this.bindTools!="function")throw new Error('Chat model must implement ".bindTools()" to use withStructuredOutput.');if(t?.strict)throw new Error('"strict" mode is not supported for this model by default.');const r=e,s=t?.name,a=Uo(r)??"A function available to call.",i=t?.method,o=t?.includeRaw;if(i==="jsonMode")throw new Error('Base withStructuredOutput implementation only supports "functionCalling" as a method.');let u=s??"extract",c;Zt(r)?c=[{type:"function",function:{name:u,description:a,parameters:Rt(r)}}]:("name"in r&&(u=r.name),c=[{type:"function",function:{name:u,description:a,parameters:r}}]);const l=this.bindTools(c),d=Er.from(m=>{if(!m.tool_calls||m.tool_calls.length===0)throw new Error("No tool calls found in the response.");const g=m.tool_calls.find(y=>y.name===u);if(!g)throw new Error(`No tool call found with name ${u}.`);return g.args});if(!o)return l.pipe(d).withConfig({runName:"StructuredOutput"});const h=bs.assign({parsed:(m,g)=>d.invoke(m.raw,g)}),f=bs.assign({parsed:()=>null}),p=h.withFallbacks({fallbacks:[f]});return _t.from([{raw:l},p]).withConfig({runName:"StructuredOutputRunnable"})}}class Bw extends ve{parseResultWithPrompt(e,t,r){return this.parseResult(e,r)}_baseMessageToString(e){return typeof e.content=="string"?e.content:this._baseMessageContentToString(e.content)}_baseMessageContentToString(e){return JSON.stringify(e)}async invoke(e,t){return typeof e=="string"?this._callWithConfig(async(r,s)=>this.parseResult([{text:r}],s?.callbacks),e,{...t,runType:"parser"}):this._callWithConfig(async(r,s)=>this.parseResult([{message:r,text:this._baseMessageToString(r)}],s?.callbacks),e,{...t,runType:"parser"})}}class cf extends Bw{parseResult(e,t){return this.parse(e[0].text,t)}async parseWithPrompt(e,t,r){return this.parse(e,r)}_type(){throw new Error("_type not implemented")}}class Bo extends Error{constructor(e,t,r,s=!1){if(super(e),Object.defineProperty(this,"llmOutput",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"observation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"sendToLLM",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.llmOutput=t,this.observation=r,this.sendToLLM=s,s&&(r===void 0||t===void 0))throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true");fh(this,"OUTPUT_PARSING_FAILURE")}}class zw extends cf{async*_transform(e){for await(const t of e)typeof t=="string"?yield this.parseResult([{text:t}]):yield this.parseResult([{message:t,text:this._baseMessageToString(t)}])}async*transform(e,t){yield*this._transformStreamWithConfig(e,this._transform.bind(this),{...t,runType:"parser"})}}class lf extends zw{constructor(e){super(e),Object.defineProperty(this,"diff",{enumerable:!0,configurable:!0,writable:!0,value:!1}),this.diff=e?.diff??this.diff}async*_transform(e){let t,r;for await(const s of e){if(typeof s!="string"&&typeof s.content!="string")throw new Error("Cannot handle non-string output.");let a;if(rm(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new Xt({message:s,text:s.content})}else if(Ps(s)){if(typeof s.content!="string")throw new Error("Cannot handle non-string message output.");a=new Xt({message:cm(s),text:s.content})}else a=new gr({text:s});r===void 0?r=a:r=r.concat(a);const i=await this.parsePartialResult([r]);i!=null&&!Ki(i,t)&&(this.diff?yield this._diff(t,i):yield i,t=i)}}getFormatInstructions(){return""}}class $l extends cf{static lc_name(){return"StructuredOutputParser"}toJSON(){return this.toJSONNotImplemented()}constructor(e){super(e),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","structured"]})}static fromZodSchema(e){return new this(e)}static fromNamesAndDescriptions(e){const t=wh(Object.fromEntries(Object.entries(e).map(([r,s])=>[r,bh().describe(s)])));return new this(t)}getFormatInstructions(){return`You must format your output as a JSON value that adheres to a given "JSON Schema" instance.
|
|
115
|
+
|
|
116
|
+
"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents.
|
|
117
|
+
|
|
118
|
+
For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}}
|
|
119
|
+
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.
|
|
120
|
+
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.
|
|
121
|
+
|
|
122
|
+
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!
|
|
123
|
+
|
|
124
|
+
Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock:
|
|
125
|
+
\`\`\`json
|
|
126
|
+
${JSON.stringify(Rt(this.schema))}
|
|
127
|
+
\`\`\`
|
|
128
|
+
`}async parse(e){try{const t=e.trim(),s=(t.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1]||t.match(/```json\s*([\s\S]*?)```/)?.[1]||t).replace(/"([^"\\]*(\\.[^"\\]*)*)"/g,(a,i)=>`"${i.replace(/\n/g,"\\n")}"`).replace(/\n/g,"");return await tf(this.schema,JSON.parse(s))}catch(t){throw new Bo(`Failed to parse. Text: "${e}". Error: ${t}`,e)}}}class Nl extends lf{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","output_parsers"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0})}static lc_name(){return"JsonOutputParser"}_concatOutputChunks(e,t){return this.diff?super._concatOutputChunks(e,t):t}_diff(e,t){if(t)return e?rg(e,t):[{op:"replace",path:"",value:t}]}async parsePartialResult(e){return vu(e[0].text)}async parse(e){return vu(e,JSON.parse)}getFormatInstructions(){return""}}function zo(n,e){if(n.function===void 0)return;let t;if(e?.partial)try{t=Oo(n.function.arguments??"{}")}catch{return}else try{t=JSON.parse(n.function.arguments)}catch(s){throw new Bo([`Function "${n.function.name}" arguments:`,"",n.function.arguments,"","are not valid JSON.",`Error: ${s.message}`].join(`
|
|
129
|
+
`))}const r={name:n.function.name,args:t,type:"tool_call"};return e?.returnId&&(r.id=n.id),r}function qw(n){if(n.id===void 0)throw new Error('All OpenAI tool calls must have an "id" field.');return{id:n.id,type:"function",function:{name:n.name,arguments:JSON.stringify(n.args)}}}function to(n,e){return{name:n.function?.name,args:n.function?.arguments,id:n.id,error:e,type:"invalid_tool_call"}}class Zw extends lf{static lc_name(){return"JsonOutputToolsParser"}constructor(e){super(e),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.returnId=e?.returnId??this.returnId}_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,t=!0){const r=e[0].message;let s;if(ln(r)&&r.tool_calls?.length?s=r.tool_calls.map(i=>{const{id:o,...u}=i;return this.returnId?{id:o,...u}:u}):r.additional_kwargs.tool_calls!==void 0&&(s=JSON.parse(JSON.stringify(r.additional_kwargs.tool_calls)).map(o=>zo(o,{returnId:this.returnId,partial:t}))),!s)return[];const a=[];for(const i of s)if(i!==void 0){const o={type:i.name,args:i.args,id:i.id};a.push(o)}return a}}class jl extends Zw{static lc_name(){return"JsonOutputKeyToolsParser"}constructor(e){super(e),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","output_parsers","openai_tools"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"returnId",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"keyName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"returnSingle",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"zodSchema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keyName=e.keyName,this.returnSingle=e.returnSingle??this.returnSingle,this.zodSchema=e.zodSchema}async _validateResult(e){if(this.zodSchema===void 0)return e;const t=await sw(this.zodSchema,e);if(t.success)return t.data;throw new Bo(`Failed to parse. Text: "${JSON.stringify(e,null,2)}". Error: ${JSON.stringify(t.error?.issues)}`,JSON.stringify(e,null,2))}async parsePartialResult(e){const r=(await super.parsePartialResult(e)).filter(a=>a.type===this.keyName);let s=r;if(r.length)return this.returnId||(s=r.map(a=>a.args)),this.returnSingle?s[0]:s}async parseResult(e){const r=(await super.parsePartialResult(e,!1)).filter(i=>i.type===this.keyName);let s=r;return r.length?(this.returnId||(s=r.map(i=>i.args)),this.returnSingle?this._validateResult(s[0]):await Promise.all(s.map(i=>this._validateResult(i)))):void 0}}function Hw(n){const{azureOpenAIApiDeploymentName:e,azureOpenAIApiInstanceName:t,azureOpenAIApiKey:r,azureOpenAIBasePath:s,baseURL:a,azureADTokenProvider:i,azureOpenAIEndpoint:o}=n;if((r||i)&&s&&e)return`${s}/${e}`;if((r||i)&&o&&e)return`${o}/openai/deployments/${e}`;if(r||i){if(!t)throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey");if(!e)throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey");return`https://${t}.openai.azure.com/openai/deployments/${e}`}return a}function Gw(n){return n!==void 0&&Array.isArray(n.lc_namespace)}function Jw(n){return n!==void 0&&ve.isRunnable(n)&&"lc_name"in n.constructor&&typeof n.constructor.lc_name=="function"&&n.constructor.lc_name()==="RunnableToolLike"}function Ww(n){return!!n&&typeof n=="object"&&"name"in n&&"schema"in n&&(Zt(n.schema)||n.schema!=null&&typeof n.schema=="object"&&"type"in n.schema&&typeof n.schema.type=="string"&&["null","boolean","object","array","number","string"].includes(n.schema.type))}function df(n){return Ww(n)||Jw(n)||Gw(n)}function Vw(n,e){return{name:n.name,description:n.description,parameters:Rt(n.schema)}}function Kw(n,e){let t;return df(n)?t={type:"function",function:Vw(n)}:t=n,t}function Xw(n,e,t){function r(o,u){var c;Object.defineProperty(o,"_zod",{value:o._zod??{},enumerable:!1}),(c=o._zod).traits??(c.traits=new Set),o._zod.traits.add(n),e(o,u);for(const l in i.prototype)l in o||Object.defineProperty(o,l,{value:i.prototype[l].bind(o)});o._zod.constr=i,o._zod.def=u}const s=t?.Parent??Object;class a extends s{}Object.defineProperty(a,"name",{value:n});function i(o){var u;const c=t?.Parent?new a:this;r(c,o),(u=c._zod).deferred??(u.deferred=[]);for(const l of c._zod.deferred)l();return c}return Object.defineProperty(i,"init",{value:r}),Object.defineProperty(i,Symbol.hasInstance,{value:o=>t?.Parent&&o instanceof t.Parent?!0:o?._zod?.traits?.has(n)}),Object.defineProperty(i,"name",{value:n}),i}class Qw extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}const Yw={};function ev(n){return Yw}function tv(n){const e=Object.values(n).filter(r=>typeof r=="number");return Object.entries(n).filter(([r,s])=>e.indexOf(+r)===-1).map(([r,s])=>s)}function rv(n,e){return typeof e=="bigint"?e.toString():e}const nv=Error.captureStackTrace?Error.captureStackTrace:(...n)=>{};function jn(n){return typeof n=="string"?n:n?.message}function sv(n,e,t){const r={...n,path:n.path??[]};if(!n.message){const s=jn(n.inst?._zod.def?.error?.(n))??jn(e?.error?.(n))??jn(t.customError?.(n))??jn(t.localeError?.(n))??"Invalid input";r.message=s}return delete r.inst,delete r.continue,e?.reportInput||delete r.input,r}const av=(n,e)=>{n.name="$ZodError",Object.defineProperty(n,"_zod",{value:n._zod,enumerable:!1}),Object.defineProperty(n,"issues",{value:e,enumerable:!1}),Object.defineProperty(n,"message",{get(){return JSON.stringify(e,rv,2)},enumerable:!0}),Object.defineProperty(n,"toString",{value:()=>n.message,enumerable:!1})},iv=Xw("$ZodError",av,{Parent:Error}),ov=n=>(e,t,r,s)=>{const a=r?Object.assign(r,{async:!1}):{async:!1},i=e._zod.run({value:t,issues:[]},a);if(i instanceof Promise)throw new Qw;if(i.issues.length){const o=new(s?.Err??n)(i.issues.map(u=>sv(u,a,ev())));throw nv(o,s?.callee),o}return i.value},uv=ov(iv);class hf{constructor(){this._map=new Map,this._idmap=new Map}add(e,...t){const r=t[0];if(this._map.set(e,r),r&&typeof r=="object"&&"id"in r){if(this._idmap.has(r.id))throw new Error(`ID ${r.id} already exists in the registry`);this._idmap.set(r.id,e)}return this}clear(){return this._map=new Map,this._idmap=new Map,this}remove(e){const t=this._map.get(e);return t&&typeof t=="object"&&"id"in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){const t=e._zod.parent;if(t){const r={...this.get(t)??{}};return delete r.id,{...r,...this._map.get(e)}}return this._map.get(e)}has(e){return this._map.has(e)}}function cv(){return new hf}const lv=cv();class Ll{constructor(e){this.counter=0,this.metadataRegistry=e?.metadata??lv,this.target=e?.target??"draft-2020-12",this.unrepresentable=e?.unrepresentable??"throw",this.override=e?.override??(()=>{}),this.io=e?.io??"output",this.seen=new Map}process(e,t={path:[],schemaPath:[]}){var r;const s=e._zod.def,a={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},i=this.seen.get(e);if(i)return i.count++,t.schemaPath.includes(e)&&(i.cycle=t.path),i.schema;const o={schema:{},count:1,cycle:void 0,path:t.path};this.seen.set(e,o);const u=e._zod.toJSONSchema?.();if(u)o.schema=u;else{const d={...t,schemaPath:[...t.schemaPath,e],path:t.path},h=e._zod.parent;if(h)o.ref=h,this.process(h,d),this.seen.get(h).isParent=!0;else{const f=o.schema;switch(s.type){case"string":{const p=f;p.type="string";const{minimum:m,maximum:g,format:y,patterns:_,contentEncoding:b}=e._zod.bag;if(typeof m=="number"&&(p.minLength=m),typeof g=="number"&&(p.maxLength=g),y&&(p.format=a[y]??y,p.format===""&&delete p.format),b&&(p.contentEncoding=b),_&&_.size>0){const v=[..._];v.length===1?p.pattern=v[0].source:v.length>1&&(o.schema.allOf=[...v.map(S=>({...this.target==="draft-7"?{type:"string"}:{},pattern:S.source}))])}break}case"number":{const p=f,{minimum:m,maximum:g,format:y,multipleOf:_,exclusiveMaximum:b,exclusiveMinimum:v}=e._zod.bag;typeof y=="string"&&y.includes("int")?p.type="integer":p.type="number",typeof v=="number"&&(p.exclusiveMinimum=v),typeof m=="number"&&(p.minimum=m,typeof v=="number"&&(v>=m?delete p.minimum:delete p.exclusiveMinimum)),typeof b=="number"&&(p.exclusiveMaximum=b),typeof g=="number"&&(p.maximum=g,typeof b=="number"&&(b<=g?delete p.maximum:delete p.exclusiveMaximum)),typeof _=="number"&&(p.multipleOf=_);break}case"boolean":{const p=f;p.type="boolean";break}case"bigint":{if(this.unrepresentable==="throw")throw new Error("BigInt cannot be represented in JSON Schema");break}case"symbol":{if(this.unrepresentable==="throw")throw new Error("Symbols cannot be represented in JSON Schema");break}case"null":{f.type="null";break}case"any":break;case"unknown":break;case"undefined":{if(this.unrepresentable==="throw")throw new Error("Undefined cannot be represented in JSON Schema");break}case"void":{if(this.unrepresentable==="throw")throw new Error("Void cannot be represented in JSON Schema");break}case"never":{f.not={};break}case"date":{if(this.unrepresentable==="throw")throw new Error("Date cannot be represented in JSON Schema");break}case"array":{const p=f,{minimum:m,maximum:g}=e._zod.bag;typeof m=="number"&&(p.minItems=m),typeof g=="number"&&(p.maxItems=g),p.type="array",p.items=this.process(s.element,{...d,path:[...d.path,"items"]});break}case"object":{const p=f;p.type="object",p.properties={};const m=s.shape;for(const _ in m)p.properties[_]=this.process(m[_],{...d,path:[...d.path,"properties",_]});const g=new Set(Object.keys(m)),y=new Set([...g].filter(_=>{const b=s.shape[_]._zod;return this.io==="input"?b.optin===void 0:b.optout===void 0}));y.size>0&&(p.required=Array.from(y)),s.catchall?._zod.def.type==="never"?p.additionalProperties=!1:s.catchall?s.catchall&&(p.additionalProperties=this.process(s.catchall,{...d,path:[...d.path,"additionalProperties"]})):this.io==="output"&&(p.additionalProperties=!1);break}case"union":{const p=f;p.anyOf=s.options.map((m,g)=>this.process(m,{...d,path:[...d.path,"anyOf",g]}));break}case"intersection":{const p=f,m=this.process(s.left,{...d,path:[...d.path,"allOf",0]}),g=this.process(s.right,{...d,path:[...d.path,"allOf",1]}),y=b=>"allOf"in b&&Object.keys(b).length===1,_=[...y(m)?m.allOf:[m],...y(g)?g.allOf:[g]];p.allOf=_;break}case"tuple":{const p=f;p.type="array";const m=s.items.map((_,b)=>this.process(_,{...d,path:[...d.path,"prefixItems",b]}));if(this.target==="draft-2020-12"?p.prefixItems=m:p.items=m,s.rest){const _=this.process(s.rest,{...d,path:[...d.path,"items"]});this.target==="draft-2020-12"?p.items=_:p.additionalItems=_}s.rest&&(p.items=this.process(s.rest,{...d,path:[...d.path,"items"]}));const{minimum:g,maximum:y}=e._zod.bag;typeof g=="number"&&(p.minItems=g),typeof y=="number"&&(p.maxItems=y);break}case"record":{const p=f;p.type="object",p.propertyNames=this.process(s.keyType,{...d,path:[...d.path,"propertyNames"]}),p.additionalProperties=this.process(s.valueType,{...d,path:[...d.path,"additionalProperties"]});break}case"map":{if(this.unrepresentable==="throw")throw new Error("Map cannot be represented in JSON Schema");break}case"set":{if(this.unrepresentable==="throw")throw new Error("Set cannot be represented in JSON Schema");break}case"enum":{const p=f,m=tv(s.entries);m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),p.enum=m;break}case"literal":{const p=f,m=[];for(const g of s.values)if(g===void 0){if(this.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof g=="bigint"){if(this.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");m.push(Number(g))}else m.push(g);if(m.length!==0)if(m.length===1){const g=m[0];p.type=g===null?"null":typeof g,p.const=g}else m.every(g=>typeof g=="number")&&(p.type="number"),m.every(g=>typeof g=="string")&&(p.type="string"),m.every(g=>typeof g=="boolean")&&(p.type="string"),m.every(g=>g===null)&&(p.type="null"),p.enum=m;break}case"file":{const p=f,m={type:"string",format:"binary",contentEncoding:"binary"},{minimum:g,maximum:y,mime:_}=e._zod.bag;g!==void 0&&(m.minLength=g),y!==void 0&&(m.maxLength=y),_?_.length===1?(m.contentMediaType=_[0],Object.assign(p,m)):p.anyOf=_.map(b=>({...m,contentMediaType:b})):Object.assign(p,m);break}case"transform":{if(this.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema");break}case"nullable":{const p=this.process(s.innerType,d);f.anyOf=[p,{type:"null"}];break}case"nonoptional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"success":{const p=f;p.type="boolean";break}case"default":{this.process(s.innerType,d),o.ref=s.innerType,f.default=JSON.parse(JSON.stringify(s.defaultValue));break}case"prefault":{this.process(s.innerType,d),o.ref=s.innerType,this.io==="input"&&(f._prefault=JSON.parse(JSON.stringify(s.defaultValue)));break}case"catch":{this.process(s.innerType,d),o.ref=s.innerType;let p;try{p=s.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}f.default=p;break}case"nan":{if(this.unrepresentable==="throw")throw new Error("NaN cannot be represented in JSON Schema");break}case"template_literal":{const p=f,m=e._zod.pattern;if(!m)throw new Error("Pattern not found in template literal");p.type="string",p.pattern=m.source;break}case"pipe":{const p=this.io==="input"?s.in._zod.def.type==="transform"?s.out:s.in:s.out;this.process(p,d),o.ref=p;break}case"readonly":{this.process(s.innerType,d),o.ref=s.innerType,f.readOnly=!0;break}case"promise":{this.process(s.innerType,d),o.ref=s.innerType;break}case"optional":{this.process(s.innerType,d),o.ref=s.innerType;break}case"lazy":{const p=e._zod.innerType;this.process(p,d),o.ref=p;break}case"custom":{if(this.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema");break}}}}const c=this.metadataRegistry.get(e);return c&&Object.assign(o.schema,c),this.io==="input"&&me(e)&&(delete o.schema.examples,delete o.schema.default),this.io==="input"&&o.schema._prefault&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,this.seen.get(e).schema}emit(e,t){const r={cycles:t?.cycles??"ref",reused:t?.reused??"inline",external:t?.external??void 0},s=this.seen.get(e);if(!s)throw new Error("Unprocessed schema. This is a bug in Zod.");const a=l=>{const d=this.target==="draft-2020-12"?"$defs":"definitions";if(r.external){const m=r.external.registry.get(l[0])?.id,g=r.external.uri??(_=>_);if(m)return{ref:g(m)};const y=l[1].defId??l[1].schema.id??`schema${this.counter++}`;return l[1].defId=y,{defId:y,ref:`${g("__shared")}#/${d}/${y}`}}if(l[1]===s)return{ref:"#"};const f=`#/${d}/`,p=l[1].schema.id??`__schema${this.counter++}`;return{defId:p,ref:f+p}},i=l=>{if(l[1].schema.$ref)return;const d=l[1],{ref:h,defId:f}=a(l);d.def={...d.schema},f&&(d.defId=f);const p=d.schema;for(const m in p)delete p[m];p.$ref=h};if(r.cycles==="throw")for(const l of this.seen.entries()){const d=l[1];if(d.cycle)throw new Error(`Cycle detected: #/${d.cycle?.join("/")}/<root>
|
|
130
|
+
|
|
131
|
+
Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const l of this.seen.entries()){const d=l[1];if(e===l[0]){i(l);continue}if(r.external){const f=r.external.registry.get(l[0])?.id;if(e!==l[0]&&f){i(l);continue}}if(this.metadataRegistry.get(l[0])?.id){i(l);continue}if(d.cycle){i(l);continue}if(d.count>1&&r.reused==="ref"){i(l);continue}}const o=(l,d)=>{const h=this.seen.get(l),f=h.def??h.schema,p={...f};if(h.ref===null)return;const m=h.ref;if(h.ref=null,m){o(m,d);const g=this.seen.get(m).schema;g.$ref&&d.target==="draft-7"?(f.allOf=f.allOf??[],f.allOf.push(g)):(Object.assign(f,g),Object.assign(f,p))}h.isParent||this.override({zodSchema:l,jsonSchema:f,path:h.path??[]})};for(const l of[...this.seen.entries()].reverse())o(l[0],{target:this.target});const u={};if(this.target==="draft-2020-12"?u.$schema="https://json-schema.org/draft/2020-12/schema":this.target==="draft-7"?u.$schema="http://json-schema.org/draft-07/schema#":console.warn(`Invalid target: ${this.target}`),r.external?.uri){const l=r.external.registry.get(e)?.id;if(!l)throw new Error("Schema is missing an `id` property");u.$id=r.external.uri(l)}Object.assign(u,s.def);const c=r.external?.defs??{};for(const l of this.seen.entries()){const d=l[1];d.def&&d.defId&&(c[d.defId]=d.def)}r.external||Object.keys(c).length>0&&(this.target==="draft-2020-12"?u.$defs=c:u.definitions=c);try{return JSON.parse(JSON.stringify(u))}catch{throw new Error("Error converting schema to JSON.")}}}function dv(n,e){if(n instanceof hf){const r=new Ll(e),s={};for(const o of n._idmap.entries()){const[u,c]=o;r.process(c)}const a={},i={registry:n,uri:e?.uri,defs:s};for(const o of n._idmap.entries()){const[u,c]=o;a[u]=r.emit(c,{...e,external:i})}if(Object.keys(s).length>0){const o=r.target==="draft-2020-12"?"$defs":"definitions";a.__shared={[o]:s}}return{schemas:a}}const t=new Ll(e);return t.process(n),t.emit(n,e)}function me(n,e){const t=e??{seen:new Set};if(t.seen.has(n))return!1;t.seen.add(n);const s=n._zod.def;switch(s.type){case"string":case"number":case"bigint":case"boolean":case"date":case"symbol":case"undefined":case"null":case"any":case"unknown":case"never":case"void":case"literal":case"enum":case"nan":case"file":case"template_literal":return!1;case"array":return me(s.element,t);case"object":{for(const a in s.shape)if(me(s.shape[a],t))return!0;return!1}case"union":{for(const a of s.options)if(me(a,t))return!0;return!1}case"intersection":return me(s.left,t)||me(s.right,t);case"tuple":{for(const a of s.items)if(me(a,t))return!0;return!!(s.rest&&me(s.rest,t))}case"record":return me(s.keyType,t)||me(s.valueType,t);case"map":return me(s.keyType,t)||me(s.valueType,t);case"set":return me(s.valueType,t);case"promise":case"optional":case"nonoptional":case"nullable":case"readonly":return me(s.innerType,t);case"lazy":return me(s.getter(),t);case"default":return me(s.innerType,t);case"prefault":return me(s.innerType,t);case"custom":return!1;case"transform":return!0;case"pipe":return me(s.in,t)||me(s.out,t);case"success":return!1;case"catch":return!1}throw new Error(`Unknown schema type: ${s.type}`)}const hv=Symbol("Let zodToJsonSchema decide on which parser to use"),Ml={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"},fv=n=>typeof n=="string"?{...Ml,basePath:["#"],definitions:{},name:n}:{...Ml,basePath:["#"],definitions:{},...n},ro=n=>"_def"in n?n._def:n;function pv(n){if(!n)return!0;for(const e in n)return!1;return!0}const mv=n=>{const e=fv(n),t=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,currentPath:t,propertyPath:void 0,seenRefs:new Set,seen:new Map(Object.entries(e.definitions).map(([r,s])=>[ro(s),{def:ro(s),path:[...e.basePath,e.definitionPath,r],jsonSchema:void 0}]))}};function ff(n,e,t,r){r?.errorMessages&&t&&(n.errorMessage={...n.errorMessage,[e]:t})}function oe(n,e,t,r,s){n[e]=t,ff(n,e,r,s)}var G;(function(n){n.ZodString="ZodString",n.ZodNumber="ZodNumber",n.ZodNaN="ZodNaN",n.ZodBigInt="ZodBigInt",n.ZodBoolean="ZodBoolean",n.ZodDate="ZodDate",n.ZodSymbol="ZodSymbol",n.ZodUndefined="ZodUndefined",n.ZodNull="ZodNull",n.ZodAny="ZodAny",n.ZodUnknown="ZodUnknown",n.ZodNever="ZodNever",n.ZodVoid="ZodVoid",n.ZodArray="ZodArray",n.ZodObject="ZodObject",n.ZodUnion="ZodUnion",n.ZodDiscriminatedUnion="ZodDiscriminatedUnion",n.ZodIntersection="ZodIntersection",n.ZodTuple="ZodTuple",n.ZodRecord="ZodRecord",n.ZodMap="ZodMap",n.ZodSet="ZodSet",n.ZodFunction="ZodFunction",n.ZodLazy="ZodLazy",n.ZodLiteral="ZodLiteral",n.ZodEnum="ZodEnum",n.ZodEffects="ZodEffects",n.ZodNativeEnum="ZodNativeEnum",n.ZodOptional="ZodOptional",n.ZodNullable="ZodNullable",n.ZodDefault="ZodDefault",n.ZodCatch="ZodCatch",n.ZodPromise="ZodPromise",n.ZodBranded="ZodBranded",n.ZodPipeline="ZodPipeline",n.ZodReadonly="ZodReadonly"})(G||(G={}));function gv(){return{}}function yv(n,e){const t={type:"array"};return n.type?._def?.typeName!==G.ZodAny&&(t.items=te(n.type._def,{...e,currentPath:[...e.currentPath,"items"]})),n.minLength&&oe(t,"minItems",n.minLength.value,n.minLength.message,e),n.maxLength&&oe(t,"maxItems",n.maxLength.value,n.maxLength.message,e),n.exactLength&&(oe(t,"minItems",n.exactLength.value,n.exactLength.message,e),oe(t,"maxItems",n.exactLength.value,n.exactLength.message,e)),t}function _v(n,e){const t={type:"integer",format:"int64"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"min":e.target==="jsonSchema7"?r.inclusive?oe(t,"minimum",r.value,r.message,e):oe(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),oe(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?oe(t,"maximum",r.value,r.message,e):oe(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),oe(t,"maximum",r.value,r.message,e));break;case"multipleOf":oe(t,"multipleOf",r.value,r.message,e);break}return t}function bv(){return{type:"boolean"}}function wv(n,e){return te(n.type._def,e)}const vv=(n,e)=>te(n.innerType._def,e);function pf(n,e,t){const r=t??e.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((s,a)=>pf(n,e,s))};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 Sv(n,e)}}const Sv=(n,e)=>{const t={type:"integer",format:"unix-time"};if(e.target==="openApi3")return t;for(const r of n.checks)switch(r.kind){case"min":oe(t,"minimum",r.value,r.message,e);break;case"max":oe(t,"maximum",r.value,r.message,e);break}return t};function Ev(n,e){return{...te(n.innerType._def,e),default:n.defaultValue()}}function Ov(n,e,t){return e.effectStrategy==="input"?te(n.schema._def,e,t):{}}function xv(n){return{type:"string",enum:[...n.values]}}const kv=n=>"type"in n&&n.type==="string"?!1:"allOf"in n;function Tv(n,e){const t=[te(n.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),te(n.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(a=>!!a);let r=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0;const s=[];return t.forEach(a=>{if(kv(a))s.push(...a.allOf),a.unevaluatedProperties===void 0&&(r=void 0);else{let i=a;if("additionalProperties"in a&&a.additionalProperties===!1){const{additionalProperties:o,...u}=a;i=u}else r=void 0;s.push(i)}}),s.length?{allOf:s,...r}:void 0}function Av(n,e){const t=typeof n.value;return t!=="bigint"&&t!=="number"&&t!=="boolean"&&t!=="string"?{type:Array.isArray(n.value)?"array":"object"}:e.target==="openApi3"?{type:t==="bigint"?"integer":t,enum:[n.value]}:{type:t==="bigint"?"integer":t,const:n.value}}let vi;const Dt={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:()=>(vi===void 0&&(vi=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),vi),base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/};function mf(n,e){const t={type:"string"};function r(s){return e.patternStrategy==="escape"?Iv(s):s}if(n.checks)for(const s of n.checks)switch(s.kind){case"min":oe(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e);break;case"max":oe(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"email":switch(e.emailStrategy){case"format:email":Ye(t,"email",s.message,e);break;case"format:idn-email":Ye(t,"idn-email",s.message,e);break;case"pattern:zod":et(t,Dt.email,s.message,e);break}break;case"url":Ye(t,"uri",s.message,e);break;case"uuid":Ye(t,"uuid",s.message,e);break;case"regex":et(t,s.regex,s.message,e);break;case"cuid":et(t,Dt.cuid,s.message,e);break;case"cuid2":et(t,Dt.cuid2,s.message,e);break;case"startsWith":et(t,RegExp(`^${r(s.value)}`),s.message,e);break;case"endsWith":et(t,RegExp(`${r(s.value)}$`),s.message,e);break;case"datetime":Ye(t,"date-time",s.message,e);break;case"date":Ye(t,"date",s.message,e);break;case"time":Ye(t,"time",s.message,e);break;case"duration":Ye(t,"duration",s.message,e);break;case"length":oe(t,"minLength",typeof t.minLength=="number"?Math.max(t.minLength,s.value):s.value,s.message,e),oe(t,"maxLength",typeof t.maxLength=="number"?Math.min(t.maxLength,s.value):s.value,s.message,e);break;case"includes":{et(t,RegExp(r(s.value)),s.message,e);break}case"ip":{s.version!=="v6"&&Ye(t,"ipv4",s.message,e),s.version!=="v4"&&Ye(t,"ipv6",s.message,e);break}case"emoji":et(t,Dt.emoji,s.message,e);break;case"ulid":{et(t,Dt.ulid,s.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{Ye(t,"binary",s.message,e);break}case"contentEncoding:base64":{oe(t,"contentEncoding","base64",s.message,e);break}case"pattern:zod":{et(t,Dt.base64,s.message,e);break}}break}case"nanoid":et(t,Dt.nanoid,s.message,e)}return t}const Iv=n=>Array.from(n).map(e=>/[a-zA-Z0-9]/.test(e)?e:`\\${e}`).join(""),Ye=(n,e,t,r)=>{n.format||n.anyOf?.some(s=>s.format)?(n.anyOf||(n.anyOf=[]),n.format&&(n.anyOf.push({format:n.format,...n.errorMessage&&r.errorMessages&&{errorMessage:{format:n.errorMessage.format}}}),delete n.format,n.errorMessage&&(delete n.errorMessage.format,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.anyOf.push({format:e,...t&&r.errorMessages&&{errorMessage:{format:t}}})):oe(n,"format",e,t,r)},et=(n,e,t,r)=>{n.pattern||n.allOf?.some(s=>s.pattern)?(n.allOf||(n.allOf=[]),n.pattern&&(n.allOf.push({pattern:n.pattern,...n.errorMessage&&r.errorMessages&&{errorMessage:{pattern:n.errorMessage.pattern}}}),delete n.pattern,n.errorMessage&&(delete n.errorMessage.pattern,Object.keys(n.errorMessage).length===0&&delete n.errorMessage)),n.allOf.push({pattern:Ul(e,r),...t&&r.errorMessages&&{errorMessage:{pattern:t}}})):oe(n,"pattern",Ul(e,r),t,r)},Ul=(n,e)=>{const t=typeof n=="function"?n():n;if(!e.applyRegexFlags||!t.flags)return t.source;const r={i:t.flags.includes("i"),m:t.flags.includes("m"),s:t.flags.includes("s")},s=r.i?t.source.toLowerCase():t.source;let a="",i=!1,o=!1,u=!1;for(let c=0;c<s.length;c++){if(i){a+=s[c],i=!1;continue}if(r.i){if(o){if(s[c].match(/[a-z]/)){u?(a+=s[c],a+=`${s[c-2]}-${s[c]}`.toUpperCase(),u=!1):s[c+1]==="-"&&s[c+2]?.match(/[a-z]/)?(a+=s[c],u=!0):a+=`${s[c]}${s[c].toUpperCase()}`;continue}}else if(s[c].match(/[a-z]/)){a+=`[${s[c]}${s[c].toUpperCase()}]`;continue}}if(r.m){if(s[c]==="^"){a+=`(^|(?<=[\r
|
|
132
|
+
]))`;continue}else if(s[c]==="$"){a+=`($|(?=[\r
|
|
133
|
+
]))`;continue}}if(r.s&&s[c]==="."){a+=o?`${s[c]}\r
|
|
134
|
+
`:`[${s[c]}\r
|
|
135
|
+
]`;continue}a+=s[c],s[c]==="\\"?i=!0:o&&s[c]==="]"?o=!1:!o&&s[c]==="["&&(o=!0)}try{const c=new RegExp(a)}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 a};function gf(n,e){if(e.target==="openApi3"&&n.keyType?._def.typeName===G.ZodEnum)return{type:"object",required:n.keyType._def.values,properties:n.keyType._def.values.reduce((r,s)=>({...r,[s]:te(n.valueType._def,{...e,currentPath:[...e.currentPath,"properties",s]})??{}}),{}),additionalProperties:!1};const t={type:"object",additionalProperties:te(n.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??{}};if(e.target==="openApi3")return t;if(n.keyType?._def.typeName===G.ZodString&&n.keyType._def.checks?.length){const r=Object.entries(mf(n.keyType._def,e)).reduce((s,[a,i])=>a==="type"?s:{...s,[a]:i},{});return{...t,propertyNames:r}}else if(n.keyType?._def.typeName===G.ZodEnum)return{...t,propertyNames:{enum:n.keyType._def.values}};return t}function Rv(n,e){if(e.mapStrategy==="record")return gf(n,e);const t=te(n.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||{},r=te(n.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[t,r],minItems:2,maxItems:2}}}function Pv(n){const e=n.values,r=Object.keys(n.values).filter(a=>typeof e[e[a]]!="number").map(a=>e[a]),s=Array.from(new Set(r.map(a=>typeof a)));return{type:s.length===1?s[0]==="string"?"string":"number":["string","number"],enum:r}}function Cv(){return{not:{}}}function $v(n){return n.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}const ws={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function Nv(n,e){if(e.target==="openApi3")return Dl(n,e);const t=n.options instanceof Map?Array.from(n.options.values()):n.options;if(t.every(r=>r._def.typeName in ws&&(!r._def.checks||!r._def.checks.length))){const r=t.reduce((s,a)=>{const i=ws[a._def.typeName];return i&&!s.includes(i)?[...s,i]:s},[]);return{type:r.length>1?r:r[0]}}else if(t.every(r=>r._def.typeName==="ZodLiteral"&&!r.description)){const r=t.reduce((s,a)=>{const i=typeof a._def.value;switch(i){case"string":case"number":case"boolean":return[...s,i];case"bigint":return[...s,"integer"];case"object":if(a._def.value===null)return[...s,"null"];case"symbol":case"undefined":case"function":default:return s}},[]);if(r.length===t.length){const s=r.filter((a,i,o)=>o.indexOf(a)===i);return{type:s.length>1?s:s[0],enum:t.reduce((a,i)=>a.includes(i._def.value)?a:[...a,i._def.value],[])}}}else if(t.every(r=>r._def.typeName==="ZodEnum"))return{type:"string",enum:t.reduce((r,s)=>[...r,...s._def.values.filter(a=>!r.includes(a))],[])};return Dl(n,e)}const Dl=(n,e)=>{const t=(n.options instanceof Map?Array.from(n.options.values()):n.options).map((r,s)=>te(r._def,{...e,currentPath:[...e.currentPath,"anyOf",`${s}`]})).filter(r=>!!r&&(!e.strictUnions||typeof r=="object"&&Object.keys(r).length>0));return t.length?{anyOf:t}:void 0};function jv(n,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(n.innerType._def.typeName)&&(!n.innerType._def.checks||!n.innerType._def.checks.length))return e.target==="openApi3"||e.nullableStrategy==="property"?{type:ws[n.innerType._def.typeName],nullable:!0}:{type:[ws[n.innerType._def.typeName],"null"]};if(e.target==="openApi3"){const r=te(n.innerType._def,{...e,currentPath:[...e.currentPath]});return r&&"$ref"in r?{allOf:[r],nullable:!0}:r&&{...r,nullable:!0}}const t=te(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return t&&{anyOf:[t,{type:"null"}]}}function Lv(n,e){const t={type:"number"};if(!n.checks)return t;for(const r of n.checks)switch(r.kind){case"int":t.type="integer",ff(t,"type",r.message,e);break;case"min":e.target==="jsonSchema7"?r.inclusive?oe(t,"minimum",r.value,r.message,e):oe(t,"exclusiveMinimum",r.value,r.message,e):(r.inclusive||(t.exclusiveMinimum=!0),oe(t,"minimum",r.value,r.message,e));break;case"max":e.target==="jsonSchema7"?r.inclusive?oe(t,"maximum",r.value,r.message,e):oe(t,"exclusiveMaximum",r.value,r.message,e):(r.inclusive||(t.exclusiveMaximum=!0),oe(t,"maximum",r.value,r.message,e));break;case"multipleOf":oe(t,"multipleOf",r.value,r.message,e);break}return t}function Mv(n,e){return e.removeAdditionalStrategy==="strict"?n.catchall._def.typeName==="ZodNever"?n.unknownKeys!=="strict":te(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0:n.catchall._def.typeName==="ZodNever"?n.unknownKeys==="passthrough":te(n.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??!0}function Uv(n,e){const t={type:"object",...Object.entries(n.shape()).reduce((r,[s,a])=>{if(a===void 0||a._def===void 0)return r;const i=[...e.currentPath,"properties",s],o=te(a._def,{...e,currentPath:i,propertyPath:i});if(o===void 0)return r;if(e.openaiStrictMode&&a.isOptional()&&!a.isNullable()&&typeof a._def?.defaultValue>"u")throw new Error(`Zod field at \`${i.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,[s]:o},required:a.isOptional()&&!e.openaiStrictMode?r.required:[...r.required,s]}},{properties:{},required:[]}),additionalProperties:Mv(n,e)};return t.required.length||delete t.required,t}const Dv=(n,e)=>{if(e.propertyPath&&e.currentPath.slice(0,e.propertyPath.length).toString()===e.propertyPath.toString())return te(n.innerType._def,{...e,currentPath:e.currentPath});const t=te(n.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return t?{anyOf:[{not:{}},t]}:{}},Fv=(n,e)=>{if(e.pipeStrategy==="input")return te(n.in._def,e);if(e.pipeStrategy==="output")return te(n.out._def,e);const t=te(n.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),r=te(n.out._def,{...e,currentPath:[...e.currentPath,"allOf",t?"1":"0"]});return{allOf:[t,r].filter(s=>s!==void 0)}};function Bv(n,e){return te(n.type._def,e)}function zv(n,e){const r={type:"array",uniqueItems:!0,items:te(n.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return n.minSize&&oe(r,"minItems",n.minSize.value,n.minSize.message,e),n.maxSize&&oe(r,"maxItems",n.maxSize.value,n.maxSize.message,e),r}function qv(n,e){return n.rest?{type:"array",minItems:n.items.length,items:n.items.map((t,r)=>te(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[]),additionalItems:te(n.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:n.items.length,maxItems:n.items.length,items:n.items.map((t,r)=>te(t._def,{...e,currentPath:[...e.currentPath,"items",`${r}`]})).reduce((t,r)=>r===void 0?t:[...t,r],[])}}function Zv(){return{not:{}}}function Hv(){return{}}const Gv=(n,e)=>te(n.innerType._def,e);function te(n,e,t=!1){const r=e.seen.get(n);if(e.override){const i=e.override?.(n,e,r,t);if(i!==hv)return i}if(r&&!t){const i=Jv(r,e);if(i!==void 0)return"$ref"in i&&e.seenRefs.add(i.$ref),i}const s={def:n,path:e.currentPath,jsonSchema:void 0};e.seen.set(n,s);const a=Vv(n,n.typeName,e,t);return a&&Kv(n,e,a),s.jsonSchema=a,a}const Jv=(n,e)=>{switch(e.$refStrategy){case"root":return{$ref:n.path.join("/")};case"extract-to-root":const t=n.path.slice(e.basePath.length+1).join("_");return t!==e.name&&e.nameStrategy==="duplicate-ref"&&(e.definitions[t]=n.def),{$ref:[...e.basePath,e.definitionPath,t].join("/")};case"relative":return{$ref:Wv(e.currentPath,n.path)};case"none":case"seen":return n.path.length<e.currentPath.length&&n.path.every((r,s)=>e.currentPath[s]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),{}):e.$refStrategy==="seen"?{}:void 0}},Wv=(n,e)=>{let t=0;for(;t<n.length&&t<e.length&&n[t]===e[t];t++);return[(n.length-t).toString(),...e.slice(t)].join("/")},Vv=(n,e,t,r)=>{switch(e){case G.ZodString:return mf(n,t);case G.ZodNumber:return Lv(n,t);case G.ZodObject:return Uv(n,t);case G.ZodBigInt:return _v(n,t);case G.ZodBoolean:return bv();case G.ZodDate:return pf(n,t);case G.ZodUndefined:return Zv();case G.ZodNull:return $v(t);case G.ZodArray:return yv(n,t);case G.ZodUnion:case G.ZodDiscriminatedUnion:return Nv(n,t);case G.ZodIntersection:return Tv(n,t);case G.ZodTuple:return qv(n,t);case G.ZodRecord:return gf(n,t);case G.ZodLiteral:return Av(n,t);case G.ZodEnum:return xv(n);case G.ZodNativeEnum:return Pv(n);case G.ZodNullable:return jv(n,t);case G.ZodOptional:return Dv(n,t);case G.ZodMap:return Rv(n,t);case G.ZodSet:return zv(n,t);case G.ZodLazy:return te(n.getter()._def,t);case G.ZodPromise:return Bv(n,t);case G.ZodNaN:case G.ZodNever:return Cv();case G.ZodEffects:return Ov(n,t,r);case G.ZodAny:return gv();case G.ZodUnknown:return Hv();case G.ZodDefault:return Ev(n,t);case G.ZodBranded:return wv(n,t);case G.ZodReadonly:return Gv(n,t);case G.ZodCatch:return vv(n,t);case G.ZodPipeline:return Fv(n,t);case G.ZodFunction:case G.ZodVoid:case G.ZodSymbol:return;default:return(s=>{})()}},Kv=(n,e,t)=>(n.description&&(t.description=n.description,e.markdownDescription&&(t.markdownDescription=n.description)),t),Xv=(n,e)=>{const t=mv(e),r=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,s=te(n._def,r===void 0?t:{...t,currentPath:[...t.basePath,t.definitionPath,r]},!1)??{},a=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;a!==void 0&&(s.title=a);const i=(()=>{if(pv(t.definitions))return;const u={},c=new Set;for(let l=0;l<500;l++){const d=Object.entries(t.definitions).filter(([h])=>!c.has(h));if(d.length===0)break;for(const[h,f]of d)u[h]=te(ro(f),{...t,currentPath:[...t.basePath,t.definitionPath,h]},!0)??{},c.add(h)}return u})(),o=r===void 0?i?{...s,[t.definitionPath]:i}:s:t.nameStrategy==="duplicate-ref"?{...s,...i||t.seenRefs.size?{[t.definitionPath]:{...i,...t.seenRefs.size?{[r]:s}:void 0}}:void 0}:{$ref:[...t.$refStrategy==="relative"?[]:t.basePath,t.definitionPath,r].join("/"),[t.definitionPath]:{...i,[r]:s}};return t.target==="jsonSchema7"?o.$schema="http://json-schema.org/draft-07/schema#":t.target==="jsonSchema2019-09"&&(o.$schema="https://json-schema.org/draft/2019-09/schema#"),o};function Qv(n,e){return Xv(n,{openaiStrictMode:!0,name:e.name,nameStrategy:"duplicate-ref",$refStrategy:"extract-to-root",nullableStrategy:"property"})}function Yv(n,e,t){return yp({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:Qv(n,{name:e})}},r=>n.parse(JSON.parse(r)))}function Ln(n,e){return n.lc_error_code=e,n.message=`${n.message}
|
|
136
|
+
|
|
137
|
+
Troubleshooting URL: https://js.langchain.com/docs/troubleshooting/errors/${e}/
|
|
138
|
+
`,n}function yf(n){let e;return n.constructor.name===Es.name?(e=new Error(n.message),e.name="TimeoutError"):n.constructor.name===qe.name?(e=new Error(n.message),e.name="AbortError"):n.status===400&&n.message.includes("tool_calls")?e=Ln(n,"INVALID_TOOL_RESULTS"):n.status===401?e=Ln(n,"MODEL_AUTHENTICATION"):n.status===429?e=Ln(n,"MODEL_RATE_LIMIT"):n.status===404?e=Ln(n,"MODEL_NOT_FOUND"):e=n,e}function _f(n){if(n)return n==="any"||n==="required"?"required":n==="auto"?"auto":n==="none"?"none":typeof n=="string"?{type:"function",function:{name:n}}:n}function e0(n,e){const t={...n};return Object.defineProperties(t,{$brand:{value:"auto-parseable-response-format",enumerable:!1},$parseRaw:{value:e,enumerable:!1}}),t}function t0(n,e,t){if(pt(n))return Yv(n,e,t);if(it(n))return e0({type:"json_schema",json_schema:{...t,name:e,strict:!0,schema:dv(n,{cycles:"ref",reused:"ref",override(r){r.jsonSchema.title=e}})}},r=>uv(n,JSON.parse(r)));throw new Error("Unsupported schema response format")}function r0(n){return n.anyOf!==void 0&&Array.isArray(n.anyOf)}function n0(n){const e=["namespace functions {",""];for(const t of n)t.description&&e.push(`// ${t.description}`),Object.keys(t.parameters.properties??{}).length>0?(e.push(`type ${t.name} = (_: {`),e.push(bf(t.parameters,0)),e.push("}) => any;")):e.push(`type ${t.name} = () => any;`),e.push("");return e.push("} // namespace functions"),e.join(`
|
|
139
|
+
`)}function bf(n,e){const t=[];for(const[r,s]of Object.entries(n.properties??{}))s.description&&e<2&&t.push(`// ${s.description}`),n.required?.includes(r)?t.push(`${r}: ${vs(s,e)},`):t.push(`${r}?: ${vs(s,e)},`);return t.map(r=>" ".repeat(e)+r).join(`
|
|
140
|
+
`)}function vs(n,e){if(r0(n))return n.anyOf.map(t=>vs(t,e)).join(" | ");switch(n.type){case"string":return n.enum?n.enum.map(t=>`"${t}"`).join(" | "):"string";case"number":return n.enum?n.enum.map(t=>`${t}`).join(" | "):"number";case"integer":return n.enum?n.enum.map(t=>`${t}`).join(" | "):"number";case"boolean":return"boolean";case"null":return"null";case"object":return["{",bf(n,e+2),"}"].join(`
|
|
141
|
+
`);case"array":return n.items?`${vs(n.items,e)}[]`:"any[]";default:return""}}function s0(n,e){let t;return df(n)?t=Kw(n):t=n,t.type==="function"&&e?.strict!==void 0&&(t.function.strict=e.strict),t}function qo(n){return"type"in n&&n.type!=="function"&&n.type!=="custom"}function a0(n){return n!=null&&typeof n=="object"&&"type"in n&&n.type!=="function"}function i0(n){return typeof n=="object"&&n!==null&&"metadata"in n&&typeof n.metadata=="object"&&n.metadata!==null&&"customTool"in n.metadata&&typeof n.metadata.customTool=="object"&&n.metadata.customTool!==null}function wf(n){return"type"in n&&n.type==="custom"&&"custom"in n&&typeof n.custom=="object"&&n.custom!==null}function o0(n){if(n.type==="custom_tool_call")return{...n,type:"tool_call",call_id:n.id,id:n.call_id,name:n.name,isCustomTool:!0,args:{input:n.input}}}function u0(n){return n.type==="tool_call"&&"isCustomTool"in n&&n.isCustomTool===!0}function c0(n){const e=()=>{if(n.custom.format){if(n.custom.format.type==="grammar")return{type:"grammar",definition:n.custom.format.grammar.definition,syntax:n.custom.format.grammar.syntax};if(n.custom.format.type==="text")return{type:"text"}}};return{type:"custom",name:n.custom.name,description:n.custom.description,format:e()}}function l0(n){const e=()=>{if(n.format){if(n.format.type==="grammar")return{type:"grammar",grammar:{definition:n.format.definition,syntax:n.format.syntax}};if(n.format.type==="text")return{type:"text"}}};return{type:"custom",custom:{name:n.name,description:n.description,format:e()}}}function d0(n,e){if(e&&typeof e=="object"&&"images"in e&&Array.isArray(e.images)){const t=e.images.filter(r=>typeof r?.image_url?.url=="string").map(r=>({type:"image",url:r.image_url.url,source_type:"url"}));return[{type:"text",text:n,source_type:"text"},...t]}return n}const Mn="__openai_function_call_ids__";function Ws(n){return n?!!(/^o\d/.test(n??"")||n.startsWith("gpt-5")&&!n.startsWith("gpt-5-chat")):!1}function h0(n){return n!==void 0&&typeof n.schema=="object"}function f0(n){return n.role!=="system"&&n.role!=="developer"&&n.role!=="assistant"&&n.role!=="user"&&n.role!=="function"&&n.role!=="tool"&&console.warn(`Unknown message role: ${n.role}`),n.role}function Zo(n){const e=n._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(!dn.isInstance(n))throw new Error("Invalid generic chat message");return f0(n)}default:throw new Error(`Unknown message type: ${e}`)}}const vf={providerName:"ChatOpenAI",fromStandardTextBlock(n){return{type:"text",text:n.text}},fromStandardImageBlock(n){if(n.source_type==="url")return{type:"image_url",image_url:{url:n.url,...n.metadata?.detail?{detail:n.metadata.detail}:{}}};if(n.source_type==="base64")return{type:"image_url",image_url:{url:`data:${n.mime_type??""};base64,${n.data}`,...n.metadata?.detail?{detail:n.metadata.detail}:{}}};throw new Error(`Image content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)},fromStandardAudioBlock(n){if(n.source_type==="url"){const e=ku({dataUrl:n.url});if(!e)throw new Error(`URL audio blocks with source_type ${n.source_type} must be formatted as a data URL for ChatOpenAI`);const t=e.mime_type||n.mime_type||"";let r;try{r=xu(t)}catch{throw new Error(`Audio blocks with source_type ${n.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 ${n.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(n.source_type==="base64"){let e;try{e=xu(n.mime_type??"")}catch{throw new Error(`Audio blocks with source_type ${n.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 ${n.source_type} must have mime type of audio/wav or audio/mp3`);return{type:"input_audio",input_audio:{format:e.subtype,data:n.data}}}throw new Error(`Audio content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)},fromStandardFileBlock(n){if(n.source_type==="url"){if(!ku({dataUrl:n.url}))throw new Error(`URL file blocks with source_type ${n.source_type} must be formatted as a data URL for ChatOpenAI`);return{type:"file",file:{file_data:n.url,...n.metadata?.filename||n.metadata?.name?{filename:n.metadata?.filename||n.metadata?.name}:{}}}}if(n.source_type==="base64")return{type:"file",file:{file_data:`data:${n.mime_type??""};base64,${n.data}`,...n.metadata?.filename||n.metadata?.name||n.metadata?.title?{filename:n.metadata?.filename||n.metadata?.name||n.metadata?.title}:{}}};if(n.source_type==="id")return{type:"file",file:{file_id:n.id}};throw new Error(`File content blocks with source_type ${n.source_type} are not supported for ChatOpenAI`)}};function Fl(n,e){return n.flatMap(t=>{let r=Zo(t);r==="system"&&Ws(e)&&(r="developer");const s=typeof t.content=="string"?t.content:t.content.map(i=>Vt(i)?hh(i,vf):i),a={role:r,content:s};if(t.name!=null&&(a.name=t.name),t.additional_kwargs.function_call!=null&&(a.function_call=t.additional_kwargs.function_call,a.content=""),ln(t)&&t.tool_calls?.length?(a.tool_calls=t.tool_calls.map(qw),a.content=""):(t.additional_kwargs.tool_calls!=null&&(a.tool_calls=t.additional_kwargs.tool_calls),t.tool_call_id!=null&&(a.tool_call_id=t.tool_call_id)),t.additional_kwargs.audio&&typeof t.additional_kwargs.audio=="object"&&"id"in t.additional_kwargs.audio){const i={role:"assistant",audio:{id:t.additional_kwargs.audio.id}};return[a,i]}return a})}class Ho extends Tt{_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","reasoningEffort","service_tier"]}get lc_secrets(){return{apiKey:"OPENAI_API_KEY",organization:"OPENAI_ORGANIZATION"}}get lc_aliases(){return{apiKey:"openai_api_key",modelName:"model",reasoningEffort:"reasoning_effort"}}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","reasoningEffort","promptCacheKey","verbosity"]}getLsParams(e){const t=this.invocationParams(e);return{ls_provider:"openai",ls_model_name:this.model,ls_model_type:"chat",ls_temperature:t.temperature??void 0,ls_max_tokens:t.max_tokens??void 0,ls_stop:e.stop}}_identifyingParams(){return{model_name:this.model,...this.invocationParams(),...this.clientConfig}}identifyingParams(){return this._identifyingParams()}constructor(e){super(e??{}),Object.defineProperty(this,"temperature",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topP",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"frequencyPenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"presencePenalty",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"n",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logitBias",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"model",{enumerable:!0,configurable:!0,writable:!0,value:"gpt-3.5-turbo"}),Object.defineProperty(this,"modelKwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stop",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stopSequences",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"user",{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,"streaming",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"streamUsage",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"maxTokens",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"topLogprobs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"organization",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"__includeRawResponse",{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,"clientConfig",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"supportsStrictToolCalling",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"audio",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"modalities",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"reasoning",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"zdrEnabled",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"service_tier",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"promptCacheKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"verbosity",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"defaultOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),this.apiKey=e?.apiKey??e?.configuration?.apiKey??Ct("OPENAI_API_KEY"),this.organization=e?.configuration?.organization??Ct("OPENAI_ORGANIZATION"),this.model=e?.model??e?.modelName??this.model,this.modelKwargs=e?.modelKwargs??{},this.timeout=e?.timeout,this.temperature=e?.temperature??this.temperature,this.topP=e?.topP??this.topP,this.frequencyPenalty=e?.frequencyPenalty??this.frequencyPenalty,this.presencePenalty=e?.presencePenalty??this.presencePenalty,this.logprobs=e?.logprobs,this.topLogprobs=e?.topLogprobs,this.n=e?.n??this.n,this.logitBias=e?.logitBias,this.stop=e?.stopSequences??e?.stop,this.stopSequences=this.stop,this.user=e?.user,this.__includeRawResponse=e?.__includeRawResponse,this.audio=e?.audio,this.modalities=e?.modalities,this.reasoning=e?.reasoning??e?.reasoningEffort?{effort:e.reasoningEffort}:void 0,this.maxTokens=e?.maxCompletionTokens??e?.maxTokens,this.disableStreaming=e?.disableStreaming===!0,this.streaming=e?.streaming===!0,this.promptCacheKey=e?.promptCacheKey??this.promptCacheKey,this.verbosity=e?.verbosity??this.verbosity,e?.streaming===!1&&(this.disableStreaming=!0),this.disableStreaming===!0&&(this.streaming=!1),this.streamUsage=e?.streamUsage??this.streamUsage,this.disableStreaming&&(this.streamUsage=!1),this.clientConfig={apiKey:this.apiKey,organization:this.organization,dangerouslyAllowBrowser:!0,...e?.configuration},e?.supportsStrictToolCalling!==void 0&&(this.supportsStrictToolCalling=e.supportsStrictToolCalling),e?.service_tier!==void 0&&(this.service_tier=e.service_tier),this.zdrEnabled=e?.zdrEnabled??!1}_getReasoningParams(e){if(!Ws(this.model))return;let t;return this.reasoning!==void 0&&(t={...t,...this.reasoning}),e?.reasoning!==void 0&&(t={...t,...e.reasoning}),t}_getResponseFormat(e){return e&&e.type==="json_schema"&&e.json_schema.schema&&Zt(e.json_schema.schema)?t0(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 r={baseURL:this.clientConfig.baseURL},s=Hw(r),a={...this.clientConfig,baseURL:s,timeout:this.timeout,maxRetries:0};a.baseURL||delete a.baseURL,this.client=new X(a)}return{...this.clientConfig,...e}}_convertChatOpenAIToolToCompletionsTool(e,t){return i0(e)?l0(e.metadata.customTool):uf(e)?t?.strict!==void 0?{...e,function:{...e.function,strict:t.strict}}:e:s0(e,t)}bindTools(e,t){let r;return t?.strict!==void 0?r=t.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling),this.withConfig({tools:e.map(s=>qo(s)?s:this._convertChatOpenAIToolToCompletionsTool(s,{strict:r})),...t})}async stream(e,t){return super.stream(e,this._combineCallOptions(t))}async invoke(e,t){return super.invoke(e,this._combineCallOptions(t))}_combineLLMOutput(...e){return e.reduce((t,r)=>(r&&r.tokenUsage&&(t.tokenUsage.completionTokens+=r.tokenUsage.completionTokens??0,t.tokenUsage.promptTokens+=r.tokenUsage.promptTokens??0,t.tokenUsage.totalTokens+=r.tokenUsage.totalTokens??0),t),{tokenUsage:{completionTokens:0,promptTokens:0,totalTokens:0}})}async getNumTokensFromMessages(e){let t=0,r=0,s=0;this.model==="gpt-3.5-turbo-0301"?(r=4,s=-1):(r=3,s=1);const a=await Promise.all(e.map(async i=>{const o=await this.getNumTokens(i.content),u=await this.getNumTokens(Zo(i)),c=i.name!==void 0?s+await this.getNumTokens(i.name):0;let l=o+r+u+c;const d=i;if(d._getType()==="function"&&(l-=2),d.additional_kwargs?.function_call&&(l+=3),d?.additional_kwargs.function_call?.name&&(l+=await this.getNumTokens(d.additional_kwargs.function_call?.name)),d.additional_kwargs.function_call?.arguments)try{l+=await this.getNumTokens(JSON.stringify(JSON.parse(d.additional_kwargs.function_call?.arguments)))}catch(h){console.error("Error parsing function arguments",h,JSON.stringify(d.additional_kwargs.function_call)),l+=await this.getNumTokens(d.additional_kwargs.function_call?.arguments)}return t+=l,l}));return t+=3,{totalCount:t,countPerMessage:a}}async _getNumTokensFromGenerations(e){return(await Promise.all(e.map(async r=>r.message.additional_kwargs?.function_call?(await this.getNumTokensFromMessages([r.message])).countPerMessage[0]:await this.getNumTokens(r.message.content)))).reduce((r,s)=>r+s,0)}async _getEstimatedTokenCountFromPrompt(e,t,r){let s=(await this.getNumTokensFromMessages(e)).totalCount;if(t&&r!=="auto"){const a=n0(t);s+=await this.getNumTokens(a),s+=9}return t&&e.find(a=>a._getType()==="system")&&(s-=4),r==="none"?s+=1:typeof r=="object"&&(s+=await this.getNumTokens(r.name)+4),s}_getStructuredOutputMethod(e){const t={...e};if(!this.model.startsWith("gpt-3")&&!this.model.startsWith("gpt-4-")&&this.model!=="gpt-4"){if(t?.method===void 0)return"jsonSchema"}else t.method==="jsonSchema"&&console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`);return t.method}withStructuredOutput(e,t){let r,s,a,i;h0(e)?(r=e.schema,s=e.name,a=e.method,i=e.includeRaw):(r=e,s=t?.name,a=t?.method,i=t?.includeRaw);let o,u;if(t?.strict!==void 0&&a==="jsonMode")throw new Error("Argument `strict` is only supported for `method` = 'function_calling'");if(a=this._getStructuredOutputMethod({...t,method:a}),a==="jsonMode"){Zt(r)?u=$l.fromZodSchema(r):u=new Nl;const h=Rt(r);o=this.withConfig({response_format:{type:"json_object"},ls_structured_output_format:{kwargs:{method:"json_mode"},schema:{title:s??"extract",...h}}})}else if(a==="jsonSchema"){const h={name:s??"extract",description:Uo(r),schema:r,strict:t?.strict},f=Rt(h.schema);if(o=this.withConfig({response_format:{type:"json_schema",json_schema:h},ls_structured_output_format:{kwargs:{method:"json_schema"},schema:{title:h.name,description:h.description,...f}}}),Zt(r)){const p=$l.fromZodSchema(r);u=Er.from(m=>"parsed"in m.additional_kwargs?m.additional_kwargs.parsed:p)}else u=new Nl}else{let h=s??"extract";if(Zt(r)){const f=Rt(r);o=this.withConfig({tools:[{type:"function",function:{name:h,description:f.description,parameters:f}}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...f}},...t?.strict!==void 0?{strict:t.strict}:{}}),u=new jl({returnSingle:!0,keyName:h,zodSchema:r})}else{let f;typeof r.name=="string"&&typeof r.parameters=="object"&&r.parameters!=null?(f=r,h=r.name):(h=r.title??h,f={name:h,description:r.description??"",parameters:r});const p=Rt(r);o=this.withConfig({tools:[{type:"function",function:f}],tool_choice:{type:"function",function:{name:h}},ls_structured_output_format:{kwargs:{method:"function_calling"},schema:{title:h,...p}},...t?.strict!==void 0?{strict:t.strict}:{}}),u=new jl({returnSingle:!0,keyName:h})}}if(!i)return o.pipe(u);const c=bs.assign({parsed:(h,f)=>u.invoke(h.raw,f)}),l=bs.assign({parsed:()=>null}),d=c.withFallbacks({fallbacks:[l]});return _t.from([{raw:o},d])}}class p0 extends Ho{invocationParams(e){let t;e?.strict!==void 0?t=e.strict:this.supportsStrictToolCalling!==void 0&&(t=this.supportsStrictToolCalling);const r={model:this.model,temperature:this.temperature,top_p:this.topP,user:this.user,stream:this.streaming,previous_response_id:e?.previous_response_id,truncation:e?.truncation,include:e?.include,tools:e?.tools?.length?this._reduceChatOpenAITools(e.tools,{stream:this.streaming,strict:t}):void 0,tool_choice:a0(e?.tool_choice)?e?.tool_choice:(()=>{const a=_f(e?.tool_choice);if(typeof a=="object"&&"type"in a){if(a.type==="function")return{type:"function",name:a.function.name};if(a.type==="allowed_tools")return{type:"allowed_tools",mode:a.allowed_tools.mode,tools:a.allowed_tools.tools};if(a.type==="custom")return{type:"custom",name:a.custom.name}}})(),text:(()=>{if(e?.text)return e.text;const a=this._getResponseFormat(e?.response_format);return a?.type==="json_schema"?a.json_schema.schema!=null?{format:{type:"json_schema",schema:a.json_schema.schema,description:a.json_schema.description,name:a.json_schema.name,strict:a.json_schema.strict},verbosity:e?.verbosity}:void 0:{format:a,verbosity:e?.verbosity}})(),parallel_tool_calls:e?.parallel_tool_calls,max_output_tokens:this.maxTokens===-1?void 0:this.maxTokens,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,...this.zdrEnabled?{store:!1}:{},...this.modelKwargs},s=this._getReasoningParams(e);return s!==void 0&&(r.reasoning=s),r}async _generate(e,t){const r=this.invocationParams(t);if(r.stream){const s=this._streamResponseChunks(e,t);let a;for await(const i of s)i.message.response_metadata={...i.generationInfo,...i.message.response_metadata},a=a?.concat(i)??i;return{generations:a?[a]:[],llmOutput:{estimatedTokenUsage:a?.message?.usage_metadata}}}else{const s=this._convertMessagesToResponsesParams(e),a=await this.completionWithRetry({input:s,...r,stream:!1},{signal:t?.signal,...t?.options});return{generations:[{text:a.output_text,message:this._convertResponsesMessageToBaseMessage(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*_streamResponseChunks(e,t,r){const s=await this.completionWithRetry({...this.invocationParams(t),input:this._convertMessagesToResponsesParams(e),stream:!0},t);for await(const a of s){const i=this._convertResponsesDeltaToBaseMessageChunk(a);i!=null&&(yield i,await r?.handleLLMNewToken(i.text||"",{prompt:t.promptIndex??0,completion:0},void 0,void 0,void 0,{chunk:i}))}}async completionWithRetry(e,t){return this.caller.call(async()=>{const r=this._getClientOptions(t);try{return e.text?.format?.type==="json_schema"&&!e.stream?await this.client.responses.parse(e,r):await this.client.responses.create(e,r)}catch(s){throw yf(s)}})}_convertResponsesMessageToBaseMessage(e){if(e.error){const u=new Error(e.error.message);throw u.name=e.error.code,u}let t;const r=[],s=[],a=[],i={model:e.model,created_at:e.created_at,id:e.id,incomplete_details:e.incomplete_details,metadata:e.metadata,object:e.object,status:e.status,user:e.user,service_tier:e.service_tier,model_name:e.model},o={};for(const u of e.output)if(u.type==="message")t=u.id,r.push(...u.content.flatMap(c=>c.type==="output_text"?("parsed"in c&&c.parsed!=null&&(o.parsed=c.parsed),{type:"text",text:c.text,annotations:c.annotations}):c.type==="refusal"?(o.refusal=c.refusal,[]):c));else if(u.type==="function_call"){const c={function:{name:u.name,arguments:u.arguments},id:u.call_id};try{s.push(zo(c,{returnId:!0}))}catch(l){let d;typeof l=="object"&&l!=null&&"message"in l&&typeof l.message=="string"&&(d=l.message),a.push(to(c,d))}o[Mn]??={},u.id&&(o[Mn][u.call_id]=u.id)}else if(u.type==="reasoning")o.reasoning=u;else if(u.type==="custom_tool_call"){const c=o0(u);c?s.push(c):a.push(to(u,"Malformed custom tool call"))}else o.tool_outputs??=[],o.tool_outputs.push(u);return new Kr({id:t,content:r,tool_calls:s,invalid_tool_calls:a,usage_metadata:e.usage,additional_kwargs:o,response_metadata:i})}_convertResponsesDeltaToBaseMessageChunk(e){const t=[];let r={},s;const a=[],i={},o={};let u;if(e.type==="response.output_text.delta")t.push({type:"text",text:e.delta,index:e.content_index});else if(e.type==="response.output_text.annotation.added")t.push({type:"text",text:"",annotations:[e.annotation],index:e.content_index});else if(e.type==="response.output_item.added"&&e.item.type==="message")u=e.item.id;else if(e.type==="response.output_item.added"&&e.item.type==="function_call")a.push({type:"tool_call_chunk",name:e.item.name,args:e.item.arguments,id:e.item.call_id,index:e.output_index}),o[Mn]={[e.item.call_id]:e.item.id};else if(e.type==="response.output_item.done"&&["web_search_call","file_search_call","computer_call","code_interpreter_call","mcp_call","mcp_list_tools","mcp_approval_request","image_generation_call","custom_tool_call"].includes(e.item.type))o.tool_outputs=[e.item];else if(e.type==="response.created")i.id=e.response.id,i.model_name=e.response.model,i.model=e.response.model;else if(e.type==="response.completed"){const c=this._convertResponsesMessageToBaseMessage(e.response);s=e.response.usage,e.response.text?.format?.type==="json_schema"&&(o.parsed??=JSON.parse(c.text));for(const[l,d]of Object.entries(e.response))l!=="id"&&(i[l]=d)}else if(e.type==="response.function_call_arguments.delta"||e.type==="response.custom_tool_call_input.delta")a.push({type:"tool_call_chunk",args:e.delta,index:e.output_index});else if(e.type==="response.web_search_call.completed"||e.type==="response.file_search_call.completed")r={tool_outputs:{id:e.item_id,type:e.type.replace("response.","").replace(".completed",""),status:"completed"}};else if(e.type==="response.refusal.done")o.refusal=e.refusal;else if(e.type==="response.output_item.added"&&"item"in e&&e.item.type==="reasoning"){const c=e.item.summary?e.item.summary.map((l,d)=>({...l,index:d})):void 0;o.reasoning={id:e.item.id,type:e.item.type,...c?{summary:c}:{}}}else if(e.type==="response.reasoning_summary_part.added")o.reasoning={type:"reasoning",summary:[{...e.part,index:e.summary_index}]};else if(e.type==="response.reasoning_summary_text.delta")o.reasoning={type:"reasoning",summary:[{text:e.delta,type:"summary_text",index:e.summary_index}]};else return e.type==="response.image_generation_call.partial_image",null;return new Xt({text:t.map(c=>c.text).join(""),message:new $t({id:u,content:t,tool_call_chunks:a,usage_metadata:s,additional_kwargs:o,response_metadata:i}),generationInfo:r})}_convertMessagesToResponsesParams(e){return e.flatMap(t=>{const r=t.additional_kwargs;let s=Zo(t);if(s==="system"&&Ws(this.model)&&(s="developer"),s==="function")throw new Error("Function messages are not supported in Responses API");if(s==="tool"){const a=t;return r?.type==="computer_call_output"?{type:"computer_call_output",output:(()=>{if(typeof a.content=="string")return{type:"computer_screenshot",image_url:a.content};if(Array.isArray(a.content)){const o=a.content.find(c=>c.type==="computer_screenshot");if(o)return o;const u=a.content.find(c=>c.type==="image_url");if(u)return{type:"computer_screenshot",image_url:typeof u.image_url=="string"?u.image_url:u.image_url.url}}throw new Error("Invalid computer call output")})(),call_id:a.tool_call_id}:a.metadata?.customTool?{type:"custom_tool_call_output",call_id:a.tool_call_id,output:a.content}:{type:"function_call_output",call_id:a.tool_call_id,id:a.id?.startsWith("fc_")?a.id:void 0,output:typeof a.content!="string"?JSON.stringify(a.content):a.content}}if(s==="assistant"){if(!this.zdrEnabled&&t.response_metadata.output!=null&&Array.isArray(t.response_metadata.output)&&t.response_metadata.output.length>0&&t.response_metadata.output.every(l=>"type"in l))return t.response_metadata.output;const a=[];if(r?.reasoning&&!this.zdrEnabled){const l=this._convertReasoningSummary(r.reasoning);a.push(l)}let{content:i}=t;r?.refusal&&(typeof i=="string"&&(i=[{type:"output_text",text:i,annotations:[]}]),i=[...i,{type:"refusal",refusal:r.refusal}]),(typeof i=="string"||i.length>0)&&a.push({type:"message",role:"assistant",...t.id&&!this.zdrEnabled&&t.id.startsWith("msg_")?{id:t.id}:{},content:typeof i=="string"?i:i.flatMap(l=>l.type==="text"?{type:"output_text",text:l.text,annotations:l.annotations??[]}:l.type==="output_text"||l.type==="refusal"?l:[])});const o=r?.[Mn];ln(t)&&t.tool_calls?.length?a.push(...t.tool_calls.map(l=>u0(l)?{type:"custom_tool_call",id:l.call_id,call_id:l.id??"",input:l.args.input,name:l.name}:{type:"function_call",name:l.name,arguments:JSON.stringify(l.args),call_id:l.id,...this.zdrEnabled?{id:o?.[l.id]}:{}})):r?.tool_calls&&a.push(...r.tool_calls.map(l=>({type:"function_call",name:l.function.name,call_id:l.id,arguments:l.function.arguments,...this.zdrEnabled?{id:o?.[l.id]}:{}})));const u=t.response_metadata.output?.length?t.response_metadata.output:r.tool_outputs,c=["computer_call","mcp_call","code_interpreter_call","image_generation_call"];if(u!=null){const d=u?.filter(h=>c.includes(h.type));d.length>0&&a.push(...d)}return a}if(s==="user"||s==="system"||s==="developer"){if(typeof t.content=="string")return{type:"message",role:s,content:t.content};const a=[],i=t.content.flatMap(o=>(o.type==="mcp_approval_response"&&a.push({type:"mcp_approval_response",approval_request_id:o.approval_request_id,approve:o.approve}),Vt(o)?hh(o,vf):o.type==="text"?{type:"input_text",text:o.text}:o.type==="image_url"?{type:"input_image",image_url:typeof o.image_url=="string"?o.image_url:o.image_url.url,detail:typeof o.image_url=="string"?"auto":o.image_url.detail}:o.type==="input_text"||o.type==="input_image"||o.type==="input_file"?o:[]));return i.length>0&&a.push({type:"message",role:s,content:i}),a}return console.warn(`Unsupported role found when converting to OpenAI Responses API: ${s}`),[]})}_convertReasoningSummary(e){const t=(e.summary.length>1?e.summary.reduce((r,s)=>{const a=r.at(-1);return a.index===s.index?a.text+=s.text:r.push(s),r},[{...e.summary[0]}]):e.summary).map(r=>Object.fromEntries(Object.entries(r).filter(([s])=>s!=="index")));return{...e,summary:t}}_reduceChatOpenAITools(e,t){const r=[];for(const s of e)qo(s)?(s.type==="image_generation"&&t?.stream&&(s.partial_images=1),r.push(s)):uf(s)?r.push({type:"function",name:s.function.name,parameters:s.function.parameters,description:s.function.description,strict:t?.strict??null}):wf(s)&&r.push(c0(s));return r}}class m0 extends Ho{invocationParams(e,t){let r;e?.strict!==void 0?r=e.strict:this.supportsStrictToolCalling!==void 0&&(r=this.supportsStrictToolCalling);let s={};e?.stream_options!==void 0?s={stream_options:e.stream_options}:this.streamUsage&&(this.streaming||t?.streaming)&&(s={stream_options:{include_usage:!0}});const a={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:e?.stop??this.stopSequences,user:this.user,stream:this.streaming,functions:e?.functions,function_call:e?.function_call,tools:e?.tools?.length?e.tools.map(o=>this._convertChatOpenAIToolToCompletionsTool(o,{strict:r})):void 0,tool_choice:_f(e?.tool_choice),response_format:this._getResponseFormat(e?.response_format),seed:e?.seed,...s,parallel_tool_calls:e?.parallel_tool_calls,...this.audio||e?.audio?{audio:this.audio||e?.audio}:{},...this.modalities||e?.modalities?{modalities:this.modalities||e?.modalities}:{},...this.modelKwargs,prompt_cache_key:e?.promptCacheKey??this.promptCacheKey,verbosity:e?.verbosity??this.verbosity};e?.prediction!==void 0&&(a.prediction=e.prediction),this.service_tier!==void 0&&(a.service_tier=this.service_tier),e?.service_tier!==void 0&&(a.service_tier=e.service_tier);const i=this._getReasoningParams(e);return i!==void 0&&i.effort!==void 0&&(a.reasoning_effort=i.effort),Ws(a.model)?a.max_completion_tokens=this.maxTokens===-1?void 0:this.maxTokens:a.max_tokens=this.maxTokens===-1?void 0:this.maxTokens,a}async _generate(e,t,r){const s={},a=this.invocationParams(t),i=Fl(e,this.model);if(a.stream){const o=this._streamResponseChunks(e,t,r),u={};for await(const p of o){p.message.response_metadata={...p.generationInfo,...p.message.response_metadata};const m=p.generationInfo?.completion??0;u[m]===void 0?u[m]=p:u[m]=u[m].concat(p)}const c=Object.entries(u).sort(([p],[m])=>parseInt(p,10)-parseInt(m,10)).map(([p,m])=>m),{functions:l,function_call:d}=this.invocationParams(t),h=await this._getEstimatedTokenCountFromPrompt(e,l,d),f=await this._getNumTokensFromGenerations(c);return s.input_tokens=h,s.output_tokens=f,s.total_tokens=h+f,{generations:c,llmOutput:{estimatedTokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}else{const o=await this.completionWithRetry({...a,stream:!1,messages:i},{signal:t?.signal,...t?.options}),{completion_tokens:u,prompt_tokens:c,total_tokens:l,prompt_tokens_details:d,completion_tokens_details:h}=o?.usage??{};u&&(s.output_tokens=(s.output_tokens??0)+u),c&&(s.input_tokens=(s.input_tokens??0)+c),l&&(s.total_tokens=(s.total_tokens??0)+l),(d?.audio_tokens!==null||d?.cached_tokens!==null)&&(s.input_token_details={...d?.audio_tokens!==null&&{audio:d?.audio_tokens},...d?.cached_tokens!==null&&{cache_read:d?.cached_tokens}}),(h?.audio_tokens!==null||h?.reasoning_tokens!==null)&&(s.output_token_details={...h?.audio_tokens!==null&&{audio:h?.audio_tokens},...h?.reasoning_tokens!==null&&{reasoning:h?.reasoning_tokens}});const f=[];for(const p of o?.choices??[]){const g={text:p.message?.content??"",message:this._convertCompletionsMessageToBaseMessage(p.message??{role:"assistant"},o)};g.generationInfo={...p.finish_reason?{finish_reason:p.finish_reason}:{},...p.logprobs?{logprobs:p.logprobs}:{}},ln(g.message)&&(g.message.usage_metadata=s),g.message=new Kr(Object.fromEntries(Object.entries(g.message).filter(([y])=>!y.startsWith("lc_")))),f.push(g)}return{generations:f,llmOutput:{tokenUsage:{promptTokens:s.input_tokens,completionTokens:s.output_tokens,totalTokens:s.total_tokens}}}}}async*_streamResponseChunks(e,t,r){const s=Fl(e,this.model),a={...this.invocationParams(t,{streaming:!0}),messages:s,stream:!0};let i;const o=await this.completionWithRetry(a,t);let u;for await(const c of o){const l=c?.choices?.[0];if(c.usage&&(u=c.usage),!l)continue;const{delta:d}=l;if(!d)continue;const h=this._convertCompletionsDeltaToBaseMessageChunk(d,c,i);i=d.role??i;const f={prompt:t.promptIndex??0,completion:l.index??0};if(typeof h.content!="string"){console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported.");continue}const p={...f};l.finish_reason!=null&&(p.finish_reason=l.finish_reason,p.system_fingerprint=c.system_fingerprint,p.model_name=c.model,p.service_tier=c.service_tier),this.logprobs&&(p.logprobs=l.logprobs);const m=new Xt({message:h,text:h.content,generationInfo:p});yield m,await r?.handleLLMNewToken(m.text??"",f,void 0,void 0,void 0,{chunk:m})}if(u){const c={...u.prompt_tokens_details?.audio_tokens!==null&&{audio:u.prompt_tokens_details?.audio_tokens},...u.prompt_tokens_details?.cached_tokens!==null&&{cache_read:u.prompt_tokens_details?.cached_tokens}},l={...u.completion_tokens_details?.audio_tokens!==null&&{audio:u.completion_tokens_details?.audio_tokens},...u.completion_tokens_details?.reasoning_tokens!==null&&{reasoning:u.completion_tokens_details?.reasoning_tokens}};yield new Xt({message:new $t({content:"",response_metadata:{usage:{...u}},usage_metadata:{input_tokens:u.prompt_tokens,output_tokens:u.completion_tokens,total_tokens:u.total_tokens,...Object.keys(c).length>0&&{input_token_details:c},...Object.keys(l).length>0&&{output_token_details:l}}}),text:""})}if(t.signal?.aborted)throw new Error("AbortError")}async completionWithRetry(e,t){const r=this._getClientOptions(t),s=e.response_format&&e.response_format.type==="json_schema";return this.caller.call(async()=>{try{return s&&!e.stream?await this.client.chat.completions.parse(e,r):await this.client.chat.completions.create(e,r)}catch(a){throw yf(a)}})}_convertCompletionsMessageToBaseMessage(e,t){const r=e.tool_calls;switch(e.role){case"assistant":{const s=[],a=[];for(const c of r??[])try{s.push(zo(c,{returnId:!0}))}catch(l){a.push(to(c,l.message))}const i={function_call:e.function_call,tool_calls:r};this.__includeRawResponse!==void 0&&(i.__raw_response=t);const o={model_name:t.model,...t.system_fingerprint?{usage:{...t.usage},system_fingerprint:t.system_fingerprint}:{}};e.audio&&(i.audio=e.audio);const u=d0(e.content||"",t.choices?.[0]?.message);return new Kr({content:u,tool_calls:s,invalid_tool_calls:a,additional_kwargs:i,response_metadata:o,id:t.id})}default:return new dn(e.content||"",e.role??"unknown")}}_convertCompletionsDeltaToBaseMessageChunk(e,t,r){const s=e.role??r,a=e.content??"";let i;e.function_call?i={function_call:e.function_call}:e.tool_calls?i={tool_calls:e.tool_calls}:i={},this.__includeRawResponse&&(i.__raw_response=t),e.audio&&(i.audio={...e.audio,index:t.choices[0].index});const o={usage:{...t.usage}};if(s==="user")return new js({content:a,response_metadata:o});if(s==="assistant"){const u=[];if(Array.isArray(e.tool_calls))for(const c of e.tool_calls)u.push({name:c.function?.name,args:c.function?.arguments,id:c.id,index:c.index,type:"tool_call_chunk"});return new $t({content:a,tool_call_chunks:u,additional_kwargs:i,id:t.id,response_metadata:o})}else return s==="system"?new Xr({content:a,response_metadata:o}):s==="developer"?new Xr({content:a,response_metadata:o,additional_kwargs:{__openai_role__:"developer"}}):s==="function"?new $s({content:a,additional_kwargs:i,name:e.name,response_metadata:o}):s==="tool"?new xo({content:a,additional_kwargs:i,tool_call_id:e.tool_call_id,response_metadata:o}):new Cs({content:a,role:s,response_metadata:o})}}class Go extends Ho{get lc_serializable_keys(){return[...super.lc_serializable_keys,"useResponsesApi"]}constructor(e){super(e),Object.defineProperty(this,"fields",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"useResponsesApi",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"responses",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"completions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.useResponsesApi=e?.useResponsesApi??!1,this.responses=e?.responses??new p0(e),this.completions=e?.completions??new m0(e)}_useResponsesApi(e){const t=e?.tools?.some(qo),r=e?.previous_response_id!=null||e?.text!=null||e?.truncation!=null||e?.include!=null||e?.reasoning?.summary!=null||this.reasoning?.summary!=null,s=e?.tools?.some(wf);return this.useResponsesApi||t||r||s}getLsParams(e){const t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.getLsParams(t):this.completions.getLsParams(t)}invocationParams(e){const t=this._combineCallOptions(e);return this._useResponsesApi(e)?this.responses.invocationParams(t):this.completions.invocationParams(t)}async _generate(e,t,r){return this._useResponsesApi(t)?this.responses._generate(e,t):this.completions._generate(e,t,r)}async*_streamResponseChunks(e,t,r){if(this._useResponsesApi(t)){yield*this.responses._streamResponseChunks(e,this._combineCallOptions(t),r);return}yield*this.completions._streamResponseChunks(e,this._combineCallOptions(t),r)}withConfig(e){const t=new Go(this.fields);return t.defaultOptions={...this.defaultOptions,...e},t}}class g0{constructor(){}async handleParseData(e,t){try{console.log("[AiParsingService] Handle parse data request");const r=await this.parseData(e);r.success?t({success:!0,data:r.data}):t({$isError:!0,message:r.error||"AI parsing failed",data:null})}catch(r){console.error("[AiParsingService] Parse data error:",r),t({$isError:!0,message:r instanceof Error?r.message:"Unknown error in AI parsing",data:null})}}async parseData(e){try{const{sourceData:t,schemaDefinition:r,prompt:s,model:a="gpt-4o-mini",apiKey:i}=e;if(!i||i.trim()==="")return{success:!1,error:"OpenAI API key is required. Please provide it in the ai-parse-data block."};const o=r.type==="array",u=this.reconstructZodSchema(r),l=new Go({apiKey:i,modelName:a,temperature:0}).withStructuredOutput(u),d=this.buildPrompt(t,r,s),h=await l.invoke(d);return{success:!0,data:o&&h&&typeof h=="object"&&"items"in h?h.items:h}}catch(t){return console.error("[AI Parsing Service] Parsing failed:",t),{success:!1,error:t instanceof Error?t.message:"Unknown error during AI parsing"}}}reconstructZodSchema(e){if(e.type==="array"&&e.items){const t=this.buildZodType(e.items);return Vs({items:Jo(t)})}if(e.type==="object"&&e.shape){const t={};for(const[r,s]of Object.entries(e.shape))t[r]=this.buildZodType(s);return Vs(t)}return mn()}buildZodType(e){let t;switch(e.type){case"string":e.enum&&Array.isArray(e.enum)&&e.enum.length>0?t=Rf(e.enum):t=Pf();break;case"number":if(e.enum&&Array.isArray(e.enum)&&e.enum.length>0){const r=e.enum.map(s=>Tf(s));t=Af(r)}else t=If();break;case"boolean":t=kf();break;case"array":t=Jo(e.items?this.buildZodType(e.items):mn());break;case"object":if(e.shape){const r={};for(const[s,a]of Object.entries(e.shape))r[s]=this.buildZodType(a);t=Vs(r)}else t=mn();break;default:t=mn()}return e.optional&&(t=t.optional()),t}buildPrompt(e,t,r){const s=typeof e=="string"?e:JSON.stringify(e,null,2),a=this.describeSchema(t),i=t.type==="array";return`You are a data parsing assistant. Your task is to extract and structure data according to the provided schema.
|
|
142
|
+
|
|
143
|
+
Source Data:
|
|
144
|
+
\`\`\`
|
|
145
|
+
${s}
|
|
146
|
+
\`\`\`
|
|
147
|
+
|
|
148
|
+
Expected Output Schema:
|
|
149
|
+
${a}
|
|
150
|
+
|
|
151
|
+
${r?`
|
|
152
|
+
Additional Instructions:
|
|
153
|
+
${r}
|
|
154
|
+
`:""}
|
|
155
|
+
|
|
156
|
+
Please parse the source data and return it in the exact format specified by the schema. Extract all relevant information and ensure the data types match the schema.${i?`
|
|
157
|
+
|
|
158
|
+
IMPORTANT: Return the array in an object with "items" field: { items: [...your array here...] }`:""}`}describeSchema(e,t=0){const r=" ".repeat(t);if(e.type==="array"&&e.items)return`Array<${this.describeSchema(e.items,0)}>`;if(e.type==="object"&&e.shape){let s=`${r}{
|
|
159
|
+
`;for(const[a,i]of Object.entries(e.shape)){const o=i.optional?" (optional)":"",u=i.description?` // ${i.description}`:"";s+=`${r} ${a}: ${this.describeSchema(i,t+1)}${o}${u}
|
|
160
|
+
`}return s+=`${r}}`,s}return e.enum&&Array.isArray(e.enum)?e.enum.map(a=>JSON.stringify(a)).join(" | "):e.type||"any"}}class y0{async handleClick(e,t){try{console.log("[CdpService] Handle click request:",e);const{tabId:r,x:s,y:a}=e;await this.click(r,s,a),t({success:!0,data:{clicked:!0}})}catch(r){console.error("[CdpService] Click error:",r),t({$isError:!0,message:r instanceof Error?r.message:"CDP click failed",data:null})}}async handleKeypress(e,t){try{console.log("[CdpService] Handle keypress request:",e);const{tabId:r,key:s,code:a,keyCode:i,modifiers:o}=e;await this.keypress(r,s,a,i,o),t({success:!0,data:{pressed:!0}})}catch(r){console.error("[CdpService] Keypress error:",r),t({$isError:!0,message:r instanceof Error?r.message:"CDP keypress failed",data:null})}}async click(e,t,r){console.log("[CdpService] Click request - tabId:",e,"x:",t,"y:",r),await chrome.debugger.attach({tabId:e},"1.3"),console.log("[CdpService] Debugger attached to tab:",e);try{await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mouseMoved",x:t,y:r,button:"none",clickCount:0}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mousePressed",x:t,y:r,button:"left",clickCount:1}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchMouseEvent",{type:"mouseReleased",x:t,y:r,button:"left",clickCount:1}),console.log("[CdpService] Click completed successfully")}finally{await chrome.debugger.detach({tabId:e}),console.log("[CdpService] Debugger detached from tab:",e)}}async keypress(e,t,r,s,a=[]){console.log("[CdpService] Keypress request - tabId:",e,"key:",t),await chrome.debugger.attach({tabId:e},"1.3"),console.log("[CdpService] Debugger attached to tab:",e);try{const i=this.convertModifiersToCdp(a);await chrome.debugger.sendCommand({tabId:e},"Input.dispatchKeyEvent",{type:"keyDown",key:t,code:r,windowsVirtualKeyCode:s,nativeVirtualKeyCode:s,modifiers:i}),await chrome.debugger.sendCommand({tabId:e},"Input.dispatchKeyEvent",{type:"keyUp",key:t,code:r,windowsVirtualKeyCode:s,nativeVirtualKeyCode:s,modifiers:i}),console.log("[CdpService] Keypress completed successfully")}finally{await chrome.debugger.detach({tabId:e}),console.log("[CdpService] Debugger detached from tab:",e)}}convertModifiersToCdp(e){let t=0;return e.includes("Alt")&&(t|=1),e.includes("Control")&&(t|=2),e.includes("Meta")&&(t|=4),e.includes("Shift")&&(t|=8),t}}class _0{constructor(e){this.tabManager=e}async run(e,t){const r={steps:{},vars:{}},s=new Map(e.steps.map(o=>[o.id,o]));let a=e.start;const i=[];for(;a;){const o=s.get(a);if(!o)break;const u=new Date().toISOString();let c=!1,l=!0,d="",h=null,f=0;if(!this.evaluateWhen(o.when,r))c=!0;else if(o.block)if(o.repeat)h=await this.executeWithRepeat(o,r,t),l=!h?.hasError,d=h?.message||"";else{const y=Math.max(1,o.retry?.attempts??1),_=o.retry?.delayMs??0,b=o.retry?.backoffFactor??1;for(;f<y;){f++;try{const v=this.resolveBindings(o.block,r);if(h=await this.runWithTimeout(()=>this.tabManager.executeBlock(v,t),o.timeoutMs),l=!h?.hasError,d=h?.message||"",l)break}catch(v){l=!1,d=v?.message||"Workflow step error"}if(f<y){const v=_*Math.pow(b,f-1);v>0&&await new Promise(S=>setTimeout(S,v))}}}else c=!0;const m=new Date().toISOString(),g={stepId:o.id,skipped:c,success:l,message:d,result:h,startedAt:u,finishedAt:m,attempts:f};if(i.push(g),r.steps[o.id]={result:h,success:l,skipped:c},o.switch&&o.switch.length>0){const y=o.switch.find(_=>this.evaluateWhen(_.when,r));if(y){!c&&typeof o.delayAfterMs=="number"&&o.delayAfterMs>0&&await new Promise(_=>setTimeout(_,o.delayAfterMs)),a=y.next;continue}}if(l&&o.onSuccess){!c&&typeof o.delayAfterMs=="number"&&o.delayAfterMs>0&&await new Promise(y=>setTimeout(y,o.delayAfterMs)),a=o.onSuccess;continue}if(!l&&o.onFailure){!c&&typeof o.delayAfterMs=="number"&&o.delayAfterMs>0&&await new Promise(y=>setTimeout(y,o.delayAfterMs)),a=o.onFailure;continue}if(o.next){!c&&typeof o.delayAfterMs=="number"&&o.delayAfterMs>0&&await new Promise(y=>setTimeout(y,o.delayAfterMs)),a=o.next;continue}break}return{steps:i}}evaluateWhen(e,t){if(!e)return!0;if(typeof e=="object"&&e!==null&&("exists"in e||"equals"in e||"notEquals"in e||"contains"in e||"regex"in e||"and"in e||"or"in e||"not"in e))return this.evaluateJsonCondition(e,t);if(e.expr&&typeof e.expr=="string")try{const s=t;return!!new Function("$",`return (${e.expr});`)(s)}catch{return!1}return e.json?this.evaluateJsonCondition(e.json,t):!0}evaluateJsonCondition(e,t){if(e.exists)return this.getByPath(t,e.exists)!==void 0;if(e.equals)return this.getByPath(t,e.equals.left)===e.equals.right;if(e.notEquals)return this.getByPath(t,e.notEquals.left)!==e.notEquals.right;if(e.contains){const r=this.getByPath(t,e.contains.value);return Array.isArray(r)?r.some(s=>(s+"").includes(e.contains.search+"")):(r+"").includes(e.contains.search+"")}if(e.regex){const r=this.getByPath(t,e.regex.value)+"";return new RegExp(e.regex.pattern,e.regex.flags||"").test(r)}return e.and?e.and.every(r=>this.evaluateJsonCondition(r,t)):e.or?e.or.some(r=>this.evaluateJsonCondition(r,t)):e.not?!this.evaluateJsonCondition(e.not,t):!1}resolveBindings(e,t){if(e==null)return e;if(typeof e=="string")return this.interpolate(e,t);if(Array.isArray(e))return e.map(r=>this.resolveBindings(r,t));if(typeof e=="object"){if(Object.prototype.hasOwnProperty.call(e,"valueFrom")||Object.prototype.hasOwnProperty.call(e,"template")){const s=e.valueFrom,a=e.template,i=e.default;try{if(typeof s=="string"){const o=this.getByPath(t,s);return o===void 0?i:o}if(typeof a=="string"){const o=this.interpolate(a,t);return o==null||o===""?i:o}}catch{return i}}const r=Array.isArray(e)?[]:{};for(const s of Object.keys(e))r[s]=this.resolveBindings(e[s],t);return r}return e}interpolate(e,t){const r=/^\$\{([^}]+)\}$/.exec(e);return r?this.getByPath(t,r[1].trim()):/^\$\./.test(e)?this.getByPath(t,e):e.replace(/\$\{([^}]+)\}/g,(s,a)=>{const i=this.getByPath(t,a.trim());return i==null?"":typeof i=="object"?JSON.stringify(i):String(i)})}getByPath(e,t){return(t.startsWith("$.")?t.slice(2):t).split(".").reduce((s,a)=>s?.[a],e)}async runWithTimeout(e,t){return!t||t<=0?e():new Promise((r,s)=>{const a=setTimeout(()=>s(new Error("Step timeout")),t);e().then(i=>{clearTimeout(a),r(i)}).catch(i=>{clearTimeout(a),s(i)})})}async executeWithRepeat(e,t,r){const s=e.repeat,a=[],i=[];let o=[],u=!1;if(s.forEach){u=!0;const c=this.getByPath(t,s.forEach);Array.isArray(c)?o=c:c!=null?o=[c]:o=[]}else if(s.count!=null){let c;typeof s.count=="string"?c=this.getByPath(t,s.count)??0:c=s.count,o=Array.from({length:Math.max(0,c)},(l,d)=>d)}else return{hasError:!0,message:"repeat requires either forEach or count",data:null};for(let c=0;c<o.length;c++){const l=o[c];u?t.forEach={item:l,index:c,total:o.length}:t.loop={index:c,count:o.length};try{const d=Math.max(1,e.retry?.attempts??1),h=e.retry?.delayMs??0,f=e.retry?.backoffFactor??1;let p=null,m=!1;for(let g=0;g<d;g++){try{const y=this.resolveBindings(e.block,t);if(p=await this.runWithTimeout(()=>this.tabManager.executeBlock(y,r),e.timeoutMs),m=!p?.hasError,m)break}catch(y){p={hasError:!0,message:y?.message||"Block execution error"}}if(g<d-1){const y=h*Math.pow(f,g);y>0&&await new Promise(_=>setTimeout(_,y))}}if(m)a.push(p);else if(i.push({index:c,item:l,error:p}),s.continueOnError)a.push(null);else return{hasError:!0,message:`Repeat failed at index ${c}: ${p?.message||"Unknown error"}`,data:{results:a,errors:i,stoppedAt:c}}}catch(d){if(i.push({index:c,item:l,error:d.message}),s.continueOnError)a.push(null);else return{hasError:!0,message:`Repeat failed at index ${c}: ${d.message}`,data:{results:a,errors:i,stoppedAt:c}}}s.delayBetween&&c<o.length-1&&await new Promise(d=>setTimeout(d,s.delayBetween))}return u?delete t.forEach:delete t.loop,{hasError:i.length>0&&!s.continueOnError,message:i.length>0?`Completed with ${i.length} error(s) out of ${o.length}`:`Completed ${o.length} iteration(s)`,data:a}}}class b0{constructor(e){this.tabManager=e,this.workflowRunner=new _0(e)}workflowRunner;async handleCollectWorkflow(e,t){const r=this.validateRequest(e);if(!r.success){t({$isError:!0,message:r.error,data:{}});return}const s=await this.tabManager.createTab(e.targetUrl,e.activateTab===!0);if(s.id===void 0){t({$isError:!0,message:"Failed to create tab or tab ID is missing",data:{}});return}try{console.log("[WorkflowService] Running workflow in tab:",s.id);const a=await this.workflowRunner.run(e.workflow,s.id);t({success:!0,targetUrl:e.targetUrl,tabId:s.id,result:a,timestamp:new Date().toISOString(),closeTabAfterCollection:e.closeTabAfterCollection!==!1})}catch(a){console.error("[WorkflowService] Workflow execution error:",a),t({$isError:!0,message:a instanceof Error?a.message:"Workflow execution failed",data:{}})}finally{await this.cleanup(s.id)}}validateRequest(e){return e.targetUrl?e.workflow?{success:!0}:{success:!1,error:"Workflow is required"}:{success:!1,error:"Target URL is required for workflow"}}async cleanup(e){console.log("[WorkflowService] Cleanup - closing tab:",e),await new Promise(t=>setTimeout(t,1e3)),await this.tabManager.closeTab(e)}}class w0{async handleRequest(e,t){try{console.log("[ApiService] Handle API request:",e.url);const r=await this.fetchData(e);t({success:!0,data:r})}catch(r){console.error("[ApiService] API request error:",r),t({$isError:!0,message:r instanceof Error?r.message:"Unknown error in API request",data:null})}}async fetchData(e){const{url:t,method:r,headers:s,body:a,timeout:i,parseJson:o,returnHeaders:u}=e;console.log(`[ApiService] Fetching ${r} ${t}`);const c=new AbortController,l=setTimeout(()=>c.abort(),i);try{const d={method:r,headers:s,signal:c.signal};a&&!["GET","HEAD"].includes(r)&&(typeof a=="string"?d.body=a:(d.body=JSON.stringify(a),!s["Content-Type"]&&!s["content-type"]&&(d.headers={...s,"Content-Type":"application/json"})));const h=await fetch(t,d);clearTimeout(l);let f;const p=h.headers.get("content-type")||"";if(o&&p.includes("application/json"))try{f=await h.json()}catch{f=await h.text()}else f=await h.text();let m;u&&(m={},h.headers.forEach((y,_)=>{m[_]=y}));const g={status:h.status,statusText:h.statusText,data:f,headers:m};return console.log(`[ApiService] Response status: ${h.status}`),g}catch(d){throw clearTimeout(l),d instanceof Error&&d.name==="AbortError"?new Error(`Request timeout after ${i}ms`):d}}}class v0{aiParsingService;cdpService;workflowService;apiService;constructor(){this.aiParsingService=new g0,this.cdpService=new y0,this.workflowService=new b0(new Cf),this.apiService=new w0}initHandler(){chrome.runtime.onMessage.addListener((e,t,r)=>{if(e.type==="COLLECT_WORKFLOW_NEW_TAB")return this.handleAsyncCollectWorkflow(e.data,r),!0;if(e.type==="CDP_CLICK"&&Ef(e)){const s=t.tab?.id;return s?(this.handleAsyncCdpClick({...e.data,tabId:s},r),!0):(r({$isError:!0,message:"Tab ID not found in sender",data:null}),!1)}if(e.type==="CDP_KEYPRESS"&&Of(e)){const s=t.tab?.id;return s?(this.handleAsyncCdpKeypress({...e.data,tabId:s},r),!0):(r({$isError:!0,message:"Tab ID not found in sender",data:null}),!1)}return e.type==="AI_PARSE_DATA"?(this.handleAsyncAiParseData(e.data,r),!0):e.type==="FETCH_API"&&xf(e)?(this.handleAsyncFetchApi(e.data,r),!0):(r({$isError:!0,message:"Invalid message type",data:{}}),!1)})}async handleAsyncCollectWorkflow(e,t){await this.workflowService.handleCollectWorkflow(e,t)}async handleAsyncCdpClick(e,t){await this.cdpService.handleClick(e,t)}async handleAsyncCdpKeypress(e,t){await this.cdpService.handleKeypress(e,t)}async handleAsyncAiParseData(e,t){await this.aiParsingService.handleParseData(e,t)}async handleAsyncFetchApi(e,t){await this.apiService.handleRequest(e,t)}}console.log("[8G Extension] Background script starting...");const S0=new v0;S0.initHandler();
|