@checksum-ai/runtime 4.15.0 → 4.16.0-beta.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.
@@ -1,72 +1,170 @@
1
- "use strict";var Rm=Object.create;var dr=Object.defineProperty;var Om=Object.getOwnPropertyDescriptor;var Nm=Object.getOwnPropertyNames;var Mm=Object.getPrototypeOf,km=Object.prototype.hasOwnProperty;var o=(t,e)=>dr(t,"name",{value:e,configurable:!0});var P=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},Pm=(t,e)=>{for(var r in e)dr(t,r,{get:e[r],enumerable:!0})},eo=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Nm(e))!km.call(t,s)&&s!==r&&dr(t,s,{get:()=>e[s],enumerable:!(n=Om(e,s))||n.enumerable});return t};var _e=(t,e,r)=>(r=t!=null?Rm(Mm(t)):{},eo(e||!t||!t.__esModule?dr(r,"default",{value:t,enumerable:!0}):r,t)),Lm=t=>eo(dr({},"__esModule",{value:!0}),t);var Xo=P((Dx,Ds)=>{"use strict";var Eh=Object.prototype.hasOwnProperty,Ae="~";function pr(){}o(pr,"Events");Object.create&&(pr.prototype=Object.create(null),new pr().__proto__||(Ae=!1));function wh(t,e,r){this.fn=t,this.context=e,this.once=r||!1}o(wh,"EE");function Yo(t,e,r,n,s){if(typeof r!="function")throw new TypeError("The listener must be a function");var i=new wh(r,n||t,s),a=Ae?Ae+e:e;return t._events[a]?t._events[a].fn?t._events[a]=[t._events[a],i]:t._events[a].push(i):(t._events[a]=i,t._eventsCount++),t}o(Yo,"addListener");function nn(t,e){--t._eventsCount===0?t._events=new pr:delete t._events[e]}o(nn,"clearEvent");function ve(){this._events=new pr,this._eventsCount=0}o(ve,"EventEmitter");ve.prototype.eventNames=o(function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Eh.call(r,n)&&e.push(Ae?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},"eventNames");ve.prototype.listeners=o(function(e){var r=Ae?Ae+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,a=new Array(i);s<i;s++)a[s]=n[s].fn;return a},"listeners");ve.prototype.listenerCount=o(function(e){var r=Ae?Ae+e:e,n=this._events[r];return n?n.fn?1:n.length:0},"listenerCount");ve.prototype.emit=o(function(e,r,n,s,i,a){var c=Ae?Ae+e:e;if(!this._events[c])return!1;var l=this._events[c],u=arguments.length,d,p;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,r),!0;case 3:return l.fn.call(l.context,r,n),!0;case 4:return l.fn.call(l.context,r,n,s),!0;case 5:return l.fn.call(l.context,r,n,s,i),!0;case 6:return l.fn.call(l.context,r,n,s,i,a),!0}for(p=1,d=new Array(u-1);p<u;p++)d[p-1]=arguments[p];l.fn.apply(l.context,d)}else{var _=l.length,g;for(p=0;p<_;p++)switch(l[p].once&&this.removeListener(e,l[p].fn,void 0,!0),u){case 1:l[p].fn.call(l[p].context);break;case 2:l[p].fn.call(l[p].context,r);break;case 3:l[p].fn.call(l[p].context,r,n);break;case 4:l[p].fn.call(l[p].context,r,n,s);break;default:if(!d)for(g=1,d=new Array(u-1);g<u;g++)d[g-1]=arguments[g];l[p].fn.apply(l[p].context,d)}}return!0},"emit");ve.prototype.on=o(function(e,r,n){return Yo(this,e,r,n,!1)},"on");ve.prototype.once=o(function(e,r,n){return Yo(this,e,r,n,!0)},"once");ve.prototype.removeListener=o(function(e,r,n,s){var i=Ae?Ae+e:e;if(!this._events[i])return this;if(!r)return nn(this,i),this;var a=this._events[i];if(a.fn)a.fn===r&&(!s||a.once)&&(!n||a.context===n)&&nn(this,i);else{for(var c=0,l=[],u=a.length;c<u;c++)(a[c].fn!==r||s&&!a[c].once||n&&a[c].context!==n)&&l.push(a[c]);l.length?this._events[i]=l.length===1?l[0]:l:nn(this,i)}return this},"removeListener");ve.prototype.removeAllListeners=o(function(e){var r;return e?(r=Ae?Ae+e:e,this._events[r]&&nn(this,r)):(this._events=new pr,this._eventsCount=0),this},"removeAllListeners");ve.prototype.off=ve.prototype.removeListener;ve.prototype.addListener=ve.prototype.on;ve.prefixed=Ae;ve.EventEmitter=ve;typeof Ds<"u"&&(Ds.exports=ve)});var ec=P((Ux,Qo)=>{"use strict";Qo.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var rc=P((Fx,an)=>{"use strict";var Th=ec(),sn=class extends Error{static{o(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},tc=o((t,e,r)=>new Promise((n,s)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let i=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(l){s(l)}return}let a=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,c=r instanceof Error?r:new sn(a);typeof t.cancel=="function"&&t.cancel(),s(c)},e);Th(t.then(n,s),()=>{clearTimeout(i)})}),"pTimeout");an.exports=tc;an.exports.default=tc;an.exports.TimeoutError=sn});var nc=P($s=>{"use strict";Object.defineProperty($s,"__esModule",{value:!0});function vh(t,e,r){let n=0,s=t.length;for(;s>0;){let i=s/2|0,a=n+i;r(t[a],e)<=0?(n=++a,s-=i+1):s=i}return n}o(vh,"lowerBound");$s.default=vh});var sc=P(Fs=>{"use strict";Object.defineProperty(Fs,"__esModule",{value:!0});var Sh=nc(),Us=class{static{o(this,"PriorityQueue")}constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let s=Sh.default(this._queue,n,(i,a)=>a.priority-i.priority);this._queue.splice(s,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};Fs.default=Us});var cn=P(js=>{"use strict";Object.defineProperty(js,"__esModule",{value:!0});var Ih=Xo(),ic=rc(),xh=sc(),on=o(()=>{},"empty"),Ah=new ic.TimeoutError,Bs=class extends Ih{static{o(this,"PQueue")}constructor(e){var r,n,s,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=on,this._resolveIdle=on,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:xh.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(i=(s=e.interval)===null||s===void 0?void 0:s.toString())!==null&&i!==void 0?i:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=on,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=on,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!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){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,s)=>{let i=o(async()=>{this._pendingCount++,this._intervalCount++;try{let a=this._timeout===void 0&&r.timeout===void 0?e():ic.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&s(Ah)});n(await a)}catch(a){s(a)}this._next()},"run");this._queue.enqueue(i,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};js.default=Bs});var vr=P((iO,Nl)=>{"use strict";var Vg="2.0.0",Wg=Number.MAX_SAFE_INTEGER||9007199254740991,qg=16,Kg=250,Zg=["major","premajor","minor","preminor","patch","prepatch","prerelease"];Nl.exports={MAX_LENGTH:256,MAX_SAFE_COMPONENT_LENGTH:qg,MAX_SAFE_BUILD_LENGTH:Kg,MAX_SAFE_INTEGER:Wg,RELEASE_TYPES:Zg,SEMVER_SPEC_VERSION:Vg,FLAG_INCLUDE_PRERELEASE:1,FLAG_LOOSE:2}});var Sr=P((aO,Ml)=>{"use strict";var Jg=typeof process=="object"&&process.env&&process.env.NODE_DEBUG&&/\bsemver\b/i.test(process.env.NODE_DEBUG)?(...t)=>console.error("SEMVER",...t):()=>{};Ml.exports=Jg});var Xt=P((ot,kl)=>{"use strict";var{MAX_SAFE_COMPONENT_LENGTH:wi,MAX_SAFE_BUILD_LENGTH:Yg,MAX_LENGTH:Xg}=vr(),Qg=Sr();ot=kl.exports={};var ey=ot.re=[],ty=ot.safeRe=[],L=ot.src=[],ry=ot.safeSrc=[],D=ot.t={},ny=0,Ti="[a-zA-Z0-9-]",sy=[["\\s",1],["\\d",Xg],[Ti,Yg]],iy=o(t=>{for(let[e,r]of sy)t=t.split(`${e}*`).join(`${e}{0,${r}}`).split(`${e}+`).join(`${e}{1,${r}}`);return t},"makeSafeRegex"),V=o((t,e,r)=>{let n=iy(e),s=ny++;Qg(t,s,e),D[t]=s,L[s]=e,ry[s]=n,ey[s]=new RegExp(e,r?"g":void 0),ty[s]=new RegExp(n,r?"g":void 0)},"createToken");V("NUMERICIDENTIFIER","0|[1-9]\\d*");V("NUMERICIDENTIFIERLOOSE","\\d+");V("NONNUMERICIDENTIFIER",`\\d*[a-zA-Z-]${Ti}*`);V("MAINVERSION",`(${L[D.NUMERICIDENTIFIER]})\\.(${L[D.NUMERICIDENTIFIER]})\\.(${L[D.NUMERICIDENTIFIER]})`);V("MAINVERSIONLOOSE",`(${L[D.NUMERICIDENTIFIERLOOSE]})\\.(${L[D.NUMERICIDENTIFIERLOOSE]})\\.(${L[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASEIDENTIFIER",`(?:${L[D.NONNUMERICIDENTIFIER]}|${L[D.NUMERICIDENTIFIER]})`);V("PRERELEASEIDENTIFIERLOOSE",`(?:${L[D.NONNUMERICIDENTIFIER]}|${L[D.NUMERICIDENTIFIERLOOSE]})`);V("PRERELEASE",`(?:-(${L[D.PRERELEASEIDENTIFIER]}(?:\\.${L[D.PRERELEASEIDENTIFIER]})*))`);V("PRERELEASELOOSE",`(?:-?(${L[D.PRERELEASEIDENTIFIERLOOSE]}(?:\\.${L[D.PRERELEASEIDENTIFIERLOOSE]})*))`);V("BUILDIDENTIFIER",`${Ti}+`);V("BUILD",`(?:\\+(${L[D.BUILDIDENTIFIER]}(?:\\.${L[D.BUILDIDENTIFIER]})*))`);V("FULLPLAIN",`v?${L[D.MAINVERSION]}${L[D.PRERELEASE]}?${L[D.BUILD]}?`);V("FULL",`^${L[D.FULLPLAIN]}$`);V("LOOSEPLAIN",`[v=\\s]*${L[D.MAINVERSIONLOOSE]}${L[D.PRERELEASELOOSE]}?${L[D.BUILD]}?`);V("LOOSE",`^${L[D.LOOSEPLAIN]}$`);V("GTLT","((?:<|>)?=?)");V("XRANGEIDENTIFIERLOOSE",`${L[D.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`);V("XRANGEIDENTIFIER",`${L[D.NUMERICIDENTIFIER]}|x|X|\\*`);V("XRANGEPLAIN",`[v=\\s]*(${L[D.XRANGEIDENTIFIER]})(?:\\.(${L[D.XRANGEIDENTIFIER]})(?:\\.(${L[D.XRANGEIDENTIFIER]})(?:${L[D.PRERELEASE]})?${L[D.BUILD]}?)?)?`);V("XRANGEPLAINLOOSE",`[v=\\s]*(${L[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[D.XRANGEIDENTIFIERLOOSE]})(?:\\.(${L[D.XRANGEIDENTIFIERLOOSE]})(?:${L[D.PRERELEASELOOSE]})?${L[D.BUILD]}?)?)?`);V("XRANGE",`^${L[D.GTLT]}\\s*${L[D.XRANGEPLAIN]}$`);V("XRANGELOOSE",`^${L[D.GTLT]}\\s*${L[D.XRANGEPLAINLOOSE]}$`);V("COERCEPLAIN",`(^|[^\\d])(\\d{1,${wi}})(?:\\.(\\d{1,${wi}}))?(?:\\.(\\d{1,${wi}}))?`);V("COERCE",`${L[D.COERCEPLAIN]}(?:$|[^\\d])`);V("COERCEFULL",L[D.COERCEPLAIN]+`(?:${L[D.PRERELEASE]})?(?:${L[D.BUILD]})?(?:$|[^\\d])`);V("COERCERTL",L[D.COERCE],!0);V("COERCERTLFULL",L[D.COERCEFULL],!0);V("LONETILDE","(?:~>?)");V("TILDETRIM",`(\\s*)${L[D.LONETILDE]}\\s+`,!0);ot.tildeTrimReplace="$1~";V("TILDE",`^${L[D.LONETILDE]}${L[D.XRANGEPLAIN]}$`);V("TILDELOOSE",`^${L[D.LONETILDE]}${L[D.XRANGEPLAINLOOSE]}$`);V("LONECARET","(?:\\^)");V("CARETTRIM",`(\\s*)${L[D.LONECARET]}\\s+`,!0);ot.caretTrimReplace="$1^";V("CARET",`^${L[D.LONECARET]}${L[D.XRANGEPLAIN]}$`);V("CARETLOOSE",`^${L[D.LONECARET]}${L[D.XRANGEPLAINLOOSE]}$`);V("COMPARATORLOOSE",`^${L[D.GTLT]}\\s*(${L[D.LOOSEPLAIN]})$|^$`);V("COMPARATOR",`^${L[D.GTLT]}\\s*(${L[D.FULLPLAIN]})$|^$`);V("COMPARATORTRIM",`(\\s*)${L[D.GTLT]}\\s*(${L[D.LOOSEPLAIN]}|${L[D.XRANGEPLAIN]})`,!0);ot.comparatorTrimReplace="$1$2$3";V("HYPHENRANGE",`^\\s*(${L[D.XRANGEPLAIN]})\\s+-\\s+(${L[D.XRANGEPLAIN]})\\s*$`);V("HYPHENRANGELOOSE",`^\\s*(${L[D.XRANGEPLAINLOOSE]})\\s+-\\s+(${L[D.XRANGEPLAINLOOSE]})\\s*$`);V("STAR","(<|>)?=?\\s*\\*");V("GTE0","^\\s*>=\\s*0\\.0\\.0\\s*$");V("GTE0PRE","^\\s*>=\\s*0\\.0\\.0-0\\s*$")});var An=P((cO,Pl)=>{"use strict";var ay=Object.freeze({loose:!0}),oy=Object.freeze({}),cy=o(t=>t?typeof t!="object"?ay:t:oy,"parseOptions");Pl.exports=cy});var vi=P((uO,$l)=>{"use strict";var Ll=/^[0-9]+$/,Dl=o((t,e)=>{if(typeof t=="number"&&typeof e=="number")return t===e?0:t<e?-1:1;let r=Ll.test(t),n=Ll.test(e);return r&&n&&(t=+t,e=+e),t===e?0:r&&!n?-1:n&&!r?1:t<e?-1:1},"compareIdentifiers"),ly=o((t,e)=>Dl(e,t),"rcompareIdentifiers");$l.exports={compareIdentifiers:Dl,rcompareIdentifiers:ly}});var Se=P((fO,Fl)=>{"use strict";var Cn=Sr(),{MAX_LENGTH:Ul,MAX_SAFE_INTEGER:Rn}=vr(),{safeRe:On,t:Nn}=Xt(),uy=An(),{compareIdentifiers:Si}=vi(),Ii=class t{static{o(this,"SemVer")}constructor(e,r){if(r=uy(r),e instanceof t){if(e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease)return e;e=e.version}else if(typeof e!="string")throw new TypeError(`Invalid version. Must be a string. Got type "${typeof e}".`);if(e.length>Ul)throw new TypeError(`version is longer than ${Ul} characters`);Cn("SemVer",e,r),this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease;let n=e.trim().match(r.loose?On[Nn.LOOSE]:On[Nn.FULL]);if(!n)throw new TypeError(`Invalid Version: ${e}`);if(this.raw=e,this.major=+n[1],this.minor=+n[2],this.patch=+n[3],this.major>Rn||this.major<0)throw new TypeError("Invalid major version");if(this.minor>Rn||this.minor<0)throw new TypeError("Invalid minor version");if(this.patch>Rn||this.patch<0)throw new TypeError("Invalid patch version");n[4]?this.prerelease=n[4].split(".").map(s=>{if(/^[0-9]+$/.test(s)){let i=+s;if(i>=0&&i<Rn)return i}return s}):this.prerelease=[],this.build=n[5]?n[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(e){if(Cn("SemVer.compare",this.version,this.options,e),!(e instanceof t)){if(typeof e=="string"&&e===this.version)return 0;e=new t(e,this.options)}return e.version===this.version?0:this.compareMain(e)||this.comparePre(e)}compareMain(e){return e instanceof t||(e=new t(e,this.options)),this.major<e.major?-1:this.major>e.major?1:this.minor<e.minor?-1:this.minor>e.minor?1:this.patch<e.patch?-1:this.patch>e.patch?1:0}comparePre(e){if(e instanceof t||(e=new t(e,this.options)),this.prerelease.length&&!e.prerelease.length)return-1;if(!this.prerelease.length&&e.prerelease.length)return 1;if(!this.prerelease.length&&!e.prerelease.length)return 0;let r=0;do{let n=this.prerelease[r],s=e.prerelease[r];if(Cn("prerelease compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Si(n,s)}while(++r)}compareBuild(e){e instanceof t||(e=new t(e,this.options));let r=0;do{let n=this.build[r],s=e.build[r];if(Cn("build compare",r,n,s),n===void 0&&s===void 0)return 0;if(s===void 0)return 1;if(n===void 0)return-1;if(n===s)continue;return Si(n,s)}while(++r)}inc(e,r,n){if(e.startsWith("pre")){if(!r&&n===!1)throw new Error("invalid increment argument: identifier is empty");if(r){let s=`-${r}`.match(this.options.loose?On[Nn.PRERELEASELOOSE]:On[Nn.PRERELEASE]);if(!s||s[1]!==r)throw new Error(`invalid identifier: ${r}`)}}switch(e){case"premajor":this.prerelease.length=0,this.patch=0,this.minor=0,this.major++,this.inc("pre",r,n);break;case"preminor":this.prerelease.length=0,this.patch=0,this.minor++,this.inc("pre",r,n);break;case"prepatch":this.prerelease.length=0,this.inc("patch",r,n),this.inc("pre",r,n);break;case"prerelease":this.prerelease.length===0&&this.inc("patch",r,n),this.inc("pre",r,n);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":{let s=Number(n)?1:0;if(this.prerelease.length===0)this.prerelease=[s];else{let i=this.prerelease.length;for(;--i>=0;)typeof this.prerelease[i]=="number"&&(this.prerelease[i]++,i=-2);if(i===-1){if(r===this.prerelease.join(".")&&n===!1)throw new Error("invalid increment argument: identifier already exists");this.prerelease.push(s)}}if(r){let i=[r,s];n===!1&&(i=[r]),Si(this.prerelease[0],r)===0?isNaN(this.prerelease[1])&&(this.prerelease=i):this.prerelease=i}break}default:throw new Error(`invalid increment argument: ${e}`)}return this.raw=this.format(),this.build.length&&(this.raw+=`+${this.build.join(".")}`),this}};Fl.exports=Ii});var Dt=P((mO,jl)=>{"use strict";var Bl=Se(),dy=o((t,e,r=!1)=>{if(t instanceof Bl)return t;try{return new Bl(t,e)}catch(n){if(!r)return null;throw n}},"parse");jl.exports=dy});var Gl=P((gO,Hl)=>{"use strict";var fy=Dt(),py=o((t,e)=>{let r=fy(t,e);return r?r.version:null},"valid");Hl.exports=py});var Vl=P((_O,zl)=>{"use strict";var my=Dt(),hy=o((t,e)=>{let r=my(t.trim().replace(/^[=v]+/,""),e);return r?r.version:null},"clean");zl.exports=hy});var Kl=P((EO,ql)=>{"use strict";var Wl=Se(),gy=o((t,e,r,n,s)=>{typeof r=="string"&&(s=n,n=r,r=void 0);try{return new Wl(t instanceof Wl?t.version:t,r).inc(e,n,s).version}catch{return null}},"inc");ql.exports=gy});var Yl=P((TO,Jl)=>{"use strict";var Zl=Dt(),yy=o((t,e)=>{let r=Zl(t,null,!0),n=Zl(e,null,!0),s=r.compare(n);if(s===0)return null;let i=s>0,a=i?r:n,c=i?n:r,l=!!a.prerelease.length;if(!!c.prerelease.length&&!l){if(!c.patch&&!c.minor)return"major";if(c.compareMain(a)===0)return c.minor&&!c.patch?"minor":"patch"}let d=l?"pre":"";return r.major!==n.major?d+"major":r.minor!==n.minor?d+"minor":r.patch!==n.patch?d+"patch":"prerelease"},"diff");Jl.exports=yy});var Ql=P((SO,Xl)=>{"use strict";var _y=Se(),by=o((t,e)=>new _y(t,e).major,"major");Xl.exports=by});var tu=P((xO,eu)=>{"use strict";var Ey=Se(),wy=o((t,e)=>new Ey(t,e).minor,"minor");eu.exports=wy});var nu=P((CO,ru)=>{"use strict";var Ty=Se(),vy=o((t,e)=>new Ty(t,e).patch,"patch");ru.exports=vy});var iu=P((OO,su)=>{"use strict";var Sy=Dt(),Iy=o((t,e)=>{let r=Sy(t,e);return r&&r.prerelease.length?r.prerelease:null},"prerelease");su.exports=Iy});var Ge=P((MO,ou)=>{"use strict";var au=Se(),xy=o((t,e,r)=>new au(t,r).compare(new au(e,r)),"compare");ou.exports=xy});var lu=P((PO,cu)=>{"use strict";var Ay=Ge(),Cy=o((t,e,r)=>Ay(e,t,r),"rcompare");cu.exports=Cy});var du=P((DO,uu)=>{"use strict";var Ry=Ge(),Oy=o((t,e)=>Ry(t,e,!0),"compareLoose");uu.exports=Oy});var Mn=P((UO,pu)=>{"use strict";var fu=Se(),Ny=o((t,e,r)=>{let n=new fu(t,r),s=new fu(e,r);return n.compare(s)||n.compareBuild(s)},"compareBuild");pu.exports=Ny});var hu=P((BO,mu)=>{"use strict";var My=Mn(),ky=o((t,e)=>t.sort((r,n)=>My(r,n,e)),"sort");mu.exports=ky});var yu=P((HO,gu)=>{"use strict";var Py=Mn(),Ly=o((t,e)=>t.sort((r,n)=>Py(n,r,e)),"rsort");gu.exports=Ly});var Ir=P((zO,_u)=>{"use strict";var Dy=Ge(),$y=o((t,e,r)=>Dy(t,e,r)>0,"gt");_u.exports=$y});var kn=P((WO,bu)=>{"use strict";var Uy=Ge(),Fy=o((t,e,r)=>Uy(t,e,r)<0,"lt");bu.exports=Fy});var xi=P((KO,Eu)=>{"use strict";var By=Ge(),jy=o((t,e,r)=>By(t,e,r)===0,"eq");Eu.exports=jy});var Ai=P((JO,wu)=>{"use strict";var Hy=Ge(),Gy=o((t,e,r)=>Hy(t,e,r)!==0,"neq");wu.exports=Gy});var Pn=P((XO,Tu)=>{"use strict";var zy=Ge(),Vy=o((t,e,r)=>zy(t,e,r)>=0,"gte");Tu.exports=Vy});var Ln=P((eN,vu)=>{"use strict";var Wy=Ge(),qy=o((t,e,r)=>Wy(t,e,r)<=0,"lte");vu.exports=qy});var Ci=P((rN,Su)=>{"use strict";var Ky=xi(),Zy=Ai(),Jy=Ir(),Yy=Pn(),Xy=kn(),Qy=Ln(),e_=o((t,e,r,n)=>{switch(e){case"===":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t===r;case"!==":return typeof t=="object"&&(t=t.version),typeof r=="object"&&(r=r.version),t!==r;case"":case"=":case"==":return Ky(t,r,n);case"!=":return Zy(t,r,n);case">":return Jy(t,r,n);case">=":return Yy(t,r,n);case"<":return Xy(t,r,n);case"<=":return Qy(t,r,n);default:throw new TypeError(`Invalid operator: ${e}`)}},"cmp");Su.exports=e_});var xu=P((sN,Iu)=>{"use strict";var t_=Se(),r_=Dt(),{safeRe:Dn,t:$n}=Xt(),n_=o((t,e)=>{if(t instanceof t_)return t;if(typeof t=="number"&&(t=String(t)),typeof t!="string")return null;e=e||{};let r=null;if(!e.rtl)r=t.match(e.includePrerelease?Dn[$n.COERCEFULL]:Dn[$n.COERCE]);else{let l=e.includePrerelease?Dn[$n.COERCERTLFULL]:Dn[$n.COERCERTL],u;for(;(u=l.exec(t))&&(!r||r.index+r[0].length!==t.length);)(!r||u.index+u[0].length!==r.index+r[0].length)&&(r=u),l.lastIndex=u.index+u[1].length+u[2].length;l.lastIndex=-1}if(r===null)return null;let n=r[2],s=r[3]||"0",i=r[4]||"0",a=e.includePrerelease&&r[5]?`-${r[5]}`:"",c=e.includePrerelease&&r[6]?`+${r[6]}`:"";return r_(`${n}.${s}.${i}${a}${c}`,e)},"coerce");Iu.exports=n_});var Cu=P((aN,Au)=>{"use strict";var Ri=class{static{o(this,"LRUCache")}constructor(){this.max=1e3,this.map=new Map}get(e){let r=this.map.get(e);if(r!==void 0)return this.map.delete(e),this.map.set(e,r),r}delete(e){return this.map.delete(e)}set(e,r){if(!this.delete(e)&&r!==void 0){if(this.map.size>=this.max){let s=this.map.keys().next().value;this.delete(s)}this.map.set(e,r)}return this}};Au.exports=Ri});var ze=P((cN,Mu)=>{"use strict";var s_=/\s+/g,Oi=class t{static{o(this,"Range")}constructor(e,r){if(r=a_(r),e instanceof t)return e.loose===!!r.loose&&e.includePrerelease===!!r.includePrerelease?e:new t(e.raw,r);if(e instanceof Ni)return this.raw=e.value,this.set=[[e]],this.formatted=void 0,this;if(this.options=r,this.loose=!!r.loose,this.includePrerelease=!!r.includePrerelease,this.raw=e.trim().replace(s_," "),this.set=this.raw.split("||").map(n=>this.parseRange(n.trim())).filter(n=>n.length),!this.set.length)throw new TypeError(`Invalid SemVer Range: ${this.raw}`);if(this.set.length>1){let n=this.set[0];if(this.set=this.set.filter(s=>!Ou(s[0])),this.set.length===0)this.set=[n];else if(this.set.length>1){for(let s of this.set)if(s.length===1&&p_(s[0])){this.set=[s];break}}}this.formatted=void 0}get range(){if(this.formatted===void 0){this.formatted="";for(let e=0;e<this.set.length;e++){e>0&&(this.formatted+="||");let r=this.set[e];for(let n=0;n<r.length;n++)n>0&&(this.formatted+=" "),this.formatted+=r[n].toString().trim()}}return this.formatted}format(){return this.range}toString(){return this.range}parseRange(e){let n=((this.options.includePrerelease&&d_)|(this.options.loose&&f_))+":"+e,s=Ru.get(n);if(s)return s;let i=this.options.loose,a=i?Ce[Ie.HYPHENRANGELOOSE]:Ce[Ie.HYPHENRANGE];e=e.replace(a,v_(this.options.includePrerelease)),ee("hyphen replace",e),e=e.replace(Ce[Ie.COMPARATORTRIM],c_),ee("comparator trim",e),e=e.replace(Ce[Ie.TILDETRIM],l_),ee("tilde trim",e),e=e.replace(Ce[Ie.CARETTRIM],u_),ee("caret trim",e);let c=e.split(" ").map(p=>m_(p,this.options)).join(" ").split(/\s+/).map(p=>T_(p,this.options));i&&(c=c.filter(p=>(ee("loose invalid filter",p,this.options),!!p.match(Ce[Ie.COMPARATORLOOSE])))),ee("range list",c);let l=new Map,u=c.map(p=>new Ni(p,this.options));for(let p of u){if(Ou(p))return[p];l.set(p.value,p)}l.size>1&&l.has("")&&l.delete("");let d=[...l.values()];return Ru.set(n,d),d}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Range is required");return this.set.some(n=>Nu(n,r)&&e.set.some(s=>Nu(s,r)&&n.every(i=>s.every(a=>i.intersects(a,r)))))}test(e){if(!e)return!1;if(typeof e=="string")try{e=new o_(e,this.options)}catch{return!1}for(let r=0;r<this.set.length;r++)if(S_(this.set[r],e,this.options))return!0;return!1}};Mu.exports=Oi;var i_=Cu(),Ru=new i_,a_=An(),Ni=xr(),ee=Sr(),o_=Se(),{safeRe:Ce,t:Ie,comparatorTrimReplace:c_,tildeTrimReplace:l_,caretTrimReplace:u_}=Xt(),{FLAG_INCLUDE_PRERELEASE:d_,FLAG_LOOSE:f_}=vr(),Ou=o(t=>t.value==="<0.0.0-0","isNullSet"),p_=o(t=>t.value==="","isAny"),Nu=o((t,e)=>{let r=!0,n=t.slice(),s=n.pop();for(;r&&n.length;)r=n.every(i=>s.intersects(i,e)),s=n.pop();return r},"isSatisfiable"),m_=o((t,e)=>(t=t.replace(Ce[Ie.BUILD],""),ee("comp",t,e),t=y_(t,e),ee("caret",t),t=h_(t,e),ee("tildes",t),t=b_(t,e),ee("xrange",t),t=w_(t,e),ee("stars",t),t),"parseComparator"),Re=o(t=>!t||t.toLowerCase()==="x"||t==="*","isX"),h_=o((t,e)=>t.trim().split(/\s+/).map(r=>g_(r,e)).join(" "),"replaceTildes"),g_=o((t,e)=>{let r=e.loose?Ce[Ie.TILDELOOSE]:Ce[Ie.TILDE];return t.replace(r,(n,s,i,a,c)=>{ee("tilde",t,n,s,i,a,c);let l;return Re(s)?l="":Re(i)?l=`>=${s}.0.0 <${+s+1}.0.0-0`:Re(a)?l=`>=${s}.${i}.0 <${s}.${+i+1}.0-0`:c?(ee("replaceTilde pr",c),l=`>=${s}.${i}.${a}-${c} <${s}.${+i+1}.0-0`):l=`>=${s}.${i}.${a} <${s}.${+i+1}.0-0`,ee("tilde return",l),l})},"replaceTilde"),y_=o((t,e)=>t.trim().split(/\s+/).map(r=>__(r,e)).join(" "),"replaceCarets"),__=o((t,e)=>{ee("caret",t,e);let r=e.loose?Ce[Ie.CARETLOOSE]:Ce[Ie.CARET],n=e.includePrerelease?"-0":"";return t.replace(r,(s,i,a,c,l)=>{ee("caret",t,s,i,a,c,l);let u;return Re(i)?u="":Re(a)?u=`>=${i}.0.0${n} <${+i+1}.0.0-0`:Re(c)?i==="0"?u=`>=${i}.${a}.0${n} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.0${n} <${+i+1}.0.0-0`:l?(ee("replaceCaret pr",l),i==="0"?a==="0"?u=`>=${i}.${a}.${c}-${l} <${i}.${a}.${+c+1}-0`:u=`>=${i}.${a}.${c}-${l} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.${c}-${l} <${+i+1}.0.0-0`):(ee("no pr"),i==="0"?a==="0"?u=`>=${i}.${a}.${c}${n} <${i}.${a}.${+c+1}-0`:u=`>=${i}.${a}.${c}${n} <${i}.${+a+1}.0-0`:u=`>=${i}.${a}.${c} <${+i+1}.0.0-0`),ee("caret return",u),u})},"replaceCaret"),b_=o((t,e)=>(ee("replaceXRanges",t,e),t.split(/\s+/).map(r=>E_(r,e)).join(" ")),"replaceXRanges"),E_=o((t,e)=>{t=t.trim();let r=e.loose?Ce[Ie.XRANGELOOSE]:Ce[Ie.XRANGE];return t.replace(r,(n,s,i,a,c,l)=>{ee("xRange",t,n,s,i,a,c,l);let u=Re(i),d=u||Re(a),p=d||Re(c),_=p;return s==="="&&_&&(s=""),l=e.includePrerelease?"-0":"",u?s===">"||s==="<"?n="<0.0.0-0":n="*":s&&_?(d&&(a=0),c=0,s===">"?(s=">=",d?(i=+i+1,a=0,c=0):(a=+a+1,c=0)):s==="<="&&(s="<",d?i=+i+1:a=+a+1),s==="<"&&(l="-0"),n=`${s+i}.${a}.${c}${l}`):d?n=`>=${i}.0.0${l} <${+i+1}.0.0-0`:p&&(n=`>=${i}.${a}.0${l} <${i}.${+a+1}.0-0`),ee("xRange return",n),n})},"replaceXRange"),w_=o((t,e)=>(ee("replaceStars",t,e),t.trim().replace(Ce[Ie.STAR],"")),"replaceStars"),T_=o((t,e)=>(ee("replaceGTE0",t,e),t.trim().replace(Ce[e.includePrerelease?Ie.GTE0PRE:Ie.GTE0],"")),"replaceGTE0"),v_=o(t=>(e,r,n,s,i,a,c,l,u,d,p,_)=>(Re(n)?r="":Re(s)?r=`>=${n}.0.0${t?"-0":""}`:Re(i)?r=`>=${n}.${s}.0${t?"-0":""}`:a?r=`>=${r}`:r=`>=${r}${t?"-0":""}`,Re(u)?l="":Re(d)?l=`<${+u+1}.0.0-0`:Re(p)?l=`<${u}.${+d+1}.0-0`:_?l=`<=${u}.${d}.${p}-${_}`:t?l=`<${u}.${d}.${+p+1}-0`:l=`<=${l}`,`${r} ${l}`.trim()),"hyphenReplace"),S_=o((t,e,r)=>{for(let n=0;n<t.length;n++)if(!t[n].test(e))return!1;if(e.prerelease.length&&!r.includePrerelease){for(let n=0;n<t.length;n++)if(ee(t[n].semver),t[n].semver!==Ni.ANY&&t[n].semver.prerelease.length>0){let s=t[n].semver;if(s.major===e.major&&s.minor===e.minor&&s.patch===e.patch)return!0}return!1}return!0},"testSet")});var xr=P((uN,Uu)=>{"use strict";var Ar=Symbol("SemVer ANY"),Pi=class t{static{o(this,"Comparator")}static get ANY(){return Ar}constructor(e,r){if(r=ku(r),e instanceof t){if(e.loose===!!r.loose)return e;e=e.value}e=e.trim().split(/\s+/).join(" "),ki("comparator",e,r),this.options=r,this.loose=!!r.loose,this.parse(e),this.semver===Ar?this.value="":this.value=this.operator+this.semver.version,ki("comp",this)}parse(e){let r=this.options.loose?Pu[Lu.COMPARATORLOOSE]:Pu[Lu.COMPARATOR],n=e.match(r);if(!n)throw new TypeError(`Invalid comparator: ${e}`);this.operator=n[1]!==void 0?n[1]:"",this.operator==="="&&(this.operator=""),n[2]?this.semver=new Du(n[2],this.options.loose):this.semver=Ar}toString(){return this.value}test(e){if(ki("Comparator.test",e,this.options.loose),this.semver===Ar||e===Ar)return!0;if(typeof e=="string")try{e=new Du(e,this.options)}catch{return!1}return Mi(e,this.operator,this.semver,this.options)}intersects(e,r){if(!(e instanceof t))throw new TypeError("a Comparator is required");return this.operator===""?this.value===""?!0:new $u(e.value,r).test(this.value):e.operator===""?e.value===""?!0:new $u(this.value,r).test(e.semver):(r=ku(r),r.includePrerelease&&(this.value==="<0.0.0-0"||e.value==="<0.0.0-0")||!r.includePrerelease&&(this.value.startsWith("<0.0.0")||e.value.startsWith("<0.0.0"))?!1:!!(this.operator.startsWith(">")&&e.operator.startsWith(">")||this.operator.startsWith("<")&&e.operator.startsWith("<")||this.semver.version===e.semver.version&&this.operator.includes("=")&&e.operator.includes("=")||Mi(this.semver,"<",e.semver,r)&&this.operator.startsWith(">")&&e.operator.startsWith("<")||Mi(this.semver,">",e.semver,r)&&this.operator.startsWith("<")&&e.operator.startsWith(">")))}};Uu.exports=Pi;var ku=An(),{safeRe:Pu,t:Lu}=Xt(),Mi=Ci(),ki=Sr(),Du=Se(),$u=ze()});var Cr=P((fN,Fu)=>{"use strict";var I_=ze(),x_=o((t,e,r)=>{try{e=new I_(e,r)}catch{return!1}return e.test(t)},"satisfies");Fu.exports=x_});var ju=P((mN,Bu)=>{"use strict";var A_=ze(),C_=o((t,e)=>new A_(t,e).set.map(r=>r.map(n=>n.value).join(" ").trim().split(" ")),"toComparators");Bu.exports=C_});var Gu=P((gN,Hu)=>{"use strict";var R_=Se(),O_=ze(),N_=o((t,e,r)=>{let n=null,s=null,i=null;try{i=new O_(e,r)}catch{return null}return t.forEach(a=>{i.test(a)&&(!n||s.compare(a)===-1)&&(n=a,s=new R_(n,r))}),n},"maxSatisfying");Hu.exports=N_});var Vu=P((_N,zu)=>{"use strict";var M_=Se(),k_=ze(),P_=o((t,e,r)=>{let n=null,s=null,i=null;try{i=new k_(e,r)}catch{return null}return t.forEach(a=>{i.test(a)&&(!n||s.compare(a)===1)&&(n=a,s=new M_(n,r))}),n},"minSatisfying");zu.exports=P_});var Ku=P((EN,qu)=>{"use strict";var Li=Se(),L_=ze(),Wu=Ir(),D_=o((t,e)=>{t=new L_(t,e);let r=new Li("0.0.0");if(t.test(r)||(r=new Li("0.0.0-0"),t.test(r)))return r;r=null;for(let n=0;n<t.set.length;++n){let s=t.set[n],i=null;s.forEach(a=>{let c=new Li(a.semver.version);switch(a.operator){case">":c.prerelease.length===0?c.patch++:c.prerelease.push(0),c.raw=c.format();case"":case">=":(!i||Wu(c,i))&&(i=c);break;case"<":case"<=":break;default:throw new Error(`Unexpected operation: ${a.operator}`)}}),i&&(!r||Wu(r,i))&&(r=i)}return r&&t.test(r)?r:null},"minVersion");qu.exports=D_});var Ju=P((TN,Zu)=>{"use strict";var $_=ze(),U_=o((t,e)=>{try{return new $_(t,e).range||"*"}catch{return null}},"validRange");Zu.exports=U_});var Un=P((SN,ed)=>{"use strict";var F_=Se(),Qu=xr(),{ANY:B_}=Qu,j_=ze(),H_=Cr(),Yu=Ir(),Xu=kn(),G_=Ln(),z_=Pn(),V_=o((t,e,r,n)=>{t=new F_(t,n),e=new j_(e,n);let s,i,a,c,l;switch(r){case">":s=Yu,i=G_,a=Xu,c=">",l=">=";break;case"<":s=Xu,i=z_,a=Yu,c="<",l="<=";break;default:throw new TypeError('Must provide a hilo val of "<" or ">"')}if(H_(t,e,n))return!1;for(let u=0;u<e.set.length;++u){let d=e.set[u],p=null,_=null;if(d.forEach(g=>{g.semver===B_&&(g=new Qu(">=0.0.0")),p=p||g,_=_||g,s(g.semver,p.semver,n)?p=g:a(g.semver,_.semver,n)&&(_=g)}),p.operator===c||p.operator===l||(!_.operator||_.operator===c)&&i(t,_.semver))return!1;if(_.operator===l&&a(t,_.semver))return!1}return!0},"outside");ed.exports=V_});var rd=P((xN,td)=>{"use strict";var W_=Un(),q_=o((t,e,r)=>W_(t,e,">",r),"gtr");td.exports=q_});var sd=P((CN,nd)=>{"use strict";var K_=Un(),Z_=o((t,e,r)=>K_(t,e,"<",r),"ltr");nd.exports=Z_});var od=P((ON,ad)=>{"use strict";var id=ze(),J_=o((t,e,r)=>(t=new id(t,r),e=new id(e,r),t.intersects(e,r)),"intersects");ad.exports=J_});var ld=P((MN,cd)=>{"use strict";var Y_=Cr(),X_=Ge();cd.exports=(t,e,r)=>{let n=[],s=null,i=null,a=t.sort((d,p)=>X_(d,p,r));for(let d of a)Y_(d,e,r)?(i=d,s||(s=d)):(i&&n.push([s,i]),i=null,s=null);s&&n.push([s,null]);let c=[];for(let[d,p]of n)d===p?c.push(d):!p&&d===a[0]?c.push("*"):p?d===a[0]?c.push(`<=${p}`):c.push(`${d} - ${p}`):c.push(`>=${d}`);let l=c.join(" || "),u=typeof e.raw=="string"?e.raw:String(e);return l.length<u.length?l:e}});var hd=P((kN,md)=>{"use strict";var ud=ze(),$i=xr(),{ANY:Di}=$i,Rr=Cr(),Ui=Ge(),Q_=o((t,e,r={})=>{if(t===e)return!0;t=new ud(t,r),e=new ud(e,r);let n=!1;e:for(let s of t.set){for(let i of e.set){let a=tb(s,i,r);if(n=n||a!==null,a)continue e}if(n)return!1}return!0},"subset"),eb=[new $i(">=0.0.0-0")],dd=[new $i(">=0.0.0")],tb=o((t,e,r)=>{if(t===e)return!0;if(t.length===1&&t[0].semver===Di){if(e.length===1&&e[0].semver===Di)return!0;r.includePrerelease?t=eb:t=dd}if(e.length===1&&e[0].semver===Di){if(r.includePrerelease)return!0;e=dd}let n=new Set,s,i;for(let g of t)g.operator===">"||g.operator===">="?s=fd(s,g,r):g.operator==="<"||g.operator==="<="?i=pd(i,g,r):n.add(g.semver);if(n.size>1)return null;let a;if(s&&i){if(a=Ui(s.semver,i.semver,r),a>0)return null;if(a===0&&(s.operator!==">="||i.operator!=="<="))return null}for(let g of n){if(s&&!Rr(g,String(s),r)||i&&!Rr(g,String(i),r))return null;for(let y of e)if(!Rr(g,String(y),r))return!1;return!0}let c,l,u,d,p=i&&!r.includePrerelease&&i.semver.prerelease.length?i.semver:!1,_=s&&!r.includePrerelease&&s.semver.prerelease.length?s.semver:!1;p&&p.prerelease.length===1&&i.operator==="<"&&p.prerelease[0]===0&&(p=!1);for(let g of e){if(d=d||g.operator===">"||g.operator===">=",u=u||g.operator==="<"||g.operator==="<=",s){if(_&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===_.major&&g.semver.minor===_.minor&&g.semver.patch===_.patch&&(_=!1),g.operator===">"||g.operator===">="){if(c=fd(s,g,r),c===g&&c!==s)return!1}else if(s.operator===">="&&!Rr(s.semver,String(g),r))return!1}if(i){if(p&&g.semver.prerelease&&g.semver.prerelease.length&&g.semver.major===p.major&&g.semver.minor===p.minor&&g.semver.patch===p.patch&&(p=!1),g.operator==="<"||g.operator==="<="){if(l=pd(i,g,r),l===g&&l!==i)return!1}else if(i.operator==="<="&&!Rr(i.semver,String(g),r))return!1}if(!g.operator&&(i||s)&&a!==0)return!1}return!(s&&u&&!i&&a!==0||i&&d&&!s&&a!==0||_||p)},"simpleSubset"),fd=o((t,e,r)=>{if(!t)return e;let n=Ui(t.semver,e.semver,r);return n>0?t:n<0||e.operator===">"&&t.operator===">="?e:t},"higherGT"),pd=o((t,e,r)=>{if(!t)return e;let n=Ui(t.semver,e.semver,r);return n<0?t:n>0||e.operator==="<"&&t.operator==="<="?e:t},"lowerLT");md.exports=Q_});var bd=P((LN,_d)=>{"use strict";var Fi=Xt(),gd=vr(),rb=Se(),yd=vi(),nb=Dt(),sb=Gl(),ib=Vl(),ab=Kl(),ob=Yl(),cb=Ql(),lb=tu(),ub=nu(),db=iu(),fb=Ge(),pb=lu(),mb=du(),hb=Mn(),gb=hu(),yb=yu(),_b=Ir(),bb=kn(),Eb=xi(),wb=Ai(),Tb=Pn(),vb=Ln(),Sb=Ci(),Ib=xu(),xb=xr(),Ab=ze(),Cb=Cr(),Rb=ju(),Ob=Gu(),Nb=Vu(),Mb=Ku(),kb=Ju(),Pb=Un(),Lb=rd(),Db=sd(),$b=od(),Ub=ld(),Fb=hd();_d.exports={parse:nb,valid:sb,clean:ib,inc:ab,diff:ob,major:cb,minor:lb,patch:ub,prerelease:db,compare:fb,rcompare:pb,compareLoose:mb,compareBuild:hb,sort:gb,rsort:yb,gt:_b,lt:bb,eq:Eb,neq:wb,gte:Tb,lte:vb,cmp:Sb,coerce:Ib,Comparator:xb,Range:Ab,satisfies:Cb,toComparators:Rb,maxSatisfying:Ob,minSatisfying:Nb,minVersion:Mb,validRange:kb,outside:Pb,gtr:Lb,ltr:Db,intersects:$b,simplifyRange:Ub,subset:Fb,SemVer:rb,re:Fi.re,src:Fi.src,tokens:Fi.t,SEMVER_SPEC_VERSION:gd.SEMVER_SPEC_VERSION,RELEASE_TYPES:gd.RELEASE_TYPES,compareIdentifiers:yd.compareIdentifiers,rcompareIdentifiers:yd.rcompareIdentifiers}});var hf=P(Qn=>{"use strict";Qn.byteLength=uw;Qn.toByteArray=fw;Qn.fromByteArray=hw;var dt=[],We=[],lw=typeof Uint8Array<"u"?Uint8Array:Array,la="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(Bt=0,pf=la.length;Bt<pf;++Bt)dt[Bt]=la[Bt],We[la.charCodeAt(Bt)]=Bt;var Bt,pf;We[45]=62;We[95]=63;function mf(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}o(mf,"getLens");function uw(t){var e=mf(t),r=e[0],n=e[1];return(r+n)*3/4-n}o(uw,"byteLength");function dw(t,e,r){return(e+r)*3/4-r}o(dw,"_byteLength");function fw(t){var e,r=mf(t),n=r[0],s=r[1],i=new lw(dw(t,n,s)),a=0,c=s>0?n-4:n,l;for(l=0;l<c;l+=4)e=We[t.charCodeAt(l)]<<18|We[t.charCodeAt(l+1)]<<12|We[t.charCodeAt(l+2)]<<6|We[t.charCodeAt(l+3)],i[a++]=e>>16&255,i[a++]=e>>8&255,i[a++]=e&255;return s===2&&(e=We[t.charCodeAt(l)]<<2|We[t.charCodeAt(l+1)]>>4,i[a++]=e&255),s===1&&(e=We[t.charCodeAt(l)]<<10|We[t.charCodeAt(l+1)]<<4|We[t.charCodeAt(l+2)]>>2,i[a++]=e>>8&255,i[a++]=e&255),i}o(fw,"toByteArray");function pw(t){return dt[t>>18&63]+dt[t>>12&63]+dt[t>>6&63]+dt[t&63]}o(pw,"tripletToBase64");function mw(t,e,r){for(var n,s=[],i=e;i<r;i+=3)n=(t[i]<<16&16711680)+(t[i+1]<<8&65280)+(t[i+2]&255),s.push(pw(n));return s.join("")}o(mw,"encodeChunk");function hw(t){for(var e,r=t.length,n=r%3,s=[],i=16383,a=0,c=r-n;a<c;a+=i)s.push(mw(t,a,a+i>c?c:a+i));return n===1?(e=t[r-1],s.push(dt[e>>2]+dt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],s.push(dt[e>>10]+dt[e>>4&63]+dt[e<<2&63]+"=")),s.join("")}o(hw,"fromByteArray")});var kf=P((J3,gt)=>{var ga=require("fs"),ts=require("path"),Fw=require("os"),Bw=require("crypto"),Cf=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function jw(){return Cf[Math.floor(Math.random()*Cf.length)]}o(jw,"_getRandomTip");function rr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(rr,"parseBoolean");function Hw(){return process.stdout.isTTY}o(Hw,"supportsAnsi");function Gw(t){return Hw()?`\x1B[2m${t}\x1B[0m`:t}o(Gw,"dim");var zw=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Vw(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
2
- `);let n;for(;(n=zw.exec(r))!=null;){let s=n[1],i=n[2]||"";i=i.trim();let a=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),a==='"'&&(i=i.replace(/\\n/g,`
3
- `),i=i.replace(/\\r/g,"\r")),e[s]=i}return e}o(Vw,"parse");function Ww(t){t=t||{};let e=Mf(t);t.path=e;let r=pe.configDotenv(t);if(!r.parsed){let a=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw a.code="MISSING_DATA",a}let n=Nf(t).split(","),s=n.length,i;for(let a=0;a<s;a++)try{let c=n[a].trim(),l=Kw(r,c);i=pe.decrypt(l.ciphertext,l.key);break}catch(c){if(a+1>=s)throw c}return pe.parse(i)}o(Ww,"_parseVault");function qw(t){console.error(`\u26A0 ${t}`)}o(qw,"_warn");function Fr(t){console.log(`\u2506 ${t}`)}o(Fr,"_debug");function Of(t){console.log(`\u25C7 ${t}`)}o(Of,"_log");function Nf(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}o(Nf,"_dotenvKey");function Kw(t,e){let r;try{r=new URL(e)}catch(c){if(c.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw c}let n=r.password;if(!n){let c=new Error("INVALID_DOTENV_KEY: Missing key part");throw c.code="INVALID_DOTENV_KEY",c}let s=r.searchParams.get("environment");if(!s){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let i=`DOTENV_VAULT_${s.toUpperCase()}`,a=t.parsed[i];if(!a){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:a,key:n}}o(Kw,"_instructions");function Mf(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)ga.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=ts.resolve(process.cwd(),".env.vault");return ga.existsSync(e)?e:null}o(Mf,"_vaultPath");function Rf(t){return t[0]==="~"?ts.join(Fw.homedir(),t.slice(1)):t}o(Rf,"_resolveHome");function Zw(t){let e=rr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=rr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&Of("loading env from encrypted .env.vault");let n=pe._parseVault(t),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),pe.populate(s,n,t),{parsed:n}}o(Zw,"_configVault");function Jw(t){let e=ts.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let s=rr(n.DOTENV_CONFIG_DEBUG||t&&t.debug),i=rr(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:s&&Fr("no encoding is specified (UTF-8 is used by default)");let a=[e];if(t&&t.path)if(!Array.isArray(t.path))a=[Rf(t.path)];else{a=[];for(let d of t.path)a.push(Rf(d))}let c,l={};for(let d of a)try{let p=pe.parse(ga.readFileSync(d,{encoding:r}));pe.populate(l,p,t)}catch(p){s&&Fr(`failed to load ${d} ${p.message}`),c=p}let u=pe.populate(n,l,t);if(s=rr(n.DOTENV_CONFIG_DEBUG||s),i=rr(n.DOTENV_CONFIG_QUIET||i),s||!i){let d=Object.keys(u).length,p=[];for(let _ of a)try{let g=ts.relative(process.cwd(),_);p.push(g)}catch(g){s&&Fr(`failed to load ${_} ${g.message}`),c=g}Of(`injected env (${d}) from ${p.join(",")} ${Gw(`// tip: ${jw()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}o(Jw,"configDotenv");function Yw(t){if(Nf(t).length===0)return pe.configDotenv(t);let e=Mf(t);return e?pe._configVault(t):(qw(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),pe.configDotenv(t))}o(Yw,"config");function Xw(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),s=n.subarray(0,12),i=n.subarray(-16);n=n.subarray(12,-16);try{let a=Bw.createDecipheriv("aes-256-gcm",r,s);return a.setAuthTag(i),`${a.update(n)}${a.final()}`}catch(a){let c=a instanceof RangeError,l=a.message==="Invalid key length",u=a.message==="Unsupported state or unable to authenticate data";if(c||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw a}}o(Xw,"decrypt");function Qw(t,e,r={}){let n=!!(r&&r.debug),s=!!(r&&r.override),i={};if(typeof e!="object"){let a=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw a.code="OBJECT_REQUIRED",a}for(let a of Object.keys(e))Object.prototype.hasOwnProperty.call(t,a)?(s===!0&&(t[a]=e[a],i[a]=e[a]),n&&Fr(s===!0?`"${a}" is already defined and WAS overwritten`:`"${a}" is already defined and was NOT overwritten`)):(t[a]=e[a],i[a]=e[a]);return i}o(Qw,"populate");var pe={configDotenv:Jw,_configVault:Zw,_parseVault:Ww,config:Yw,decrypt:Xw,parse:Vw,populate:Qw};gt.exports.configDotenv=pe.configDotenv;gt.exports._configVault=pe._configVault;gt.exports._parseVault=pe._parseVault;gt.exports.config=pe.config;gt.exports.decrypt=pe.decrypt;gt.exports.parse=pe.parse;gt.exports.populate=pe.populate;gt.exports=pe});var ya=P((I5,Ff)=>{Ff.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var rs=P(jf=>{var Bf={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function s0(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}o(s0,"E");for(let t of Object.keys(Bf))jf[t]=s0(Bf[t])});var Wf=P((C5,Vf)=>{var i0=require("fs"),de=require("path"),Hf=ya(),a0=rs(),o0=typeof process=="object"&&process.platform==="win32",Gf=o(t=>typeof t=="object"&&t!==null,"is_Obj"),zf=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function ne(t){this.sep=de.sep,this.fs=i0,Gf(t)&&Gf(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}o(ne,"Utils");Vf.exports=ne;ne.prototype.makeDir=function(t){let e=this;function r(n){let s=n.split(e.sep)[0];n.split(e.sep).forEach(function(i){if(!(!i||i.substr(-1,1)===":")){s+=e.sep+i;var a;try{a=e.fs.statSync(s)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(s);else throw c}if(a&&a.isFile())throw a0.FILE_IN_THE_WAY(`"${s}"`)}})}o(r,"mkdirSync"),r(t)};ne.prototype.writeFileTo=function(t,e,r,n){let s=this;if(s.fs.existsSync(t)){if(!r)return!1;var i=s.fs.statSync(t);if(i.isDirectory())return!1}var a=de.dirname(t);s.fs.existsSync(a)||s.makeDir(a);var c;try{c=s.fs.openSync(t,"w",438)}catch{s.fs.chmodSync(t,438),c=s.fs.openSync(t,"w",438)}if(c)try{s.fs.writeSync(c,e,0,e.length,0)}finally{s.fs.closeSync(c)}return s.fs.chmodSync(t,n||438),!0};ne.prototype.writeFileToAsync=function(t,e,r,n,s){typeof n=="function"&&(s=n,n=void 0);let i=this;i.fs.exists(t,function(a){if(a&&!r)return s(!1);i.fs.stat(t,function(c,l){if(a&&l&&l.isDirectory())return s(!1);var u=de.dirname(t);i.fs.exists(u,function(d){if(!d)try{i.makeDir(u)}catch{return s(!1)}let p=o(function(_){i.fs.write(_,e,0,e.length,0,function(g){i.fs.close(_,function(){if(g)return s(!1);i.fs.chmod(t,n||438,function(){s(!0)})})})},"writeToFd");i.fs.open(t,"w",438,function(_,g){_?i.fs.chmod(t,438,function(){i.fs.open(t,"w",438,function(y,E){if(y||!E)return s(!1);p(E)})}):g?p(g):s(!1)})})})})};ne.prototype.findFiles=function(t){let e=this;function r(n,s,i,a){typeof s=="boolean"&&(i=s,s=void 0);let c=[];return e.fs.readdirSync(n).forEach(function(l){let u=de.join(n,l),d=e.fs.statSync(u);if((!s||s.test(u))&&c.push(de.normalize(u)+(d.isDirectory()?e.sep:"")),d.isDirectory()&&i){let p=e.fs.realpathSync(u);a.has(p)||(a.add(p),c=c.concat(r(u,s,i,a)))}}),c}return o(r,"findSync"),r(t,void 0,!0,new Set([e.fs.realpathSync(t)]))};ne.prototype.findFilesAsync=function(t,e){let r=this,n=[],s=!1,i=o(function(c){s||(s=!0,e(c,c?void 0:n))},"finish"),a=o(function(c,l,u){r.fs.readdir(c,function(d,p){if(d)return u(d);let _=p.length;if(!_)return u();p.forEach(function(g){let y=de.join(c,g);r.fs.stat(y,function(E,w){if(E)return u(E);if(!w){--_||u();return}if(n.push(de.normalize(y)+(w.isDirectory()?r.sep:"")),!w.isDirectory()){--_||u();return}r.fs.realpath(y,function(S,I){if(S)return u(S);if(l.has(I)){--_||u();return}l.add(I),a(y,l,function(m){if(m)return u(m);--_||u()})})})})})},"walk");r.fs.realpath(t,function(c,l){if(c)return i(c);a(t,new Set([l]),i)})};ne.prototype.getAttributes=function(){};ne.prototype.setAttributes=function(){};ne.crc32update=function(t,e){return zf[(t^e)&255]^t>>>8};ne.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let n=0;n<e;)r=ne.crc32update(r,t[n++]);return~r>>>0};ne.methodToString=function(t){switch(t){case Hf.STORED:return"STORED ("+t+")";case Hf.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ne.canonical=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.join(".",e)};ne.zipnamefix=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.posix.join(".",e)};ne.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let n=r-1;n>=0;n--)if(e(t[n],n,t))return t[n]};ne.sanitize=function(t,e){t=de.resolve(de.normalize(t));for(var r=e.split("/"),n=0,s=r.length;n<s;n++){var i=de.normalize(de.join(t,r.slice(n,s).join(de.sep)));if(i===t||i.startsWith(t+de.sep))return i}return de.normalize(de.join(t,de.basename(e)))};ne.toBuffer=o(function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)},"toBuffer");ne.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};ne.writeBigUInt64LE=function(t,e,r){let n=e>>>0,s=Math.floor(e/4294967296)>>>0;t.writeUInt32LE(n,r),t.writeUInt32LE(s,r+4)};ne.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};ne.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};ne.isWin=o0;ne.crcTable=zf});var Kf=P((O5,qf)=>{var c0=require("path");qf.exports=function(t,{fs:e}){var r=t||"",n=i(),s=null;function i(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return o(i,"newAttr"),r&&e.existsSync(r)?(s=e.statSync(r),n.directory=s.isDirectory(),n.mtime=s.mtime,n.atime=s.atime,n.executable=(73&s.mode)!==0,n.readonly=(128&s.mode)===0,n.hidden=c0.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:o(function(){},"decodeAttributes"),encodeAttributes:o(function(){},"encodeAttributes"),toJSON:o(function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Jf=P((M5,Zf)=>{Zf.exports={efs:!0,encode:o(t=>Buffer.from(t,"utf8"),"encode"),decode:o(t=>t.toString("utf8"),"decode")}});var sr=P((P5,nr)=>{nr.exports=Wf();nr.exports.Constants=ya();nr.exports.Errors=rs();nr.exports.FileAttr=Kf();nr.exports.decoder=Jf()});var Xf=P((L5,Yf)=>{var It=sr(),M=It.Constants;Yf.exports=function(){var t=20,e=10,r=0,n=0,s=0,i=0,a=0,c=0,l=0,u=0,d=0,p=0,_=0,g=0,y=0;t|=It.isWin?2560:768,r|=M.FLG_EFS;let E={extraLen:0},w=o(m=>Math.max(0,m)>>>0,"uint32"),S=o(m=>Math.max(0,m)&65535,"uint16"),I=o(m=>Math.max(0,m)&255,"uint8");return s=It.fromDate2DOS(new Date),{get made(){return t},set made(m){t=m},get version(){return e},set version(m){e=m},get flags(){return r},set flags(m){r=m},get flags_efs(){return(r&M.FLG_EFS)>0},set flags_efs(m){m?r|=M.FLG_EFS:r&=~M.FLG_EFS},get flags_desc(){return(r&M.FLG_DESC)>0},set flags_desc(m){m?r|=M.FLG_DESC:r&=~M.FLG_DESC},get method(){return n},set method(m){switch(m){case M.STORED:this.version=10;break;case M.DEFLATED:default:this.version=20}n=m},get time(){return It.fromDOS2Date(this.timeval)},set time(m){m=new Date(m),this.timeval=It.fromDate2DOS(m)},get timeval(){return s},set timeval(m){s=w(m)},get timeHighByte(){return I(s>>>8)},get crc(){return i},set crc(m){i=w(m)},get compressedSize(){return a},set compressedSize(m){a=w(m)},get size(){return c},set size(m){c=w(m)},get fileNameLength(){return l},set fileNameLength(m){l=m},get extraLength(){return u},set extraLength(m){u=m},get extraLocalLength(){return E.extraLen},set extraLocalLength(m){E.extraLen=m},get commentLength(){return d},set commentLength(m){d=m},get diskNumStart(){return p},set diskNumStart(m){p=w(m)},get inAttr(){return _},set inAttr(m){_=w(m)},get attr(){return g},set attr(m){g=w(m)},get fileAttr(){return(g||0)>>16&4095},get offset(){return y},set offset(m){y=w(m)},get encrypted(){return(r&M.FLG_ENC)===M.FLG_ENC},get centralHeaderSize(){return M.CENHDR+l+u+d},get realDataOffset(){return y+M.LOCHDR+E.fnameLen+E.extraLen},get localHeader(){return E},loadLocalHeaderFromBinary:o(function(m){var T=m.slice(y,y+M.LOCHDR);if(T.readUInt32LE(0)!==M.LOCSIG)throw It.Errors.INVALID_LOC();E.version=T.readUInt16LE(M.LOCVER),E.flags=T.readUInt16LE(M.LOCFLG),E.flags_desc=(E.flags&M.FLG_DESC)>0,E.method=T.readUInt16LE(M.LOCHOW),E.time=T.readUInt32LE(M.LOCTIM),E.crc=T.readUInt32LE(M.LOCCRC),E.compressedSize=T.readUInt32LE(M.LOCSIZ),E.size=T.readUInt32LE(M.LOCLEN),E.fnameLen=T.readUInt16LE(M.LOCNAM),E.extraLen=T.readUInt16LE(M.LOCEXT);let A=y+M.LOCHDR+E.fnameLen,N=A+E.extraLen;return m.slice(A,N)},"loadLocalHeaderFromBinary"),loadFromBinary:o(function(m){if(m.length!==M.CENHDR||m.readUInt32LE(0)!==M.CENSIG)throw It.Errors.INVALID_CEN();t=m.readUInt16LE(M.CENVEM),e=m.readUInt16LE(M.CENVER),r=m.readUInt16LE(M.CENFLG),n=m.readUInt16LE(M.CENHOW),s=m.readUInt32LE(M.CENTIM),i=m.readUInt32LE(M.CENCRC),a=m.readUInt32LE(M.CENSIZ),c=m.readUInt32LE(M.CENLEN),l=m.readUInt16LE(M.CENNAM),u=m.readUInt16LE(M.CENEXT),d=m.readUInt16LE(M.CENCOM),p=m.readUInt16LE(M.CENDSK),_=m.readUInt16LE(M.CENATT),g=m.readUInt32LE(M.CENATX),y=m.readUInt32LE(M.CENOFF)},"loadFromBinary"),localHeaderToBinary:o(function(){var m=Buffer.alloc(M.LOCHDR);return m.writeUInt32LE(M.LOCSIG,0),m.writeUInt16LE(e,M.LOCVER),m.writeUInt16LE(r&~M.FLG_DESC,M.LOCFLG),m.writeUInt16LE(n,M.LOCHOW),m.writeUInt32LE(s,M.LOCTIM),m.writeUInt32LE(i,M.LOCCRC),m.writeUInt32LE(a,M.LOCSIZ),m.writeUInt32LE(c,M.LOCLEN),m.writeUInt16LE(l,M.LOCNAM),m.writeUInt16LE(E.extraLen,M.LOCEXT),m},"localHeaderToBinary"),centralHeaderToBinary:o(function(){var m=Buffer.alloc(M.CENHDR+l+u+d);return m.writeUInt32LE(M.CENSIG,0),m.writeUInt16LE(t,M.CENVEM),m.writeUInt16LE(e,M.CENVER),m.writeUInt16LE(r&~M.FLG_DESC,M.CENFLG),m.writeUInt16LE(n,M.CENHOW),m.writeUInt32LE(s,M.CENTIM),m.writeUInt32LE(i,M.CENCRC),m.writeUInt32LE(a,M.CENSIZ),m.writeUInt32LE(c,M.CENLEN),m.writeUInt16LE(l,M.CENNAM),m.writeUInt16LE(u,M.CENEXT),m.writeUInt16LE(d,M.CENCOM),m.writeUInt16LE(p,M.CENDSK),m.writeUInt16LE(_,M.CENATT),m.writeUInt32LE(g,M.CENATX),m.writeUInt32LE(y,M.CENOFF),m},"centralHeaderToBinary"),toJSON:o(function(){let m=o(function(T){return T+" bytes"},"bytes");return{made:t,version:e,flags:r,method:It.methodToString(n),time:this.time,crc:"0x"+i.toString(16).toUpperCase(),compressedSize:m(a),size:m(c),fileNameLength:m(l),extraLength:m(u),commentLength:m(d),diskNumStart:p,inAttr:_,attr:g,offset:y,centralHeaderSize:m(M.CENHDR+l+u+d)}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var ep=P(($5,Qf)=>{var qe=sr(),H=qe.Constants;Qf.exports=function(){var t=0,e=0,r=0,n=0,s=0;let i=o(()=>t>H.EF_ZIP64_OR_16||e>H.EF_ZIP64_OR_16||r>H.EF_ZIP64_OR_32||n>H.EF_ZIP64_OR_32,"needsZip64");return{get diskEntries(){return t},set diskEntries(a){t=e=a},get totalEntries(){return e},set totalEntries(a){e=t=a},get size(){return r},set size(a){r=a},get offset(){return n},set offset(a){n=a},get commentLength(){return s},set commentLength(a){s=a},get mainHeaderSize(){return(i()?H.ZIP64HDR+H.END64HDR:0)+H.ENDHDR+s},loadFromBinary:o(function(a){if((a.length!==H.ENDHDR||a.readUInt32LE(0)!==H.ENDSIG)&&(a.length<H.ZIP64HDR||a.readUInt32LE(0)!==H.ZIP64SIG))throw qe.Errors.INVALID_END();a.readUInt32LE(0)===H.ENDSIG?(t=a.readUInt16LE(H.ENDSUB),e=a.readUInt16LE(H.ENDTOT),r=a.readUInt32LE(H.ENDSIZ),n=a.readUInt32LE(H.ENDOFF),s=a.readUInt16LE(H.ENDCOM)):(t=qe.readBigUInt64LE(a,H.ZIP64SUB),e=qe.readBigUInt64LE(a,H.ZIP64TOT),r=qe.readBigUInt64LE(a,H.ZIP64SIZB),n=qe.readBigUInt64LE(a,H.ZIP64OFF),s=0)},"loadFromBinary"),toBinary:o(function(){if(!i()){var a=Buffer.alloc(H.ENDHDR+s);return a.writeUInt32LE(H.ENDSIG,0),a.writeUInt32LE(0,4),a.writeUInt16LE(t,H.ENDSUB),a.writeUInt16LE(e,H.ENDTOT),a.writeUInt32LE(r,H.ENDSIZ),a.writeUInt32LE(n,H.ENDOFF),a.writeUInt16LE(s,H.ENDCOM),a.fill(" ",H.ENDHDR),a}var a=Buffer.alloc(this.mainHeaderSize);let c=0;a.writeUInt32LE(H.ZIP64SIG,c),qe.writeBigUInt64LE(a,H.ZIP64HDR-H.ZIP64LEAD,c+H.ZIP64SIZE),a.writeUInt16LE(45,c+H.ZIP64VEM),a.writeUInt16LE(45,c+H.ZIP64VER),a.writeUInt32LE(0,c+H.ZIP64DSK),a.writeUInt32LE(0,c+H.ZIP64DSKDIR),qe.writeBigUInt64LE(a,t,c+H.ZIP64SUB),qe.writeBigUInt64LE(a,e,c+H.ZIP64TOT),qe.writeBigUInt64LE(a,r,c+H.ZIP64SIZB),qe.writeBigUInt64LE(a,n,c+H.ZIP64OFF);let l=n+r;return c+=H.ZIP64HDR,a.writeUInt32LE(H.END64SIG,c),a.writeUInt32LE(0,c+H.END64START),qe.writeBigUInt64LE(a,l,c+H.END64OFF),a.writeUInt32LE(1,c+H.END64NUMDISKS),c+=H.END64HDR,a.writeUInt32LE(H.ENDSIG,c),a.writeUInt32LE(0,c+4),a.writeUInt16LE(Math.min(t,H.EF_ZIP64_OR_16),c+H.ENDSUB),a.writeUInt16LE(Math.min(e,H.EF_ZIP64_OR_16),c+H.ENDTOT),a.writeUInt32LE(Math.min(r,H.EF_ZIP64_OR_32),c+H.ENDSIZ),a.writeUInt32LE(Math.min(n,H.EF_ZIP64_OR_32),c+H.ENDOFF),a.writeUInt16LE(s,c+H.ENDCOM),a.fill(" ",c+H.ENDHDR),a},"toBinary"),toJSON:o(function(){let a=o(function(c,l){let u=c.toString(16).toUpperCase();for(;u.length<l;)u="0"+u;return"0x"+u},"offset");return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:a(n,4),commentLength:s}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var ba=P(_a=>{_a.EntryHeader=Xf();_a.MainHeader=ep()});var rp=P((B5,tp)=>{tp.exports=function(t){var e=require("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:o(function(){return e.deflateRawSync(t,r)},"deflate"),deflateAsync:o(function(n){var s=e.createDeflateRaw(r),i=[],a=0;s.on("data",function(c){i.push(c),a+=c.length}),s.on("end",function(){var c=Buffer.alloc(a),l=0;c.fill(0);for(var u=0;u<i.length;u++){var d=i[u];d.copy(c,l),l+=d.length}n&&n(c)}),s.end(t)},"deflateAsync")}}});var sp=P((H5,np)=>{var l0=+(process?.versions?.node??"").split(".")[0]||0;np.exports=function(t,e){var r=require("zlib");let n=l0>=15&&e>0?{maxOutputLength:e}:{};return{inflate:o(function(){return r.inflateRawSync(t,n)},"inflate"),inflateAsync:o(function(s){var i=r.createInflateRaw(n),a=[],c=0;i.on("data",function(l){a.push(l),c+=l.length}),i.on("end",function(){var l=Buffer.alloc(c),u=0;l.fill(0);for(var d=0;d<a.length;d++){var p=a[d];p.copy(l,u),u+=p.length}s&&s(l)}),i.end(t)},"inflateAsync")}}});var lp=P((z5,cp)=>{"use strict";var{randomFillSync:ip}=require("crypto"),u0=rs(),d0=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),op=o((t,e)=>Math.imul(t,e)>>>0,"uMul"),ap=o((t,e)=>d0[(t^e)&255]^t>>>8,"crc32update"),Br=o(()=>typeof ip=="function"?ip(Buffer.alloc(12)):Br.node(),"genSalt");Br.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var ns={genSalt:Br};function ss(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}o(ss,"Initkeys");ss.prototype.updateKeys=function(t){let e=this.keys;return e[0]=ap(e[0],t),e[1]+=e[0]&255,e[1]=op(e[1],134775813)+1,e[2]=ap(e[2],e[1]>>>24),t};ss.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return op(t,t^1)>>8&255};function f0(t){let e=new ss(t);return function(r){let n=Buffer.alloc(r.length),s=0;for(let i of r)n[s++]=e.updateKeys(i^e.next());return n}}o(f0,"make_decrypter");function p0(t){let e=new ss(t);return function(r,n,s=0){n||(n=Buffer.alloc(r.length));for(let i of r){let a=e.next();n[s++]=i^a,e.updateKeys(i)}return n}}o(p0,"make_encrypter");function m0(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=f0(r),s=n(t.slice(0,12)),i=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(s[11]!==i)throw u0.WRONG_PASSWORD();return n(t.slice(12))}o(m0,"decrypt");function h0(t){Buffer.isBuffer(t)&&t.length>=12?ns.genSalt=function(){return t.slice(0,12)}:t==="node"?ns.genSalt=Br.node:ns.genSalt=Br}o(h0,"_salter");function g0(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let s=p0(r),i=ns.genSalt();i[11]=e.crc>>>24&255,n&&(i[10]=e.crc>>>16&255);let a=Buffer.alloc(t.length+12);return s(i,a),s(t,a,12)}o(g0,"encrypt");cp.exports={decrypt:m0,encrypt:g0,_salter:h0}});var up=P(is=>{is.Deflater=rp();is.Inflater=sp();is.ZipCrypto=lp()});var wa=P((q5,dp)=>{var X=sr(),y0=ba(),je=X.Constants,Ea=up();dp.exports=function(t,e){var r=new y0.EntryHeader,n=Buffer.alloc(0),s=Buffer.alloc(0),i=!1,a=null,c=Buffer.alloc(0),l=Buffer.alloc(0),u=!0;let d=t,p=typeof d.decoder=="object"?d.decoder:X.decoder;u=p.hasOwnProperty("efs")?p.efs:!1;function _(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(l=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}o(_,"getCompressedDataFromZip");function g(m){let T=r.flags_desc||r.localHeader.flags_desc?r.crc:r.localHeader.crc;return X.crc32(m)===T}o(g,"crc32OK");function y(m,T,A){if(typeof T>"u"&&typeof m=="string"&&(A=m,m=void 0),i)return m&&T&&T(Buffer.alloc(0),X.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var N=_();if(N.length===0)return m&&T&&T(N),N;if(r.encrypted){if(typeof A!="string"&&!Buffer.isBuffer(A))throw X.Errors.INVALID_PASS_PARAM();N=Ea.ZipCrypto.decrypt(N,r,A)}var O;switch(r.method){case X.Constants.STORED:if(O=Buffer.alloc(N.length),N.copy(O),g(O))return m&&T&&T(O),O;throw m&&T&&T(O,X.Errors.BAD_CRC()),X.Errors.BAD_CRC();case X.Constants.DEFLATED:var b=new Ea.Inflater(N,r.size);if(m)b.inflateAsync(function(j){T&&(g(j)?T(j):T(j,X.Errors.BAD_CRC()))});else{if(O=b.inflate(),!g(O))throw X.Errors.BAD_CRC(`"${p.decode(n)}"`);return O}break;default:throw m&&T&&T(Buffer.alloc(0),X.Errors.UNKNOWN_METHOD()),X.Errors.UNKNOWN_METHOD()}}o(y,"decompress");function E(m,T){if((!a||!a.length)&&Buffer.isBuffer(e))return m&&T&&T(_()),_();if(a.length&&!i){var A;switch(r.method){case X.Constants.STORED:return r.compressedSize=r.size,A=Buffer.alloc(a.length),a.copy(A),m&&T&&T(A),A;default:case X.Constants.DEFLATED:var N=new Ea.Deflater(a);if(m)N.deflateAsync(function(b){A=Buffer.alloc(b.length),r.compressedSize=b.length,b.copy(A),T&&T(A)});else{var O=N.deflate();return r.compressedSize=O.length,O}N=null;break}}else if(m&&T)T(Buffer.alloc(0));else return Buffer.alloc(0)}o(E,"compress");function w(m,T){return X.readBigUInt64LE(m,T)}o(w,"readUInt64LE");function S(m){try{for(var T=0,A,N,O;T+4<m.length;)A=m.readUInt16LE(T),T+=2,N=m.readUInt16LE(T),T+=2,O=m.slice(T,T+N),T+=N,je.ID_ZIP64===A&&I(O)}catch{throw X.Errors.EXTRA_FIELD_PARSE_ERROR()}}o(S,"parseExtra");function I(m){var T,A,N,O;m.length>=je.EF_ZIP64_SCOMP&&(T=w(m,je.EF_ZIP64_SUNCOMP),r.size===je.EF_ZIP64_OR_32&&(r.size=T)),m.length>=je.EF_ZIP64_RHO&&(A=w(m,je.EF_ZIP64_SCOMP),r.compressedSize===je.EF_ZIP64_OR_32&&(r.compressedSize=A)),m.length>=je.EF_ZIP64_DSN&&(N=w(m,je.EF_ZIP64_RHO),r.offset===je.EF_ZIP64_OR_32&&(r.offset=N)),m.length>=je.EF_ZIP64_DSN+4&&(O=m.readUInt32LE(je.EF_ZIP64_DSN),r.diskNumStart===je.EF_ZIP64_OR_16&&(r.diskNumStart=O))}return o(I,"parseZip64ExtendedInformation"),{get entryName(){return p.decode(n)},get rawEntryName(){return n},set entryName(m){n=X.toBuffer(m,p.encode);var T=n[n.length-1];i=T===47||T===92,r.fileNameLength=n.length},get efs(){return typeof u=="function"?u(this.entryName):u},get extra(){return c},set extra(m){c=m,r.extraLength=m.length,S(m)},get comment(){return p.decode(s)},set comment(m){if(s=X.toBuffer(m,p.encode),r.commentLength=s.length,s.length>65535)throw X.Errors.COMMENT_TOO_LONG()},get name(){let m=p.decode(n);return i?m.replace(/[/\\]$/,"").split("/").pop():m.split("/").pop()},get isDirectory(){return i},getCompressedData:o(function(){return E(!1,null)},"getCompressedData"),getCompressedDataAsync:o(function(m){E(!0,m)},"getCompressedDataAsync"),setData:o(function(m){a=X.toBuffer(m,X.decoder.encode),!i&&a.length?(r.size=a.length,r.method=X.Constants.DEFLATED,r.crc=X.crc32(m),r.changed=!0):r.method=X.Constants.STORED},"setData"),getData:o(function(m){return r.changed?a:y(!1,null,m)},"getData"),getDataAsync:o(function(m,T){r.changed?m(a):y(!0,m,T)},"getDataAsync"),set attr(m){r.attr=m},get attr(){return r.attr},set header(m){r.loadFromBinary(m)},get header(){return r},packCentralHeader:o(function(){r.flags_efs=this.efs,r.extraLength=c.length;var m=r.centralHeaderToBinary(),T=X.Constants.CENHDR;return n.copy(m,T),T+=n.length,c.copy(m,T),T+=r.extraLength,s.copy(m,T),m},"packCentralHeader"),packLocalHeader:o(function(){let m=0;r.flags_efs=this.efs,r.extraLocalLength=l.length;let T=r.localHeaderToBinary(),A=Buffer.alloc(T.length+n.length+r.extraLocalLength);return T.copy(A,m),m+=T.length,n.copy(A,m),m+=n.length,l.copy(A,m),m+=l.length,A},"packLocalHeader"),toJSON:o(function(){let m=o(function(T){return"<"+(T&&T.length+" bytes buffer"||"null")+">"},"bytes");return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:m(e),data:m(a)}},"toJSON"),toString:o(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var mp=P((Z5,pp)=>{var fp=wa(),_0=ba(),Ne=sr();pp.exports=function(t,e){var r=[],n=Object.create(null),s=Buffer.alloc(0),i=new _0.MainHeader,a=!1,c=null;let l=new Set,u=e,{noSort:d,decoder:p}=u;t?y(u.readEntries):a=!0;function _(){let w=new Set;for(let S of Object.keys(n)){let I=S.split("/");if(I.pop(),!!I.length)for(let m=0;m<I.length;m++){let T=I.slice(0,m+1).join("/")+"/";w.add(T)}}for(let S of w)if(!(S in n)){let I=new fp(u);I.entryName=S,I.attr=16,I.temporary=!0,r.push(I),n[I.entryName]=I,l.add(I)}}o(_,"makeTemporaryFolders");function g(){if(a=!0,n=Object.create(null),i.diskEntries>(t.length-i.offset)/Ne.Constants.CENHDR)throw Ne.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(i.diskEntries);for(var w=i.offset,S=0;S<r.length;S++){var I=w,m=new fp(u,t);m.header=t.slice(I,I+=Ne.Constants.CENHDR),m.entryName=t.slice(I,I+=m.header.fileNameLength),m.header.extraLength&&(m.extra=t.slice(I,I+=m.header.extraLength)),m.header.commentLength&&(m.comment=t.slice(I,I+m.header.commentLength)),w+=m.header.centralHeaderSize,r[S]=m,n[m.entryName]=m}l.clear(),_()}o(g,"readEntries");function y(w){var S=t.length-Ne.Constants.ENDHDR,I=Math.max(0,S-65535),m=I,T=t.length,A=-1,N=0;for(typeof u.trailingSpace=="boolean"&&u.trailingSpace&&(I=0),S;S>=m;S--)if(t[S]===80){if(t.readUInt32LE(S)===Ne.Constants.ENDSIG){A=S,N=S,T=S+Ne.Constants.ENDHDR,m=S-Ne.Constants.END64HDR;continue}if(t.readUInt32LE(S)===Ne.Constants.END64SIG){m=I;continue}if(t.readUInt32LE(S)===Ne.Constants.ZIP64SIG){A=S,T=S+Ne.readBigUInt64LE(t,S+Ne.Constants.ZIP64SIZE)+Ne.Constants.ZIP64LEAD;break}}if(A==-1)throw Ne.Errors.INVALID_FORMAT();i.loadFromBinary(t.slice(A,T)),i.commentLength&&(s=t.slice(N+Ne.Constants.ENDHDR)),w&&g()}o(y,"readMainHeader");function E(){r.length>1&&!d&&(r=r.map(w=>({entry:w,key:w.entryName.toLowerCase()})).sort((w,S)=>w.key.localeCompare(S.key)).map(w=>w.entry))}return o(E,"sortEntries"),{get entries(){return a||g(),r.filter(w=>!l.has(w))},get comment(){return p.decode(s)},set comment(w){s=Ne.toBuffer(w,p.encode),i.commentLength=s.length},getEntryCount:o(function(){return a?r.length:i.diskEntries},"getEntryCount"),forEach:o(function(w){this.entries.forEach(w)},"forEach"),getEntry:o(function(w){return a||g(),n[w]||null},"getEntry"),setEntry:o(function(w){a||g(),r.push(w),n[w.entryName]=w,i.totalEntries=r.length},"setEntry"),deleteFile:o(function(w,S=!0){a||g();let I=n[w];this.getEntryChildren(I,S).map(T=>T.entryName).forEach(this.deleteEntry)},"deleteFile"),deleteEntry:o(function(w){a||g();let S=n[w],I=r.indexOf(S);I>=0&&(r.splice(I,1),delete n[w],i.totalEntries=r.length)},"deleteEntry"),getEntryChildren:o(function(w,S=!0){if(a||g(),typeof w=="object")if(w.isDirectory&&S){let I=[],m=w.entryName;for(let T of r)T.entryName.startsWith(m)&&I.push(T);return I}else return[w];return[]},"getEntryChildren"),getChildCount:o(function(w){if(w&&w.isDirectory){let S=this.getEntryChildren(w);return S.includes(w)?S.length-1:S.length}return 0},"getChildCount"),compressToBuffer:o(function(){a||g(),E();let w=[],S=[],I=0,m=0;i.size=0,i.offset=0;let T=0;for(let O of this.entries){let b=O.getCompressedData();O.header.offset=m;let j=O.packLocalHeader(),G=j.length+b.length;m+=G,w.push(j),w.push(b);let B=O.packCentralHeader();S.push(B),i.size+=B.length,I+=G+B.length,T++}I+=i.mainHeaderSize,i.offset=m,i.totalEntries=T,m=0;let A=Buffer.alloc(I);for(let O of w)O.copy(A,m),m+=O.length;for(let O of S)O.copy(A,m),m+=O.length;let N=i.toBinary();return s&&s.copy(N,N.length-s.length),N.copy(A,m),t=A,a=!1,A},"compressToBuffer"),toAsyncBuffer:o(function(w,S,I,m){try{a||g(),E();let T=[],A=[],N=0,O=0,b=0;i.size=0,i.offset=0;let j=o(function(G){if(G.length>0){let B=G.shift(),Z=B.entryName+B.extra.toString();I&&I(Z),B.getCompressedDataAsync(function(ce){m&&m(Z),B.header.offset=O;let ke=B.packLocalHeader(),xt=ke.length+ce.length;O+=xt,T.push(ke),T.push(ce);let K=B.packCentralHeader();A.push(K),i.size+=K.length,N+=xt+K.length,b++,j(G)})}else{N+=i.mainHeaderSize,i.offset=O,i.totalEntries=b,O=0;let B=Buffer.alloc(N);T.forEach(function(ce){ce.copy(B,O),O+=ce.length}),A.forEach(function(ce){ce.copy(B,O),O+=ce.length});let Z=i.toBinary();s&&s.copy(Z,Z.length-s.length),Z.copy(B,O),t=B,a=!1,w(B)}},"compress2Buffer");j(Array.from(this.entries))}catch(T){S(T)}},"toAsyncBuffer")}}});var yp=P((Y5,gp)=>{var ae=sr(),ie=require("path"),b0=wa(),E0=mp(),jt=o((...t)=>ae.findLast(t,e=>typeof e=="boolean"),"get_Bool"),hp=o((...t)=>ae.findLast(t,e=>typeof e=="string"),"get_Str"),w0=o((...t)=>ae.findLast(t,e=>typeof e=="function"),"get_Fun"),T0={noSort:!1,readEntries:!1,method:ae.Constants.NONE,fs:null};gp.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),T0);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(n,t),t=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(t)&&(r=t,n.method=ae.Constants.BUFFER,t=void 0)),Object.assign(n,e);let s=new ae(n),i=o(y=>{y.filter(E=>E.attr).sort((E,w)=>w.path.length-E.path.length).forEach(E=>s.fs.chmodSync(E.path,E.attr))},"applyDirAttributes");if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=ae.decoder),t&&typeof t=="string")if(s.fs.existsSync(t))n.method=ae.Constants.FILE,n.filename=t,r=s.fs.readFileSync(t);else throw ae.Errors.INVALID_FILENAME();let a=new E0(r,n),{canonical:c,sanitize:l,zipnamefix:u}=ae;function d(y){if(y&&a){var E;if(typeof y=="string"&&(E=a.getEntry(ie.posix.normalize(y))),typeof y=="object"&&typeof y.entryName<"u"&&typeof y.header<"u"&&(E=a.getEntry(y.entryName)),E)return E}return null}o(d,"getEntry");function p(y){let{join:E,normalize:w,sep:S}=ie.posix;return E(ie.isAbsolute(y)?"/":".",w(S+y.split("\\").join(S)+S))}o(p,"fixPath");function _(y){return y instanceof RegExp?(function(E){return function(w){return E.test(w)}})(y):typeof y!="function"?()=>!0:y}o(_,"filenameFilter");let g=o((y,E)=>{let w=E.slice(-1);return w=w===s.sep?s.sep:"",ie.relative(y,E)+w},"relativePath");return{readFile:o(function(y,E){var w=d(y);return w&&w.getData(E)||null},"readFile"),childCount:o(function(y){let E=d(y);if(E)return a.getChildCount(E)},"childCount"),readFileAsync:o(function(y,E){var w=d(y);w?w.getDataAsync(E):E(null,"getEntry failed for:"+y)},"readFileAsync"),readAsText:o(function(y,E){var w=d(y);if(w){var S=w.getData();if(S&&S.length)return S.toString(E||"utf8")}return""},"readAsText"),readAsTextAsync:o(function(y,E,w){var S=d(y);S?S.getDataAsync(function(I,m){if(m){E(I,m);return}I&&I.length?E(I.toString(w||"utf8")):E("")}):E("")},"readAsTextAsync"),deleteFile:o(function(y,E=!0){var w=d(y);w&&a.deleteFile(w.entryName,E)},"deleteFile"),deleteEntry:o(function(y){var E=d(y);E&&a.deleteEntry(E.entryName)},"deleteEntry"),addZipComment:o(function(y){a.comment=y},"addZipComment"),getZipComment:o(function(){return a.comment||""},"getZipComment"),addZipEntryComment:o(function(y,E){var w=d(y);w&&(w.comment=E)},"addZipEntryComment"),getZipEntryComment:o(function(y){var E=d(y);return E&&E.comment||""},"getZipEntryComment"),updateFile:o(function(y,E){var w=d(y);w&&w.setData(E)},"updateFile"),addLocalFile:o(function(y,E,w,S){if(s.fs.existsSync(y)){E=E?p(E):"";let I=ie.win32.basename(ie.win32.normalize(y));E+=w||I;let m=s.fs.statSync(y),T=m.isFile()?s.fs.readFileSync(y):Buffer.alloc(0);m.isDirectory()&&(E+=s.sep),this.addFile(E,T,S,m)}else throw ae.Errors.FILE_NOT_FOUND(y)},"addLocalFile"),addLocalFileAsync:o(function(y,E){y=typeof y=="object"?y:{localPath:y};let w=ie.resolve(y.localPath),{comment:S}=y,{zipPath:I,zipName:m}=y,T=this;s.fs.stat(w,function(A,N){if(A)return E(A,!1);I=I?p(I):"";let O=ie.win32.basename(ie.win32.normalize(w));if(I+=m||O,N.isFile())s.fs.readFile(w,function(b,j){return b?E(b,!1):(T.addFile(I,j,S,N),setImmediate(E,void 0,!0))});else if(N.isDirectory())return I+=s.sep,T.addFile(I,Buffer.alloc(0),S,N),setImmediate(E,void 0,!0)})},"addLocalFileAsync"),addLocalFolder:o(function(y,E,w){if(w=_(w),E=E?p(E):"",y=ie.normalize(y),s.fs.existsSync(y)){let S=s.findFiles(y),I=this;if(S.length)for(let m of S){let T=ie.join(E,g(y,m));w(T)&&I.addLocalFile(m,ie.dirname(T))}}else throw ae.Errors.FILE_NOT_FOUND(y)},"addLocalFolder"),addLocalFolderAsync:o(function(y,E,w,S){S=_(S),w=w?p(w):"",y=ie.normalize(y);var I=this;s.fs.open(y,"r",function(m){if(m&&m.code==="ENOENT")E(void 0,ae.Errors.FILE_NOT_FOUND(y));else if(m)E(void 0,m);else{var T=s.findFiles(y),A=-1,N=o(function(){if(A+=1,A<T.length){var O=T[A],b=g(y,O).split("\\").join("/");b=b.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),S(b)?s.fs.stat(O,function(j,G){j&&E(void 0,j),G.isFile()?s.fs.readFile(O,function(B,Z){B?E(void 0,B):(I.addFile(w+b,Z,"",G),N())}):(I.addFile(w+b+"/",Buffer.alloc(0),"",G),N())}):process.nextTick(()=>{N()})}else E(!0,void 0)},"next");N()}})},"addLocalFolderAsync"),addLocalFolderAsync2:o(function(y,E){let w=this;y=typeof y=="object"?y:{localPath:y};let S=ie.resolve(p(y.localPath)),{zipPath:I,filter:m,namefix:T}=y;m instanceof RegExp?m=(function(O){return function(b){return O.test(b)}})(m):typeof m!="function"&&(m=o(function(){return!0},"filter")),I=I?p(I):"",T==="latin1"&&(T=o(O=>O.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),"namefix")),typeof T!="function"&&(T=o(O=>O,"namefix"));let A=o(O=>ie.join(I,T(g(S,O))),"relPathFix"),N=o(O=>ie.win32.basename(ie.win32.normalize(T(O))),"fileNameFix");s.fs.open(S,"r",function(O){O&&O.code==="ENOENT"?E(void 0,ae.Errors.FILE_NOT_FOUND(S)):O?E(void 0,O):s.findFilesAsync(S,function(b,j){if(b)return E(b);j=j.filter(G=>m(A(G))),j.length||E(void 0,!1),setImmediate(j.reverse().reduce(function(G,B){return function(Z,ce){if(Z||ce===!1)return setImmediate(G,Z,!1);w.addLocalFileAsync({localPath:B,zipPath:ie.dirname(A(B)),zipName:N(B)},G)}},E))})})},"addLocalFolderAsync2"),addLocalFolderPromise:o(function(y,E){return new Promise((w,S)=>{this.addLocalFolderAsync2(Object.assign({localPath:y},E),(I,m)=>{I&&S(I),m&&w(this)})})},"addLocalFolderPromise"),addFile:o(function(y,E,w,S){y=u(y);let I=d(y),m=I!=null;m||(I=new b0(n),I.entryName=y),I.comment=w||"";let T=typeof S=="object"&&S instanceof s.fs.Stats;T&&(I.header.time=S.mtime);var A=I.isDirectory?16:0;let N=I.isDirectory?16384:32768;return T?N|=4095&S.mode:typeof S=="number"?N|=4095&S:N|=I.isDirectory?493:420,A=(A|N<<16)>>>0,I.attr=A,I.setData(E),m||a.setEntry(I),I},"addFile"),getEntries:o(function(y){return a.password=y,a?a.entries:[]},"getEntries"),getEntry:o(function(y){return d(y)},"getEntry"),getEntryCount:o(function(){return a.getEntryCount()},"getEntryCount"),forEach:o(function(y){return a.forEach(y)},"forEach"),extractEntryTo:o(function(y,E,w,S,I,m){S=jt(!1,S),I=jt(!1,I),w=jt(!0,w),m=hp(I,m);var T=d(y);if(!T)throw ae.Errors.NO_ENTRY();var A=c(T.entryName),N=l(E,m&&!T.isDirectory?c(m):w?A:ie.basename(A));if(T.isDirectory){var O=a.getEntryChildren(T);return O.forEach(function(G){if(G.isDirectory)return;var B=G.getData();if(!B)throw ae.Errors.CANT_EXTRACT_FILE();var Z=c(w?G.entryName:G.entryName.substring(T.entryName.length)),ce=l(E,Z);let ke=I?G.header.fileAttr:void 0;s.writeFileTo(ce,B,S,ke)}),!0}var b=T.getData(a.password);if(!b)throw ae.Errors.CANT_EXTRACT_FILE();if(s.fs.existsSync(N)&&!S)throw ae.Errors.CANT_OVERRIDE();let j=I?y.header.fileAttr:void 0;return s.writeFileTo(N,b,S,j),!0},"extractEntryTo"),test:o(function(y){if(!a)return!1;for(var E of a.entries)try{if(E.isDirectory)continue;var w=E.getData(y);if(!w)return!1}catch{return!1}return!0},"test"),extractAllTo:o(function(y,E,w,S){if(w=jt(!1,w),S=hp(w,S),E=jt(!1,E),!a)throw ae.Errors.NO_ZIP();let I=[];a.entries.forEach(function(m){var T=l(y,c(m.entryName));if(m.isDirectory){s.makeDir(T),w&&I.push({path:T,attr:m.header.fileAttr});return}var A=m.getData(S);if(!A)throw ae.Errors.CANT_EXTRACT_FILE();let N=w?m.header.fileAttr:void 0;s.writeFileTo(T,A,E,N);try{s.fs.utimesSync(T,m.header.time,m.header.time)}catch{}}),i(I)},"extractAllTo"),extractAllToAsync:o(function(y,E,w,S){if(S=w0(E,w,S),w=jt(!1,w),E=jt(!1,E),!S)return new Promise((b,j)=>{this.extractAllToAsync(y,E,w,function(G){G?j(G):b(this)})});if(!a){S(ae.Errors.NO_ZIP());return}y=ie.resolve(y);let I=o(b=>l(y,ie.normalize(c(b.entryName))),"getPath"),m=o((b,j)=>new Error(b+': "'+j+'"'),"getError"),T=[],A=[];a.entries.forEach(b=>{b.isDirectory?T.push(b):A.push(b)});let N=[];for(let b of T){let j=I(b),G=w?b.header.fileAttr:void 0;try{s.makeDir(j)}catch{S(m("Unable to create folder",j));continue}G&&N.push({path:j,attr:G});try{s.fs.utimesSync(j,b.header.time,b.header.time)}catch{}}let O=o(b=>{if(!b)try{i(N)}catch(j){return S(m("Unable to set folder permissions",j.path||""))}S(b)},"done");A.reverse().reduce(function(b,j){return function(G){if(G)b(G);else{let B=ie.normalize(c(j.entryName)),Z=l(y,B);j.getDataAsync(function(ce,ke){if(ke)b(ke);else if(!ce)b(ae.Errors.CANT_EXTRACT_FILE());else{let xt=w?j.header.fileAttr:void 0;s.writeFileToAsync(Z,ce,E,xt,function(K){if(!K)return b(m("Unable to write file",Z));s.fs.utimes(Z,j.header.time,j.header.time,function(){b()})})}})}}},O)()},"extractAllToAsync"),writeZip:o(function(y,E){if(arguments.length===1&&typeof y=="function"&&(E=y,y=""),!y&&n.filename&&(y=n.filename),!!y){var w=a.compressToBuffer();if(w){var S=s.writeFileTo(y,w,!0);typeof E=="function"&&E(S?null:new Error("failed"),"")}}},"writeZip"),writeZipPromise:o(function(y,E){let{overwrite:w,perm:S}=Object.assign({overwrite:!0},E);return new Promise((I,m)=>{!y&&n.filename&&(y=n.filename),y||m("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(T=>{let A=o(N=>N?I(N):m("ADM-ZIP: Wasn't able to write zip file"),"ret");s.writeFileToAsync(y,T,w,S,A)},m)})},"writeZipPromise"),toBufferPromise:o(function(){return new Promise((y,E)=>{a.toAsyncBuffer(y,E)})},"toBufferPromise"),toBuffer:o(function(y,E,w,S){return typeof y=="function"?(a.toAsyncBuffer(y,E,w,S),null):a.compressToBuffer()},"toBuffer")}}});var Sp=P((tH,yt)=>{var va=require("fs"),os=require("path"),S0=require("os"),I0=require("crypto"),bp=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function x0(){return bp[Math.floor(Math.random()*bp.length)]}o(x0,"_getRandomTip");function ir(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}o(ir,"parseBoolean");function A0(){return process.stdout.isTTY}o(A0,"supportsAnsi");function C0(t){return A0()?`\x1B[2m${t}\x1B[0m`:t}o(C0,"dim");var R0=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function O0(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
4
- `);let n;for(;(n=R0.exec(r))!=null;){let s=n[1],i=n[2]||"";i=i.trim();let a=i[0];i=i.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),a==='"'&&(i=i.replace(/\\n/g,`
5
- `),i=i.replace(/\\r/g,"\r")),e[s]=i}return e}o(O0,"parse");function N0(t){t=t||{};let e=vp(t);t.path=e;let r=me.configDotenv(t);if(!r.parsed){let a=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw a.code="MISSING_DATA",a}let n=Tp(t).split(","),s=n.length,i;for(let a=0;a<s;a++)try{let c=n[a].trim(),l=k0(r,c);i=me.decrypt(l.ciphertext,l.key);break}catch(c){if(a+1>=s)throw c}return me.parse(i)}o(N0,"_parseVault");function M0(t){console.error(`\u26A0 ${t}`)}o(M0,"_warn");function jr(t){console.log(`\u2506 ${t}`)}o(jr,"_debug");function wp(t){console.log(`\u25C7 ${t}`)}o(wp,"_log");function Tp(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}o(Tp,"_dotenvKey");function k0(t,e){let r;try{r=new URL(e)}catch(c){if(c.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw c}let n=r.password;if(!n){let c=new Error("INVALID_DOTENV_KEY: Missing key part");throw c.code="INVALID_DOTENV_KEY",c}let s=r.searchParams.get("environment");if(!s){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let i=`DOTENV_VAULT_${s.toUpperCase()}`,a=t.parsed[i];if(!a){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${i} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:a,key:n}}o(k0,"_instructions");function vp(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)va.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=os.resolve(process.cwd(),".env.vault");return va.existsSync(e)?e:null}o(vp,"_vaultPath");function Ep(t){return t[0]==="~"?os.join(S0.homedir(),t.slice(1)):t}o(Ep,"_resolveHome");function P0(t){let e=ir(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=ir(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&wp("loading env from encrypted .env.vault");let n=me._parseVault(t),s=process.env;return t&&t.processEnv!=null&&(s=t.processEnv),me.populate(s,n,t),{parsed:n}}o(P0,"_configVault");function L0(t){let e=os.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let s=ir(n.DOTENV_CONFIG_DEBUG||t&&t.debug),i=ir(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:s&&jr("no encoding is specified (UTF-8 is used by default)");let a=[e];if(t&&t.path)if(!Array.isArray(t.path))a=[Ep(t.path)];else{a=[];for(let d of t.path)a.push(Ep(d))}let c,l={};for(let d of a)try{let p=me.parse(va.readFileSync(d,{encoding:r}));me.populate(l,p,t)}catch(p){s&&jr(`failed to load ${d} ${p.message}`),c=p}let u=me.populate(n,l,t);if(s=ir(n.DOTENV_CONFIG_DEBUG||s),i=ir(n.DOTENV_CONFIG_QUIET||i),s||!i){let d=Object.keys(u).length,p=[];for(let _ of a)try{let g=os.relative(process.cwd(),_);p.push(g)}catch(g){s&&jr(`failed to load ${_} ${g.message}`),c=g}wp(`injected env (${d}) from ${p.join(",")} ${C0(`// tip: ${x0()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}o(L0,"configDotenv");function D0(t){if(Tp(t).length===0)return me.configDotenv(t);let e=vp(t);return e?me._configVault(t):(M0(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),me.configDotenv(t))}o(D0,"config");function $0(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),s=n.subarray(0,12),i=n.subarray(-16);n=n.subarray(12,-16);try{let a=I0.createDecipheriv("aes-256-gcm",r,s);return a.setAuthTag(i),`${a.update(n)}${a.final()}`}catch(a){let c=a instanceof RangeError,l=a.message==="Invalid key length",u=a.message==="Unsupported state or unable to authenticate data";if(c||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw a}}o($0,"decrypt");function U0(t,e,r={}){let n=!!(r&&r.debug),s=!!(r&&r.override),i={};if(typeof e!="object"){let a=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw a.code="OBJECT_REQUIRED",a}for(let a of Object.keys(e))Object.prototype.hasOwnProperty.call(t,a)?(s===!0&&(t[a]=e[a],i[a]=e[a]),n&&jr(s===!0?`"${a}" is already defined and WAS overwritten`:`"${a}" is already defined and was NOT overwritten`)):(t[a]=e[a],i[a]=e[a]);return i}o(U0,"populate");var me={configDotenv:L0,_configVault:P0,_parseVault:N0,config:D0,decrypt:$0,parse:O0,populate:U0};yt.exports.configDotenv=me.configDotenv;yt.exports._configVault=me._configVault;yt.exports._parseVault=me._parseVault;yt.exports.config=me.config;yt.exports.decrypt=me.decrypt;yt.exports.parse=me.parse;yt.exports.populate=me.populate;yt.exports=me});var tv={};Pm(tv,{TestRunMonitor:()=>Ts});module.exports=Lm(tv);var As=o(t=>new Promise(e=>setTimeout(e,t)),"awaitSleep");var d5=require("@playwright/test");var k3=require("@playwright/test");var Uv=require("@playwright/test");var Pv=require("@playwright/test");var to=Object.defineProperty,q=o((t,e)=>{let r={};for(var n in t)to(r,n,{get:t[n],enumerable:!0});return e||to(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function ro(t){let e=Symbol.for(t);return{brand(r,n){let s=n?Symbol.for(`${t}.${n}`):e;class i extends r{static{o(this,"_Branded")}[s]=!0;constructor(...c){super(...c)}static isInstance(c){return typeof c=="object"&&c!==null&&s in c&&c[s]===!0}}return Object.defineProperty(i,"name",{value:r.name}),i},sub(r){return ro(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}o(ro,"createNamespace");var no=ro("langchain");var Cs=no.sub("error"),so=class extends Cs.brand(Error){static{o(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},$m=class extends Cs.brand(so,"model-abort"){static{o(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},Kv=class io extends Cs.brand(so,"context-overflow"){static{o(this,"ContextOverflowError")}name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(e){let r=new io(e.message);return r.cause=e,r}};var Um=/([A-Z]+)([A-Z][a-z0-9]+)/g,Fm=/([a-z0-9])([A-Z])/g,Bm=/[-_\s]+/g;function jm(t){return t.replace(Um,"$1_$2").replace(Fm,"$1_$2").replace(Bm,"_").toLowerCase()}o(jm,"snakeCase");function ao(t,e){return e?.[t]||jm(t)}o(ao,"keyToJson");function oo(t,e,r){let n={};for(let s in t)Object.hasOwn(t,s)&&(n[e(s,r)]=t[s]);return n}o(oo,"mapKeys");var Hm="__lc_escaped__";function Gm(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}o(Gm,"needsEscaping");function zm(t){return{[Hm]:t}}o(zm,"escapeObject");function Vm(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}o(Vm,"isSerializableLike");function Wm(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}o(Wm,"createNotImplemented");function Wr(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return Wm(t);if(Vm(t))return t;e.add(t);let r=t;if(Gm(r))return e.delete(t),zm(r);let n={};for(let[s,i]of Object.entries(r))n[s]=Wr(i,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>Wr(r,e)):t}o(Wr,"escapeIfNeeded");function co(t){return Array.isArray(t)?[...t]:{...t}}o(co,"shallowCopy");function qm(t,e){let r=co(t);for(let[n,s]of Object.entries(e)){let[i,...a]=n.split(".").reverse(),c=r;for(let l of a.reverse()){if(c[l]===void 0)break;c[l]=co(c[l]),c=c[l]}c[i]!==void 0&&(c[i]={lc:1,type:"secret",id:[s]})}return r}o(qm,"replaceSecrets");function Rs(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}o(Rs,"get_lc_unique_name");var Ot=class lo{static{o(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,Rs(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof lo||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((c,l)=>(c[l]=l in this?this[l]:this.lc_kwargs[l],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(e,Reflect.get(c,"lc_aliases",this)),Object.assign(r,Reflect.get(c,"lc_secrets",this)),Object.assign(n,Reflect.get(c,"lc_attributes",this));Object.keys(r).forEach(c=>{let l=this,u=n,[d,...p]=c.split(".").reverse();for(let _ of p.reverse()){if(!(_ in l)||l[_]===void 0)return;(!(_ in u)||u[_]===void 0)&&(typeof l[_]=="object"&&l[_]!=null?u[_]={}:Array.isArray(l[_])&&(u[_]=[])),l=l[_],u=u[_]}d in l&&l[d]!==void 0&&(u[d]=u[d]||l[d])});let s={},i=new WeakSet;i.add(this);for(let[c,l]of Object.entries(n))s[c]=Wr(l,i);let a=oo(Object.keys(r).length?qm(s,r):s,ao,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:a}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function fr(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}o(fr,"isDataContentBlock");function qr(t){return fr(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}o(qr,"isURLContentBlock");function Kr(t){return fr(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}o(Kr,"isBase64ContentBlock");function Os(t){return fr(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}o(Os,"isIDContentBlock");function Zr({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let s=e?Uint8Array.from(atob(r[2]),i=>i.charCodeAt(0)):r[2];return{mime_type:n,data:s}}}o(Zr,"parseBase64DataUrl");function k(t,e){return F(t)&&t.type===e}o(k,"_isContentBlock");function F(t){return typeof t=="object"&&t!==null}o(F,"_isObject");function fe(t){return Array.isArray(t)}o(fe,"_isArray");function x(t){return typeof t=="string"}o(x,"_isString");function Ue(t){return typeof t=="number"}o(Ue,"_isNumber");function Jr(t){return t instanceof Uint8Array}o(Jr,"_isBytesArray");function Ns(t){try{return JSON.parse(t)}catch{return}}o(Ns,"safeParseJson");var Fe=o(t=>t(),"iife");function Km(t){if(t.type==="char_location"&&x(t.document_title)&&Ue(t.start_char_index)&&Ue(t.end_char_index)&&x(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="page_location"&&x(t.document_title)&&Ue(t.start_page_number)&&Ue(t.end_page_number)&&x(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="content_block_location"&&x(t.document_title)&&Ue(t.start_block_index)&&Ue(t.end_block_index)&&x(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:s}}if(t.type==="web_search_result_location"&&x(t.url)&&x(t.title)&&x(t.encrypted_index)&&x(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:s,...i}=t;return{...i,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:s}}if(t.type==="search_result_location"&&x(t.source)&&x(t.title)&&Ue(t.start_block_index)&&Ue(t.end_block_index)&&x(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:s,cited_text:i,...a}=t;return{...a,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:s,citedText:i}}}o(Km,"convertAnthropicAnnotation");function fo(t){if(k(t,"document")&&F(t.source)&&"type"in t.source){if(t.source.type==="base64"&&x(t.source.media_type)&&x(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&x(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&x(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&x(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(k(t,"image")&&F(t.source)&&"type"in t.source){if(t.source.type==="base64"&&x(t.source.media_type)&&x(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&x(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&x(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}o(fo,"convertToV1FromAnthropicContentBlock");function po(t){function*e(){for(let r of t){let n=fo(r);n?yield n:yield r}}return o(e,"iterateContent"),Array.from(e())}o(po,"convertToV1FromAnthropicInput");function uo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"text")&&x(n.text)){let{text:s,citations:i,...a}=n;if(fe(i)&&i.length){let c=i.reduce((l,u)=>{let d=Km(u);return d?[...l,d]:l},[]);yield{...a,type:"text",text:s,annotations:c};continue}else{yield{...a,type:"text",text:s};continue}}else if(k(n,"thinking")&&x(n.thinking)){let{thinking:s,signature:i,...a}=n;yield{...a,type:"reasoning",reasoning:s,signature:i};continue}else if(k(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(k(n,"tool_use")&&x(n.name)&&x(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(k(n,"input_json_delta")){if(Zm(t)&&t.tool_call_chunks?.length){let s=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:s.id,name:s.name,args:s.args,index:s.index};continue}}else if(k(n,"server_tool_use")&&x(n.name)&&x(n.id)){let{name:s,id:i}=n;if(s==="web_search"){yield{id:i,type:"server_tool_call",name:"web_search",args:{query:Fe(()=>{if(typeof n.input=="string")return n.input;if(F(n.input)&&x(n.input.query))return n.input.query;if(x(n.partial_json)){let a=Ns(n.partial_json);if(a?.query)return a.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:i,type:"server_tool_call",name:"code_execution",args:{code:Fe(()=>{if(typeof n.input=="string")return n.input;if(F(n.input)&&x(n.input.code))return n.input.code;if(x(n.partial_json)){let a=Ns(n.partial_json);if(a?.code)return a.code}return""})}};continue}}else if(k(n,"web_search_tool_result")&&x(n.tool_use_id)&&fe(n.content)){let{content:s,tool_use_id:i}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:i,status:"success",output:{urls:s.reduce((a,c)=>k(c,"web_search_result")?[...a,c.url]:a,[])}};continue}else if(k(n,"code_execution_tool_result")&&x(n.tool_use_id)&&F(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(k(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(k(n,"mcp_tool_result")&&x(n.tool_use_id)&&F(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(k(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(k(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(k(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let s=fo(n);if(s){yield s;continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(uo,"convertToV1FromAnthropicMessage");var mo={translateContent:uo,translateContentChunk:uo};function Zm(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}o(Zm,"_isAIMessageChunk");function Jm(t){return qr(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Kr(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:Os(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}o(Jm,"convertToV1FromDataContentBlock");function ho(t){return t.map(Jm)}o(ho,"convertToV1FromDataContent");function go(t){return!!(k(t,"image_url")&&F(t.image_url)||k(t,"input_audio")&&F(t.input_audio)||k(t,"file")&&F(t.file))}o(go,"isOpenAIDataBlock");function yo(t){if(k(t,"image_url")&&F(t.image_url)&&x(t.image_url.url)){let e=Zr({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(k(t,"input_audio")&&F(t.input_audio)&&x(t.input_audio.data)&&x(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(k(t,"file")&&F(t.file)&&x(t.file.data)){let e=Zr({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(x(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}o(yo,"convertToV1FromOpenAIDataBlock");function Ym(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Yr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}o(Ym,"convertToV1FromChatCompletions");function Xm(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Yr(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}o(Xm,"convertToV1FromChatCompletionsChunk");function Yr(t){let e=[];for(let r of t)go(r)?e.push(yo(r)):e.push(r);return e}o(Yr,"convertToV1FromChatCompletionsInput");function Qm(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:s}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:s}}if(t.type==="file_citation"){let{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}o(Qm,"convertResponsesAnnotation");function _o(t){function*e(){F(t.additional_kwargs?.reasoning)&&fe(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,s)=>F(s)&&x(s.text)?`${n}${s.text}`:n,"")});let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r)if(k(n,"text")){let{text:s,annotations:i,phase:a,extras:c,...l}=n,u=F(c)?{...c}:{};x(a)&&(u.phase=a);let d=Object.keys(u).length>0?{extras:u}:{};Array.isArray(i)?yield{...l,...d,type:"text",text:String(s),annotations:i.map(Qm)}:yield{...l,...d,type:"text",text:String(s)}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(F(t.additional_kwargs)&&fe(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(k(n,"web_search_call")){let s={};if(F(n.action)&&x(n.action.query)&&(s.query=n.action.query),yield{id:n.id,type:"server_tool_call",name:"web_search",args:s},n.status==="completed"||n.status==="failed"){let i={};F(n.action)&&(i.action=n.action),yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:i}}continue}else if(k(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{queries:fe(n.queries)?n.queries:[]}},(n.status==="completed"||n.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:fe(n.results)?{results:n.results}:{}});continue}else if(k(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(k(n,"code_interpreter_call")){if(x(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),fe(n.outputs)){let s=Fe(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(let i of n.outputs)if(k(i,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:s??0,stderr:[0,void 0].includes(s)?void 0:String(i.logs),stdout:[0,void 0].includes(s)?String(i.logs):void 0}};continue}}continue}else if(k(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(k(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(k(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(k(n,"tool_search_call")){let s={};F(n.arguments)&&Object.assign(s,n.arguments);let i={};x(n.execution)&&(i.execution=n.execution),x(n.status)&&(i.status=n.status),x(n.call_id)&&(i.call_id=n.call_id),yield{id:x(n.id)?n.id:"",type:"server_tool_call",name:"tool_search",args:s,...Object.keys(i).length>0?{extras:i}:{}};continue}else if(k(n,"tool_search_output")){let s={name:"tool_search"};x(n.execution)&&(s.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:x(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:fe(n.tools)?n.tools:[]},extras:s};continue}else if(k(n,"image_generation_call")){x(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:x(n.id)?n.id:void 0,metadata:{status:x(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}F(n)&&(yield{type:"non_standard",value:n})}}return o(e,"iterateContent"),Array.from(e())}o(_o,"convertToV1FromResponses");function eh(t){function*e(){yield*_o(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return o(e,"iterateContent"),Array.from(e())}o(eh,"convertToV1FromResponsesChunk");var bo={translateContent:o(t=>typeof t.content=="string"?Ym(t):_o(t),"translateContent"),translateContentChunk:o(t=>typeof t.content=="string"?Xm(t):eh(t),"translateContentChunk")};function Ms(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}o(Ms,"isMessage");function Eo(t,e="pretty"){return e==="pretty"?th(t):JSON.stringify(t)}o(Eo,"convertToFormattedString");function th(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),s="=".repeat(n),i=r.length%2===0?s:`${s}=`;if(e.push(`${s}${r}${i}`),t.type==="ai"){let a=t;if(a.tool_calls&&a.tool_calls.length>0){e.push("Tool Calls:");for(let c of a.tool_calls){e.push(` ${c.name} (${c.id})`),e.push(` Call ID: ${c.id}`),e.push(" Args:");for(let[l,u]of Object.entries(c.args))e.push(` ${l}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){let a=t;a.name&&e.push(`Name: ${a.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
6
- `)}o(th,"convertToPrettyString");var ks=Symbol.for("langchain.message");function rh(t,e){function r(n,s){if(typeof n!="object"||n===null||n===void 0)return n;if(s>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(a=>r(a,s+1));let i={};for(let a of Object.keys(n))i[a]=r(n[a],s+1);return i}return o(r,"helper"),JSON.stringify(r(t,0),null,2)}o(rh,"stringifyWithDepthLimit");var ft=class extends Ot{static{o(this,"BaseMessage")}lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[ks]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){let e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){let t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[ho,Yr,po].reduce((e,r)=>r(e),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&ks in t&&t[ks]===!0&&Ms(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let e=rh(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return Eo(this,t)}};function Ps(t){let e=[],r=[];for(let n of t)if(n.function){let s=n.function.name;try{let i=JSON.parse(n.function.arguments);e.push({name:s||"",args:i||{},id:n.id})}catch{r.push({name:s,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}o(Ps,"defaultToolCallParser");function Ls(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}o(Ls,"convertFileFormatToMimeType");function ih(t){if(F(t.document)&&F(t.document.source)){let e=Ls(F(t.document)&&x(t.document.format)?t.document.format:"");if(F(t.document.source)){if(F(t.document.source.s3Location)&&x(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(Jr(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(x(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(fe(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>F(n)&&x(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}o(ih,"convertConverseDocumentBlock");function ah(t){if(k(t,"image")&&F(t.image)){let e=Ls(F(t.image)&&x(t.image.format)?t.image.format:"");if(F(t.image.source)){if(F(t.image.source.s3Location)&&x(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(Jr(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}o(ah,"convertConverseImageBlock");function oh(t){if(k(t,"video")&&F(t.video)){let e=Ls(F(t.video)&&x(t.video.format)?t.video.format:"");if(F(t.video.source)){if(F(t.video.source.s3Location)&&x(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(Jr(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}o(oh,"convertConverseVideoBlock");function wo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(k(n,"citations_content")&&F(n.citationsContent)){yield{type:"text",text:fe(n.citationsContent.content)?n.citationsContent.content.reduce((s,i)=>F(i)&&x(i.text)?s+i.text:s,""):"",annotations:fe(n.citationsContent.citations)?n.citationsContent.citations.reduce((s,i)=>{if(F(i)){let a=fe(i.sourceContent)?i.sourceContent.reduce((l,u)=>F(u)&&x(u.text)?l+u.text:l,""):"",c=Fe(()=>{if(F(i.location)){let l=i.location.documentChar||i.location.documentPage||i.location.documentChunk;if(F(l))return{source:Ue(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:Ue(l.start)?l.start:void 0,endIndex:Ue(l.end)?l.end:void 0}}return{}});s.push({type:"citation",citedText:a,...c})}return s},[]):[]};continue}else if(k(n,"document")&&F(n.document)){yield ih(n);continue}else if(k(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(k(n,"image")&&F(n.image)){yield ah(n);continue}else if(k(n,"reasoning_content")&&x(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(k(n,"tool_call"))continue;if(k(n,"video")&&F(n.video)){yield oh(n);continue}}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(wo,"convertToV1FromChatBedrockConverseMessage");var To={translateContent:wo,translateContentChunk:wo};function vo(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(vo,"convertToV1FromDeepSeekMessage");var So={translateContent:vo,translateContentChunk:vo};function Io(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"thinking")&&x(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(k(n,"inlineData")&&F(n.inlineData)&&x(n.inlineData.mimeType)&&x(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(k(n,"functionCall")&&F(n.functionCall)&&x(n.functionCall.name)&&F(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(k(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(k(n,"fileData")&&F(n.fileData)&&x(n.fileData.mimeType)&&x(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(k(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(k(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(Io,"convertToV1FromChatGoogleMessage");var xo={translateContent:Io,translateContentChunk:Io};function Ao(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(k(n,"reasoning")&&x(n.reasoning)){let s=Fe(()=>{let i=r.indexOf(n);if(fe(t.additional_kwargs?.signatures)&&i>=0)return t.additional_kwargs.signatures.at(i)});x(s)?yield{type:"reasoning",reasoning:n.reasoning,signature:s}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(k(n,"thinking")&&x(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(k(n,"text")&&x(n.text)){yield{type:"text",text:n.text};continue}else if(k(n,"image_url")){if(x(n.image_url))if(n.image_url.startsWith("data:")){let s=n.image_url.match(/^data:([^;]+);base64,(.+)$/);s?yield{type:"image",data:s[2],mimeType:s[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(k(n,"media")&&x(n.mimeType)&&x(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return o(e,"iterateContent"),Array.from(e())}o(Ao,"convertToV1FromChatVertexMessage");var Co={translateContent:Ao,translateContentChunk:Ao};function Ro(t){let e=[],r=t.additional_kwargs?.reasoning;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,s=n.match(/<think>([\s\S]*?)<\/think>/);if(s){let i=s[1].trim();i.length>0&&e.push({type:"reasoning",reasoning:i}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&e.push({type:"text",text:n})}else for(let n of t.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)){let s=n.text,i=s.match(/<think>([\s\S]*?)<\/think>/);if(i){let a=i[1].trim();a.length>0&&e.push({type:"reasoning",reasoning:a}),s=s.replace(/<think>[\s\S]*?<\/think>/,"").trim()}s.length>0&&e.push({type:"text",text:s})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(Ro,"convertToV1FromGroqMessage");var Oo={translateContent:Ro,translateContentChunk:Ro};function No(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(No,"convertToV1FromOllamaMessage");var Mo={translateContent:No,translateContentChunk:No};function ko(t){let e=[],r=t.additional_kwargs?.reasoning_details,n=!1;if(Array.isArray(r)&&r.length>0)for(let s of r){if(s==null||typeof s!="object")continue;let i=s.type;if(i==="reasoning.summary"){let a=s.summary;x(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}else if(i==="reasoning.text"){let a=s.text;x(a)&&a.length>0&&(e.push({type:"reasoning",reasoning:a}),n=!0)}}if(!n){let s=t.additional_kwargs?.reasoning_content;x(s)&&s.length>0&&e.push({type:"reasoning",reasoning:s})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let s of t.content)typeof s=="object"&&"type"in s&&s.type==="text"&&"text"in s&&x(s.text)&&e.push({type:"text",text:s.text});for(let s of t.tool_calls??[])e.push({type:"tool_call",id:s.id,name:s.name,args:s.args});return e}o(ko,"convertToV1FromOpenRouterMessage");var Po={translateContent:ko,translateContentChunk:ko};function Lo(t){let e=[];if(F(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(fe(n.summary)){let s=n.summary.reduce((i,a)=>F(a)&&x(a.text)?`${i}${a.text}`:i,"");s.length>0&&e.push({type:"reasoning",reasoning:s})}}let r=t.additional_kwargs?.reasoning_content;if(x(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&x(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}o(Lo,"convertToV1FromXAIMessage");var Do={translateContent:Lo,translateContentChunk:Lo};function $o(t){function*e(){let r=Fe(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let n=t.additional_kwargs?.originalTextContentBlock;if(n?.thoughtSignature&&!t.content.some(s=>"thoughtSignature"in s)){let s=[...t.content];for(let i=s.length-1;i>=0;i--){let a=s[i];if(a.type==="text"&&!a.thought)return a.thoughtSignature=n.thoughtSignature,s}}return t.content}});for(let n of r){let s=Fe(()=>k(n,"text")&&x(n.text)?{type:"text",text:n.text}:k(n,"inlineData")&&F(n.inlineData)&&x(n.inlineData.mimeType)&&x(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:k(n,"functionCall")&&F(n.functionCall)&&x(n.functionCall.name)&&F(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:k(n,"functionResponse")?{type:"non_standard",value:n}:k(n,"fileData")&&F(n.fileData)&&x(n.fileData.mimeType)&&x(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:k(n,"executableCode")?{type:"non_standard",value:n}:k(n,"codeExecutionResult")?{type:"non_standard",value:n}:{type:"non_standard",value:n}),i=Fe(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:s.type==="text"?s.text:"",reasoningContentBlock:s}:s),a={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...i};for(let c in a)a[c]===void 0&&delete a[c];yield a}}return o(e,"iterateContent"),Array.from(e())}o($o,"convertToV1FromChatGoogleMessage");var Uo={translateContent:$o,translateContentChunk:$o};globalThis.lc_block_translators_registry??=new Map([["anthropic",mo],["bedrock-converse",To],["deepseek",So],["google",Uo],["google-genai",xo],["google-vertexai",Co],["groq",Oo],["ollama",Mo],["openai",bo],["openrouter",Po],["xai",Do]]);function Fo(t){return globalThis.lc_block_translators_registry.get(t)}o(Fo,"getTranslator");function Bo(t,e){let r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}o(Bo,"mergeModalitiesTokenDetails");function ch(t,e){let r={...Bo(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}o(ch,"mergeInputTokenDetails");function lh(t,e){let r={...Bo(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}o(lh,"mergeOutputTokenDetails");function Xr(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:ch(t?.input_token_details,e?.input_token_details),output_token_details:lh(t?.output_token_details,e?.output_token_details)}}o(Xr,"mergeUsageMetadata");var bt=class extends ft{static{o(this,"AIMessage")}type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;let r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
7
-
8
- Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){let[s,i]=Ps(r);e.tool_calls=s??[],e.invalid_tool_calls=i??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){if(e.tool_calls){let i=e.tool_calls.filter(a=>!e.contentBlocks?.some(c=>c.type==="tool_call"&&c.id===a.id&&c.name===a.name));e.contentBlocks.push(...i.map(a=>({type:"tool_call",id:a.id,name:a.name,args:a.args})))}let s=e.contentBlocks.filter(i=>i.type==="tool_call").filter(i=>!e.tool_calls?.some(a=>a.id===i.id&&a.name===i.name));s.length>0&&(e.tool_calls=[...e.tool_calls??[],...s.map(i=>({type:"tool_call",id:i.id,name:i.name,args:i.args}))])}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let e=Fo(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls){let e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function gh(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}o(gh,"_contentBlockToString");function tn(t,e="Human",r="AI"){let n=[];for(let s of t){let i;if(s.type==="human")i=e;else if(s.type==="ai")i=r;else if(s.type==="system")i="System";else if(s.type==="tool")i="Tool";else if(s.type==="generic")i=s.role;else throw new Error(`Got unsupported message type: ${s.type}`);let a=s.name?`${s.name}, `:"",c=typeof s.content=="string"?s.content:Array.isArray(s.content)?s.content.map(gh).filter(Boolean).join(""):"",l=`${i}: ${a}${c}`;if(s.type==="ai"){let u=s;u.tool_calls&&u.tool_calls.length>0?l+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(l+=JSON.stringify(u.additional_kwargs.function_call))}n.push(l)}return n.join(`
9
- `)}o(tn,"getBufferString");var $="0123456789abcdef".split(""),yh=[-2147483648,8388608,32768,128],Ze=[24,16,8,0],rn=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],ge=[];function rt(t,e){e?(ge[0]=ge[16]=ge[1]=ge[2]=ge[3]=ge[4]=ge[5]=ge[6]=ge[7]=ge[8]=ge[9]=ge[10]=ge[11]=ge[12]=ge[13]=ge[14]=ge[15]=0,this.blocks=ge):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}o(rt,"Sha256");rt.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,s=0,i,a=t.length,c=this.blocks;s<a;){if(this.hashed&&(this.hashed=!1,c[0]=this.block,this.block=c[16]=c[1]=c[2]=c[3]=c[4]=c[5]=c[6]=c[7]=c[8]=c[9]=c[10]=c[11]=c[12]=c[13]=c[14]=c[15]=0),e)for(i=this.start;s<a&&i<64;++s)c[i>>>2]|=t[s]<<Ze[i++&3];else for(i=this.start;s<a&&i<64;++s)n=t.charCodeAt(s),n<128?c[i>>>2]|=n<<Ze[i++&3]:n<2048?(c[i>>>2]|=(192|n>>>6)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]):n<55296||n>=57344?(c[i>>>2]|=(224|n>>>12)<<Ze[i++&3],c[i>>>2]|=(128|n>>>6&63)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++s)&1023),c[i>>>2]|=(240|n>>>18)<<Ze[i++&3],c[i>>>2]|=(128|n>>>12&63)<<Ze[i++&3],c[i>>>2]|=(128|n>>>6&63)<<Ze[i++&3],c[i>>>2]|=(128|n&63)<<Ze[i++&3]);this.lastByteIndex=i,this.bytes+=i-this.start,i>=64?(this.block=c[16],this.start=i-64,this.hash(),this.hashed=!0):this.start=i}return this.bytes>4294967295&&(this.hBytes+=this.bytes/4294967296<<0,this.bytes=this.bytes%4294967296),this}};rt.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=yh[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};rt.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=this.blocks,u,d,p,_,g,y,E,w,S,I,m;for(u=16;u<64;++u)g=l[u-15],d=(g>>>7|g<<25)^(g>>>18|g<<14)^g>>>3,g=l[u-2],p=(g>>>17|g<<15)^(g>>>19|g<<13)^g>>>10,l[u]=l[u-16]+d+l[u-7]+p<<0;for(m=e&r,u=0;u<64;u+=4)this.first?(this.is224?(w=300032,g=l[0]-1413257819,c=g-150054599<<0,n=g+24177077<<0):(w=704751109,g=l[0]-210244248,c=g-1521486534<<0,n=g+143694565<<0),this.first=!1):(d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),p=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),w=t&e,_=w^t&r^m,E=s&i^~s&a,g=c+p+E+rn[u]+l[u],y=d+_,c=n+g<<0,n=g+y<<0),d=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),p=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),S=n&t,_=S^n&e^w,E=a&c^~a&s,g=i+p+E+rn[u+1]+l[u+1],y=d+_,a=r+g<<0,r=g+y<<0,d=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),p=(a>>>6|a<<26)^(a>>>11|a<<21)^(a>>>25|a<<7),I=r&n,_=I^r&t^S,E=i&a^~i&c,g=s+p+E+rn[u+2]+l[u+2],y=d+_,i=e+g<<0,e=g+y<<0,d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),p=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),m=e&r,_=m^e&n^I,E=i&a^~i&c,g=s+p+E+rn[u+3]+l[u+3],y=d+_,s=t+g<<0,t=g+y<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+s<<0,this.h5=this.h5+i<<0,this.h6=this.h6+a<<0,this.h7=this.h7+c<<0};rt.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=$[t>>>28&15]+$[t>>>24&15]+$[t>>>20&15]+$[t>>>16&15]+$[t>>>12&15]+$[t>>>8&15]+$[t>>>4&15]+$[t&15]+$[e>>>28&15]+$[e>>>24&15]+$[e>>>20&15]+$[e>>>16&15]+$[e>>>12&15]+$[e>>>8&15]+$[e>>>4&15]+$[e&15]+$[r>>>28&15]+$[r>>>24&15]+$[r>>>20&15]+$[r>>>16&15]+$[r>>>12&15]+$[r>>>8&15]+$[r>>>4&15]+$[r&15]+$[n>>>28&15]+$[n>>>24&15]+$[n>>>20&15]+$[n>>>16&15]+$[n>>>12&15]+$[n>>>8&15]+$[n>>>4&15]+$[n&15]+$[s>>>28&15]+$[s>>>24&15]+$[s>>>20&15]+$[s>>>16&15]+$[s>>>12&15]+$[s>>>8&15]+$[s>>>4&15]+$[s&15]+$[i>>>28&15]+$[i>>>24&15]+$[i>>>20&15]+$[i>>>16&15]+$[i>>>12&15]+$[i>>>8&15]+$[i>>>4&15]+$[i&15]+$[a>>>28&15]+$[a>>>24&15]+$[a>>>20&15]+$[a>>>16&15]+$[a>>>12&15]+$[a>>>8&15]+$[a>>>4&15]+$[a&15];return this.is224||(l+=$[c>>>28&15]+$[c>>>24&15]+$[c>>>20&15]+$[c>>>16&15]+$[c>>>12&15]+$[c>>>8&15]+$[c>>>4&15]+$[c&15]),l};rt.prototype.toString=rt.prototype.hex;rt.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,s=this.h4,i=this.h5,a=this.h6,c=this.h7,l=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,a>>>24&255,a>>>16&255,a>>>8&255,a&255];return this.is224||l.push(c>>>24&255,c>>>16&255,c>>>8&255,c&255),l};rt.prototype.array=rt.prototype.digest;rt.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};var Oh=_e(cn(),1);var ac=/^(?:[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 mr(t){return typeof t=="string"&&ac.test(t)}o(mr,"validate");function hr(t){if(!mr(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}o(hr,"parse");var be=[];for(let t=0;t<256;++t)be.push((t+256).toString(16).slice(1));function Et(t,e=0){return(be[t[e+0]]+be[t[e+1]]+be[t[e+2]]+be[t[e+3]]+"-"+be[t[e+4]]+be[t[e+5]]+"-"+be[t[e+6]]+be[t[e+7]]+"-"+be[t[e+8]]+be[t[e+9]]+"-"+be[t[e+10]]+be[t[e+11]]+be[t[e+12]]+be[t[e+13]]+be[t[e+14]]+be[t[e+15]]).toLowerCase()}o(Et,"unsafeStringify");var Nh=new Uint8Array(16);function gr(){return crypto.getRandomValues(Nh)}o(gr,"rng");function Mh(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}o(Mh,"f");function Hs(t,e){return t<<e|t>>>32-e}o(Hs,"ROTL");function oc(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let s=t.length/4+2,i=Math.ceil(s/16),a=new Array(i);for(let c=0;c<i;++c){let l=new Uint32Array(16);for(let u=0;u<16;++u)l[u]=t[c*64+u*4]<<24|t[c*64+u*4+1]<<16|t[c*64+u*4+2]<<8|t[c*64+u*4+3];a[c]=l}a[i-1][14]=(t.length-1)*8/2**32,a[i-1][14]=Math.floor(a[i-1][14]),a[i-1][15]=(t.length-1)*8&4294967295;for(let c=0;c<i;++c){let l=new Uint32Array(80);for(let y=0;y<16;++y)l[y]=a[c][y];for(let y=16;y<80;++y)l[y]=Hs(l[y-3]^l[y-8]^l[y-14]^l[y-16],1);let u=r[0],d=r[1],p=r[2],_=r[3],g=r[4];for(let y=0;y<80;++y){let E=Math.floor(y/20),w=Hs(u,5)+Mh(E,d,p,_)+g+e[E]+l[y]>>>0;g=_,_=p,p=Hs(d,30)>>>0,d=u,u=w}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+p>>>0,r[3]=r[3]+_>>>0,r[4]=r[4]+g>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}o(oc,"sha1");function kh(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}o(kh,"stringToBytes");var cc="6ba7b810-9dad-11d1-80b4-00c04fd430c8",lc="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function uc(t,e,r,n,s,i){let a=typeof r=="string"?kh(r):r,c=typeof n=="string"?hr(n):n;if(typeof n=="string"&&(n=hr(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+a.length);if(l.set(c),l.set(a,c.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,s){if(i??=0,i<0||i+16>s.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);for(let u=0;u<16;++u)s[i+u]=l[u];return s}return Et(l)}o(uc,"v35");function Gs(t,e,r,n){return uc(80,oc,t,e,r,n)}o(Gs,"v5");Gs.DNS=cc;Gs.URL=lc;var zs={};function fc(t,e,r){let n;if(t)n=dc(t.random??t.rng?.()??gr(),t.msecs,t.seq,e,r);else{let s=Date.now(),i=gr();Lh(zs,s,i),n=dc(i,zs.msecs,zs.seq,e,r)}return e??Et(n)}o(fc,"v7");function Lh(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}o(Lh,"updateV7State");function dc(t,e,r,n,s=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),s=0;else if(s<0||s+16>n.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[s++]=e/1099511627776&255,n[s++]=e/4294967296&255,n[s++]=e/16777216&255,n[s++]=e/65536&255,n[s++]=e/256&255,n[s++]=e&255,n[s++]=112|r>>>28&15,n[s++]=r>>>20&255,n[s++]=128|r>>>14&63,n[s++]=r>>>6&255,n[s++]=r<<2&255|t[10]&3,n[s++]=t[11],n[s++]=t[12],n[s++]=t[13],n[s++]=t[14],n[s++]=t[15],n}o(dc,"v7Bytes");var nt=fc;var pc=Symbol.for("ls:tracing_async_local_storage"),Mt=Symbol.for("lc:context_variables"),mc=o(t=>{globalThis[pc]=t},"setGlobalAsyncLocalStorageInstance"),wt=o(()=>globalThis[pc],"getGlobalAsyncLocalStorageInstance");var Dh=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),$h=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),Uh=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Ws=o(()=>typeof Deno<"u","isDeno"),Fh=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Ws(),"isNode"),Bh=o(()=>{let t;return Dh()?t="browser":Fh()?t="node":$h()?t="webworker":Uh()?t="jsdom":Ws()?t="deno":t="other",t},"getEnv"),Vs;function hc(){return Vs===void 0&&(Vs={library:"langchain-js",runtime:Bh()}),Vs}o(hc,"getRuntimeEnvironment");function Je(t){try{return typeof process<"u"?process.env?.[t]:Ws()?Deno?.env.get(t):void 0}catch{return}}o(Je,"getEnvironmentVariable");var jh=class{static{o(this,"BaseCallbackHandlerMethodsClass")}};var qt=class extends jh{static{o(this,"BaseCallbackHandler")}lc_serializable=!1;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,Rs(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Ot.prototype.toJSON.call(this)}toJSONNotImplemented(){return Ot.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends qt{static{o(this,"Handler")}name=nt();constructor(){super(),Object.assign(this,t)}}return new e}},gc=o(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var yc=/^(?:[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 Hh(t){return typeof t=="string"&&yc.test(t)}o(Hh,"validate");var _c=Hh;function Gh(t){if(!_c(t))throw TypeError("Invalid UUID");let e,r=new Uint8Array(16);return r[0]=(e=parseInt(t.slice(0,8),16))>>>24,r[1]=e>>>16&255,r[2]=e>>>8&255,r[3]=e&255,r[4]=(e=parseInt(t.slice(9,13),16))>>>8,r[5]=e&255,r[6]=(e=parseInt(t.slice(14,18),16))>>>8,r[7]=e&255,r[8]=(e=parseInt(t.slice(19,23),16))>>>8,r[9]=e&255,r[10]=(e=parseInt(t.slice(24,36),16))/1099511627776&255,r[11]=e/4294967296&255,r[12]=e>>>24&255,r[13]=e>>>16&255,r[14]=e>>>8&255,r[15]=e&255,r}o(Gh,"parse");var bc=Gh;var Ee=[];for(let t=0;t<256;++t)Ee.push((t+256).toString(16).slice(1));function Kt(t,e=0){return(Ee[t[e+0]]+Ee[t[e+1]]+Ee[t[e+2]]+Ee[t[e+3]]+"-"+Ee[t[e+4]]+Ee[t[e+5]]+"-"+Ee[t[e+6]]+Ee[t[e+7]]+"-"+Ee[t[e+8]]+Ee[t[e+9]]+"-"+Ee[t[e+10]]+Ee[t[e+11]]+Ee[t[e+12]]+Ee[t[e+13]]+Ee[t[e+14]]+Ee[t[e+15]]).toLowerCase()}o(Kt,"unsafeStringify");var Ec=_e(require("node:crypto"));var un=new Uint8Array(256),ln=un.length;function yr(){return ln>un.length-16&&(Ec.default.randomFillSync(un),ln=0),un.slice(ln,ln+=16)}o(yr,"rng");function zh(t){t=unescape(encodeURIComponent(t));let e=[];for(let r=0;r<t.length;++r)e.push(t.charCodeAt(r));return e}o(zh,"stringToBytes");var Vh="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Wh="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function qs(t,e,r){function n(s,i,a,c){var l;if(typeof s=="string"&&(s=zh(s)),typeof i=="string"&&(i=bc(i)),((l=i)===null||l===void 0?void 0:l.length)!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let u=new Uint8Array(16+s.length);if(u.set(i),u.set(s,i.length),u=r(u),u[6]=u[6]&15|e,u[8]=u[8]&63|128,a){c=c||0;for(let d=0;d<16;++d)a[c+d]=u[d];return a}return Kt(u)}o(n,"generateUUID");try{n.name=t}catch{}return n.DNS=Vh,n.URL=Wh,n}o(qs,"v35");var wc=_e(require("node:crypto")),Ks={randomUUID:wc.default.randomUUID};function qh(t,e,r){if(Ks.randomUUID&&!e&&!t)return Ks.randomUUID();t=t||{};let n=t.random||(t.rng||yr)();if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){r=r||0;for(let s=0;s<16;++s)e[r+s]=n[s];return e}return Kt(n)}o(qh,"v4");var kt=qh;var Tc=_e(require("node:crypto"));function Kh(t){return Array.isArray(t)?t=Buffer.from(t):typeof t=="string"&&(t=Buffer.from(t,"utf8")),Tc.default.createHash("sha1").update(t).digest()}o(Kh,"sha1");var vc=Kh;var Zh=qs("v5",80,vc),Zs=Zh;var Sc=null,Ic=null,Ye=0;function Jh(t,e,r){t=t||{};let n=e&&r||0,s=e||new Uint8Array(16),i=t.random||(t.rng||yr)(),a=t.msecs!==void 0?t.msecs:Date.now(),c=t.seq!==void 0?t.seq:null,l=Ic,u=Sc;return a>Ye&&t.msecs===void 0&&(Ye=a,c!==null&&(l=null,u=null)),c!==null&&(c>2147483647&&(c=2147483647),l=c>>>19&4095,u=c&524287),(l===null||u===null)&&(l=i[6]&127,l=l<<8|i[7],u=i[8]&63,u=u<<8|i[9],u=u<<5|i[10]>>>3),a+1e4>Ye&&c===null?++u>524287&&(u=0,++l>4095&&(l=0,Ye++)):Ye=a,Ic=l,Sc=u,s[n++]=Ye/1099511627776&255,s[n++]=Ye/4294967296&255,s[n++]=Ye/16777216&255,s[n++]=Ye/65536&255,s[n++]=Ye/256&255,s[n++]=Ye&255,s[n++]=l>>>4&15|112,s[n++]=l&255,s[n++]=u>>>13&63|128,s[n++]=u>>>5&255,s[n++]=u<<3&255|i[10]&7,s[n++]=i[11],s[n++]=i[12],s[n++]=i[13],s[n++]=i[14],s[n++]=i[15],e||Kt(s)}o(Jh,"v7");var _r=Jh;var xc="gen_ai.operation.name",Ac="gen_ai.system",Js="gen_ai.request.model",Cc="gen_ai.response.model",Ys="gen_ai.usage.input_tokens",Xs="gen_ai.usage.output_tokens",Qs="gen_ai.usage.total_tokens",Rc="gen_ai.request.max_tokens",Oc="gen_ai.request.temperature",Nc="gen_ai.request.top_p",Mc="gen_ai.request.frequency_penalty",kc="gen_ai.request.presence_penalty",Pc="gen_ai.response.finish_reasons",Lc="gen_ai.prompt",Dc="gen_ai.completion",$c="gen_ai.request.extra_query",Uc="gen_ai.request.extra_body",Fc="gen_ai.serialized.name",Bc="gen_ai.serialized.signature",jc="gen_ai.serialized.doc",Hc="gen_ai.response.id",Gc="gen_ai.response.service_tier",zc="gen_ai.response.system_fingerprint",Vc="gen_ai.usage.input_token_details",Wc="gen_ai.usage.output_token_details",qc="langsmith.trace.session_id",Kc="langsmith.trace.session_name",Zc="langsmith.span.kind",Jc="langsmith.trace.name",Yc="langsmith.metadata",ei="langsmith.span.tags";var Xc="langsmith.request.streaming",Qc="langsmith.request.headers";var Qh=o((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),eg,el=Symbol.for("ls:fetch_implementation");var tl=o(()=>globalThis[el]===void 0?!0:eg??!1,"_shouldStreamForGlobalFetchImplementation"),rl=o(t=>async(...e)=>{if(t||te("DEBUG")==="true"){let[n,s]=e;console.log(`\u2192 ${s?.method||"GET"} ${n}`)}let r=await(globalThis[el]??Qh)(...e);return(t||te("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var br=o(()=>te("PROJECT")??Be("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var nl={};function Pt(t){nl[t]||(console.warn(t),nl[t]=!0)}o(Pt,"warnOnce");var R=o(t=>BigInt(t),"n"),ol=R("0x9E3779B1"),cl=R("0x85EBCA77"),tg=R("0xC2B2AE3D"),Tt=R("0x9E3779B185EBCA87"),Lt=R("0xC2B2AE3D27D4EB4F"),ll=R("0x165667B19E3779F9"),si=R("0x85EBCA77C2B2AE63"),rg=R("0x27D4EB2F165667C5"),ng=R("0x165667919E3779F9"),sg=R("0x9FB21C651E98DF25");function ig(t){let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.substring(r,r+2),16);return e}o(ig,"hexToBytes");var st=ig("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),Jt=(R(1)<<R(128))-R(1),W=(R(1)<<R(64))-R(1),mn=(R(1)<<R(32))-R(1),pt=64,ul=pt/8,ag=8,dn=4;function Y(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}o(Y,"getView");function Q(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}o(Q,"readBigUInt64LE");function Zt(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}o(Zt,"readUInt32LE");function ti(t,e=0){return t[e]}o(ti,"readUInt8");var og=o(t=>(t&R(255))<<R(56)|(t&R(65280))<<R(40)|(t&R(16711680))<<R(24)|(t&R(4278190080))<<R(8)|(t&R(0xff00000000))>>R(8)|(t&R(0xff0000000000))>>R(24)|(t&R(0xff000000000000))>>R(40)|(t&R(0xff00000000000000))>>R(56),"bswap64"),cg=o(t=>(t=(t&R(65535))<<R(16)|(t&R(4294901760))>>R(16),t=(t&R(16711935))<<R(8)|(t&R(4278255360))>>R(8),t),"bswap32"),lg=o((t,e)=>(t&mn)*(e&mn)&W,"XXH_mult32to64"),Yt=o(t=>{if(!t)throw new Error("Assert failed")},"assert");function ug(t,e){return(t<<e|t>>R(32)-e)&mn}o(ug,"rotl32");function dl(t,e,r){for(let n=0;n<ul;n++){let s=Q(e,n*8),i=s^Q(r,n*8);t[n^1]+=s,t[n]+=lg(i,i>>R(32))}return t}o(dl,"XXH3_accumulate_512");function sl(t,e,r,n){for(let s=0;s<n;s++)dl(t,Y(e,s*pt),Y(r,s*8));return t}o(sl,"XXH3_accumulate");function dg(t,e){for(let r=0;r<ul;r++){let n=Q(e,r*8),s=t[r];s=ri(s,R(47)),s^=n,s*=ol,t[r]=s&W}return t}o(dg,"XXH3_scrambleAcc");function fn(t,e){return fl(t[0]^Q(e,0),t[1]^Q(e,ag))}o(fn,"XXH3_mix2Accs");function il(t,e,r){let n=r;return n+=fn(t.slice(0),Y(e,0*dn)),n+=fn(t.slice(2),Y(e,4*dn)),n+=fn(t.slice(4),Y(e,8*dn)),n+=fn(t.slice(6),Y(e,12*dn)),it(n&W)}o(il,"XXH3_mergeAccs");function fg(t,e,r,n,s){let i=Math.floor((r.byteLength-pt)/8),a=pt*i,c=Math.floor((e.byteLength-1)/a);for(let l=0;l<c;l++)t=sl(t,Y(e,l*a),r,i),t=s(t,Y(r,r.byteLength-pt));{let l=Math.floor((e.byteLength-1-a*c)/pt);t=sl(t,Y(e,c*a),r,l),t=n(t,Y(e,e.byteLength-pt),Y(r,r.byteLength-pt-7))}return t}o(fg,"XXH3_hashLong");function pg(t,e,r){let n=new BigUint64Array([tg,Tt,Lt,ll,si,cl,rg,ol]);Yt(t.length>128),n=fg(n,t,e,dl,dg),Yt(n.length*8==64);{let s=il(n,Y(e,11),R(t.byteLength)*Tt&W);return il(n,Y(e,e.byteLength-pt-11),~(R(t.byteLength)*Lt)&W)<<R(64)|s}}o(pg,"XXH3_hashLong_128b");function fl(t,e){let r=t*e&Jt;return r&W^r>>R(64)}o(fl,"XXH3_mul128_fold64");function al(t,e,r){return fl((Q(t,0)^Q(e,0)+r)&W,(Q(t,8)^Q(e,8)-r)&W)}o(al,"XXH3_mix16B");function pn(t,e,r,n,s){let i=t&W,a=t>>R(64)&W;return i+=al(e,n,s),i^=Q(r,0)+Q(r,8),i&=W,a+=al(r,Y(n,16),s),a^=Q(e,0)+Q(e,8),a&=W,a<<R(64)|i}o(pn,"XXH3_mix32B");function it(t){return t^=t>>R(37),t*=ng,t&=W,t^=t>>R(32),t}o(it,"XXH3_avalanche");function hn(t){return t^=t>>R(33),t*=Lt,t&=W,t^=t>>R(29),t*=ll,t&=W,t^=t>>R(32),t}o(hn,"XXH3_avalanche64");function mg(t,e,r){let n=t.byteLength;Yt(n>0&&n<=3);let s=R(ti(t,n-1))|R(n<<8)|R(ti(t,0)<<16)|R(ti(t,n>>1)<<24),i=(R(Zt(e,0))^R(Zt(e,4)))+r,a=(s^i)&W,c=(R(Zt(e,8))^R(Zt(e,12)))-r,l=(ug(cg(s),R(13))^c)&W;return(hn(l)&W)<<R(64)|hn(a)}o(mg,"XXH3_len_1to3_128b");function ri(t,e){return t^t>>e}o(ri,"xorshift64");function hg(t,e,r){let n=t.byteLength;Yt(n>=4&&n<=8);{let s=Zt(t,0),i=Zt(t,n-4),a=R(s)|R(i)<<R(32),c=(Q(e,16)^Q(e,24))+r&W,u=(a^c)*(Tt+(R(n)<<R(2)))&Jt;return u+=(u&W)<<R(65),u&=Jt,u^=u>>R(67),ri(ri(u&W,R(35))*sg&W,R(28))|it(u>>R(64))<<R(64)}}o(hg,"XXH3_len_4to8_128b");function gg(t,e,r){let n=t.byteLength;Yt(n>=9&&n<=16);{let s=(Q(e,32)^Q(e,40))+r&W,i=(Q(e,48)^Q(e,56))-r&W,a=Q(t),c=Q(t,n-8),l=(a^c^s)*Tt,u=(l&W)+(R(n-1)<<R(54));l=l&(Jt^W)|u,c^=i,l+=c+(c&mn)*(cl-R(1))<<R(64),l&=Jt,l^=og(l>>R(64));let d=(l&W)*Lt;return d+=(l>>R(64))*Lt<<R(64),d&=Jt,it(d&W)|it(d>>R(64))<<R(64)}}o(gg,"XXH3_len_9to16_128b");function yg(t,e){let r=t.byteLength;return Yt(r<=16),r>8?gg(t,st,e):r>=4?hg(t,st,e):r>0?mg(t,st,e):hn(e^Q(st,64)^Q(st,72))|hn(e^Q(st,80)^Q(st,88))<<R(64)}o(yg,"XXH3_len_0to16_128b");function ni(t){return~t+R(1)&W}o(ni,"inv64");function _g(t,e,r){let n=R(t.byteLength)*Tt&W,s=R(t.byteLength-1)/R(32);for(;s>=0;){let c=Number(s);n=pn(n,Y(t,16*c),Y(t,t.byteLength-16*(c+1)),Y(e,32*c),r),s--}let i=n+(n>>R(64))&W;i=it(i);let a=(n&W)*Tt+(n>>R(64))*si+(R(t.byteLength)-r&W)*Lt;return a&=W,a=ni(it(a)),i|a<<R(64)}o(_g,"XXH3_len_17to128_128b");function bg(t,e,r){let n=R(t.byteLength)*Tt&W;for(let a=32;a<160;a+=32)n=pn(n,Y(t,a-32),Y(t,a-16),Y(e,a-32),r);n=it(n&W)|it(n>>R(64))<<R(64);for(let a=160;a<=t.byteLength;a+=32)n=pn(n,Y(t,a-32),Y(t,a-16),Y(e,3+a-160),r);n=pn(n,Y(t,t.byteLength-16),Y(t,t.byteLength-32),Y(e,103),ni(r));let s=n+(n>>R(64))&W;s=it(s);let i=(n&W)*Tt+(n>>R(64))*si+(R(t.byteLength)-r&W)*Lt;return i&=W,i=ni(it(i)),s|i<<R(64)}o(bg,"XXH3_len_129to240_128b");function pl(t,e=R(0)){let r=t.byteLength;return r<=16?yg(t,e):r<=128?_g(t,st,e):r<=240?bg(t,st,e):pg(t,st,e)}o(pl,"XXH3_128");function ml(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&W,s=t>>R(64);return r.setBigUint64(0,s,!1),r.setBigUint64(8,n,!1),e}o(ml,"xxh128ToBytes");var hl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function z(t,e){if(!hl.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}o(z,"assertUuid");function gn(t){let e=typeof t=="string"?Date.parse(t):t;return _r({msecs:e,seq:0})}o(gn,"uuid7FromTime");function Eg(t){if(!hl.test(t))return null;let e=t[14];return parseInt(e,16)}o(Eg,"getUuidVersion");function wg(t){let e=t.replace(/-/g,""),r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}o(wg,"uuidToBytes");function Tg(t){let e=Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}o(Tg,"bytesToUuid");var vg=new TextEncoder;function Sg(t){let e=vg.encode(t),r=pl(e);return ml(r)}o(Sg,"_fastHash128");function Er(t,e){let r=`${t}:${e}`,n=Sg(r),s=new Uint8Array(16);if(Eg(t)===7){let a=wg(t);s.set(a.slice(0,6),0)}else{let a=Date.now();s[0]=a/1099511627776&255,s[1]=a/4294967296&255,s[2]=a/16777216&255,s[3]=a/65536&255,s[4]=a/256&255,s[5]=a&255}return s[6]=112|n[0]&15,s[7]=n[1],s[8]=128|n[2]&63,s.set(n.slice(3,10),9),Tg(s)}o(Er,"nonCryptographicUuid7Deterministic");var He=_e(require("node:fs"),1),Xe=_e(require("node:fs/promises"),1),Ig=_e(require("node:path"),1);var wr=Ig;async function gl(t){await Xe.mkdir(t,{recursive:!0})}o(gl,"mkdir");async function yl(t,e){let r=`${t}.tmp`;await Xe.writeFile(r,e,{encoding:"utf8",mode:384}),await Xe.rename(r,t)}o(yl,"writeFileAtomic");async function _l(t){return Xe.readdir(t)}o(_l,"readdir");async function bl(t){return Xe.stat(t)}o(bl,"stat");function yn(t){return He.existsSync(t)}o(yn,"existsSync");function El(t){He.mkdirSync(t,{recursive:!0})}o(El,"mkdirSync");function wl(t,e){He.writeFileSync(t,e)}o(wl,"writeFileSync");function Tl(t,e){He.renameSync(t,e)}o(Tl,"renameSync");function vl(t){He.unlinkSync(t)}o(vl,"unlinkSync");function Sl(t){return He.readFileSync(t,"utf-8")}o(Sl,"readFileSync");function Ag(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}o(Ag,"isStale");var _n=class{static{o(this,"PromptCache")}constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,r){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:r}),this._metrics.hits+=1,n.value}set(e,r,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let i=this.cache.keys().next().value;i!==void 0&&this.cache.delete(i)}let s={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,s)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let r={};for(let[i,a]of this.cache.entries())r[i]=a.value;let n=wr.dirname(e);yn(n)||El(n);let s=`${e}.tmp`;try{wl(s,JSON.stringify({entries:r},null,2)),Tl(s,e)}catch(i){throw yn(s)&&vl(s),i}}load(e){if(!yn(e))return 0;let r;try{let i=Sl(e);r=JSON.parse(i).entries??null}catch{return 0}if(!r)return 0;let n=0,s=Date.now();for(let[i,a]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let c={value:a,createdAt:s};this.cache.set(i,c),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,n]of this.cache.entries())Ag(n,this.ttlSeconds)&&e.push([r,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[r,n]of e)if(n.refreshFunc!==void 0)try{let s=await n.refreshFunc();this.set(r,s,n.refreshFunc),this._metrics.refreshes+=1}catch(s){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,s)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},bn=new _n;var En="0.5.16";var at,Cg=o(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),Rg=o(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),Og=o(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),Il=o(()=>typeof Deno<"u","isDeno"),Ng=o(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!Il(),"isNode"),oi=o(()=>at||(typeof Bun<"u"?at="bun":Cg()?at="browser":Ng()?at="node":Rg()?at="webworker":Og()?at="jsdom":Il()?at="deno":at="other",at),"getEnv"),ii;function wn(){if(ii===void 0){let t=oi(),e=kg();ii={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:En,...e}}return ii}o(wn,"getRuntimeEnvironment");function ci(){let t=Mg(),e={},r=["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(let[n,s]of Object.entries(t))typeof s=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=s:e[n]=s);return e}o(ci,"getLangSmithEnvVarsMetadata");function Mg(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,r]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}o(Mg,"getLangSmithEnvironmentVariables");function Be(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}o(Be,"getEnvironmentVariable");function te(t){return Be(`LANGSMITH_${t}`)||Be(`LANGCHAIN_${t}`)}o(te,"getLangSmithEnvironmentVariable");var ai;function kg(){if(ai!==void 0)return ai;let t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(let r of t){let n=Be(r);n!==void 0&&(e[r]=n)}return ai=e,e}o(kg,"getShas");function Tn(){return Be("OTEL_ENABLED")==="true"||te("OTEL_ENABLED")==="true"}o(Tn,"getOtelEnabled");var di=class{static{o(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&Tn()&&(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 n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}},fi=class{static{o(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new di})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},pi=class{static{o(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},li=Symbol.for("ls:otel_trace"),ui=Symbol.for("ls:otel_context"),xl=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),Pg=new fi,Lg=new pi,mi=class{static{o(this,"OTELProvider")}getTraceInstance(){return globalThis[li]??Pg}getContextInstance(){return globalThis[ui]??Lg}initializeGlobalInstances(e){globalThis[li]===void 0&&(globalThis[li]=e.trace),globalThis[ui]===void 0&&(globalThis[ui]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[xl]=e}getDefaultOTLPTracerComponents(){return globalThis[xl]??void 0}},hi=new mi;function vn(){return hi.getTraceInstance()}o(vn,"getOTELTrace");function Al(){return hi.getContextInstance()}o(Al,"getOTELContext");function Cl(){return hi.getDefaultOTLPTracerComponents()}o(Cl,"getDefaultOTLPTracerComponents");var Dg={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function $g(t){return Dg[t]||t}o($g,"getOperationName");var Sn=class{static{o(this,"LangSmithToOTELTranslator")}constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let s=this.createSpanForRun(n,n.run,r.get(n.id));s&&!n.run.end_time&&this.spans.set(n.id,s)}else this.updateSpanForRun(n,n.run)}catch(s){console.error(`Error processing operation ${n.id}:`,s)}}createSpanForRun(e,r,n){let s=n&&vn().getSpan(n);if(s)try{return this.finishSpanSetup(s,r,e)}catch(i){console.error(`Failed to create span for run ${e.id}:`,i);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let s=r.end_time;s&&(n.end(new Date(s)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(Zc,r.run_type);let c=$g(r.run_type||"chain");e.setAttribute(xc,c)}"name"in r&&r.name&&e.setAttribute(Jc,r.name),"session_id"in r&&r.session_id&&e.setAttribute(qc,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(Kc,r.session_name),this.setGenAiSystem(e,r);let s=this.extractModelName(r);s&&e.setAttribute(Js,s),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Ys,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Xs,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute(Qs,r.total_tokens),this.setInvocationParameters(e,r);let i=r.extra?.metadata||{};for(let[c,l]of Object.entries(i))l!=null&&e.setAttribute(`${Yc}.${c}`,String(l));let a=r.tags;if(a&&Array.isArray(a)?e.setAttribute(ei,a.join(", ")):a&&e.setAttribute(ei,String(a)),"serialized"in r&&typeof r.serialized=="object"){let c=r.serialized;c.name&&e.setAttribute(Fc,String(c.name)),c.signature&&e.setAttribute(Bc,String(c.signature)),c.doc&&e.setAttribute(jc,String(c.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",s=this.extractModelName(r);if(s){let i=s.toLowerCase();i.includes("anthropic")||i.startsWith("claude")?n="anthropic":i.includes("bedrock")?n="aws.bedrock":i.includes("azure")&&i.includes("openai")?n="az.ai.openai":i.includes("azure")&&i.includes("inference")?n="az.ai.inference":i.includes("cohere")?n="cohere":i.includes("deepseek")?n="deepseek":i.includes("gemini")?n="gemini":i.includes("groq")?n="groq":i.includes("watson")||i.includes("ibm")?n="ibm.watsonx.ai":i.includes("mistral")?n="mistral_ai":i.includes("gpt")||i.includes("openai")?n="openai":i.includes("perplexity")||i.includes("sonar")?n="perplexity":i.includes("vertex")?n="vertex_ai":(i.includes("xai")||i.includes("grok"))&&(n="xai")}e.setAttribute(Ac,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(Rc,n.max_tokens),n.temperature!==void 0&&e.setAttribute(Oc,n.temperature),n.top_p!==void 0&&e.setAttribute(Nc,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(Mc,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(kc,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(Js,n.model),n.stream!==void 0&&e.setAttribute(Xc,n.stream),n.extra_headers&&e.setAttribute(Qc,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute($c,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(Uc,JSON.stringify(n.extra_body))),e.setAttribute(Lc,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,s=this.getUnifiedRunTokens(n);if(s&&(e.setAttribute(Ys,s[0]),e.setAttribute(Xs,s[1]),e.setAttribute(Qs,s[0]+s[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(Cc,String(n.model)),n.id&&e.setAttribute(Hc,n.id),n.choices&&Array.isArray(n.choices)){let i=n.choices.map(a=>a.finish_reason).filter(a=>a).map(String);i.length>0&&e.setAttribute(Pc,i.join(", "))}if(n.service_tier&&e.setAttribute(Gc,n.service_tier),n.system_fingerprint&&e.setAttribute(zc,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let i=n.usage_metadata;i.input_token_details&&e.setAttribute(Vc,JSON.stringify(i.input_token_details)),i.output_token_details&&e.setAttribute(Wc,JSON.stringify(i.output_token_details))}}e.setAttribute(Dc,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;let n=Object.keys(e);for(let a of n){let c=e[a];if(!(!c||typeof c!="object")&&(r=this.extractUnifiedRunTokens(c.usage_metadata),r||c.lc===1&&c.kwargs&&typeof c.kwargs=="object"&&(r=this.extractUnifiedRunTokens(c.kwargs.usage_metadata),r)))return r}let s=e.generations||[];if(!Array.isArray(s))return null;let i=Array.isArray(s[0])?s.flat():s;for(let a of i)if(typeof a=="object"&&a.message&&typeof a.message=="object"&&a.message.kwargs&&typeof a.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(a.message.kwargs.usage_metadata),r))return r;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 Ug=Object.prototype.toString,Fg=o(t=>Ug.call(t)==="[object Error]","isError"),Bg=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function gi(t){if(!(t&&Fg(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:Bg.has(r)}o(gi,"isNetworkError");function jg(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}o(jg,"validateRetries");function In(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be \u2265 ${r}.`)}}o(In,"validateNumberOption");var yi=class extends Error{static{o(this,"AbortError")}constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function Hg(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,s=Math.round(n*e.minTimeout*e.factor**(r-1));return s=Math.min(s,e.maxTimeout),s}o(Hg,"calculateDelay");function Rl(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}o(Rl,"calculateRemainingTime");async function Gg({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:s}){let i=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(i instanceof yi)throw i.originalError;let a=Number.isFinite(s.retries)?Math.max(0,s.retries-r):s.retries,c=s.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:i,attemptNumber:e,retriesLeft:a,retriesConsumed:r});if(await s.onFailedAttempt(l),Rl(n,c)<=0)throw i;let u=await s.shouldConsumeRetry(l),d=Rl(n,c);if(d<=0||a<=0)throw i;if(i instanceof TypeError&&!gi(i)){if(u)throw i;return s.signal?.throwIfAborted(),!1}if(!await s.shouldRetry(l))throw i;if(!u)return s.signal?.throwIfAborted(),!1;let p=Hg(r,s),_=Math.min(p,d);return _>0&&await new Promise((g,y)=>{let E=o(()=>{clearTimeout(w),s.signal?.removeEventListener("abort",E),y(s.signal.reason)},"onAbort"),w=setTimeout(()=>{s.signal?.removeEventListener("abort",E),g()},_);s.unref&&w.unref?.(),s.signal?.addEventListener("abort",E,{once:!0})}),s.signal?.throwIfAborted(),!0}o(Gg,"onAttemptFailure");async function _i(t,e={}){if(e={...e},jg(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,In("factor",e.factor,{min:0,allowInfinity:!1}),In("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),In("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),In("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,s=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let i=await t(r);return e.signal?.throwIfAborted(),i}catch(i){await Gg({error:i,attemptNumber:r,retriesConsumed:n,startTime:s,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}o(_i,"pRetry");var xn=_e(cn(),1),Ol="default"in xn.default?xn.default.default:xn.default;var zg=[408,425,429,500,502,503,504],Tr=class{static{o(this,"AsyncCaller")}constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new Ol({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let s=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&s>0&&this.queueSizeBytes+s>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${s} bytes.`));s>0&&(this.queueSizeBytes+=s);let i=this.onFailedResponseHook,a=this.queue.add(()=>_i(()=>r(...n).catch(c=>{throw c instanceof Error?c:new Error(c)}),{async onFailedAttempt({error:c}){if(typeof c!="object"||c==null)throw c;let l="message"in c&&typeof c.message=="string"?c.message:void 0;if(l?.startsWith("Cancel")||l?.startsWith("TimeoutError")||l?.startsWith("AbortError")||"name"in c&&c.name==="TimeoutError"||"code"in c&&c.code==="ECONNABORTED")throw c;let u="response"in c?c.response:void 0;if(i&&await i(u))return;let d=u?.status??("status"in c?c.status:void 0);if(d!=null&&(typeof d=="number"||typeof d=="string")&&!zg.includes(+d))throw c},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return s>0&&(a=a.finally(()=>{this.queueSizeBytes-=s})),e.signal?Promise.race([a,new Promise((c,l)=>{e.signal?.addEventListener("abort",()=>{l(new Error("AbortError"))})})]):a}};function bi(t){return typeof t?._getType=="function"}o(bi,"isLangChainMessage");function Ei(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}o(Ei,"convertLangChainMessageToExample");var Bb=_e(bd(),1);function Bn(t){return`Invalid prompt identifier format: "${t}". Expected one of:
1
+ "use strict";var am=Object.create;var Yr=Object.defineProperty;var om=Object.getOwnPropertyDescriptor;var cm=Object.getOwnPropertyNames;var lm=Object.getPrototypeOf,um=Object.prototype.hasOwnProperty;var a=(t,e)=>Yr(t,"name",{value:e,configurable:!0});var re=(t,e)=>()=>{try{return e||t((e={exports:{}}).exports,e),e.exports}catch(r){throw e=0,r}},dm=(t,e)=>{for(var r in e)Yr(t,r,{get:e[r],enumerable:!0})},Ho=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of cm(e))!um.call(t,i)&&i!==r&&Yr(t,i,{get:()=>e[i],enumerable:!(n=om(e,i))||n.enumerable});return t};var He=(t,e,r)=>(r=t!=null?am(lm(t)):{},Ho(e||!t||!t.__esModule?Yr(r,"default",{value:t,enumerable:!0}):r,t)),fm=t=>Ho(Yr({},"__esModule",{value:!0}),t);var Fc=re((aS,ys)=>{"use strict";var Ym=Object.prototype.hasOwnProperty,ke="~";function Qr(){}a(Qr,"Events");Object.create&&(Qr.prototype=Object.create(null),new Qr().__proto__||(ke=!1));function Xm(t,e,r){this.fn=t,this.context=e,this.once=r||!1}a(Xm,"EE");function $c(t,e,r,n,i){if(typeof r!="function")throw new TypeError("The listener must be a function");var s=new Xm(r,n||t,i),o=ke?ke+e:e;return t._events[o]?t._events[o].fn?t._events[o]=[t._events[o],s]:t._events[o].push(s):(t._events[o]=s,t._eventsCount++),t}a($c,"addListener");function $n(t,e){--t._eventsCount===0?t._events=new Qr:delete t._events[e]}a($n,"clearEvent");function Ie(){this._events=new Qr,this._eventsCount=0}a(Ie,"EventEmitter");Ie.prototype.eventNames=a(function(){var e=[],r,n;if(this._eventsCount===0)return e;for(n in r=this._events)Ym.call(r,n)&&e.push(ke?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(r)):e},"eventNames");Ie.prototype.listeners=a(function(e){var r=ke?ke+e:e,n=this._events[r];if(!n)return[];if(n.fn)return[n.fn];for(var i=0,s=n.length,o=new Array(s);i<s;i++)o[i]=n[i].fn;return o},"listeners");Ie.prototype.listenerCount=a(function(e){var r=ke?ke+e:e,n=this._events[r];return n?n.fn?1:n.length:0},"listenerCount");Ie.prototype.emit=a(function(e,r,n,i,s,o){var c=ke?ke+e:e;if(!this._events[c])return!1;var l=this._events[c],u=arguments.length,d,f;if(l.fn){switch(l.once&&this.removeListener(e,l.fn,void 0,!0),u){case 1:return l.fn.call(l.context),!0;case 2:return l.fn.call(l.context,r),!0;case 3:return l.fn.call(l.context,r,n),!0;case 4:return l.fn.call(l.context,r,n,i),!0;case 5:return l.fn.call(l.context,r,n,i,s),!0;case 6:return l.fn.call(l.context,r,n,i,s,o),!0}for(f=1,d=new Array(u-1);f<u;f++)d[f-1]=arguments[f];l.fn.apply(l.context,d)}else{var y=l.length,h;for(f=0;f<y;f++)switch(l[f].once&&this.removeListener(e,l[f].fn,void 0,!0),u){case 1:l[f].fn.call(l[f].context);break;case 2:l[f].fn.call(l[f].context,r);break;case 3:l[f].fn.call(l[f].context,r,n);break;case 4:l[f].fn.call(l[f].context,r,n,i);break;default:if(!d)for(h=1,d=new Array(u-1);h<u;h++)d[h-1]=arguments[h];l[f].fn.apply(l[f].context,d)}}return!0},"emit");Ie.prototype.on=a(function(e,r,n){return $c(this,e,r,n,!1)},"on");Ie.prototype.once=a(function(e,r,n){return $c(this,e,r,n,!0)},"once");Ie.prototype.removeListener=a(function(e,r,n,i){var s=ke?ke+e:e;if(!this._events[s])return this;if(!r)return $n(this,s),this;var o=this._events[s];if(o.fn)o.fn===r&&(!i||o.once)&&(!n||o.context===n)&&$n(this,s);else{for(var c=0,l=[],u=o.length;c<u;c++)(o[c].fn!==r||i&&!o[c].once||n&&o[c].context!==n)&&l.push(o[c]);l.length?this._events[s]=l.length===1?l[0]:l:$n(this,s)}return this},"removeListener");Ie.prototype.removeAllListeners=a(function(e){var r;return e?(r=ke?ke+e:e,this._events[r]&&$n(this,r)):(this._events=new Qr,this._eventsCount=0),this},"removeAllListeners");Ie.prototype.off=Ie.prototype.removeListener;Ie.prototype.addListener=Ie.prototype.on;Ie.prefixed=ke;Ie.EventEmitter=Ie;typeof ys<"u"&&(ys.exports=Ie)});var jc=re((cS,Bc)=>{"use strict";Bc.exports=(t,e)=>(e=e||(()=>{}),t.then(r=>new Promise(n=>{n(e())}).then(()=>r),r=>new Promise(n=>{n(e())}).then(()=>{throw r})))});var zc=re((lS,Bn)=>{"use strict";var Qm=jc(),Fn=class extends Error{static{a(this,"TimeoutError")}constructor(e){super(e),this.name="TimeoutError"}},Hc=a((t,e,r)=>new Promise((n,i)=>{if(typeof e!="number"||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0){n(t);return}let s=setTimeout(()=>{if(typeof r=="function"){try{n(r())}catch(l){i(l)}return}let o=typeof r=="string"?r:`Promise timed out after ${e} milliseconds`,c=r instanceof Error?r:new Fn(o);typeof t.cancel=="function"&&t.cancel(),i(c)},e);Qm(t.then(n,i),()=>{clearTimeout(s)})}),"pTimeout");Bn.exports=Hc;Bn.exports.default=Hc;Bn.exports.TimeoutError=Fn});var Gc=re(_s=>{"use strict";Object.defineProperty(_s,"__esModule",{value:!0});function eh(t,e,r){let n=0,i=t.length;for(;i>0;){let s=i/2|0,o=n+s;r(t[o],e)<=0?(n=++o,i-=s+1):i=s}return n}a(eh,"lowerBound");_s.default=eh});var Vc=re(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});var th=Gc(),bs=class{static{a(this,"PriorityQueue")}constructor(){this._queue=[]}enqueue(e,r){r=Object.assign({priority:0},r);let n={priority:r.priority,run:e};if(this.size&&this._queue[this.size-1].priority>=r.priority){this._queue.push(n);return}let i=th.default(this._queue,n,(s,o)=>o.priority-s.priority);this._queue.splice(i,0,n)}dequeue(){let e=this._queue.shift();return e?.run}filter(e){return this._queue.filter(r=>r.priority===e.priority).map(r=>r.run)}get size(){return this._queue.length}};ws.default=bs});var Hn=re(Ts=>{"use strict";Object.defineProperty(Ts,"__esModule",{value:!0});var rh=Fc(),Wc=zc(),nh=Vc(),jn=a(()=>{},"empty"),ih=new Wc.TimeoutError,Es=class extends rh{static{a(this,"PQueue")}constructor(e){var r,n,i,s;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=jn,this._resolveIdle=jn,e=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:nh.default},e),!(typeof e.intervalCap=="number"&&e.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(n=(r=e.intervalCap)===null||r===void 0?void 0:r.toString())!==null&&n!==void 0?n:""}\` (${typeof e.intervalCap})`);if(e.interval===void 0||!(Number.isFinite(e.interval)&&e.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(s=(i=e.interval)===null||i===void 0?void 0:i.toString())!==null&&s!==void 0?s:""}\` (${typeof e.interval})`);this._carryoverConcurrencyCount=e.carryoverConcurrencyCount,this._isIntervalIgnored=e.intervalCap===1/0||e.interval===0,this._intervalCap=e.intervalCap,this._interval=e.interval,this._queue=new e.queueClass,this._queueClass=e.queueClass,this.concurrency=e.concurrency,this._timeout=e.timeout,this._throwOnTimeout=e.throwOnTimeout===!0,this._isPaused=e.autoStart===!1}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=jn,this._pendingCount===0&&(this._resolveIdle(),this._resolveIdle=jn,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){let e=Date.now();if(this._intervalId===void 0){let r=this._intervalEnd-e;if(r<0)this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0;else return this._timeoutId===void 0&&(this._timeoutId=setTimeout(()=>{this._onResumeInterval()},r)),!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){let e=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){let r=this._queue.dequeue();return r?(this.emit("active"),r(),e&&this._initializeIntervalIfNeeded(),!0):!1}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||this._intervalId!==void 0||(this._intervalId=setInterval(()=>{this._onInterval()},this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){this._intervalCount===0&&this._pendingCount===0&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(e){if(!(typeof e=="number"&&e>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${e}\` (${typeof e})`);this._concurrency=e,this._processQueue()}async add(e,r={}){return new Promise((n,i)=>{let s=a(async()=>{this._pendingCount++,this._intervalCount++;try{let o=this._timeout===void 0&&r.timeout===void 0?e():Wc.default(Promise.resolve(e()),r.timeout===void 0?this._timeout:r.timeout,()=>{(r.throwOnTimeout===void 0?this._throwOnTimeout:r.throwOnTimeout)&&i(ih)});n(await o)}catch(o){i(o)}this._next()},"run");this._queue.enqueue(s,r),this._tryToStartAnother(),this.emit("add")})}async addAll(e,r){return Promise.all(e.map(async n=>this.add(n,r)))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(this._queue.size!==0)return new Promise(e=>{let r=this._resolveEmpty;this._resolveEmpty=()=>{r(),e()}})}async onIdle(){if(!(this._pendingCount===0&&this._queue.size===0))return new Promise(e=>{let r=this._resolveIdle;this._resolveIdle=()=>{r(),e()}})}get size(){return this._queue.size}sizeBy(e){return this._queue.filter(e).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(e){this._timeout=e}};Ts.default=Es});var Xd=re(Ni=>{"use strict";Ni.byteLength=J_;Ni.toByteArray=Y_;Ni.fromByteArray=eb;var mt=[],Ke=[],K_=typeof Uint8Array<"u"?Uint8Array:Array,Za="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";for(dr=0,Zd=Za.length;dr<Zd;++dr)mt[dr]=Za[dr],Ke[Za.charCodeAt(dr)]=dr;var dr,Zd;Ke[45]=62;Ke[95]=63;function Yd(t){var e=t.length;if(e%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var r=t.indexOf("=");r===-1&&(r=e);var n=r===e?0:4-r%4;return[r,n]}a(Yd,"getLens");function J_(t){var e=Yd(t),r=e[0],n=e[1];return(r+n)*3/4-n}a(J_,"byteLength");function Z_(t,e,r){return(e+r)*3/4-r}a(Z_,"_byteLength");function Y_(t){var e,r=Yd(t),n=r[0],i=r[1],s=new K_(Z_(t,n,i)),o=0,c=i>0?n-4:n,l;for(l=0;l<c;l+=4)e=Ke[t.charCodeAt(l)]<<18|Ke[t.charCodeAt(l+1)]<<12|Ke[t.charCodeAt(l+2)]<<6|Ke[t.charCodeAt(l+3)],s[o++]=e>>16&255,s[o++]=e>>8&255,s[o++]=e&255;return i===2&&(e=Ke[t.charCodeAt(l)]<<2|Ke[t.charCodeAt(l+1)]>>4,s[o++]=e&255),i===1&&(e=Ke[t.charCodeAt(l)]<<10|Ke[t.charCodeAt(l+1)]<<4|Ke[t.charCodeAt(l+2)]>>2,s[o++]=e>>8&255,s[o++]=e&255),s}a(Y_,"toByteArray");function X_(t){return mt[t>>18&63]+mt[t>>12&63]+mt[t>>6&63]+mt[t&63]}a(X_,"tripletToBase64");function Q_(t,e,r){for(var n,i=[],s=e;s<r;s+=3)n=(t[s]<<16&16711680)+(t[s+1]<<8&65280)+(t[s+2]&255),i.push(X_(n));return i.join("")}a(Q_,"encodeChunk");function eb(t){for(var e,r=t.length,n=r%3,i=[],s=16383,o=0,c=r-n;o<c;o+=s)i.push(Q_(t,o,o+s>c?c:o+s));return n===1?(e=t[r-1],i.push(mt[e>>2]+mt[e<<4&63]+"==")):n===2&&(e=(t[r-2]<<8)+t[r-1],i.push(mt[e>>10]+mt[e>>4&63]+mt[e<<2&63]+"=")),i.join("")}a(eb,"fromByteArray")});var io=re((t3,Tt)=>{var no=require("fs"),Di=require("path"),Sb=require("os"),xb=require("crypto"),ff=["\u25C8 encrypted .env [www.dotenvx.com]","\u25C8 secrets for agents [www.dotenvx.com]","\u2301 auth for agents [www.vestauth.com]","\u2318 custom filepath { path: '/custom/path/.env' }","\u2318 enable debugging { debug: true }","\u2318 override existing { override: true }","\u2318 suppress logs { quiet: true }","\u2318 multiple files { path: ['.env.local', '.env'] }"];function Ib(){return ff[Math.floor(Math.random()*ff.length)]}a(Ib,"_getRandomTip");function zr(t){return typeof t=="string"?!["false","0","no","off",""].includes(t.toLowerCase()):!!t}a(zr,"parseBoolean");function Ab(){return process.stdout.isTTY}a(Ab,"supportsAnsi");function Cb(t){return Ab()?`\x1B[2m${t}\x1B[0m`:t}a(Cb,"dim");var Rb=/(?:^|^)\s*(?:export\s+)?([\w.-]+)(?:\s*=\s*?|:\s+?)(\s*'(?:\\'|[^'])*'|\s*"(?:\\"|[^"])*"|\s*`(?:\\`|[^`])*`|[^#\r\n]+)?\s*(?:#.*)?(?:$|$)/mg;function Ob(t){let e={},r=t.toString();r=r.replace(/\r\n?/mg,`
2
+ `);let n;for(;(n=Rb.exec(r))!=null;){let i=n[1],s=n[2]||"";s=s.trim();let o=s[0];s=s.replace(/^(['"`])([\s\S]*)\1$/mg,"$2"),o==='"'&&(s=s.replace(/\\n/g,`
3
+ `),s=s.replace(/\\r/g,"\r")),e[i]=s}return e}a(Ob,"parse");function kb(t){t=t||{};let e=gf(t);t.path=e;let r=me.configDotenv(t);if(!r.parsed){let o=new Error(`MISSING_DATA: Cannot parse ${e} for an unknown reason`);throw o.code="MISSING_DATA",o}let n=hf(t).split(","),i=n.length,s;for(let o=0;o<i;o++)try{let c=n[o].trim(),l=Pb(r,c);s=me.decrypt(l.ciphertext,l.key);break}catch(c){if(o+1>=i)throw c}return me.parse(s)}a(kb,"_parseVault");function Mb(t){console.error(`\u26A0 ${t}`)}a(Mb,"_warn");function En(t){console.log(`\u2506 ${t}`)}a(En,"_debug");function mf(t){console.log(`\u25C7 ${t}`)}a(mf,"_log");function hf(t){return t&&t.DOTENV_KEY&&t.DOTENV_KEY.length>0?t.DOTENV_KEY:process.env.DOTENV_KEY&&process.env.DOTENV_KEY.length>0?process.env.DOTENV_KEY:""}a(hf,"_dotenvKey");function Pb(t,e){let r;try{r=new URL(e)}catch(c){if(c.code==="ERR_INVALID_URL"){let l=new Error("INVALID_DOTENV_KEY: Wrong format. Must be in valid uri format like dotenv://:key_1234@dotenvx.com/vault/.env.vault?environment=development");throw l.code="INVALID_DOTENV_KEY",l}throw c}let n=r.password;if(!n){let c=new Error("INVALID_DOTENV_KEY: Missing key part");throw c.code="INVALID_DOTENV_KEY",c}let i=r.searchParams.get("environment");if(!i){let c=new Error("INVALID_DOTENV_KEY: Missing environment part");throw c.code="INVALID_DOTENV_KEY",c}let s=`DOTENV_VAULT_${i.toUpperCase()}`,o=t.parsed[s];if(!o){let c=new Error(`NOT_FOUND_DOTENV_ENVIRONMENT: Cannot locate environment ${s} in your .env.vault file.`);throw c.code="NOT_FOUND_DOTENV_ENVIRONMENT",c}return{ciphertext:o,key:n}}a(Pb,"_instructions");function gf(t){let e=null;if(t&&t.path&&t.path.length>0)if(Array.isArray(t.path))for(let r of t.path)no.existsSync(r)&&(e=r.endsWith(".vault")?r:`${r}.vault`);else e=t.path.endsWith(".vault")?t.path:`${t.path}.vault`;else e=Di.resolve(process.cwd(),".env.vault");return no.existsSync(e)?e:null}a(gf,"_vaultPath");function pf(t){return t[0]==="~"?Di.join(Sb.homedir(),t.slice(1)):t}a(pf,"_resolveHome");function Nb(t){let e=zr(process.env.DOTENV_CONFIG_DEBUG||t&&t.debug),r=zr(process.env.DOTENV_CONFIG_QUIET||t&&t.quiet);(e||!r)&&mf("loading env from encrypted .env.vault");let n=me._parseVault(t),i=process.env;return t&&t.processEnv!=null&&(i=t.processEnv),me.populate(i,n,t),{parsed:n}}a(Nb,"_configVault");function Lb(t){let e=Di.resolve(process.cwd(),".env"),r="utf8",n=process.env;t&&t.processEnv!=null&&(n=t.processEnv);let i=zr(n.DOTENV_CONFIG_DEBUG||t&&t.debug),s=zr(n.DOTENV_CONFIG_QUIET||t&&t.quiet);t&&t.encoding?r=t.encoding:i&&En("no encoding is specified (UTF-8 is used by default)");let o=[e];if(t&&t.path)if(!Array.isArray(t.path))o=[pf(t.path)];else{o=[];for(let d of t.path)o.push(pf(d))}let c,l={};for(let d of o)try{let f=me.parse(no.readFileSync(d,{encoding:r}));me.populate(l,f,t)}catch(f){i&&En(`failed to load ${d} ${f.message}`),c=f}let u=me.populate(n,l,t);if(i=zr(n.DOTENV_CONFIG_DEBUG||i),s=zr(n.DOTENV_CONFIG_QUIET||s),i||!s){let d=Object.keys(u).length,f=[];for(let y of o)try{let h=Di.relative(process.cwd(),y);f.push(h)}catch(h){i&&En(`failed to load ${y} ${h.message}`),c=h}mf(`injected env (${d}) from ${f.join(",")} ${Cb(`// tip: ${Ib()}`)}`)}return c?{parsed:l,error:c}:{parsed:l}}a(Lb,"configDotenv");function Db(t){if(hf(t).length===0)return me.configDotenv(t);let e=gf(t);return e?me._configVault(t):(Mb(`you set DOTENV_KEY but you are missing a .env.vault file at ${e}`),me.configDotenv(t))}a(Db,"config");function Ub(t,e){let r=Buffer.from(e.slice(-64),"hex"),n=Buffer.from(t,"base64"),i=n.subarray(0,12),s=n.subarray(-16);n=n.subarray(12,-16);try{let o=xb.createDecipheriv("aes-256-gcm",r,i);return o.setAuthTag(s),`${o.update(n)}${o.final()}`}catch(o){let c=o instanceof RangeError,l=o.message==="Invalid key length",u=o.message==="Unsupported state or unable to authenticate data";if(c||l){let d=new Error("INVALID_DOTENV_KEY: It must be 64 characters long (or more)");throw d.code="INVALID_DOTENV_KEY",d}else if(u){let d=new Error("DECRYPTION_FAILED: Please check your DOTENV_KEY");throw d.code="DECRYPTION_FAILED",d}else throw o}}a(Ub,"decrypt");function $b(t,e,r={}){let n=!!(r&&r.debug),i=!!(r&&r.override),s={};if(typeof e!="object"){let o=new Error("OBJECT_REQUIRED: Please check the processEnv argument being passed to populate");throw o.code="OBJECT_REQUIRED",o}for(let o of Object.keys(e))Object.prototype.hasOwnProperty.call(t,o)?(i===!0&&(t[o]=e[o],s[o]=e[o]),n&&En(i===!0?`"${o}" is already defined and WAS overwritten`:`"${o}" is already defined and was NOT overwritten`)):(t[o]=e[o],s[o]=e[o]);return s}a($b,"populate");var me={configDotenv:Lb,_configVault:Nb,_parseVault:kb,config:Db,decrypt:Ub,parse:Ob,populate:$b};Tt.exports.configDotenv=me.configDotenv;Tt.exports._configVault=me._configVault;Tt.exports._parseVault=me._parseVault;Tt.exports.config=me.config;Tt.exports.decrypt=me.decrypt;Tt.exports.parse=me.parse;Tt.exports.populate=me.populate;Tt.exports=me});var so=re((O3,Tf)=>{Tf.exports={LOCHDR:30,LOCSIG:67324752,LOCVER:4,LOCFLG:6,LOCHOW:8,LOCTIM:10,LOCCRC:14,LOCSIZ:18,LOCLEN:22,LOCNAM:26,LOCEXT:28,EXTSIG:134695760,EXTHDR:16,EXTCRC:4,EXTSIZ:8,EXTLEN:12,CENHDR:46,CENSIG:33639248,CENVEM:4,CENVER:6,CENFLG:8,CENHOW:10,CENTIM:12,CENCRC:16,CENSIZ:20,CENLEN:24,CENNAM:28,CENEXT:30,CENCOM:32,CENDSK:34,CENATT:36,CENATX:38,CENOFF:42,ENDHDR:22,ENDSIG:101010256,ENDSUB:8,ENDTOT:10,ENDSIZ:12,ENDOFF:16,ENDCOM:20,END64HDR:20,END64SIG:117853008,END64START:4,END64OFF:8,END64NUMDISKS:16,ZIP64SIG:101075792,ZIP64HDR:56,ZIP64LEAD:12,ZIP64SIZE:4,ZIP64VEM:12,ZIP64VER:14,ZIP64DSK:16,ZIP64DSKDIR:20,ZIP64SUB:24,ZIP64TOT:32,ZIP64SIZB:40,ZIP64OFF:48,ZIP64EXTRA:56,STORED:0,SHRUNK:1,REDUCED1:2,REDUCED2:3,REDUCED3:4,REDUCED4:5,IMPLODED:6,DEFLATED:8,ENHANCED_DEFLATED:9,PKWARE:10,BZIP2:12,LZMA:14,IBM_TERSE:18,IBM_LZ77:19,AES_ENCRYPT:99,FLG_ENC:1,FLG_COMP1:2,FLG_COMP2:4,FLG_DESC:8,FLG_ENH:16,FLG_PATCH:32,FLG_STR:64,FLG_EFS:2048,FLG_MSK:4096,FILE:2,BUFFER:1,NONE:0,EF_ID:0,EF_SIZE:2,ID_ZIP64:1,ID_AVINFO:7,ID_PFS:8,ID_OS2:9,ID_NTFS:10,ID_OPENVMS:12,ID_UNIX:13,ID_FORK:14,ID_PATCH:15,ID_X509_PKCS7:20,ID_X509_CERTID_F:21,ID_X509_CERTID_C:22,ID_STRONGENC:23,ID_RECORD_MGT:24,ID_X509_PKCS7_RL:25,ID_IBM1:101,ID_IBM2:102,ID_POSZIP:18064,EF_ZIP64_OR_32:4294967295,EF_ZIP64_OR_16:65535,EF_ZIP64_SUNCOMP:0,EF_ZIP64_SCOMP:8,EF_ZIP64_RHO:16,EF_ZIP64_DSN:24}});var Ui=re(Sf=>{var vf={INVALID_LOC:"Invalid LOC header (bad signature)",INVALID_CEN:"Invalid CEN header (bad signature)",INVALID_END:"Invalid END header (bad signature)",DESCRIPTOR_NOT_EXIST:"No descriptor present",DESCRIPTOR_UNKNOWN:"Unknown descriptor format",DESCRIPTOR_FAULTY:"Descriptor data is malformed",NO_DATA:"Nothing to decompress",BAD_CRC:"CRC32 checksum failed {0}",FILE_IN_THE_WAY:"There is a file in the way: {0}",UNKNOWN_METHOD:"Invalid/unsupported compression method",AVAIL_DATA:"inflate::Available inflate data did not terminate",INVALID_DISTANCE:"inflate::Invalid literal/length or distance code in fixed or dynamic block",TO_MANY_CODES:"inflate::Dynamic block code description: too many length or distance codes",INVALID_REPEAT_LEN:"inflate::Dynamic block code description: repeat more than specified lengths",INVALID_REPEAT_FIRST:"inflate::Dynamic block code description: repeat lengths with no first length",INCOMPLETE_CODES:"inflate::Dynamic block code description: code lengths codes incomplete",INVALID_DYN_DISTANCE:"inflate::Dynamic block code description: invalid distance code lengths",INVALID_CODES_LEN:"inflate::Dynamic block code description: invalid literal/length code lengths",INVALID_STORE_BLOCK:"inflate::Stored block length did not match one's complement",INVALID_BLOCK_TYPE:"inflate::Invalid block type (type == 3)",CANT_EXTRACT_FILE:"Could not extract the file",CANT_OVERRIDE:"Target file already exists",DISK_ENTRY_TOO_LARGE:"Number of disk entries is too large",NO_ZIP:"No zip file was loaded",NO_ENTRY:"Entry doesn't exist",DIRECTORY_CONTENT_ERROR:"A directory cannot have content",FILE_NOT_FOUND:'File not found: "{0}"',NOT_IMPLEMENTED:"Not implemented",INVALID_FILENAME:"Invalid filename",INVALID_FORMAT:"Invalid or unsupported zip format. No END header found",INVALID_PASS_PARAM:"Incompatible password parameter",WRONG_PASSWORD:"Wrong Password",COMMENT_TOO_LONG:"Comment is too long",EXTRA_FIELD_PARSE_ERROR:"Extra field parsing error"};function zb(t){return function(...e){return e.length&&(t=t.replace(/\{(\d)\}/g,(r,n)=>e[n]||"")),new Error("ADM-ZIP: "+t)}}a(zb,"E");for(let t of Object.keys(vf))Sf[t]=zb(vf[t])});var Rf=re((P3,Cf)=>{var Gb=require("fs"),de=require("path"),xf=so(),Vb=Ui(),Wb=typeof process=="object"&&process.platform==="win32",If=a(t=>typeof t=="object"&&t!==null,"is_Obj"),Af=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=3988292384^e>>>1:e>>>=1;return e>>>0});function ie(t){this.sep=de.sep,this.fs=Gb,If(t)&&If(t.fs)&&typeof t.fs.statSync=="function"&&(this.fs=t.fs)}a(ie,"Utils");Cf.exports=ie;ie.prototype.makeDir=function(t){let e=this;function r(n){let i=n.split(e.sep)[0];n.split(e.sep).forEach(function(s){if(!(!s||s.substr(-1,1)===":")){i+=e.sep+s;var o;try{o=e.fs.statSync(i)}catch(c){if(c.message&&c.message.startsWith("ENOENT"))e.fs.mkdirSync(i);else throw c}if(o&&o.isFile())throw Vb.FILE_IN_THE_WAY(`"${i}"`)}})}a(r,"mkdirSync"),r(t)};ie.prototype.writeFileTo=function(t,e,r,n){let i=this;if(i.fs.existsSync(t)){if(!r)return!1;var s=i.fs.statSync(t);if(s.isDirectory())return!1}var o=de.dirname(t);i.fs.existsSync(o)||i.makeDir(o);var c;try{c=i.fs.openSync(t,"w",438)}catch{i.fs.chmodSync(t,438),c=i.fs.openSync(t,"w",438)}if(c)try{i.fs.writeSync(c,e,0,e.length,0)}finally{i.fs.closeSync(c)}return i.fs.chmodSync(t,n||438),!0};ie.prototype.writeFileToAsync=function(t,e,r,n,i){typeof n=="function"&&(i=n,n=void 0);let s=this;s.fs.exists(t,function(o){if(o&&!r)return i(!1);s.fs.stat(t,function(c,l){if(o&&l&&l.isDirectory())return i(!1);var u=de.dirname(t);s.fs.exists(u,function(d){if(!d)try{s.makeDir(u)}catch{return i(!1)}let f=a(function(y){s.fs.write(y,e,0,e.length,0,function(h){s.fs.close(y,function(){if(h)return i(!1);s.fs.chmod(t,n||438,function(){i(!0)})})})},"writeToFd");s.fs.open(t,"w",438,function(y,h){y?s.fs.chmod(t,438,function(){s.fs.open(t,"w",438,function(g,b){if(g||!b)return i(!1);f(b)})}):h?f(h):i(!1)})})})})};ie.prototype.findFiles=function(t){let e=this;function r(n,i,s,o){typeof i=="boolean"&&(s=i,i=void 0);let c=[];return e.fs.readdirSync(n).forEach(function(l){let u=de.join(n,l),d=e.fs.statSync(u);if((!i||i.test(u))&&c.push(de.normalize(u)+(d.isDirectory()?e.sep:"")),d.isDirectory()&&s){let f=e.fs.realpathSync(u);o.has(f)||(o.add(f),c=c.concat(r(u,i,s,o)))}}),c}return a(r,"findSync"),r(t,void 0,!0,new Set([e.fs.realpathSync(t)]))};ie.prototype.findFilesAsync=function(t,e){let r=this,n=[],i=!1,s=a(function(c){i||(i=!0,e(c,c?void 0:n))},"finish"),o=a(function(c,l,u){r.fs.readdir(c,function(d,f){if(d)return u(d);let y=f.length;if(!y)return u();f.forEach(function(h){let g=de.join(c,h);r.fs.stat(g,function(b,w){if(b)return u(b);if(!w){--y||u();return}if(n.push(de.normalize(g)+(w.isDirectory()?r.sep:"")),!w.isDirectory()){--y||u();return}r.fs.realpath(g,function(v,S){if(v)return u(v);if(l.has(S)){--y||u();return}l.add(S),o(g,l,function(p){if(p)return u(p);--y||u()})})})})})},"walk");r.fs.realpath(t,function(c,l){if(c)return s(c);o(t,new Set([l]),s)})};ie.prototype.getAttributes=function(){};ie.prototype.setAttributes=function(){};ie.crc32update=function(t,e){return Af[(t^e)&255]^t>>>8};ie.crc32=function(t){typeof t=="string"&&(t=Buffer.from(t,"utf8"));let e=t.length,r=-1;for(let n=0;n<e;)r=ie.crc32update(r,t[n++]);return~r>>>0};ie.methodToString=function(t){switch(t){case xf.STORED:return"STORED ("+t+")";case xf.DEFLATED:return"DEFLATED ("+t+")";default:return"UNSUPPORTED ("+t+")"}};ie.canonical=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.join(".",e)};ie.zipnamefix=function(t){if(!t)return"";let e=de.posix.normalize("/"+t.split("\\").join("/"));return de.posix.join(".",e)};ie.findLast=function(t,e){if(!Array.isArray(t))throw new TypeError("arr is not array");let r=t.length>>>0;for(let n=r-1;n>=0;n--)if(e(t[n],n,t))return t[n]};ie.sanitize=function(t,e){t=de.resolve(de.normalize(t));for(var r=e.split("/"),n=0,i=r.length;n<i;n++){var s=de.normalize(de.join(t,r.slice(n,i).join(de.sep)));if(s===t||s.startsWith(t+de.sep))return s}return de.normalize(de.join(t,de.basename(e)))};ie.toBuffer=a(function(e,r){return Buffer.isBuffer(e)?e:e instanceof Uint8Array?Buffer.from(e):typeof e=="string"?r(e):Buffer.alloc(0)},"toBuffer");ie.readBigUInt64LE=function(t,e){let r=t.readUInt32LE(e);return t.readUInt32LE(e+4)*4294967296+r};ie.writeBigUInt64LE=function(t,e,r){let n=e>>>0,i=Math.floor(e/4294967296)>>>0;t.writeUInt32LE(n,r),t.writeUInt32LE(i,r+4)};ie.fromDOS2Date=function(t){return new Date((t>>25&127)+1980,Math.max((t>>21&15)-1,0),Math.max(t>>16&31,1),t>>11&31,t>>5&63,(t&31)<<1)};ie.fromDate2DOS=function(t){let e=0,r=0;return t.getFullYear()>1979&&(e=(t.getFullYear()-1980&127)<<9|t.getMonth()+1<<5|t.getDate(),r=t.getHours()<<11|t.getMinutes()<<5|t.getSeconds()>>1),e<<16|r};ie.isWin=Wb;ie.crcTable=Af});var kf=re((L3,Of)=>{var qb=require("path");Of.exports=function(t,{fs:e}){var r=t||"",n=s(),i=null;function s(){return{directory:!1,readonly:!1,hidden:!1,executable:!1,mtime:0,atime:0}}return a(s,"newAttr"),r&&e.existsSync(r)?(i=e.statSync(r),n.directory=i.isDirectory(),n.mtime=i.mtime,n.atime=i.atime,n.executable=(73&i.mode)!==0,n.readonly=(128&i.mode)===0,n.hidden=qb.basename(r)[0]==="."):console.warn("Invalid path: "+r),{get directory(){return n.directory},get readOnly(){return n.readonly},get hidden(){return n.hidden},get mtime(){return n.mtime},get atime(){return n.atime},get executable(){return n.executable},decodeAttributes:a(function(){},"decodeAttributes"),encodeAttributes:a(function(){},"encodeAttributes"),toJSON:a(function(){return{path:r,isDirectory:n.directory,isReadOnly:n.readonly,isHidden:n.hidden,isExecutable:n.executable,mTime:n.mtime,aTime:n.atime}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Pf=re((U3,Mf)=>{Mf.exports={efs:!0,encode:a(t=>Buffer.from(t,"utf8"),"encode"),decode:a(t=>t.toString("utf8"),"decode")}});var Vr=re((F3,Gr)=>{Gr.exports=Rf();Gr.exports.Constants=so();Gr.exports.Errors=Ui();Gr.exports.FileAttr=kf();Gr.exports.decoder=Pf()});var Lf=re((B3,Nf)=>{var Dt=Vr(),M=Dt.Constants;Nf.exports=function(){var t=20,e=10,r=0,n=0,i=0,s=0,o=0,c=0,l=0,u=0,d=0,f=0,y=0,h=0,g=0;t|=Dt.isWin?2560:768,r|=M.FLG_EFS;let b={extraLen:0},w=a(p=>Math.max(0,p)>>>0,"uint32"),v=a(p=>Math.max(0,p)&65535,"uint16"),S=a(p=>Math.max(0,p)&255,"uint8");return i=Dt.fromDate2DOS(new Date),{get made(){return t},set made(p){t=p},get version(){return e},set version(p){e=p},get flags(){return r},set flags(p){r=p},get flags_efs(){return(r&M.FLG_EFS)>0},set flags_efs(p){p?r|=M.FLG_EFS:r&=~M.FLG_EFS},get flags_desc(){return(r&M.FLG_DESC)>0},set flags_desc(p){p?r|=M.FLG_DESC:r&=~M.FLG_DESC},get method(){return n},set method(p){switch(p){case M.STORED:this.version=10;break;case M.DEFLATED:default:this.version=20}n=p},get time(){return Dt.fromDOS2Date(this.timeval)},set time(p){p=new Date(p),this.timeval=Dt.fromDate2DOS(p)},get timeval(){return i},set timeval(p){i=w(p)},get timeHighByte(){return S(i>>>8)},get crc(){return s},set crc(p){s=w(p)},get compressedSize(){return o},set compressedSize(p){o=w(p)},get size(){return c},set size(p){c=w(p)},get fileNameLength(){return l},set fileNameLength(p){l=p},get extraLength(){return u},set extraLength(p){u=p},get extraLocalLength(){return b.extraLen},set extraLocalLength(p){b.extraLen=p},get commentLength(){return d},set commentLength(p){d=p},get diskNumStart(){return f},set diskNumStart(p){f=w(p)},get inAttr(){return y},set inAttr(p){y=w(p)},get attr(){return h},set attr(p){h=w(p)},get fileAttr(){return(h||0)>>16&4095},get offset(){return g},set offset(p){g=w(p)},get encrypted(){return(r&M.FLG_ENC)===M.FLG_ENC},get centralHeaderSize(){return M.CENHDR+l+u+d},get realDataOffset(){return g+M.LOCHDR+b.fnameLen+b.extraLen},get localHeader(){return b},loadLocalHeaderFromBinary:a(function(p){var T=p.slice(g,g+M.LOCHDR);if(T.readUInt32LE(0)!==M.LOCSIG)throw Dt.Errors.INVALID_LOC();b.version=T.readUInt16LE(M.LOCVER),b.flags=T.readUInt16LE(M.LOCFLG),b.flags_desc=(b.flags&M.FLG_DESC)>0,b.method=T.readUInt16LE(M.LOCHOW),b.time=T.readUInt32LE(M.LOCTIM),b.crc=T.readUInt32LE(M.LOCCRC),b.compressedSize=T.readUInt32LE(M.LOCSIZ),b.size=T.readUInt32LE(M.LOCLEN),b.fnameLen=T.readUInt16LE(M.LOCNAM),b.extraLen=T.readUInt16LE(M.LOCEXT);let I=g+M.LOCHDR+b.fnameLen,C=I+b.extraLen;return p.slice(I,C)},"loadLocalHeaderFromBinary"),loadFromBinary:a(function(p){if(p.length!==M.CENHDR||p.readUInt32LE(0)!==M.CENSIG)throw Dt.Errors.INVALID_CEN();t=p.readUInt16LE(M.CENVEM),e=p.readUInt16LE(M.CENVER),r=p.readUInt16LE(M.CENFLG),n=p.readUInt16LE(M.CENHOW),i=p.readUInt32LE(M.CENTIM),s=p.readUInt32LE(M.CENCRC),o=p.readUInt32LE(M.CENSIZ),c=p.readUInt32LE(M.CENLEN),l=p.readUInt16LE(M.CENNAM),u=p.readUInt16LE(M.CENEXT),d=p.readUInt16LE(M.CENCOM),f=p.readUInt16LE(M.CENDSK),y=p.readUInt16LE(M.CENATT),h=p.readUInt32LE(M.CENATX),g=p.readUInt32LE(M.CENOFF)},"loadFromBinary"),localHeaderToBinary:a(function(){var p=Buffer.alloc(M.LOCHDR);return p.writeUInt32LE(M.LOCSIG,0),p.writeUInt16LE(e,M.LOCVER),p.writeUInt16LE(r&~M.FLG_DESC,M.LOCFLG),p.writeUInt16LE(n,M.LOCHOW),p.writeUInt32LE(i,M.LOCTIM),p.writeUInt32LE(s,M.LOCCRC),p.writeUInt32LE(o,M.LOCSIZ),p.writeUInt32LE(c,M.LOCLEN),p.writeUInt16LE(l,M.LOCNAM),p.writeUInt16LE(b.extraLen,M.LOCEXT),p},"localHeaderToBinary"),centralHeaderToBinary:a(function(){var p=Buffer.alloc(M.CENHDR+l+u+d);return p.writeUInt32LE(M.CENSIG,0),p.writeUInt16LE(t,M.CENVEM),p.writeUInt16LE(e,M.CENVER),p.writeUInt16LE(r&~M.FLG_DESC,M.CENFLG),p.writeUInt16LE(n,M.CENHOW),p.writeUInt32LE(i,M.CENTIM),p.writeUInt32LE(s,M.CENCRC),p.writeUInt32LE(o,M.CENSIZ),p.writeUInt32LE(c,M.CENLEN),p.writeUInt16LE(l,M.CENNAM),p.writeUInt16LE(u,M.CENEXT),p.writeUInt16LE(d,M.CENCOM),p.writeUInt16LE(f,M.CENDSK),p.writeUInt16LE(y,M.CENATT),p.writeUInt32LE(h,M.CENATX),p.writeUInt32LE(g,M.CENOFF),p},"centralHeaderToBinary"),toJSON:a(function(){let p=a(function(T){return T+" bytes"},"bytes");return{made:t,version:e,flags:r,method:Dt.methodToString(n),time:this.time,crc:"0x"+s.toString(16).toUpperCase(),compressedSize:p(o),size:p(c),fileNameLength:p(l),extraLength:p(u),commentLength:p(d),diskNumStart:f,inAttr:y,attr:h,offset:g,centralHeaderSize:p(M.CENHDR+l+u+d)}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Uf=re((H3,Df)=>{var Je=Vr(),j=Je.Constants;Df.exports=function(){var t=0,e=0,r=0,n=0,i=0;let s=a(()=>t>j.EF_ZIP64_OR_16||e>j.EF_ZIP64_OR_16||r>j.EF_ZIP64_OR_32||n>j.EF_ZIP64_OR_32,"needsZip64");return{get diskEntries(){return t},set diskEntries(o){t=e=o},get totalEntries(){return e},set totalEntries(o){e=t=o},get size(){return r},set size(o){r=o},get offset(){return n},set offset(o){n=o},get commentLength(){return i},set commentLength(o){i=o},get mainHeaderSize(){return(s()?j.ZIP64HDR+j.END64HDR:0)+j.ENDHDR+i},loadFromBinary:a(function(o){if((o.length!==j.ENDHDR||o.readUInt32LE(0)!==j.ENDSIG)&&(o.length<j.ZIP64HDR||o.readUInt32LE(0)!==j.ZIP64SIG))throw Je.Errors.INVALID_END();o.readUInt32LE(0)===j.ENDSIG?(t=o.readUInt16LE(j.ENDSUB),e=o.readUInt16LE(j.ENDTOT),r=o.readUInt32LE(j.ENDSIZ),n=o.readUInt32LE(j.ENDOFF),i=o.readUInt16LE(j.ENDCOM)):(t=Je.readBigUInt64LE(o,j.ZIP64SUB),e=Je.readBigUInt64LE(o,j.ZIP64TOT),r=Je.readBigUInt64LE(o,j.ZIP64SIZB),n=Je.readBigUInt64LE(o,j.ZIP64OFF),i=0)},"loadFromBinary"),toBinary:a(function(){if(!s()){var o=Buffer.alloc(j.ENDHDR+i);return o.writeUInt32LE(j.ENDSIG,0),o.writeUInt32LE(0,4),o.writeUInt16LE(t,j.ENDSUB),o.writeUInt16LE(e,j.ENDTOT),o.writeUInt32LE(r,j.ENDSIZ),o.writeUInt32LE(n,j.ENDOFF),o.writeUInt16LE(i,j.ENDCOM),o.fill(" ",j.ENDHDR),o}var o=Buffer.alloc(this.mainHeaderSize);let c=0;o.writeUInt32LE(j.ZIP64SIG,c),Je.writeBigUInt64LE(o,j.ZIP64HDR-j.ZIP64LEAD,c+j.ZIP64SIZE),o.writeUInt16LE(45,c+j.ZIP64VEM),o.writeUInt16LE(45,c+j.ZIP64VER),o.writeUInt32LE(0,c+j.ZIP64DSK),o.writeUInt32LE(0,c+j.ZIP64DSKDIR),Je.writeBigUInt64LE(o,t,c+j.ZIP64SUB),Je.writeBigUInt64LE(o,e,c+j.ZIP64TOT),Je.writeBigUInt64LE(o,r,c+j.ZIP64SIZB),Je.writeBigUInt64LE(o,n,c+j.ZIP64OFF);let l=n+r;return c+=j.ZIP64HDR,o.writeUInt32LE(j.END64SIG,c),o.writeUInt32LE(0,c+j.END64START),Je.writeBigUInt64LE(o,l,c+j.END64OFF),o.writeUInt32LE(1,c+j.END64NUMDISKS),c+=j.END64HDR,o.writeUInt32LE(j.ENDSIG,c),o.writeUInt32LE(0,c+4),o.writeUInt16LE(Math.min(t,j.EF_ZIP64_OR_16),c+j.ENDSUB),o.writeUInt16LE(Math.min(e,j.EF_ZIP64_OR_16),c+j.ENDTOT),o.writeUInt32LE(Math.min(r,j.EF_ZIP64_OR_32),c+j.ENDSIZ),o.writeUInt32LE(Math.min(n,j.EF_ZIP64_OR_32),c+j.ENDOFF),o.writeUInt16LE(i,c+j.ENDCOM),o.fill(" ",c+j.ENDHDR),o},"toBinary"),toJSON:a(function(){let o=a(function(c,l){let u=c.toString(16).toUpperCase();for(;u.length<l;)u="0"+u;return"0x"+u},"offset");return{diskEntries:t,totalEntries:e,size:r+" bytes",offset:o(n,4),commentLength:i}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var oo=re(ao=>{ao.EntryHeader=Lf();ao.MainHeader=Uf()});var Ff=re((V3,$f)=>{$f.exports=function(t){var e=require("zlib"),r={chunkSize:(parseInt(t.length/1024)+1)*1024};return{deflate:a(function(){return e.deflateRawSync(t,r)},"deflate"),deflateAsync:a(function(n){var i=e.createDeflateRaw(r),s=[],o=0;i.on("data",function(c){s.push(c),o+=c.length}),i.on("end",function(){var c=Buffer.alloc(o),l=0;c.fill(0);for(var u=0;u<s.length;u++){var d=s[u];d.copy(c,l),l+=d.length}n&&n(c)}),i.end(t)},"deflateAsync")}}});var jf=re((q3,Bf)=>{var Kb=+(process?.versions?.node??"").split(".")[0]||0;Bf.exports=function(t,e){var r=require("zlib");let n=Kb>=15&&e>0?{maxOutputLength:e}:{};return{inflate:a(function(){return r.inflateRawSync(t,n)},"inflate"),inflateAsync:a(function(i){var s=r.createInflateRaw(n),o=[],c=0;s.on("data",function(l){o.push(l),c+=l.length}),s.on("end",function(){var l=Buffer.alloc(c),u=0;l.fill(0);for(var d=0;d<o.length;d++){var f=o[d];f.copy(l,u),u+=f.length}i&&i(l)}),s.end(t)},"inflateAsync")}}});var Wf=re((J3,Vf)=>{"use strict";var{randomFillSync:Hf}=require("crypto"),Jb=Ui(),Zb=new Uint32Array(256).map((t,e)=>{for(let r=0;r<8;r++)(e&1)!==0?e=e>>>1^3988292384:e>>>=1;return e>>>0}),Gf=a((t,e)=>Math.imul(t,e)>>>0,"uMul"),zf=a((t,e)=>Zb[(t^e)&255]^t>>>8,"crc32update"),Tn=a(()=>typeof Hf=="function"?Hf(Buffer.alloc(12)):Tn.node(),"genSalt");Tn.node=()=>{let t=Buffer.alloc(12),e=t.length;for(let r=0;r<e;r++)t[r]=Math.random()*256&255;return t};var $i={genSalt:Tn};function Fi(t){let e=Buffer.isBuffer(t)?t:Buffer.from(t);this.keys=new Uint32Array([305419896,591751049,878082192]);for(let r=0;r<e.length;r++)this.updateKeys(e[r])}a(Fi,"Initkeys");Fi.prototype.updateKeys=function(t){let e=this.keys;return e[0]=zf(e[0],t),e[1]+=e[0]&255,e[1]=Gf(e[1],134775813)+1,e[2]=zf(e[2],e[1]>>>24),t};Fi.prototype.next=function(){let t=(this.keys[2]|2)>>>0;return Gf(t,t^1)>>8&255};function Yb(t){let e=new Fi(t);return function(r){let n=Buffer.alloc(r.length),i=0;for(let s of r)n[i++]=e.updateKeys(s^e.next());return n}}a(Yb,"make_decrypter");function Xb(t){let e=new Fi(t);return function(r,n,i=0){n||(n=Buffer.alloc(r.length));for(let s of r){let o=e.next();n[i++]=s^o,e.updateKeys(s)}return n}}a(Xb,"make_encrypter");function Qb(t,e,r){if(!t||!Buffer.isBuffer(t)||t.length<12)return Buffer.alloc(0);let n=Yb(r),i=n(t.slice(0,12)),s=(e.flags&8)===8?e.timeHighByte:e.crc>>>24;if(i[11]!==s)throw Jb.WRONG_PASSWORD();return n(t.slice(12))}a(Qb,"decrypt");function ew(t){Buffer.isBuffer(t)&&t.length>=12?$i.genSalt=function(){return t.slice(0,12)}:t==="node"?$i.genSalt=Tn.node:$i.genSalt=Tn}a(ew,"_salter");function tw(t,e,r,n=!1){t==null&&(t=Buffer.alloc(0)),Buffer.isBuffer(t)||(t=Buffer.from(t.toString()));let i=Xb(r),s=$i.genSalt();s[11]=e.crc>>>24&255,n&&(s[10]=e.crc>>>16&255);let o=Buffer.alloc(t.length+12);return i(s,o),i(t,o,12)}a(tw,"encrypt");Vf.exports={decrypt:Qb,encrypt:tw,_salter:ew}});var qf=re(Bi=>{Bi.Deflater=Ff();Bi.Inflater=jf();Bi.ZipCrypto=Wf()});var lo=re((X3,Kf)=>{var X=Vr(),rw=oo(),Ve=X.Constants,co=qf();Kf.exports=function(t,e){var r=new rw.EntryHeader,n=Buffer.alloc(0),i=Buffer.alloc(0),s=!1,o=null,c=Buffer.alloc(0),l=Buffer.alloc(0),u=!0;let d=t,f=typeof d.decoder=="object"?d.decoder:X.decoder;u=f.hasOwnProperty("efs")?f.efs:!1;function y(){return!e||!(e instanceof Uint8Array)?Buffer.alloc(0):(l=r.loadLocalHeaderFromBinary(e),e.slice(r.realDataOffset,r.realDataOffset+r.compressedSize))}a(y,"getCompressedDataFromZip");function h(p){let T=r.flags_desc||r.localHeader.flags_desc?r.crc:r.localHeader.crc;return X.crc32(p)===T}a(h,"crc32OK");function g(p,T,I){if(typeof T>"u"&&typeof p=="string"&&(I=p,p=void 0),s)return p&&T&&T(Buffer.alloc(0),X.Errors.DIRECTORY_CONTENT_ERROR()),Buffer.alloc(0);var C=y();if(C.length===0)return p&&T&&T(C),C;if(r.encrypted){if(typeof I!="string"&&!Buffer.isBuffer(I))throw X.Errors.INVALID_PASS_PARAM();C=co.ZipCrypto.decrypt(C,r,I)}var k;switch(r.method){case X.Constants.STORED:if(k=Buffer.alloc(C.length),C.copy(k),h(k))return p&&T&&T(k),k;throw p&&T&&T(k,X.Errors.BAD_CRC()),X.Errors.BAD_CRC();case X.Constants.DEFLATED:var E=new co.Inflater(C,r.size);if(p)E.inflateAsync(function(U){T&&(h(U)?T(U):T(U,X.Errors.BAD_CRC()))});else{if(k=E.inflate(),!h(k))throw X.Errors.BAD_CRC(`"${f.decode(n)}"`);return k}break;default:throw p&&T&&T(Buffer.alloc(0),X.Errors.UNKNOWN_METHOD()),X.Errors.UNKNOWN_METHOD()}}a(g,"decompress");function b(p,T){if((!o||!o.length)&&Buffer.isBuffer(e))return p&&T&&T(y()),y();if(o.length&&!s){var I;switch(r.method){case X.Constants.STORED:return r.compressedSize=r.size,I=Buffer.alloc(o.length),o.copy(I),p&&T&&T(I),I;default:case X.Constants.DEFLATED:var C=new co.Deflater(o);if(p)C.deflateAsync(function(E){I=Buffer.alloc(E.length),r.compressedSize=E.length,E.copy(I),T&&T(I)});else{var k=C.deflate();return r.compressedSize=k.length,k}C=null;break}}else if(p&&T)T(Buffer.alloc(0));else return Buffer.alloc(0)}a(b,"compress");function w(p,T){return X.readBigUInt64LE(p,T)}a(w,"readUInt64LE");function v(p){try{for(var T=0,I,C,k;T+4<p.length;)I=p.readUInt16LE(T),T+=2,C=p.readUInt16LE(T),T+=2,k=p.slice(T,T+C),T+=C,Ve.ID_ZIP64===I&&S(k)}catch{throw X.Errors.EXTRA_FIELD_PARSE_ERROR()}}a(v,"parseExtra");function S(p){var T,I,C,k;p.length>=Ve.EF_ZIP64_SCOMP&&(T=w(p,Ve.EF_ZIP64_SUNCOMP),r.size===Ve.EF_ZIP64_OR_32&&(r.size=T)),p.length>=Ve.EF_ZIP64_RHO&&(I=w(p,Ve.EF_ZIP64_SCOMP),r.compressedSize===Ve.EF_ZIP64_OR_32&&(r.compressedSize=I)),p.length>=Ve.EF_ZIP64_DSN&&(C=w(p,Ve.EF_ZIP64_RHO),r.offset===Ve.EF_ZIP64_OR_32&&(r.offset=C)),p.length>=Ve.EF_ZIP64_DSN+4&&(k=p.readUInt32LE(Ve.EF_ZIP64_DSN),r.diskNumStart===Ve.EF_ZIP64_OR_16&&(r.diskNumStart=k))}return a(S,"parseZip64ExtendedInformation"),{get entryName(){return f.decode(n)},get rawEntryName(){return n},set entryName(p){n=X.toBuffer(p,f.encode);var T=n[n.length-1];s=T===47||T===92,r.fileNameLength=n.length},get efs(){return typeof u=="function"?u(this.entryName):u},get extra(){return c},set extra(p){c=p,r.extraLength=p.length,v(p)},get comment(){return f.decode(i)},set comment(p){if(i=X.toBuffer(p,f.encode),r.commentLength=i.length,i.length>65535)throw X.Errors.COMMENT_TOO_LONG()},get name(){let p=f.decode(n);return s?p.replace(/[/\\]$/,"").split("/").pop():p.split("/").pop()},get isDirectory(){return s},getCompressedData:a(function(){return b(!1,null)},"getCompressedData"),getCompressedDataAsync:a(function(p){b(!0,p)},"getCompressedDataAsync"),setData:a(function(p){o=X.toBuffer(p,X.decoder.encode),!s&&o.length?(r.size=o.length,r.method=X.Constants.DEFLATED,r.crc=X.crc32(p),r.changed=!0):r.method=X.Constants.STORED},"setData"),getData:a(function(p){return r.changed?o:g(!1,null,p)},"getData"),getDataAsync:a(function(p,T){r.changed?p(o):g(!0,p,T)},"getDataAsync"),set attr(p){r.attr=p},get attr(){return r.attr},set header(p){r.loadFromBinary(p)},get header(){return r},packCentralHeader:a(function(){r.flags_efs=this.efs,r.extraLength=c.length;var p=r.centralHeaderToBinary(),T=X.Constants.CENHDR;return n.copy(p,T),T+=n.length,c.copy(p,T),T+=r.extraLength,i.copy(p,T),p},"packCentralHeader"),packLocalHeader:a(function(){let p=0;r.flags_efs=this.efs,r.extraLocalLength=l.length;let T=r.localHeaderToBinary(),I=Buffer.alloc(T.length+n.length+r.extraLocalLength);return T.copy(I,p),p+=T.length,n.copy(I,p),p+=n.length,l.copy(I,p),p+=l.length,I},"packLocalHeader"),toJSON:a(function(){let p=a(function(T){return"<"+(T&&T.length+" bytes buffer"||"null")+">"},"bytes");return{entryName:this.entryName,name:this.name,comment:this.comment,isDirectory:this.isDirectory,header:r.toJSON(),compressedData:p(e),data:p(o)}},"toJSON"),toString:a(function(){return JSON.stringify(this.toJSON(),null," ")},"toString")}}});var Yf=re((e5,Zf)=>{var Jf=lo(),nw=oo(),Ne=Vr();Zf.exports=function(t,e){var r=[],n=Object.create(null),i=Buffer.alloc(0),s=new nw.MainHeader,o=!1,c=null;let l=new Set,u=e,{noSort:d,decoder:f}=u;t?g(u.readEntries):o=!0;function y(){let w=new Set;for(let v of Object.keys(n)){let S=v.split("/");if(S.pop(),!!S.length)for(let p=0;p<S.length;p++){let T=S.slice(0,p+1).join("/")+"/";w.add(T)}}for(let v of w)if(!(v in n)){let S=new Jf(u);S.entryName=v,S.attr=16,S.temporary=!0,r.push(S),n[S.entryName]=S,l.add(S)}}a(y,"makeTemporaryFolders");function h(){if(o=!0,n=Object.create(null),s.diskEntries>(t.length-s.offset)/Ne.Constants.CENHDR)throw Ne.Errors.DISK_ENTRY_TOO_LARGE();r=new Array(s.diskEntries);for(var w=s.offset,v=0;v<r.length;v++){var S=w,p=new Jf(u,t);p.header=t.slice(S,S+=Ne.Constants.CENHDR),p.entryName=t.slice(S,S+=p.header.fileNameLength),p.header.extraLength&&(p.extra=t.slice(S,S+=p.header.extraLength)),p.header.commentLength&&(p.comment=t.slice(S,S+p.header.commentLength)),w+=p.header.centralHeaderSize,r[v]=p,n[p.entryName]=p}l.clear(),y()}a(h,"readEntries");function g(w){var v=t.length-Ne.Constants.ENDHDR,S=Math.max(0,v-65535),p=S,T=t.length,I=-1,C=0;for(typeof u.trailingSpace=="boolean"&&u.trailingSpace&&(S=0),v;v>=p;v--)if(t[v]===80){if(t.readUInt32LE(v)===Ne.Constants.ENDSIG){I=v,C=v,T=v+Ne.Constants.ENDHDR,p=v-Ne.Constants.END64HDR;continue}if(t.readUInt32LE(v)===Ne.Constants.END64SIG){p=S;continue}if(t.readUInt32LE(v)===Ne.Constants.ZIP64SIG){I=v,T=v+Ne.readBigUInt64LE(t,v+Ne.Constants.ZIP64SIZE)+Ne.Constants.ZIP64LEAD;break}}if(I==-1)throw Ne.Errors.INVALID_FORMAT();s.loadFromBinary(t.slice(I,T)),s.commentLength&&(i=t.slice(C+Ne.Constants.ENDHDR)),w&&h()}a(g,"readMainHeader");function b(){r.length>1&&!d&&(r=r.map(w=>({entry:w,key:w.entryName.toLowerCase()})).sort((w,v)=>w.key.localeCompare(v.key)).map(w=>w.entry))}return a(b,"sortEntries"),{get entries(){return o||h(),r.filter(w=>!l.has(w))},get comment(){return f.decode(i)},set comment(w){i=Ne.toBuffer(w,f.encode),s.commentLength=i.length},getEntryCount:a(function(){return o?r.length:s.diskEntries},"getEntryCount"),forEach:a(function(w){this.entries.forEach(w)},"forEach"),getEntry:a(function(w){return o||h(),n[w]||null},"getEntry"),setEntry:a(function(w){o||h(),r.push(w),n[w.entryName]=w,s.totalEntries=r.length},"setEntry"),deleteFile:a(function(w,v=!0){o||h();let S=n[w];this.getEntryChildren(S,v).map(T=>T.entryName).forEach(this.deleteEntry)},"deleteFile"),deleteEntry:a(function(w){o||h();let v=n[w],S=r.indexOf(v);S>=0&&(r.splice(S,1),delete n[w],s.totalEntries=r.length)},"deleteEntry"),getEntryChildren:a(function(w,v=!0){if(o||h(),typeof w=="object")if(w.isDirectory&&v){let S=[],p=w.entryName;for(let T of r)T.entryName.startsWith(p)&&S.push(T);return S}else return[w];return[]},"getEntryChildren"),getChildCount:a(function(w){if(w&&w.isDirectory){let v=this.getEntryChildren(w);return v.includes(w)?v.length-1:v.length}return 0},"getChildCount"),compressToBuffer:a(function(){o||h(),b();let w=[],v=[],S=0,p=0;s.size=0,s.offset=0;let T=0;for(let k of this.entries){let E=k.getCompressedData();k.header.offset=p;let U=k.packLocalHeader(),D=U.length+E.length;p+=D,w.push(U),w.push(E);let N=k.packCentralHeader();v.push(N),s.size+=N.length,S+=D+N.length,T++}S+=s.mainHeaderSize,s.offset=p,s.totalEntries=T,p=0;let I=Buffer.alloc(S);for(let k of w)k.copy(I,p),p+=k.length;for(let k of v)k.copy(I,p),p+=k.length;let C=s.toBinary();return i&&i.copy(C,C.length-i.length),C.copy(I,p),t=I,o=!1,I},"compressToBuffer"),toAsyncBuffer:a(function(w,v,S,p){try{o||h(),b();let T=[],I=[],C=0,k=0,E=0;s.size=0,s.offset=0;let U=a(function(D){if(D.length>0){let N=D.shift(),W=N.entryName+N.extra.toString();S&&S(W),N.getCompressedDataAsync(function(te){p&&p(W),N.header.offset=k;let Se=N.packLocalHeader(),nt=Se.length+te.length;k+=nt,T.push(Se),T.push(te);let q=N.packCentralHeader();I.push(q),s.size+=q.length,C+=nt+q.length,E++,U(D)})}else{C+=s.mainHeaderSize,s.offset=k,s.totalEntries=E,k=0;let N=Buffer.alloc(C);T.forEach(function(te){te.copy(N,k),k+=te.length}),I.forEach(function(te){te.copy(N,k),k+=te.length});let W=s.toBinary();i&&i.copy(W,W.length-i.length),W.copy(N,k),t=N,o=!1,w(N)}},"compress2Buffer");U(Array.from(this.entries))}catch(T){v(T)}},"toAsyncBuffer")}}});var ep=re((r5,Qf)=>{var oe=Vr(),ae=require("path"),iw=lo(),sw=Yf(),fr=a((...t)=>oe.findLast(t,e=>typeof e=="boolean"),"get_Bool"),Xf=a((...t)=>oe.findLast(t,e=>typeof e=="string"),"get_Str"),aw=a((...t)=>oe.findLast(t,e=>typeof e=="function"),"get_Fun"),ow={noSort:!1,readEntries:!1,method:oe.Constants.NONE,fs:null};Qf.exports=function(t,e){let r=null,n=Object.assign(Object.create(null),ow);t&&typeof t=="object"&&(t instanceof Uint8Array||(Object.assign(n,t),t=n.input?n.input:void 0,n.input&&delete n.input),Buffer.isBuffer(t)&&(r=t,n.method=oe.Constants.BUFFER,t=void 0)),Object.assign(n,e);let i=new oe(n),s=a(g=>{g.filter(b=>b.attr).sort((b,w)=>w.path.length-b.path.length).forEach(b=>i.fs.chmodSync(b.path,b.attr))},"applyDirAttributes");if((typeof n.decoder!="object"||typeof n.decoder.encode!="function"||typeof n.decoder.decode!="function")&&(n.decoder=oe.decoder),t&&typeof t=="string")if(i.fs.existsSync(t))n.method=oe.Constants.FILE,n.filename=t,r=i.fs.readFileSync(t);else throw oe.Errors.INVALID_FILENAME();let o=new sw(r,n),{canonical:c,sanitize:l,zipnamefix:u}=oe;function d(g){if(g&&o){var b;if(typeof g=="string"&&(b=o.getEntry(ae.posix.normalize(g))),typeof g=="object"&&typeof g.entryName<"u"&&typeof g.header<"u"&&(b=o.getEntry(g.entryName)),b)return b}return null}a(d,"getEntry");function f(g){let{join:b,normalize:w,sep:v}=ae.posix;return b(ae.isAbsolute(g)?"/":".",w(v+g.split("\\").join(v)+v))}a(f,"fixPath");function y(g){return g instanceof RegExp?(function(b){return function(w){return b.test(w)}})(g):typeof g!="function"?()=>!0:g}a(y,"filenameFilter");let h=a((g,b)=>{let w=b.slice(-1);return w=w===i.sep?i.sep:"",ae.relative(g,b)+w},"relativePath");return{readFile:a(function(g,b){var w=d(g);return w&&w.getData(b)||null},"readFile"),childCount:a(function(g){let b=d(g);if(b)return o.getChildCount(b)},"childCount"),readFileAsync:a(function(g,b){var w=d(g);w?w.getDataAsync(b):b(null,"getEntry failed for:"+g)},"readFileAsync"),readAsText:a(function(g,b){var w=d(g);if(w){var v=w.getData();if(v&&v.length)return v.toString(b||"utf8")}return""},"readAsText"),readAsTextAsync:a(function(g,b,w){var v=d(g);v?v.getDataAsync(function(S,p){if(p){b(S,p);return}S&&S.length?b(S.toString(w||"utf8")):b("")}):b("")},"readAsTextAsync"),deleteFile:a(function(g,b=!0){var w=d(g);w&&o.deleteFile(w.entryName,b)},"deleteFile"),deleteEntry:a(function(g){var b=d(g);b&&o.deleteEntry(b.entryName)},"deleteEntry"),addZipComment:a(function(g){o.comment=g},"addZipComment"),getZipComment:a(function(){return o.comment||""},"getZipComment"),addZipEntryComment:a(function(g,b){var w=d(g);w&&(w.comment=b)},"addZipEntryComment"),getZipEntryComment:a(function(g){var b=d(g);return b&&b.comment||""},"getZipEntryComment"),updateFile:a(function(g,b){var w=d(g);w&&w.setData(b)},"updateFile"),addLocalFile:a(function(g,b,w,v){if(i.fs.existsSync(g)){b=b?f(b):"";let S=ae.win32.basename(ae.win32.normalize(g));b+=w||S;let p=i.fs.statSync(g),T=p.isFile()?i.fs.readFileSync(g):Buffer.alloc(0);p.isDirectory()&&(b+=i.sep),this.addFile(b,T,v,p)}else throw oe.Errors.FILE_NOT_FOUND(g)},"addLocalFile"),addLocalFileAsync:a(function(g,b){g=typeof g=="object"?g:{localPath:g};let w=ae.resolve(g.localPath),{comment:v}=g,{zipPath:S,zipName:p}=g,T=this;i.fs.stat(w,function(I,C){if(I)return b(I,!1);S=S?f(S):"";let k=ae.win32.basename(ae.win32.normalize(w));if(S+=p||k,C.isFile())i.fs.readFile(w,function(E,U){return E?b(E,!1):(T.addFile(S,U,v,C),setImmediate(b,void 0,!0))});else if(C.isDirectory())return S+=i.sep,T.addFile(S,Buffer.alloc(0),v,C),setImmediate(b,void 0,!0)})},"addLocalFileAsync"),addLocalFolder:a(function(g,b,w){if(w=y(w),b=b?f(b):"",g=ae.normalize(g),i.fs.existsSync(g)){let v=i.findFiles(g),S=this;if(v.length)for(let p of v){let T=ae.join(b,h(g,p));w(T)&&S.addLocalFile(p,ae.dirname(T))}}else throw oe.Errors.FILE_NOT_FOUND(g)},"addLocalFolder"),addLocalFolderAsync:a(function(g,b,w,v){v=y(v),w=w?f(w):"",g=ae.normalize(g);var S=this;i.fs.open(g,"r",function(p){if(p&&p.code==="ENOENT")b(void 0,oe.Errors.FILE_NOT_FOUND(g));else if(p)b(void 0,p);else{var T=i.findFiles(g),I=-1,C=a(function(){if(I+=1,I<T.length){var k=T[I],E=h(g,k).split("\\").join("/");E=E.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),v(E)?i.fs.stat(k,function(U,D){U&&b(void 0,U),D.isFile()?i.fs.readFile(k,function(N,W){N?b(void 0,N):(S.addFile(w+E,W,"",D),C())}):(S.addFile(w+E+"/",Buffer.alloc(0),"",D),C())}):process.nextTick(()=>{C()})}else b(!0,void 0)},"next");C()}})},"addLocalFolderAsync"),addLocalFolderAsync2:a(function(g,b){let w=this;g=typeof g=="object"?g:{localPath:g};let v=ae.resolve(f(g.localPath)),{zipPath:S,filter:p,namefix:T}=g;p instanceof RegExp?p=(function(k){return function(E){return k.test(E)}})(p):typeof p!="function"&&(p=a(function(){return!0},"filter")),S=S?f(S):"",T==="latin1"&&(T=a(k=>k.normalize("NFD").replace(/[\u0300-\u036f]/g,"").replace(/[^\x20-\x7E]/g,""),"namefix")),typeof T!="function"&&(T=a(k=>k,"namefix"));let I=a(k=>ae.join(S,T(h(v,k))),"relPathFix"),C=a(k=>ae.win32.basename(ae.win32.normalize(T(k))),"fileNameFix");i.fs.open(v,"r",function(k){k&&k.code==="ENOENT"?b(void 0,oe.Errors.FILE_NOT_FOUND(v)):k?b(void 0,k):i.findFilesAsync(v,function(E,U){if(E)return b(E);U=U.filter(D=>p(I(D))),U.length||b(void 0,!1),setImmediate(U.reverse().reduce(function(D,N){return function(W,te){if(W||te===!1)return setImmediate(D,W,!1);w.addLocalFileAsync({localPath:N,zipPath:ae.dirname(I(N)),zipName:C(N)},D)}},b))})})},"addLocalFolderAsync2"),addLocalFolderPromise:a(function(g,b){return new Promise((w,v)=>{this.addLocalFolderAsync2(Object.assign({localPath:g},b),(S,p)=>{S&&v(S),p&&w(this)})})},"addLocalFolderPromise"),addFile:a(function(g,b,w,v){g=u(g);let S=d(g),p=S!=null;p||(S=new iw(n),S.entryName=g),S.comment=w||"";let T=typeof v=="object"&&v instanceof i.fs.Stats;T&&(S.header.time=v.mtime);var I=S.isDirectory?16:0;let C=S.isDirectory?16384:32768;return T?C|=4095&v.mode:typeof v=="number"?C|=4095&v:C|=S.isDirectory?493:420,I=(I|C<<16)>>>0,S.attr=I,S.setData(b),p||o.setEntry(S),S},"addFile"),getEntries:a(function(g){return o.password=g,o?o.entries:[]},"getEntries"),getEntry:a(function(g){return d(g)},"getEntry"),getEntryCount:a(function(){return o.getEntryCount()},"getEntryCount"),forEach:a(function(g){return o.forEach(g)},"forEach"),extractEntryTo:a(function(g,b,w,v,S,p){v=fr(!1,v),S=fr(!1,S),w=fr(!0,w),p=Xf(S,p);var T=d(g);if(!T)throw oe.Errors.NO_ENTRY();var I=c(T.entryName),C=l(b,p&&!T.isDirectory?c(p):w?I:ae.basename(I));if(T.isDirectory){var k=o.getEntryChildren(T);return k.forEach(function(D){if(D.isDirectory)return;var N=D.getData();if(!N)throw oe.Errors.CANT_EXTRACT_FILE();var W=c(w?D.entryName:D.entryName.substring(T.entryName.length)),te=l(b,W);let Se=S?D.header.fileAttr:void 0;i.writeFileTo(te,N,v,Se)}),!0}var E=T.getData(o.password);if(!E)throw oe.Errors.CANT_EXTRACT_FILE();if(i.fs.existsSync(C)&&!v)throw oe.Errors.CANT_OVERRIDE();let U=S?g.header.fileAttr:void 0;return i.writeFileTo(C,E,v,U),!0},"extractEntryTo"),test:a(function(g){if(!o)return!1;for(var b of o.entries)try{if(b.isDirectory)continue;var w=b.getData(g);if(!w)return!1}catch{return!1}return!0},"test"),extractAllTo:a(function(g,b,w,v){if(w=fr(!1,w),v=Xf(w,v),b=fr(!1,b),!o)throw oe.Errors.NO_ZIP();let S=[];o.entries.forEach(function(p){var T=l(g,c(p.entryName));if(p.isDirectory){i.makeDir(T),w&&S.push({path:T,attr:p.header.fileAttr});return}var I=p.getData(v);if(!I)throw oe.Errors.CANT_EXTRACT_FILE();let C=w?p.header.fileAttr:void 0;i.writeFileTo(T,I,b,C);try{i.fs.utimesSync(T,p.header.time,p.header.time)}catch{}}),s(S)},"extractAllTo"),extractAllToAsync:a(function(g,b,w,v){if(v=aw(b,w,v),w=fr(!1,w),b=fr(!1,b),!v)return new Promise((E,U)=>{this.extractAllToAsync(g,b,w,function(D){D?U(D):E(this)})});if(!o){v(oe.Errors.NO_ZIP());return}g=ae.resolve(g);let S=a(E=>l(g,ae.normalize(c(E.entryName))),"getPath"),p=a((E,U)=>new Error(E+': "'+U+'"'),"getError"),T=[],I=[];o.entries.forEach(E=>{E.isDirectory?T.push(E):I.push(E)});let C=[];for(let E of T){let U=S(E),D=w?E.header.fileAttr:void 0;try{i.makeDir(U)}catch{v(p("Unable to create folder",U));continue}D&&C.push({path:U,attr:D});try{i.fs.utimesSync(U,E.header.time,E.header.time)}catch{}}let k=a(E=>{if(!E)try{s(C)}catch(U){return v(p("Unable to set folder permissions",U.path||""))}v(E)},"done");I.reverse().reduce(function(E,U){return function(D){if(D)E(D);else{let N=ae.normalize(c(U.entryName)),W=l(g,N);U.getDataAsync(function(te,Se){if(Se)E(Se);else if(!te)E(oe.Errors.CANT_EXTRACT_FILE());else{let nt=w?U.header.fileAttr:void 0;i.writeFileToAsync(W,te,b,nt,function(q){if(!q)return E(p("Unable to write file",W));i.fs.utimes(W,U.header.time,U.header.time,function(){E()})})}})}}},k)()},"extractAllToAsync"),writeZip:a(function(g,b){if(arguments.length===1&&typeof g=="function"&&(b=g,g=""),!g&&n.filename&&(g=n.filename),!!g){var w=o.compressToBuffer();if(w){var v=i.writeFileTo(g,w,!0);typeof b=="function"&&b(v?null:new Error("failed"),"")}}},"writeZip"),writeZipPromise:a(function(g,b){let{overwrite:w,perm:v}=Object.assign({overwrite:!0},b);return new Promise((S,p)=>{!g&&n.filename&&(g=n.filename),g||p("ADM-ZIP: ZIP File Name Missing"),this.toBufferPromise().then(T=>{let I=a(C=>C?S(C):p("ADM-ZIP: Wasn't able to write zip file"),"ret");i.writeFileToAsync(g,T,w,v,I)},p)})},"writeZipPromise"),toBufferPromise:a(function(){return new Promise((g,b)=>{o.toAsyncBuffer(g,b)})},"toBufferPromise"),toBuffer:a(function(g,b,w,v){return typeof g=="function"?(o.toAsyncBuffer(g,b,w,v),null):o.compressToBuffer()},"toBuffer")}}});var x0={};dm(x0,{TestRunMonitor:()=>ns});module.exports=fm(x0);var cs=a(t=>new Promise(e=>setTimeout(e,t)),"awaitSleep");var g3=require("@playwright/test");var $6=require("@playwright/test");var cE=require("@playwright/test");var iE=require("@playwright/test");var zo=Object.defineProperty,V=a((t,e)=>{let r={};for(var n in t)zo(r,n,{get:t[n],enumerable:!0});return e||zo(r,Symbol.toStringTag,{value:"Module"}),r},"__exportAll");function Go(t){let e=Symbol.for(t);return{brand(r,n){let i=n?Symbol.for(`${t}.${n}`):e;class s extends r{static{a(this,"_Branded")}[i]=!0;constructor(...c){super(...c)}static isInstance(c){return typeof c=="object"&&c!==null&&i in c&&c[i]===!0}}return Object.defineProperty(s,"name",{value:r.name}),s},sub(r){return Go(`${t}.${r}`)},isInstance(r){return typeof r=="object"&&r!==null&&e in r&&r[e]===!0}}}a(Go,"createNamespace");var Vo=Go("langchain");var ls=Vo.sub("error"),Wo=class extends ls.brand(Error){static{a(this,"LangChainError")}name="LangChainError";constructor(t){super(t),Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}},mm=class extends ls.brand(Wo,"model-abort"){static{a(this,"ModelAbortError")}name="ModelAbortError";partialOutput;constructor(t,e){super(t),this.partialOutput=e}},_E=class qo extends ls.brand(Wo,"context-overflow"){static{a(this,"ContextOverflowError")}name="ContextOverflowError";cause;constructor(e){super(e??"Input exceeded the model's context window.")}static fromError(e){let r=new qo(e.message);return r.cause=e,r}};var hm=/([A-Z]+)([A-Z][a-z0-9]+)/g,gm=/([a-z0-9])([A-Z])/g,ym=/[-_\s]+/g;function _m(t){return t.replace(hm,"$1_$2").replace(gm,"$1_$2").replace(ym,"_").toLowerCase()}a(_m,"snakeCase");function Ko(t,e){return e?.[t]||_m(t)}a(Ko,"keyToJson");function Jo(t,e,r){let n={};for(let i in t)Object.hasOwn(t,i)&&(n[e(i,r)]=t[i]);return n}a(Jo,"mapKeys");var bm="__lc_escaped__";function wm(t){return"lc"in t||Object.keys(t).length===1&&"__lc_escaped__"in t}a(wm,"needsEscaping");function Em(t){return{[bm]:t}}a(Em,"escapeObject");function Tm(t){return t!==null&&typeof t=="object"&&"lc_serializable"in t&&typeof t.toJSON=="function"}a(Tm,"isSerializableLike");function vm(t){let e;return t!==null&&typeof t=="object"?"lc_id"in t&&Array.isArray(t.lc_id)?e=t.lc_id:e=[t.constructor?.name??"Object"]:e=[typeof t],{lc:1,type:"not_implemented",id:e}}a(vm,"createNotImplemented");function An(t,e=new WeakSet){if(t!==null&&typeof t=="object"&&!Array.isArray(t)){if(e.has(t))return vm(t);if(Tm(t))return t;e.add(t);let r=t;if(wm(r))return e.delete(t),Em(r);let n={};for(let[i,s]of Object.entries(r))n[i]=An(s,e);return e.delete(t),n}return Array.isArray(t)?t.map(r=>An(r,e)):t}a(An,"escapeIfNeeded");function Zo(t){return Array.isArray(t)?[...t]:{...t}}a(Zo,"shallowCopy");function Sm(t,e){let r=Zo(t);for(let[n,i]of Object.entries(e)){let[s,...o]=n.split(".").reverse(),c=r;for(let l of o.reverse()){if(c[l]===void 0)break;c[l]=Zo(c[l]),c=c[l]}c[s]!==void 0&&(c[s]={lc:1,type:"secret",id:[i]})}return r}a(Sm,"replaceSecrets");function us(t){let e=Object.getPrototypeOf(t);return typeof t.lc_name=="function"&&(typeof e.lc_name!="function"||t.lc_name()!==e.lc_name())?t.lc_name():t.name}a(us,"get_lc_unique_name");var Bt=class Yo{static{a(this,"Serializable")}lc_serializable=!1;lc_kwargs;static lc_name(){return this.name}get lc_id(){return[...this.lc_namespace,us(this.constructor)]}get lc_secrets(){}get lc_attributes(){}get lc_aliases(){}get lc_serializable_keys(){}constructor(e,...r){this.lc_serializable_keys!==void 0?this.lc_kwargs=Object.fromEntries(Object.entries(e||{}).filter(([n])=>this.lc_serializable_keys?.includes(n))):this.lc_kwargs=e??{}}toJSON(){if(!this.lc_serializable)return this.toJSONNotImplemented();if(this.lc_kwargs instanceof Yo||typeof this.lc_kwargs!="object"||Array.isArray(this.lc_kwargs))return this.toJSONNotImplemented();let e={},r={},n=Object.keys(this.lc_kwargs).reduce((c,l)=>(c[l]=l in this?this[l]:this.lc_kwargs[l],c),{});for(let c=Object.getPrototypeOf(this);c;c=Object.getPrototypeOf(c))Object.assign(e,Reflect.get(c,"lc_aliases",this)),Object.assign(r,Reflect.get(c,"lc_secrets",this)),Object.assign(n,Reflect.get(c,"lc_attributes",this));Object.keys(r).forEach(c=>{let l=this,u=n,[d,...f]=c.split(".").reverse();for(let y of f.reverse()){if(!(y in l)||l[y]===void 0)return;(!(y in u)||u[y]===void 0)&&(typeof l[y]=="object"&&l[y]!=null?u[y]={}:Array.isArray(l[y])&&(u[y]=[])),l=l[y],u=u[y]}d in l&&l[d]!==void 0&&(u[d]=u[d]||l[d])});let i={},s=new WeakSet;s.add(this);for(let[c,l]of Object.entries(n))i[c]=An(l,s);let o=Jo(Object.keys(r).length?Sm(i,r):i,Ko,e);return{lc:1,type:"constructor",id:this.lc_id,kwargs:o}}toJSONNotImplemented(){return{lc:1,type:"not_implemented",id:this.lc_id}}};function Xr(t){return typeof t=="object"&&t!==null&&"type"in t&&typeof t.type=="string"&&"source_type"in t&&(t.source_type==="url"||t.source_type==="base64"||t.source_type==="text"||t.source_type==="id")}a(Xr,"isDataContentBlock");function Cn(t){return Xr(t)&&t.source_type==="url"&&"url"in t&&typeof t.url=="string"}a(Cn,"isURLContentBlock");function Rn(t){return Xr(t)&&t.source_type==="base64"&&"data"in t&&typeof t.data=="string"}a(Rn,"isBase64ContentBlock");function ds(t){return Xr(t)&&t.source_type==="id"&&"id"in t&&typeof t.id=="string"}a(ds,"isIDContentBlock");function On({dataUrl:t,asTypedArray:e=!1}){let r=t.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/),n;if(r){n=r[1].toLowerCase();let i=e?Uint8Array.from(atob(r[2]),s=>s.charCodeAt(0)):r[2];return{mime_type:n,data:i}}}a(On,"parseBase64DataUrl");function P(t,e){return B(t)&&t.type===e}a(P,"_isContentBlock");function B(t){return typeof t=="object"&&t!==null}a(B,"_isObject");function fe(t){return Array.isArray(t)}a(fe,"_isArray");function A(t){return typeof t=="string"}a(A,"_isString");function ze(t){return typeof t=="number"}a(ze,"_isNumber");function kn(t){return t instanceof Uint8Array}a(kn,"_isBytesArray");function fs(t){try{return JSON.parse(t)}catch{return}}a(fs,"safeParseJson");var Ge=a(t=>t(),"iife");function xm(t){if(t.type==="char_location"&&A(t.document_title)&&ze(t.start_char_index)&&ze(t.end_char_index)&&A(t.cited_text)){let{document_title:e,start_char_index:r,end_char_index:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"char",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="page_location"&&A(t.document_title)&&ze(t.start_page_number)&&ze(t.end_page_number)&&A(t.cited_text)){let{document_title:e,start_page_number:r,end_page_number:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"page",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="content_block_location"&&A(t.document_title)&&ze(t.start_block_index)&&ze(t.end_block_index)&&A(t.cited_text)){let{document_title:e,start_block_index:r,end_block_index:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"block",title:e??void 0,startIndex:r,endIndex:n,citedText:i}}if(t.type==="web_search_result_location"&&A(t.url)&&A(t.title)&&A(t.encrypted_index)&&A(t.cited_text)){let{url:e,title:r,encrypted_index:n,cited_text:i,...s}=t;return{...s,type:"citation",source:"url",url:e,title:r,startIndex:Number(n),endIndex:Number(n),citedText:i}}if(t.type==="search_result_location"&&A(t.source)&&A(t.title)&&ze(t.start_block_index)&&ze(t.end_block_index)&&A(t.cited_text)){let{source:e,title:r,start_block_index:n,end_block_index:i,cited_text:s,...o}=t;return{...o,type:"citation",source:"search",url:e,title:r??void 0,startIndex:n,endIndex:i,citedText:s}}}a(xm,"convertAnthropicAnnotation");function Qo(t){if(P(t,"document")&&B(t.source)&&"type"in t.source){if(t.source.type==="base64"&&A(t.source.media_type)&&A(t.source.data))return{type:"file",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&A(t.source.url))return{type:"file",url:t.source.url};if(t.source.type==="file"&&A(t.source.file_id))return{type:"file",fileId:t.source.file_id};if(t.source.type==="text"&&A(t.source.data))return{type:"file",mimeType:String(t.source.media_type??"text/plain"),data:t.source.data}}else if(P(t,"image")&&B(t.source)&&"type"in t.source){if(t.source.type==="base64"&&A(t.source.media_type)&&A(t.source.data))return{type:"image",mimeType:t.source.media_type,data:t.source.data};if(t.source.type==="url"&&A(t.source.url))return{type:"image",url:t.source.url};if(t.source.type==="file"&&A(t.source.file_id))return{type:"image",fileId:t.source.file_id}}}a(Qo,"convertToV1FromAnthropicContentBlock");function ec(t){function*e(){for(let r of t){let n=Qo(r);n?yield n:yield r}}return a(e,"iterateContent"),Array.from(e())}a(ec,"convertToV1FromAnthropicInput");function Xo(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(P(n,"text")&&A(n.text)){let{text:i,citations:s,...o}=n;if(fe(s)&&s.length){let c=s.reduce((l,u)=>{let d=xm(u);return d?[...l,d]:l},[]);yield{...o,type:"text",text:i,annotations:c};continue}else{yield{...o,type:"text",text:i};continue}}else if(P(n,"thinking")&&A(n.thinking)){let{thinking:i,signature:s,...o}=n;yield{...o,type:"reasoning",reasoning:i,signature:s};continue}else if(P(n,"redacted_thinking")){yield{type:"non_standard",value:n};continue}else if(P(n,"tool_use")&&A(n.name)&&A(n.id)){yield{type:"tool_call",id:n.id,name:n.name,args:n.input};continue}else if(P(n,"input_json_delta")){if(Im(t)&&t.tool_call_chunks?.length){let i=t.tool_call_chunks[0];yield{type:"tool_call_chunk",id:i.id,name:i.name,args:i.args,index:i.index};continue}}else if(P(n,"server_tool_use")&&A(n.name)&&A(n.id)){let{name:i,id:s}=n;if(i==="web_search"){yield{id:s,type:"server_tool_call",name:"web_search",args:{query:Ge(()=>{if(typeof n.input=="string")return n.input;if(B(n.input)&&A(n.input.query))return n.input.query;if(A(n.partial_json)){let o=fs(n.partial_json);if(o?.query)return o.query}return""})}};continue}else if(n.name==="code_execution"){yield{id:s,type:"server_tool_call",name:"code_execution",args:{code:Ge(()=>{if(typeof n.input=="string")return n.input;if(B(n.input)&&A(n.input.code))return n.input.code;if(A(n.partial_json)){let o=fs(n.partial_json);if(o?.code)return o.code}return""})}};continue}}else if(P(n,"web_search_tool_result")&&A(n.tool_use_id)&&fe(n.content)){let{content:i,tool_use_id:s}=n;yield{type:"server_tool_call_result",name:"web_search",toolCallId:s,status:"success",output:{urls:i.reduce((o,c)=>P(c,"web_search_result")?[...o,c.url]:o,[])}};continue}else if(P(n,"code_execution_tool_result")&&A(n.tool_use_id)&&B(n.content)){yield{type:"server_tool_call_result",name:"code_execution",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(P(n,"mcp_tool_use")){yield{id:n.id,type:"server_tool_call",name:"mcp_tool_use",args:n.input};continue}else if(P(n,"mcp_tool_result")&&A(n.tool_use_id)&&B(n.content)){yield{type:"server_tool_call_result",name:"mcp_tool_use",toolCallId:n.tool_use_id,status:"success",output:n.content};continue}else if(P(n,"container_upload")){yield{type:"server_tool_call",name:"container_upload",args:n.input};continue}else if(P(n,"search_result")){yield{id:n.id,type:"non_standard",value:n};continue}else if(P(n,"tool_result")){yield{id:n.id,type:"non_standard",value:n};continue}else{let i=Qo(n);if(i){yield i;continue}}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(Xo,"convertToV1FromAnthropicMessage");var tc={translateContent:Xo,translateContentChunk:Xo};function Im(t){return typeof t?._getType=="function"&&typeof t.concat=="function"&&t._getType()==="ai"}a(Im,"_isAIMessageChunk");function Am(t){return Cn(t)?{type:t.type,mimeType:t.mime_type,url:t.url,metadata:t.metadata}:Rn(t)?{type:t.type,mimeType:t.mime_type??"application/octet-stream",data:t.data,metadata:t.metadata}:ds(t)?{type:t.type,mimeType:t.mime_type,fileId:t.id,metadata:t.metadata}:t}a(Am,"convertToV1FromDataContentBlock");function rc(t){return t.map(Am)}a(rc,"convertToV1FromDataContent");function nc(t){return!!(P(t,"image_url")&&B(t.image_url)||P(t,"input_audio")&&B(t.input_audio)||P(t,"file")&&B(t.file))}a(nc,"isOpenAIDataBlock");function ic(t){if(P(t,"image_url")&&B(t.image_url)&&A(t.image_url.url)){let e=On({dataUrl:t.image_url.url});return e?{type:"image",mimeType:e.mime_type,data:e.data}:{type:"image",url:t.image_url.url}}else{if(P(t,"input_audio")&&B(t.input_audio)&&A(t.input_audio.data)&&A(t.input_audio.format))return{type:"audio",data:t.input_audio.data,mimeType:`audio/${t.input_audio.format}`};if(P(t,"file")&&B(t.file)&&A(t.file.data)){let e=On({dataUrl:t.file.data});if(e)return{type:"file",data:e.data,mimeType:e.mime_type};if(A(t.file.file_id))return{type:"file",fileId:t.file.file_id}}}return t}a(ic,"convertToV1FromOpenAIDataBlock");function Cm(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Mn(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}a(Cm,"convertToV1FromChatCompletions");function Rm(t){let e=[];typeof t.content=="string"?t.content.length>0&&e.push({type:"text",text:t.content}):e.push(...Mn(t.content));for(let r of t.tool_calls??[])e.push({type:"tool_call",id:r.id,name:r.name,args:r.args});return e}a(Rm,"convertToV1FromChatCompletionsChunk");function Mn(t){let e=[];for(let r of t)nc(r)?e.push(ic(r)):e.push(r);return e}a(Mn,"convertToV1FromChatCompletionsInput");function Om(t){if(t.type==="url_citation"){let{url:e,title:r,start_index:n,end_index:i}=t;return{type:"citation",url:e,title:r,startIndex:n,endIndex:i}}if(t.type==="file_citation"){let{file_id:e,filename:r,index:n}=t;return{type:"citation",title:r,startIndex:n,endIndex:n,fileId:e}}return t}a(Om,"convertResponsesAnnotation");function sc(t){function*e(){B(t.additional_kwargs?.reasoning)&&fe(t.additional_kwargs.reasoning.summary)&&(yield{type:"reasoning",reasoning:t.additional_kwargs.reasoning.summary.reduce((n,i)=>B(i)&&A(i.text)?`${n}${i.text}`:n,"")});let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r)if(P(n,"text")){let{text:i,annotations:s,phase:o,extras:c,...l}=n,u=B(c)?{...c}:{};A(o)&&(u.phase=o);let d=Object.keys(u).length>0?{extras:u}:{};Array.isArray(s)?yield{...l,...d,type:"text",text:String(i),annotations:s.map(Om)}:yield{...l,...d,type:"text",text:String(i)}}for(let n of t.tool_calls??[])yield{type:"tool_call",id:n.id,name:n.name,args:n.args};if(B(t.additional_kwargs)&&fe(t.additional_kwargs.tool_outputs))for(let n of t.additional_kwargs.tool_outputs){if(P(n,"web_search_call")){let i={};if(B(n.action)&&A(n.action.query)&&(i.query=n.action.query),yield{id:n.id,type:"server_tool_call",name:"web_search",args:i},n.status==="completed"||n.status==="failed"){let s={};B(n.action)&&(s.action=n.action),yield{type:"server_tool_call_result",toolCallId:A(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:s}}continue}else if(P(n,"file_search_call")){yield{id:n.id,type:"server_tool_call",name:"file_search",args:{queries:fe(n.queries)?n.queries:[]}},(n.status==="completed"||n.status==="failed")&&(yield{type:"server_tool_call_result",toolCallId:A(n.id)?n.id:"",status:n.status==="completed"?"success":"error",output:fe(n.results)?{results:n.results}:{}});continue}else if(P(n,"computer_call")){yield{type:"non_standard",value:n};continue}else if(P(n,"code_interpreter_call")){if(A(n.code)&&(yield{id:n.id,type:"server_tool_call",name:"code_interpreter",args:{code:n.code}}),fe(n.outputs)){let i=Ge(()=>{if(n.status!=="in_progress"){if(n.status==="completed")return 0;if(n.status==="incomplete")return 127;if(n.status!=="interpreting"&&n.status==="failed")return 1}});for(let s of n.outputs)if(P(s,"logs")){yield{type:"server_tool_call_result",toolCallId:n.id??"",status:"success",output:{type:"code_interpreter_output",returnCode:i??0,stderr:[0,void 0].includes(i)?void 0:String(s.logs),stdout:[0,void 0].includes(i)?String(s.logs):void 0}};continue}}continue}else if(P(n,"mcp_call")){yield{id:n.id,type:"server_tool_call",name:"mcp_call",args:n.input};continue}else if(P(n,"mcp_list_tools")){yield{id:n.id,type:"server_tool_call",name:"mcp_list_tools",args:n.input};continue}else if(P(n,"mcp_approval_request")){yield{type:"non_standard",value:n};continue}else if(P(n,"tool_search_call")){let i={};B(n.arguments)&&Object.assign(i,n.arguments);let s={};A(n.execution)&&(s.execution=n.execution),A(n.status)&&(s.status=n.status),A(n.call_id)&&(s.call_id=n.call_id),yield{id:A(n.id)?n.id:"",type:"server_tool_call",name:"tool_search",args:i,...Object.keys(s).length>0?{extras:s}:{}};continue}else if(P(n,"tool_search_output")){let i={name:"tool_search"};A(n.execution)&&(i.execution=n.execution),yield{type:"server_tool_call_result",toolCallId:A(n.id)?n.id:"",status:n.status==="completed"?"success":n.status==="failed"?"error":"success",output:{tools:fe(n.tools)?n.tools:[]},extras:i};continue}else if(P(n,"image_generation_call")){A(n.result)&&(yield{type:"image",mimeType:"image/png",data:n.result,id:A(n.id)?n.id:void 0,metadata:{status:A(n.status)?n.status:void 0}}),yield{type:"non_standard",value:n};continue}B(n)&&(yield{type:"non_standard",value:n})}}return a(e,"iterateContent"),Array.from(e())}a(sc,"convertToV1FromResponses");function km(t){function*e(){yield*sc(t);for(let r of t.tool_call_chunks??[])yield{type:"tool_call_chunk",id:r.id,name:r.name,args:r.args}}return a(e,"iterateContent"),Array.from(e())}a(km,"convertToV1FromResponsesChunk");var ac={translateContent:a(t=>typeof t.content=="string"?Cm(t):sc(t),"translateContent"),translateContentChunk:a(t=>typeof t.content=="string"?Rm(t):km(t),"translateContentChunk")};function ps(t){return typeof t=="object"&&t!==null&&"type"in t&&"content"in t&&(typeof t.content=="string"||Array.isArray(t.content))}a(ps,"isMessage");function oc(t,e="pretty"){return e==="pretty"?Mm(t):JSON.stringify(t)}a(oc,"convertToFormattedString");function Mm(t){let e=[],r=` ${t.type.charAt(0).toUpperCase()+t.type.slice(1)} Message `,n=Math.floor((80-r.length)/2),i="=".repeat(n),s=r.length%2===0?i:`${i}=`;if(e.push(`${i}${r}${s}`),t.type==="ai"){let o=t;if(o.tool_calls&&o.tool_calls.length>0){e.push("Tool Calls:");for(let c of o.tool_calls){e.push(` ${c.name} (${c.id})`),e.push(` Call ID: ${c.id}`),e.push(" Args:");for(let[l,u]of Object.entries(c.args))e.push(` ${l}: ${typeof u=="object"?JSON.stringify(u):u}`)}}}if(t.type==="tool"){let o=t;o.name&&e.push(`Name: ${o.name}`)}return typeof t.content=="string"&&t.content.trim()&&(e.length>1&&e.push(""),e.push(t.content)),e.join(`
4
+ `)}a(Mm,"convertToPrettyString");var ms=Symbol.for("langchain.message");function Pm(t,e){function r(n,i){if(typeof n!="object"||n===null||n===void 0)return n;if(i>=e)return Array.isArray(n)?"[Array]":"[Object]";if(Array.isArray(n))return n.map(o=>r(o,i+1));let s={};for(let o of Object.keys(n))s[o]=r(n[o],i+1);return s}return a(r,"helper"),JSON.stringify(r(t,0),null,2)}a(Pm,"stringifyWithDepthLimit");var ht=class extends Bt{static{a(this,"BaseMessage")}lc_namespace=["langchain_core","messages"];lc_serializable=!0;get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}[ms]=!0;id;name;content;additional_kwargs;response_metadata;_getType(){return this.type}getType(){return this._getType()}constructor(t){let e=typeof t=="string"||Array.isArray(t)?{content:t}:t;e.additional_kwargs||(e.additional_kwargs={}),e.response_metadata||(e.response_metadata={}),super(e),this.name=e.name,e.content===void 0&&e.contentBlocks!==void 0?(this.content=e.contentBlocks,this.response_metadata={output_version:"v1",...e.response_metadata}):e.content!==void 0?(this.content=e.content??[],this.response_metadata=e.response_metadata):(this.content=[],this.response_metadata=e.response_metadata),this.additional_kwargs=e.additional_kwargs,this.id=e.id}get text(){return typeof this.content=="string"?this.content:Array.isArray(this.content)?this.content.map(t=>typeof t=="string"?t:t.type==="text"?t.text:"").join(""):""}get contentBlocks(){let t=typeof this.content=="string"?[{type:"text",text:this.content}]:this.content;return[rc,Mn,ec].reduce((e,r)=>r(e),t)}toDict(){return{type:this.getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}static isInstance(t){return typeof t=="object"&&t!==null&&ms in t&&t[ms]===!0&&ps(t)}_updateId(t){this.id=t,this.lc_kwargs.id=t}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](t){if(t===null)return this;let e=Pm(this._printableFields,Math.max(4,t));return`${this.constructor.lc_name()} ${e}`}toFormattedString(t="pretty"){return oc(this,t)}};function hs(t){let e=[],r=[];for(let n of t)if(n.function){let i=n.function.name;try{let s=JSON.parse(n.function.arguments);e.push({name:i||"",args:s||{},id:n.id})}catch{r.push({name:i,args:n.function.arguments,id:n.id,error:"Malformed args."})}}else continue;return[e,r]}a(hs,"defaultToolCallParser");function gs(t){switch(t){case"csv":return"text/csv";case"doc":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"docx":return"application/vnd.openxmlformats-officedocument.wordprocessingml.document";case"html":return"text/html";case"md":return"text/markdown";case"pdf":return"application/pdf";case"txt":return"text/plain";case"xls":return"application/vnd.ms-excel";case"xlsx":return"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";case"gif":return"image/gif";case"jpeg":return"image/jpeg";case"jpg":return"image/jpeg";case"png":return"image/png";case"webp":return"image/webp";case"flv":return"video/flv";case"mkv":return"video/mkv";case"mov":return"video/mov";case"mp4":return"video/mp4";case"mpeg":return"video/mpeg";case"mpg":return"video/mpg";case"three_gp":return"video/three_gp";case"webm":return"video/webm";case"wmv":return"video/wmv";default:return"application/octet-stream"}}a(gs,"convertFileFormatToMimeType");function Dm(t){if(B(t.document)&&B(t.document.source)){let e=gs(B(t.document)&&A(t.document.format)?t.document.format:"");if(B(t.document.source)){if(B(t.document.source.s3Location)&&A(t.document.source.s3Location.uri))return{type:"file",mimeType:e,fileId:t.document.source.s3Location.uri};if(kn(t.document.source.bytes))return{type:"file",mimeType:e,data:t.document.source.bytes};if(A(t.document.source.text))return{type:"file",mimeType:e,data:Buffer.from(t.document.source.text).toString("base64")};if(fe(t.document.source.content))return{type:"file",mimeType:e,data:t.document.source.content.reduce((r,n)=>B(n)&&A(n.text)?r+n.text:r,"")}}}return{type:"non_standard",value:t}}a(Dm,"convertConverseDocumentBlock");function Um(t){if(P(t,"image")&&B(t.image)){let e=gs(B(t.image)&&A(t.image.format)?t.image.format:"");if(B(t.image.source)){if(B(t.image.source.s3Location)&&A(t.image.source.s3Location.uri))return{type:"image",mimeType:e,fileId:t.image.source.s3Location.uri};if(kn(t.image.source.bytes))return{type:"image",mimeType:e,data:t.image.source.bytes}}}return{type:"non_standard",value:t}}a(Um,"convertConverseImageBlock");function $m(t){if(P(t,"video")&&B(t.video)){let e=gs(B(t.video)&&A(t.video.format)?t.video.format:"");if(B(t.video.source)){if(B(t.video.source.s3Location)&&A(t.video.source.s3Location.uri))return{type:"video",mimeType:e,fileId:t.video.source.s3Location.uri};if(kn(t.video.source.bytes))return{type:"video",mimeType:e,data:t.video.source.bytes}}}return{type:"non_standard",value:t}}a($m,"convertConverseVideoBlock");function cc(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(P(n,"cache_point")){yield{type:"non_standard",value:n};continue}else if(P(n,"citations_content")&&B(n.citationsContent)){yield{type:"text",text:fe(n.citationsContent.content)?n.citationsContent.content.reduce((i,s)=>B(s)&&A(s.text)?i+s.text:i,""):"",annotations:fe(n.citationsContent.citations)?n.citationsContent.citations.reduce((i,s)=>{if(B(s)){let o=fe(s.sourceContent)?s.sourceContent.reduce((l,u)=>B(u)&&A(u.text)?l+u.text:l,""):"",c=Ge(()=>{if(B(s.location)){let l=s.location.documentChar||s.location.documentPage||s.location.documentChunk;if(B(l))return{source:ze(l.documentIndex)?l.documentIndex.toString():void 0,startIndex:ze(l.start)?l.start:void 0,endIndex:ze(l.end)?l.end:void 0}}return{}});i.push({type:"citation",citedText:o,...c})}return i},[]):[]};continue}else if(P(n,"document")&&B(n.document)){yield Dm(n);continue}else if(P(n,"guard_content")){yield{type:"non_standard",value:n};continue}else if(P(n,"image")&&B(n.image)){yield Um(n);continue}else if(P(n,"reasoning_content")&&A(n.reasoningText)){yield{type:"reasoning",reasoning:n.reasoningText};continue}else if(P(n,"text")&&A(n.text)){yield{type:"text",text:n.text};continue}else if(P(n,"tool_result")){yield{type:"non_standard",value:n};continue}else{if(P(n,"tool_call"))continue;if(P(n,"video")&&B(n.video)){yield $m(n);continue}}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(cc,"convertToV1FromChatBedrockConverseMessage");var lc={translateContent:cc,translateContentChunk:cc};function uc(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(A(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&A(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}a(uc,"convertToV1FromDeepSeekMessage");var dc={translateContent:uc,translateContentChunk:uc};function fc(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(P(n,"text")&&A(n.text)){yield{type:"text",text:n.text};continue}else if(P(n,"thinking")&&A(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(P(n,"inlineData")&&B(n.inlineData)&&A(n.inlineData.mimeType)&&A(n.inlineData.data)){yield{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data};continue}else if(P(n,"functionCall")&&B(n.functionCall)&&A(n.functionCall.name)&&B(n.functionCall.args)){yield{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args};continue}else if(P(n,"functionResponse")){yield{type:"non_standard",value:n};continue}else if(P(n,"fileData")&&B(n.fileData)&&A(n.fileData.mimeType)&&A(n.fileData.fileUri)){yield{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri};continue}else if(P(n,"executableCode")){yield{type:"non_standard",value:n};continue}else if(P(n,"codeExecutionResult")){yield{type:"non_standard",value:n};continue}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(fc,"convertToV1FromChatGoogleMessage");var pc={translateContent:fc,translateContentChunk:fc};function mc(t){function*e(){let r=typeof t.content=="string"?[{type:"text",text:t.content}]:t.content;for(let n of r){if(P(n,"reasoning")&&A(n.reasoning)){let i=Ge(()=>{let s=r.indexOf(n);if(fe(t.additional_kwargs?.signatures)&&s>=0)return t.additional_kwargs.signatures.at(s)});A(i)?yield{type:"reasoning",reasoning:n.reasoning,signature:i}:yield{type:"reasoning",reasoning:n.reasoning};continue}else if(P(n,"thinking")&&A(n.thinking)){yield{type:"reasoning",reasoning:n.thinking,...n.signature?{signature:n.signature}:{}};continue}else if(P(n,"text")&&A(n.text)){yield{type:"text",text:n.text};continue}else if(P(n,"image_url")){if(A(n.image_url))if(n.image_url.startsWith("data:")){let i=n.image_url.match(/^data:([^;]+);base64,(.+)$/);i?yield{type:"image",data:i[2],mimeType:i[1]}:yield{type:"image",url:n.image_url}}else yield{type:"image",url:n.image_url};continue}else if(P(n,"media")&&A(n.mimeType)&&A(n.data)){yield{type:"file",mimeType:n.mimeType,data:n.data};continue}yield{type:"non_standard",value:n}}}return a(e,"iterateContent"),Array.from(e())}a(mc,"convertToV1FromChatVertexMessage");var hc={translateContent:mc,translateContentChunk:mc};function gc(t){let e=[],r=t.additional_kwargs?.reasoning;if(A(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string"){let n=t.content,i=n.match(/<think>([\s\S]*?)<\/think>/);if(i){let s=i[1].trim();s.length>0&&e.push({type:"reasoning",reasoning:s}),n=n.replace(/<think>[\s\S]*?<\/think>/,"").trim()}n.length>0&&e.push({type:"text",text:n})}else for(let n of t.content)if(typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&A(n.text)){let i=n.text,s=i.match(/<think>([\s\S]*?)<\/think>/);if(s){let o=s[1].trim();o.length>0&&e.push({type:"reasoning",reasoning:o}),i=i.replace(/<think>[\s\S]*?<\/think>/,"").trim()}i.length>0&&e.push({type:"text",text:i})}for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}a(gc,"convertToV1FromGroqMessage");var yc={translateContent:gc,translateContentChunk:gc};function _c(t){let e=[],r=t.additional_kwargs?.reasoning_content;if(A(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&A(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}a(_c,"convertToV1FromOllamaMessage");var bc={translateContent:_c,translateContentChunk:_c};function wc(t){let e=[],r=t.additional_kwargs?.reasoning_details,n=!1;if(Array.isArray(r)&&r.length>0)for(let i of r){if(i==null||typeof i!="object")continue;let s=i.type;if(s==="reasoning.summary"){let o=i.summary;A(o)&&o.length>0&&(e.push({type:"reasoning",reasoning:o}),n=!0)}else if(s==="reasoning.text"){let o=i.text;A(o)&&o.length>0&&(e.push({type:"reasoning",reasoning:o}),n=!0)}}if(!n){let i=t.additional_kwargs?.reasoning_content;A(i)&&i.length>0&&e.push({type:"reasoning",reasoning:i})}if(typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let i of t.content)typeof i=="object"&&"type"in i&&i.type==="text"&&"text"in i&&A(i.text)&&e.push({type:"text",text:i.text});for(let i of t.tool_calls??[])e.push({type:"tool_call",id:i.id,name:i.name,args:i.args});return e}a(wc,"convertToV1FromOpenRouterMessage");var Ec={translateContent:wc,translateContentChunk:wc};function Tc(t){let e=[];if(B(t.additional_kwargs?.reasoning)){let n=t.additional_kwargs.reasoning;if(fe(n.summary)){let i=n.summary.reduce((s,o)=>B(o)&&A(o.text)?`${s}${o.text}`:s,"");i.length>0&&e.push({type:"reasoning",reasoning:i})}}let r=t.additional_kwargs?.reasoning_content;if(A(r)&&r.length>0&&e.push({type:"reasoning",reasoning:r}),typeof t.content=="string")t.content.length>0&&e.push({type:"text",text:t.content});else for(let n of t.content)typeof n=="object"&&"type"in n&&n.type==="text"&&"text"in n&&A(n.text)&&e.push({type:"text",text:n.text});for(let n of t.tool_calls??[])e.push({type:"tool_call",id:n.id,name:n.name,args:n.args});return e}a(Tc,"convertToV1FromXAIMessage");var vc={translateContent:Tc,translateContentChunk:Tc};function Sc(t){function*e(){let r=Ge(()=>{if(typeof t.content=="string")return t.additional_kwargs.originalTextContentBlock?[{...t.additional_kwargs.originalTextContentBlock,type:"text"}]:[{type:"text",text:t.content}];{let n=t.additional_kwargs?.originalTextContentBlock;if(n?.thoughtSignature&&!t.content.some(i=>"thoughtSignature"in i)){let i=[...t.content];for(let s=i.length-1;s>=0;s--){let o=i[s];if(o.type==="text"&&!o.thought)return o.thoughtSignature=n.thoughtSignature,i}}return t.content}});for(let n of r){let i=Ge(()=>P(n,"text")&&A(n.text)?{type:"text",text:n.text}:P(n,"inlineData")&&B(n.inlineData)&&A(n.inlineData.mimeType)&&A(n.inlineData.data)?{type:"file",mimeType:n.inlineData.mimeType,data:n.inlineData.data}:P(n,"functionCall")&&B(n.functionCall)&&A(n.functionCall.name)&&B(n.functionCall.args)?{type:"tool_call",id:t.id,name:n.functionCall.name,args:n.functionCall.args}:P(n,"functionResponse")?{type:"non_standard",value:n}:P(n,"fileData")&&B(n.fileData)&&A(n.fileData.mimeType)&&A(n.fileData.fileUri)?{type:"file",mimeType:n.fileData.mimeType,fileId:n.fileData.fileUri}:P(n,"executableCode")?{type:"non_standard",value:n}:P(n,"codeExecutionResult")?{type:"non_standard",value:n}:{type:"non_standard",value:n}),s=Ge(()=>"thought"in n&&n.thought?{type:"reasoning",reasoning:i.type==="text"?i.text:"",reasoningContentBlock:i}:i),o={thought:n.thought,thoughtSignature:n.thoughtSignature,partMetadata:n.partMetadata,...s};for(let c in o)o[c]===void 0&&delete o[c];yield o}}return a(e,"iterateContent"),Array.from(e())}a(Sc,"convertToV1FromChatGoogleMessage");var xc={translateContent:Sc,translateContentChunk:Sc};globalThis.lc_block_translators_registry??=new Map([["anthropic",tc],["bedrock-converse",lc],["deepseek",dc],["google",xc],["google-genai",pc],["google-vertexai",hc],["groq",yc],["ollama",bc],["openai",ac],["openrouter",Ec],["xai",vc]]);function Ic(t){return globalThis.lc_block_translators_registry.get(t)}a(Ic,"getTranslator");function Ac(t,e){let r={};return(t?.audio!==void 0||e?.audio!==void 0)&&(r.audio=(t?.audio??0)+(e?.audio??0)),(t?.image!==void 0||e?.image!==void 0)&&(r.image=(t?.image??0)+(e?.image??0)),(t?.video!==void 0||e?.video!==void 0)&&(r.video=(t?.video??0)+(e?.video??0)),(t?.document!==void 0||e?.document!==void 0)&&(r.document=(t?.document??0)+(e?.document??0)),(t?.text!==void 0||e?.text!==void 0)&&(r.text=(t?.text??0)+(e?.text??0)),r}a(Ac,"mergeModalitiesTokenDetails");function Fm(t,e){let r={...Ac(t,e)};return(t?.cache_read!==void 0||e?.cache_read!==void 0)&&(r.cache_read=(t?.cache_read??0)+(e?.cache_read??0)),(t?.cache_creation!==void 0||e?.cache_creation!==void 0)&&(r.cache_creation=(t?.cache_creation??0)+(e?.cache_creation??0)),r}a(Fm,"mergeInputTokenDetails");function Bm(t,e){let r={...Ac(t,e)};return(t?.reasoning!==void 0||e?.reasoning!==void 0)&&(r.reasoning=(t?.reasoning??0)+(e?.reasoning??0)),r}a(Bm,"mergeOutputTokenDetails");function Pn(t,e){return{input_tokens:(t?.input_tokens??0)+(e?.input_tokens??0),output_tokens:(t?.output_tokens??0)+(e?.output_tokens??0),total_tokens:(t?.total_tokens??0)+(e?.total_tokens??0),input_token_details:Fm(t?.input_token_details,e?.input_token_details),output_token_details:Bm(t?.output_token_details,e?.output_token_details)}}a(Pn,"mergeUsageMetadata");var St=class extends ht{static{a(this,"AIMessage")}type="ai";tool_calls=[];invalid_tool_calls=[];usage_metadata;get lc_aliases(){return{...super.lc_aliases,tool_calls:"tool_calls",invalid_tool_calls:"invalid_tool_calls",usage_metadata:"usage_metadata"}}constructor(t){let e;if(typeof t=="string"||Array.isArray(t))e={content:t,tool_calls:[],invalid_tool_calls:[],additional_kwargs:{}};else{e=t;let r=e.additional_kwargs?.tool_calls,n=e.tool_calls;r!=null&&r.length>0&&(n===void 0||n.length===0)&&console.warn(["New LangChain packages are available that more efficiently handle",`tool calling.
5
+
6
+ Please upgrade your packages to versions that set`,"message tool calls. e.g., `pnpm install @langchain/anthropic`,","pnpm install @langchain/openai`, etc."].join(" "));try{if(r!=null&&n===void 0){let[i,s]=hs(r);e.tool_calls=i??[],e.invalid_tool_calls=s??[]}else e.tool_calls=e.tool_calls??[],e.invalid_tool_calls=e.invalid_tool_calls??[]}catch{e.tool_calls=[],e.invalid_tool_calls=[]}if(e.response_metadata!==void 0&&"output_version"in e.response_metadata&&e.response_metadata.output_version==="v1"&&(e.contentBlocks=e.content,e.content=void 0),e.contentBlocks!==void 0){if(e.tool_calls){let s=e.tool_calls.filter(o=>!e.contentBlocks?.some(c=>c.type==="tool_call"&&c.id===o.id&&c.name===o.name));e.contentBlocks.push(...s.map(o=>({type:"tool_call",id:o.id,name:o.name,args:o.args})))}let i=e.contentBlocks.filter(s=>s.type==="tool_call").filter(s=>!e.tool_calls?.some(o=>o.id===s.id&&o.name===s.name));i.length>0&&(e.tool_calls=[...e.tool_calls??[],...i.map(s=>({type:"tool_call",id:s.id,name:s.name,args:s.args}))])}}super(e),typeof e!="string"&&(this.tool_calls=e.tool_calls??this.tool_calls,this.invalid_tool_calls=e.invalid_tool_calls??this.invalid_tool_calls),this.usage_metadata=e.usage_metadata}static lc_name(){return"AIMessage"}get contentBlocks(){if(this.response_metadata&&"output_version"in this.response_metadata&&this.response_metadata.output_version==="v1")return this.content;if(this.response_metadata&&"model_provider"in this.response_metadata&&typeof this.response_metadata.model_provider=="string"){let e=Ic(this.response_metadata.model_provider);if(e)return e.translateContent(this)}let t=super.contentBlocks;if(this.tool_calls){let e=this.tool_calls.filter(r=>!t.some(n=>n.id===r.id&&n.name===r.name));t.push(...e.map(r=>({type:"tool_call",id:r.id,name:r.name,args:r.args})))}return t}get _printableFields(){return{...super._printableFields,tool_calls:this.tool_calls,invalid_tool_calls:this.invalid_tool_calls,usage_metadata:this.usage_metadata}}static isInstance(t){return super.isInstance(t)&&t.type==="ai"}};function qm(t){if(typeof t=="string")return t;switch(t.type){case"text":return t.text??"";case"text-plain":return t.text??"[text-plain file]";case"image":case"image_url":return"[image]";case"audio":case"input_audio":return"[audio]";case"video":return"[video]";case"file":return"[file]";case"reasoning":case"tool_call":case"tool_call_chunk":case"invalid_tool_call":case"server_tool_call":case"server_tool_call_chunk":case"server_tool_call_result":case"non_standard":return"";default:return t.type?`[${t.type}]`:""}}a(qm,"_contentBlockToString");function Dn(t,e="Human",r="AI"){let n=[];for(let i of t){let s;if(i.type==="human")s=e;else if(i.type==="ai")s=r;else if(i.type==="system")s="System";else if(i.type==="tool")s="Tool";else if(i.type==="generic")s=i.role;else throw new Error(`Got unsupported message type: ${i.type}`);let o=i.name?`${i.name}, `:"",c=typeof i.content=="string"?i.content:Array.isArray(i.content)?i.content.map(qm).filter(Boolean).join(""):"",l=`${s}: ${o}${c}`;if(i.type==="ai"){let u=i;u.tool_calls&&u.tool_calls.length>0?l+=JSON.stringify(u.tool_calls):u.additional_kwargs&&"function_call"in u.additional_kwargs&&(l+=JSON.stringify(u.additional_kwargs.function_call))}n.push(l)}return n.join(`
7
+ `)}a(Dn,"getBufferString");var $="0123456789abcdef".split(""),Km=[-2147483648,8388608,32768,128],Ye=[24,16,8,0],Un=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298],ge=[];function it(t,e){e?(ge[0]=ge[16]=ge[1]=ge[2]=ge[3]=ge[4]=ge[5]=ge[6]=ge[7]=ge[8]=ge[9]=ge[10]=ge[11]=ge[12]=ge[13]=ge[14]=ge[15]=0,this.blocks=ge):this.blocks=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],t?(this.h0=3238371032,this.h1=914150663,this.h2=812702999,this.h3=4144912697,this.h4=4290775857,this.h5=1750603025,this.h6=1694076839,this.h7=3204075428):(this.h0=1779033703,this.h1=3144134277,this.h2=1013904242,this.h3=2773480762,this.h4=1359893119,this.h5=2600822924,this.h6=528734635,this.h7=1541459225),this.block=this.start=this.bytes=this.hBytes=0,this.finalized=this.hashed=!1,this.first=!0,this.is224=t}a(it,"Sha256");it.prototype.update=function(t){if(!this.finalized){var e,r=typeof t;if(r!=="string"){if(r==="object"){if(t===null)throw new Error(ERROR);if(ARRAY_BUFFER&&t.constructor===ArrayBuffer)t=new Uint8Array(t);else if(!Array.isArray(t)&&(!ARRAY_BUFFER||!ArrayBuffer.isView(t)))throw new Error(ERROR)}else throw new Error(ERROR);e=!0}for(var n,i=0,s,o=t.length,c=this.blocks;i<o;){if(this.hashed&&(this.hashed=!1,c[0]=this.block,this.block=c[16]=c[1]=c[2]=c[3]=c[4]=c[5]=c[6]=c[7]=c[8]=c[9]=c[10]=c[11]=c[12]=c[13]=c[14]=c[15]=0),e)for(s=this.start;i<o&&s<64;++i)c[s>>>2]|=t[i]<<Ye[s++&3];else for(s=this.start;i<o&&s<64;++i)n=t.charCodeAt(i),n<128?c[s>>>2]|=n<<Ye[s++&3]:n<2048?(c[s>>>2]|=(192|n>>>6)<<Ye[s++&3],c[s>>>2]|=(128|n&63)<<Ye[s++&3]):n<55296||n>=57344?(c[s>>>2]|=(224|n>>>12)<<Ye[s++&3],c[s>>>2]|=(128|n>>>6&63)<<Ye[s++&3],c[s>>>2]|=(128|n&63)<<Ye[s++&3]):(n=65536+((n&1023)<<10|t.charCodeAt(++i)&1023),c[s>>>2]|=(240|n>>>18)<<Ye[s++&3],c[s>>>2]|=(128|n>>>12&63)<<Ye[s++&3],c[s>>>2]|=(128|n>>>6&63)<<Ye[s++&3],c[s>>>2]|=(128|n&63)<<Ye[s++&3]);this.lastByteIndex=s,this.bytes+=s-this.start,s>=64?(this.block=c[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}};it.prototype.finalize=function(){if(!this.finalized){this.finalized=!0;var t=this.blocks,e=this.lastByteIndex;t[16]=this.block,t[e>>>2]|=Km[e&3],this.block=t[16],e>=56&&(this.hashed||this.hash(),t[0]=this.block,t[16]=t[1]=t[2]=t[3]=t[4]=t[5]=t[6]=t[7]=t[8]=t[9]=t[10]=t[11]=t[12]=t[13]=t[14]=t[15]=0),t[14]=this.hBytes<<3|this.bytes>>>29,t[15]=this.bytes<<3,this.hash()}};it.prototype.hash=function(){var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,c=this.h7,l=this.blocks,u,d,f,y,h,g,b,w,v,S,p;for(u=16;u<64;++u)h=l[u-15],d=(h>>>7|h<<25)^(h>>>18|h<<14)^h>>>3,h=l[u-2],f=(h>>>17|h<<15)^(h>>>19|h<<13)^h>>>10,l[u]=l[u-16]+d+l[u-7]+f<<0;for(p=e&r,u=0;u<64;u+=4)this.first?(this.is224?(w=300032,h=l[0]-1413257819,c=h-150054599<<0,n=h+24177077<<0):(w=704751109,h=l[0]-210244248,c=h-1521486534<<0,n=h+143694565<<0),this.first=!1):(d=(t>>>2|t<<30)^(t>>>13|t<<19)^(t>>>22|t<<10),f=(i>>>6|i<<26)^(i>>>11|i<<21)^(i>>>25|i<<7),w=t&e,y=w^t&r^p,b=i&s^~i&o,h=c+f+b+Un[u]+l[u],g=d+y,c=n+h<<0,n=h+g<<0),d=(n>>>2|n<<30)^(n>>>13|n<<19)^(n>>>22|n<<10),f=(c>>>6|c<<26)^(c>>>11|c<<21)^(c>>>25|c<<7),v=n&t,y=v^n&e^w,b=o&c^~o&i,h=s+f+b+Un[u+1]+l[u+1],g=d+y,o=r+h<<0,r=h+g<<0,d=(r>>>2|r<<30)^(r>>>13|r<<19)^(r>>>22|r<<10),f=(o>>>6|o<<26)^(o>>>11|o<<21)^(o>>>25|o<<7),S=r&n,y=S^r&t^v,b=s&o^~s&c,h=i+f+b+Un[u+2]+l[u+2],g=d+y,s=e+h<<0,e=h+g<<0,d=(e>>>2|e<<30)^(e>>>13|e<<19)^(e>>>22|e<<10),f=(s>>>6|s<<26)^(s>>>11|s<<21)^(s>>>25|s<<7),p=e&r,y=p^e&n^S,b=s&o^~s&c,h=i+f+b+Un[u+3]+l[u+3],g=d+y,i=t+h<<0,t=h+g<<0,this.chromeBugWorkAround=!0;this.h0=this.h0+t<<0,this.h1=this.h1+e<<0,this.h2=this.h2+r<<0,this.h3=this.h3+n<<0,this.h4=this.h4+i<<0,this.h5=this.h5+s<<0,this.h6=this.h6+o<<0,this.h7=this.h7+c<<0};it.prototype.hex=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,c=this.h7,l=$[t>>>28&15]+$[t>>>24&15]+$[t>>>20&15]+$[t>>>16&15]+$[t>>>12&15]+$[t>>>8&15]+$[t>>>4&15]+$[t&15]+$[e>>>28&15]+$[e>>>24&15]+$[e>>>20&15]+$[e>>>16&15]+$[e>>>12&15]+$[e>>>8&15]+$[e>>>4&15]+$[e&15]+$[r>>>28&15]+$[r>>>24&15]+$[r>>>20&15]+$[r>>>16&15]+$[r>>>12&15]+$[r>>>8&15]+$[r>>>4&15]+$[r&15]+$[n>>>28&15]+$[n>>>24&15]+$[n>>>20&15]+$[n>>>16&15]+$[n>>>12&15]+$[n>>>8&15]+$[n>>>4&15]+$[n&15]+$[i>>>28&15]+$[i>>>24&15]+$[i>>>20&15]+$[i>>>16&15]+$[i>>>12&15]+$[i>>>8&15]+$[i>>>4&15]+$[i&15]+$[s>>>28&15]+$[s>>>24&15]+$[s>>>20&15]+$[s>>>16&15]+$[s>>>12&15]+$[s>>>8&15]+$[s>>>4&15]+$[s&15]+$[o>>>28&15]+$[o>>>24&15]+$[o>>>20&15]+$[o>>>16&15]+$[o>>>12&15]+$[o>>>8&15]+$[o>>>4&15]+$[o&15];return this.is224||(l+=$[c>>>28&15]+$[c>>>24&15]+$[c>>>20&15]+$[c>>>16&15]+$[c>>>12&15]+$[c>>>8&15]+$[c>>>4&15]+$[c&15]),l};it.prototype.toString=it.prototype.hex;it.prototype.digest=function(){this.finalize();var t=this.h0,e=this.h1,r=this.h2,n=this.h3,i=this.h4,s=this.h5,o=this.h6,c=this.h7,l=[t>>>24&255,t>>>16&255,t>>>8&255,t&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255,r>>>24&255,r>>>16&255,r>>>8&255,r&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255,i>>>24&255,i>>>16&255,i>>>8&255,i&255,s>>>24&255,s>>>16&255,s>>>8&255,s&255,o>>>24&255,o>>>16&255,o>>>8&255,o&255];return this.is224||l.push(c>>>24&255,c>>>16&255,c>>>8&255,c&255),l};it.prototype.array=it.prototype.digest;it.prototype.arrayBuffer=function(){this.finalize();var t=new ArrayBuffer(this.is224?28:32),e=new DataView(t);return e.setUint32(0,this.h0),e.setUint32(4,this.h1),e.setUint32(8,this.h2),e.setUint32(12,this.h3),e.setUint32(16,this.h4),e.setUint32(20,this.h5),e.setUint32(24,this.h6),this.is224||e.setUint32(28,this.h7),t};var oh=He(Hn(),1);var qc=/^(?:[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 en(t){return typeof t=="string"&&qc.test(t)}a(en,"validate");function tn(t){if(!en(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}a(tn,"parse");var we=[];for(let t=0;t<256;++t)we.push((t+256).toString(16).slice(1));function xt(t,e=0){return(we[t[e+0]]+we[t[e+1]]+we[t[e+2]]+we[t[e+3]]+"-"+we[t[e+4]]+we[t[e+5]]+"-"+we[t[e+6]]+we[t[e+7]]+"-"+we[t[e+8]]+we[t[e+9]]+"-"+we[t[e+10]]+we[t[e+11]]+we[t[e+12]]+we[t[e+13]]+we[t[e+14]]+we[t[e+15]]).toLowerCase()}a(xt,"unsafeStringify");var ch=new Uint8Array(16);function rn(){return crypto.getRandomValues(ch)}a(rn,"rng");function lh(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}a(lh,"f");function vs(t,e){return t<<e|t>>>32-e}a(vs,"ROTL");function Kc(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let i=t.length/4+2,s=Math.ceil(i/16),o=new Array(s);for(let c=0;c<s;++c){let l=new Uint32Array(16);for(let u=0;u<16;++u)l[u]=t[c*64+u*4]<<24|t[c*64+u*4+1]<<16|t[c*64+u*4+2]<<8|t[c*64+u*4+3];o[c]=l}o[s-1][14]=(t.length-1)*8/2**32,o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=(t.length-1)*8&4294967295;for(let c=0;c<s;++c){let l=new Uint32Array(80);for(let g=0;g<16;++g)l[g]=o[c][g];for(let g=16;g<80;++g)l[g]=vs(l[g-3]^l[g-8]^l[g-14]^l[g-16],1);let u=r[0],d=r[1],f=r[2],y=r[3],h=r[4];for(let g=0;g<80;++g){let b=Math.floor(g/20),w=vs(u,5)+lh(b,d,f,y)+h+e[b]+l[g]>>>0;h=y,y=f,f=vs(d,30)>>>0,d=u,u=w}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+f>>>0,r[3]=r[3]+y>>>0,r[4]=r[4]+h>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}a(Kc,"sha1");function uh(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}a(uh,"stringToBytes");var Jc="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Zc="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function Yc(t,e,r,n,i,s){let o=typeof r=="string"?uh(r):r,c=typeof n=="string"?tn(n):n;if(typeof n=="string"&&(n=tn(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+o.length);if(l.set(c),l.set(o,c.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,i){if(s??=0,s<0||s+16>i.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[s+u]=l[u];return i}return xt(l)}a(Yc,"v35");function Ss(t,e,r,n){return Yc(80,Kc,t,e,r,n)}a(Ss,"v5");Ss.DNS=Jc;Ss.URL=Zc;var xs={};function Qc(t,e,r){let n;if(t)n=Xc(t.random??t.rng?.()??rn(),t.msecs,t.seq,e,r);else{let i=Date.now(),s=rn();fh(xs,i,s),n=Xc(s,xs.msecs,xs.seq,e,r)}return e??xt(n)}a(Qc,"v7");function fh(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}a(fh,"updateV7State");function Xc(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}a(Xc,"v7Bytes");var st=Qc;var el=Symbol.for("ls:tracing_async_local_storage"),Ht=Symbol.for("lc:context_variables"),tl=a(t=>{globalThis[el]=t},"setGlobalAsyncLocalStorageInstance"),It=a(()=>globalThis[el],"getGlobalAsyncLocalStorageInstance");var ph=a(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),mh=a(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),hh=a(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),As=a(()=>typeof Deno<"u","isDeno"),gh=a(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!As(),"isNode"),yh=a(()=>{let t;return ph()?t="browser":gh()?t="node":mh()?t="webworker":hh()?t="jsdom":As()?t="deno":t="other",t},"getEnv"),Is;function rl(){return Is===void 0&&(Is={library:"langchain-js",runtime:yh()}),Is}a(rl,"getRuntimeEnvironment");function Xe(t){try{return typeof process<"u"?process.env?.[t]:As()?Deno?.env.get(t):void 0}catch{return}}a(Xe,"getEnvironmentVariable");var _h=class{static{a(this,"BaseCallbackHandlerMethodsClass")}};var _r=class extends _h{static{a(this,"BaseCallbackHandler")}lc_serializable=!1;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,us(this.constructor)]}lc_kwargs;ignoreLLM=!1;ignoreChain=!1;ignoreAgent=!1;ignoreRetriever=!1;ignoreCustomEvent=!1;raiseError=!1;awaitHandlers=Xe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false";constructor(t){super(),this.lc_kwargs=t||{},t&&(this.ignoreLLM=t.ignoreLLM??this.ignoreLLM,this.ignoreChain=t.ignoreChain??this.ignoreChain,this.ignoreAgent=t.ignoreAgent??this.ignoreAgent,this.ignoreRetriever=t.ignoreRetriever??this.ignoreRetriever,this.ignoreCustomEvent=t.ignoreCustomEvent??this.ignoreCustomEvent,this.raiseError=t.raiseError??this.raiseError,this.awaitHandlers=this.raiseError||(t._awaitHandler??this.awaitHandlers))}copy(){return new this.constructor(this)}toJSON(){return Bt.prototype.toJSON.call(this)}toJSONNotImplemented(){return Bt.prototype.toJSONNotImplemented.call(this)}static fromMethods(t){class e extends _r{static{a(this,"Handler")}name=st();constructor(){super(),Object.assign(this,t)}}return new e}},nl=a(t=>{let e=t;return e!==void 0&&typeof e.copy=="function"&&typeof e.name=="string"&&typeof e.awaitHandlers=="boolean"},"isBaseCallbackHandler");var il=/^(?:[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 bh(t){return typeof t=="string"&&il.test(t)}a(bh,"validate");var nn=bh;function wh(t){if(!nn(t))throw TypeError("Invalid UUID");let e;return Uint8Array.of((e=parseInt(t.slice(0,8),16))>>>24,e>>>16&255,e>>>8&255,e&255,(e=parseInt(t.slice(9,13),16))>>>8,e&255,(e=parseInt(t.slice(14,18),16))>>>8,e&255,(e=parseInt(t.slice(19,23),16))>>>8,e&255,(e=parseInt(t.slice(24,36),16))/1099511627776&255,e/4294967296&255,e>>>24&255,e>>>16&255,e>>>8&255,e&255)}a(wh,"parse");var zn=wh;var Ee=[];for(let t=0;t<256;++t)Ee.push((t+256).toString(16).slice(1));function br(t,e=0){return(Ee[t[e+0]]+Ee[t[e+1]]+Ee[t[e+2]]+Ee[t[e+3]]+"-"+Ee[t[e+4]]+Ee[t[e+5]]+"-"+Ee[t[e+6]]+Ee[t[e+7]]+"-"+Ee[t[e+8]]+Ee[t[e+9]]+"-"+Ee[t[e+10]]+Ee[t[e+11]]+Ee[t[e+12]]+Ee[t[e+13]]+Ee[t[e+14]]+Ee[t[e+15]]).toLowerCase()}a(br,"unsafeStringify");var Eh=new Uint8Array(16);function wr(){return crypto.getRandomValues(Eh)}a(wr,"rng");function Th(t,e,r){return!e&&!t&&crypto.randomUUID?crypto.randomUUID():vh(t,e,r)}a(Th,"v4");function vh(t,e,r){t=t||{};let n=t.random??t.rng?.()??wr();if(n.length<16)throw new Error("Random bytes length must be >= 16");if(n[6]=n[6]&15|64,n[8]=n[8]&63|128,e){if(r=r||0,r<0||r+16>e.length)throw new RangeError(`UUID byte range ${r}:${r+15} is out of buffer bounds`);for(let i=0;i<16;++i)e[r+i]=n[i];return e}return br(n)}a(vh,"_v4");var zt=Th;function Sh(t,e,r,n){switch(t){case 0:return e&r^~e&n;case 1:return e^r^n;case 2:return e&r^e&n^r&n;case 3:return e^r^n}}a(Sh,"f");function Cs(t,e){return t<<e|t>>>32-e}a(Cs,"ROTL");function xh(t){let e=[1518500249,1859775393,2400959708,3395469782],r=[1732584193,4023233417,2562383102,271733878,3285377520],n=new Uint8Array(t.length+1);n.set(t),n[t.length]=128,t=n;let i=t.length/4+2,s=Math.ceil(i/16),o=new Array(s);for(let c=0;c<s;++c){let l=new Uint32Array(16);for(let u=0;u<16;++u)l[u]=t[c*64+u*4]<<24|t[c*64+u*4+1]<<16|t[c*64+u*4+2]<<8|t[c*64+u*4+3];o[c]=l}o[s-1][14]=(t.length-1)*8/2**32,o[s-1][14]=Math.floor(o[s-1][14]),o[s-1][15]=(t.length-1)*8&4294967295;for(let c=0;c<s;++c){let l=new Uint32Array(80);for(let g=0;g<16;++g)l[g]=o[c][g];for(let g=16;g<80;++g)l[g]=Cs(l[g-3]^l[g-8]^l[g-14]^l[g-16],1);let u=r[0],d=r[1],f=r[2],y=r[3],h=r[4];for(let g=0;g<80;++g){let b=Math.floor(g/20),w=Cs(u,5)+Sh(b,d,f,y)+h+e[b]+l[g]>>>0;h=y,y=f,f=Cs(d,30)>>>0,d=u,u=w}r[0]=r[0]+u>>>0,r[1]=r[1]+d>>>0,r[2]=r[2]+f>>>0,r[3]=r[3]+y>>>0,r[4]=r[4]+h>>>0}return Uint8Array.of(r[0]>>24,r[0]>>16,r[0]>>8,r[0],r[1]>>24,r[1]>>16,r[1]>>8,r[1],r[2]>>24,r[2]>>16,r[2]>>8,r[2],r[3]>>24,r[3]>>16,r[3]>>8,r[3],r[4]>>24,r[4]>>16,r[4]>>8,r[4])}a(xh,"sha1");var sl=xh;function Ih(t){t=unescape(encodeURIComponent(t));let e=new Uint8Array(t.length);for(let r=0;r<t.length;++r)e[r]=t.charCodeAt(r);return e}a(Ih,"stringToBytes");var Rs="6ba7b810-9dad-11d1-80b4-00c04fd430c8",Os="6ba7b811-9dad-11d1-80b4-00c04fd430c8";function ks(t,e,r,n,i,s){let o=typeof r=="string"?Ih(r):r,c=typeof n=="string"?zn(n):n;if(typeof n=="string"&&(n=zn(n)),n?.length!==16)throw TypeError("Namespace must be array-like (16 iterable integer values, 0-255)");let l=new Uint8Array(16+o.length);if(l.set(c),l.set(o,c.length),l=e(l),l[6]=l[6]&15|t,l[8]=l[8]&63|128,i){if(s??=0,s<0||s+16>i.length)throw new RangeError(`UUID byte range ${s}:${s+15} is out of buffer bounds`);for(let u=0;u<16;++u)i[s+u]=l[u];return i}return br(l)}a(ks,"v35");function Ms(t,e,r,n){return ks(80,sl,t,e,r,n)}a(Ms,"v5");Ms.DNS=Rs;Ms.URL=Os;var Ps=Ms;var Ns={};function Ah(t,e,r){let n;if(t)n=al(t.random??t.rng?.()??wr(),t.msecs,t.seq,e,r);else{let i=Date.now(),s=wr();Ch(Ns,i,s),n=al(s,Ns.msecs,Ns.seq,e,r)}return e??br(n)}a(Ah,"v7");function Ch(t,e,r){return t.msecs??=-1/0,t.seq??=0,e>t.msecs?(t.seq=r[6]<<23|r[7]<<16|r[8]<<8|r[9],t.msecs=e):(t.seq=t.seq+1|0,t.seq===0&&t.msecs++),t}a(Ch,"updateV7State");function al(t,e,r,n,i=0){if(t.length<16)throw new Error("Random bytes length must be >= 16");if(!n)n=new Uint8Array(16),i=0;else if(i<0||i+16>n.length)throw new RangeError(`UUID byte range ${i}:${i+15} is out of buffer bounds`);return e??=Date.now(),r??=t[6]*127<<24|t[7]<<16|t[8]<<8|t[9],n[i++]=e/1099511627776&255,n[i++]=e/4294967296&255,n[i++]=e/16777216&255,n[i++]=e/65536&255,n[i++]=e/256&255,n[i++]=e&255,n[i++]=112|r>>>28&15,n[i++]=r>>>20&255,n[i++]=128|r>>>14&63,n[i++]=r>>>6&255,n[i++]=r<<2&255|t[10]&3,n[i++]=t[11],n[i++]=t[12],n[i++]=t[13],n[i++]=t[14],n[i++]=t[15],n}a(al,"v7Bytes");var Er=Ah;var ol="gen_ai.operation.name",cl="gen_ai.system",Ls="gen_ai.request.model",ll="gen_ai.response.model",Ds="gen_ai.usage.input_tokens",Us="gen_ai.usage.output_tokens",$s="gen_ai.usage.total_tokens",ul="gen_ai.request.max_tokens",dl="gen_ai.request.temperature",fl="gen_ai.request.top_p",pl="gen_ai.request.frequency_penalty",ml="gen_ai.request.presence_penalty",hl="gen_ai.response.finish_reasons",gl="gen_ai.prompt",yl="gen_ai.completion",_l="gen_ai.request.extra_query",bl="gen_ai.request.extra_body",wl="gen_ai.serialized.name",El="gen_ai.serialized.signature",Tl="gen_ai.serialized.doc",vl="gen_ai.response.id",Sl="gen_ai.response.service_tier",xl="gen_ai.response.system_fingerprint",Il="gen_ai.usage.input_token_details",Al="gen_ai.usage.output_token_details",Cl="langsmith.trace.session_id",Rl="langsmith.trace.session_name",Ol="langsmith.span.kind",kl="langsmith.trace.name",Ml="langsmith.metadata",Fs="langsmith.span.tags";var Pl="langsmith.request.streaming",Nl="langsmith.request.headers";var Bs="langsmith.usage_metadata";var kh=a((...t)=>fetch(...t),"DEFAULT_FETCH_IMPLEMENTATION"),Mh,Ll=Symbol.for("ls:fetch_implementation");var Dl=a(()=>globalThis[Ll]===void 0?!0:Mh??!1,"_shouldStreamForGlobalFetchImplementation"),Ul=a(t=>async(...e)=>{if(t||Z("DEBUG")==="true"){let[n,i]=e;console.log(`\u2192 ${i?.method||"GET"} ${n}`)}let r=await(globalThis[Ll]??kh)(...e);return(t||Z("DEBUG")==="true")&&console.log(`\u2190 ${r.status} ${r.statusText} ${r.url}`),r},"_getFetchImplementation");var sn=a(()=>Z("PROJECT")??ye("LANGCHAIN_SESSION")??"default","getDefaultProjectName");var $l={};function _e(t,e){let r=e?.code??t;$l[r]||($l[r]=!0,e?.type&&typeof process<"u"&&typeof process.emitWarning=="function"?process.emitWarning(t,{type:e.type,code:e.code}):e?.type&&e?.code?console.warn(`${e.type} [${e.code}]: ${t}`):console.warn(t))}a(_e,"warnOnce");var O=a(t=>BigInt(t),"n"),Hl=O("0x9E3779B1"),zl=O("0x85EBCA77"),Ph=O("0xC2B2AE3D"),At=O("0x9E3779B185EBCA87"),Gt=O("0xC2B2AE3D27D4EB4F"),Gl=O("0x165667B19E3779F9"),Gs=O("0x85EBCA77C2B2AE63"),Nh=O("0x27D4EB2F165667C5"),Lh=O("0x165667919E3779F9"),Dh=O("0x9FB21C651E98DF25");function Uh(t){let e=new Uint8Array(t.length/2);for(let r=0;r<t.length;r+=2)e[r/2]=parseInt(t.substring(r,r+2),16);return e}a(Uh,"hexToBytes");var at=Uh("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"),vr=(O(1)<<O(128))-O(1),z=(O(1)<<O(64))-O(1),qn=(O(1)<<O(32))-O(1),gt=64,Vl=gt/8,$h=8,Gn=4;function Y(t,e=0){return new Uint8Array(t.buffer,t.byteOffset+e,t.length-e)}a(Y,"getView");function Q(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getBigUint64(0,!0)}a(Q,"readBigUInt64LE");function Tr(t,e=0){return new DataView(t.buffer,t.byteOffset+e).getUint32(0,!0)}a(Tr,"readUInt32LE");function js(t,e=0){return t[e]}a(js,"readUInt8");var Fh=a(t=>(t&O(255))<<O(56)|(t&O(65280))<<O(40)|(t&O(16711680))<<O(24)|(t&O(4278190080))<<O(8)|(t&O(0xff00000000))>>O(8)|(t&O(0xff0000000000))>>O(24)|(t&O(0xff000000000000))>>O(40)|(t&O(0xff00000000000000))>>O(56),"bswap64"),Bh=a(t=>(t=(t&O(65535))<<O(16)|(t&O(4294901760))>>O(16),t=(t&O(16711935))<<O(8)|(t&O(4278255360))>>O(8),t),"bswap32"),jh=a((t,e)=>(t&qn)*(e&qn)&z,"XXH_mult32to64"),Sr=a(t=>{if(!t)throw new Error("Assert failed")},"assert");function Hh(t,e){return(t<<e|t>>O(32)-e)&qn}a(Hh,"rotl32");function Wl(t,e,r){for(let n=0;n<Vl;n++){let i=Q(e,n*8),s=i^Q(r,n*8);t[n^1]+=i,t[n]+=jh(s,s>>O(32))}return t}a(Wl,"XXH3_accumulate_512");function Fl(t,e,r,n){for(let i=0;i<n;i++)Wl(t,Y(e,i*gt),Y(r,i*8));return t}a(Fl,"XXH3_accumulate");function zh(t,e){for(let r=0;r<Vl;r++){let n=Q(e,r*8),i=t[r];i=Hs(i,O(47)),i^=n,i*=Hl,t[r]=i&z}return t}a(zh,"XXH3_scrambleAcc");function Vn(t,e){return ql(t[0]^Q(e,0),t[1]^Q(e,$h))}a(Vn,"XXH3_mix2Accs");function Bl(t,e,r){let n=r;return n+=Vn(t.slice(0),Y(e,0*Gn)),n+=Vn(t.slice(2),Y(e,4*Gn)),n+=Vn(t.slice(4),Y(e,8*Gn)),n+=Vn(t.slice(6),Y(e,12*Gn)),ot(n&z)}a(Bl,"XXH3_mergeAccs");function Gh(t,e,r,n,i){let s=Math.floor((r.byteLength-gt)/8),o=gt*s,c=Math.floor((e.byteLength-1)/o);for(let l=0;l<c;l++)t=Fl(t,Y(e,l*o),r,s),t=i(t,Y(r,r.byteLength-gt));{let l=Math.floor((e.byteLength-1-o*c)/gt);t=Fl(t,Y(e,c*o),r,l),t=n(t,Y(e,e.byteLength-gt),Y(r,r.byteLength-gt-7))}return t}a(Gh,"XXH3_hashLong");function Vh(t,e,r){let n=new BigUint64Array([Ph,At,Gt,Gl,Gs,zl,Nh,Hl]);Sr(t.length>128),n=Gh(n,t,e,Wl,zh),Sr(n.length*8==64);{let i=Bl(n,Y(e,11),O(t.byteLength)*At&z);return Bl(n,Y(e,e.byteLength-gt-11),~(O(t.byteLength)*Gt)&z)<<O(64)|i}}a(Vh,"XXH3_hashLong_128b");function ql(t,e){let r=t*e&vr;return r&z^r>>O(64)}a(ql,"XXH3_mul128_fold64");function jl(t,e,r){return ql((Q(t,0)^Q(e,0)+r)&z,(Q(t,8)^Q(e,8)-r)&z)}a(jl,"XXH3_mix16B");function Wn(t,e,r,n,i){let s=t&z,o=t>>O(64)&z;return s+=jl(e,n,i),s^=Q(r,0)+Q(r,8),s&=z,o+=jl(r,Y(n,16),i),o^=Q(e,0)+Q(e,8),o&=z,o<<O(64)|s}a(Wn,"XXH3_mix32B");function ot(t){return t^=t>>O(37),t*=Lh,t&=z,t^=t>>O(32),t}a(ot,"XXH3_avalanche");function Kn(t){return t^=t>>O(33),t*=Gt,t&=z,t^=t>>O(29),t*=Gl,t&=z,t^=t>>O(32),t}a(Kn,"XXH3_avalanche64");function Wh(t,e,r){let n=t.byteLength;Sr(n>0&&n<=3);let i=O(js(t,n-1))|O(n<<8)|O(js(t,0)<<16)|O(js(t,n>>1)<<24),s=(O(Tr(e,0))^O(Tr(e,4)))+r,o=(i^s)&z,c=(O(Tr(e,8))^O(Tr(e,12)))-r,l=(Hh(Bh(i),O(13))^c)&z;return(Kn(l)&z)<<O(64)|Kn(o)}a(Wh,"XXH3_len_1to3_128b");function Hs(t,e){return t^t>>e}a(Hs,"xorshift64");function qh(t,e,r){let n=t.byteLength;Sr(n>=4&&n<=8);{let i=Tr(t,0),s=Tr(t,n-4),o=O(i)|O(s)<<O(32),c=(Q(e,16)^Q(e,24))+r&z,u=(o^c)*(At+(O(n)<<O(2)))&vr;return u+=(u&z)<<O(65),u&=vr,u^=u>>O(67),Hs(Hs(u&z,O(35))*Dh&z,O(28))|ot(u>>O(64))<<O(64)}}a(qh,"XXH3_len_4to8_128b");function Kh(t,e,r){let n=t.byteLength;Sr(n>=9&&n<=16);{let i=(Q(e,32)^Q(e,40))+r&z,s=(Q(e,48)^Q(e,56))-r&z,o=Q(t),c=Q(t,n-8),l=(o^c^i)*At,u=(l&z)+(O(n-1)<<O(54));l=l&(vr^z)|u,c^=s,l+=c+(c&qn)*(zl-O(1))<<O(64),l&=vr,l^=Fh(l>>O(64));let d=(l&z)*Gt;return d+=(l>>O(64))*Gt<<O(64),d&=vr,ot(d&z)|ot(d>>O(64))<<O(64)}}a(Kh,"XXH3_len_9to16_128b");function Jh(t,e){let r=t.byteLength;return Sr(r<=16),r>8?Kh(t,at,e):r>=4?qh(t,at,e):r>0?Wh(t,at,e):Kn(e^Q(at,64)^Q(at,72))|Kn(e^Q(at,80)^Q(at,88))<<O(64)}a(Jh,"XXH3_len_0to16_128b");function zs(t){return~t+O(1)&z}a(zs,"inv64");function Zh(t,e,r){let n=O(t.byteLength)*At&z,i=O(t.byteLength-1)/O(32);for(;i>=0;){let c=Number(i);n=Wn(n,Y(t,16*c),Y(t,t.byteLength-16*(c+1)),Y(e,32*c),r),i--}let s=n+(n>>O(64))&z;s=ot(s);let o=(n&z)*At+(n>>O(64))*Gs+(O(t.byteLength)-r&z)*Gt;return o&=z,o=zs(ot(o)),s|o<<O(64)}a(Zh,"XXH3_len_17to128_128b");function Yh(t,e,r){let n=O(t.byteLength)*At&z;for(let o=32;o<160;o+=32)n=Wn(n,Y(t,o-32),Y(t,o-16),Y(e,o-32),r);n=ot(n&z)|ot(n>>O(64))<<O(64);for(let o=160;o<=t.byteLength;o+=32)n=Wn(n,Y(t,o-32),Y(t,o-16),Y(e,3+o-160),r);n=Wn(n,Y(t,t.byteLength-16),Y(t,t.byteLength-32),Y(e,103),zs(r));let i=n+(n>>O(64))&z;i=ot(i);let s=(n&z)*At+(n>>O(64))*Gs+(O(t.byteLength)-r&z)*Gt;return s&=z,s=zs(ot(s)),i|s<<O(64)}a(Yh,"XXH3_len_129to240_128b");function Kl(t,e=O(0)){let r=t.byteLength;return r<=16?Jh(t,e):r<=128?Zh(t,at,e):r<=240?Yh(t,at,e):Vh(t,at,e)}a(Kl,"XXH3_128");function Jl(t){let e=new Uint8Array(16),r=new DataView(e.buffer),n=t&z,i=t>>O(64);return r.setBigUint64(0,i,!1),r.setBigUint64(8,n,!1),e}a(Jl,"xxh128ToBytes");var Zl=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function H(t,e){if(!Zl.test(t)){let r=e!==void 0?`Invalid UUID for ${e}: ${t}`:`Invalid UUID: ${t}`;throw new Error(r)}return t}a(H,"assertUuid");function Jn(t){let e=typeof t=="string"?Date.parse(t):t;return Er({msecs:e,seq:0})}a(Jn,"uuid7FromTime");function Yl(t){if(!Zl.test(t))return null;let e=t[14];return parseInt(e,16)}a(Yl,"getUuidVersion");function Xh(t){let e=t.replace(/-/g,""),r=new Uint8Array(16);for(let n=0;n<16;n++)r[n]=parseInt(e.slice(n*2,n*2+2),16);return r}a(Xh,"uuidToBytes");function Qh(t){let e=Array.from(t).map(r=>r.toString(16).padStart(2,"0")).join("");return`${e.slice(0,8)}-${e.slice(8,12)}-${e.slice(12,16)}-${e.slice(16,20)}-${e.slice(20)}`}a(Qh,"bytesToUuid");var eg=new TextEncoder;function tg(t){let e=eg.encode(t),r=Kl(e);return Jl(r)}a(tg,"_fastHash128");function xr(t,e){let r=`${t}:${e}`,n=tg(r),i=new Uint8Array(16);if(Yl(t)===7){let o=Xh(t);i.set(o.slice(0,6),0)}else{let o=Date.now();i[0]=o/1099511627776&255,i[1]=o/4294967296&255,i[2]=o/16777216&255,i[3]=o/65536&255,i[4]=o/256&255,i[5]=o&255}return i[6]=112|n[0]&15,i[7]=n[1],i[8]=128|n[2]&63,i.set(n.slice(3,10),9),Qh(i)}a(xr,"nonCryptographicUuid7Deterministic");var Vs=a(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>Z(r)==="true"),"isEnvTracingEnabled");var qs=class{static{a(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Ws=Symbol.for("ls:tracing_async_local_storage"),rg=new qs,Ks=class{static{a(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Ws]??rg}initializeGlobalInstance(e){globalThis[Ws]===void 0&&(globalThis[Ws]=e)}},ng=new Ks;function Js(t=!1){let e=ng.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
8
+
9
+ Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}a(Js,"getCurrentRunTree");var De=He(require("node:fs"),1),Ue=He(require("node:fs/promises"),1),ig=He(require("node:path"),1);var Qe=ig;async function Zn(t){await Ue.mkdir(t,{recursive:!0})}a(Zn,"mkdir");async function Ir(t,e){let r=`${t}.tmp`;await Ue.writeFile(r,e,{encoding:"utf8",mode:384}),await Ue.rename(r,t)}a(Ir,"writeFileAtomic");async function Xl(t){return Ue.readdir(t)}a(Xl,"readdir");async function Ql(t){return Ue.stat(t)}a(Ql,"stat");function Ar(t){return De.existsSync(t)}a(Ar,"existsSync");function eu(t){De.mkdirSync(t,{recursive:!0})}a(eu,"mkdirSync");function tu(t,e){De.writeFileSync(t,e)}a(tu,"writeFileSync");function ru(t,e){De.renameSync(t,e)}a(ru,"renameSync");function nu(t){De.unlinkSync(t)}a(nu,"unlinkSync");function Vt(t){return De.readFileSync(t,"utf-8")}a(Vt,"readFileSync");async function iu(t){await Ue.mkdir(t,{mode:448})}a(iu,"mkdirExclusive");function su(t){try{return De.statSync(t).mtimeMs}catch{return}}a(su,"statMtimeMs");async function Yn(t){await Ue.rm(t,{recursive:!0,force:!0})}a(Yn,"rmRecursive");function sg(t,e){return e===null?!1:Date.now()-t.createdAt>e*1e3}a(sg,"isStale");var Xn=class{static{a(this,"PromptCache")}constructor(e={}){Object.defineProperty(this,"cache",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"maxSize",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"ttlSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshIntervalSeconds",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"refreshTimer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_metrics",{enumerable:!0,configurable:!0,writable:!0,value:{hits:0,misses:0,refreshes:0,refreshErrors:0}}),this.configure(e)}get metrics(){return{...this._metrics}}get totalRequests(){return this._metrics.hits+this._metrics.misses}get hitRate(){let e=this.totalRequests;return e>0?this._metrics.hits/e:0}resetMetrics(){this._metrics={hits:0,misses:0,refreshes:0,refreshErrors:0}}get(e,r){if(this.maxSize===0)return;let n=this.cache.get(e);if(!n){this._metrics.misses+=1;return}return this.cache.delete(e),this.cache.set(e,{...n,refreshFunc:r}),this._metrics.hits+=1,n.value}set(e,r,n){if(this.maxSize===0)return;if(this.refreshTimer===void 0&&this.startRefreshLoop(),!this.cache.has(e)&&this.cache.size>=this.maxSize){let s=this.cache.keys().next().value;s!==void 0&&this.cache.delete(s)}let i={value:r,createdAt:Date.now(),refreshFunc:n};this.cache.delete(e),this.cache.set(e,i)}invalidate(e){this.cache.delete(e)}clear(){this.cache.clear()}get size(){return this.cache.size}stop(){this.refreshTimer&&(clearInterval(this.refreshTimer),this.refreshTimer=void 0)}dump(e){let r={};for(let[s,o]of this.cache.entries())r[s]=o.value;let n=Qe.dirname(e);Ar(n)||eu(n);let i=`${e}.tmp`;try{tu(i,JSON.stringify({entries:r},null,2)),ru(i,e)}catch(s){throw Ar(i)&&nu(i),s}}load(e){if(!Ar(e))return 0;let r;try{let s=Vt(e);r=JSON.parse(s).entries??null}catch{return 0}if(!r)return 0;let n=0,i=Date.now();for(let[s,o]of Object.entries(r)){if(this.cache.size>=this.maxSize)break;let c={value:o,createdAt:i};this.cache.set(s,c),n+=1}return n}startRefreshLoop(){this.stop(),this.ttlSeconds!==null&&(this.refreshTimer=setInterval(()=>{this.refreshStaleEntries().catch(e=>{console.warn("Unexpected error in cache refresh loop:",e)})},this.refreshIntervalSeconds*1e3),this.refreshTimer.unref&&this.refreshTimer.unref())}getStaleEntries(){let e=[];for(let[r,n]of this.cache.entries())sg(n,this.ttlSeconds)&&e.push([r,n]);return e}async refreshStaleEntries(){let e=this.getStaleEntries();if(e.length!==0){for(let[r,n]of e)if(n.refreshFunc!==void 0)try{let i=await n.refreshFunc();this.set(r,i,n.refreshFunc),this._metrics.refreshes+=1}catch(i){this._metrics.refreshErrors+=1,console.warn(`Failed to refresh cache entry ${r}:`,i)}}}configure(e){this.stop(),this.refreshIntervalSeconds=e.refreshIntervalSeconds??60,this.maxSize=e.maxSize??100,this.ttlSeconds=e.ttlSeconds??300}},Qn=new Xn;function au(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}a(au,"isAbortError");var an=a(t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)},"castToError");var $e=class extends Error{static{a(this,"LangsmithError")}},Te=class t extends $e{static{a(this,"APIError")}constructor(e,r,n,i){super(`${t.makeMessage(e,r,n)}`),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"error",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.status=e,this.headers=i,this.error=r}static makeMessage(e,r,n){let i=r?.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&i?`${e} ${i}`:e?`${e} status code (no body)`:i||"(no status code or body)"}static generate(e,r,n,i){if(!e||!i)return new yt({message:n,cause:an(r)});let s=r;return e===400?new qt(e,s,n,i):e===401?new Kt(e,s,n,i):e===403?new Jt(e,s,n,i):e===404?new Zt(e,s,n,i):e===409?new Yt(e,s,n,i):e===422?new Xt(e,s,n,i):e===429?new Qt(e,s,n,i):e>=500?new er(e,s,n,i):new t(e,s,n,i)}},Ct=class extends Te{static{a(this,"APIUserAbortError")}constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},yt=class extends Te{static{a(this,"APIConnectionError")}constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},Wt=class extends yt{static{a(this,"APIConnectionTimeoutError")}constructor({message:e}={}){super({message:e??"Request timed out."})}},qt=class extends Te{static{a(this,"BadRequestError")}},Kt=class extends Te{static{a(this,"AuthenticationError")}},Jt=class extends Te{static{a(this,"PermissionDeniedError")}},Zt=class extends Te{static{a(this,"NotFoundError")}},Yt=class extends Te{static{a(this,"ConflictError")}},Xt=class extends Te{static{a(this,"UnprocessableEntityError")}},Qt=class extends Te{static{a(this,"RateLimitError")}},er=class extends Te{static{a(this,"InternalServerError")}};var ei="0.8.9";var ct,og=a(()=>typeof window<"u"&&typeof window.document<"u","isBrowser"),cg=a(()=>typeof globalThis=="object"&&globalThis.constructor&&globalThis.constructor.name==="DedicatedWorkerGlobalScope","isWebWorker"),lg=a(()=>typeof window<"u"&&window.name==="nodejs"||typeof navigator<"u"&&navigator.userAgent.includes("jsdom"),"isJsDom"),lu=a(()=>typeof globalThis.Deno<"u","isDeno"),ug=a(()=>typeof process<"u"&&typeof process.versions<"u"&&typeof process.versions.node<"u"&&!lu(),"isNode"),on=a(()=>ct||(typeof Bun<"u"?ct="bun":og()?ct="browser":ug()?ct="node":cg()?ct="webworker":lg()?ct="jsdom":lu()?ct="deno":ct="other",ct),"getEnv"),Ys;function ti(){if(Ys===void 0){let t=on(),e=fg();Ys={library:"langsmith",runtime:t,sdk:"langsmith-js",sdk_version:ei,...e}}return Ys}a(ti,"getRuntimeEnvironment");function Qs(){let t=dg(),e={},r=["LANGCHAIN_API_KEY","LANGCHAIN_ENDPOINT","LANGCHAIN_TRACING_V2","LANGCHAIN_PROJECT","LANGCHAIN_SESSION","LANGSMITH_API_KEY","LANGSMITH_ENDPOINT","LANGSMITH_TRACING_V2","LANGSMITH_CONFIG_FILE","LANGSMITH_PROJECT","LANGSMITH_SESSION"];for(let[n,i]of Object.entries(t))typeof i=="string"&&!r.includes(n)&&!n.toLowerCase().includes("key")&&!n.toLowerCase().includes("secret")&&!n.toLowerCase().includes("token")&&(n==="LANGCHAIN_REVISION_ID"?e.revision_id=i:e[n]=i);return e}a(Qs,"getLangSmithEnvVarsMetadata");function dg(){let t={};try{if(typeof process<"u"&&process.env)for(let[e,r]of Object.entries(process.env))(e.startsWith("LANGCHAIN_")||e.startsWith("LANGSMITH_"))&&r!=null&&((e.toLowerCase().includes("key")||e.toLowerCase().includes("secret")||e.toLowerCase().includes("token"))&&typeof r=="string"?t[e]=r.slice(0,2)+"*".repeat(r.length-4)+r.slice(-2):t[e]=r)}catch{}return t}a(dg,"getLangSmithEnvironmentVariables");function ye(t){try{return typeof process<"u"?process.env?.[t]:void 0}catch{return}}a(ye,"getEnvironmentVariable");function Z(t){return ye(`LANGSMITH_${t}`)||ye(`LANGCHAIN_${t}`)}a(Z,"getLangSmithEnvironmentVariable");var Xs;function fg(){if(Xs!==void 0)return Xs;let t=["VERCEL_GIT_COMMIT_SHA","NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA","COMMIT_REF","RENDER_GIT_COMMIT","CI_COMMIT_SHA","CIRCLE_SHA1","CF_PAGES_COMMIT_SHA","REACT_APP_GIT_SHA","SOURCE_VERSION","GITHUB_SHA","TRAVIS_COMMIT","GIT_COMMIT","BUILD_VCS_NUMBER","bamboo_planRepository_revision","Build.SourceVersion","BITBUCKET_COMMIT","DRONE_COMMIT_SHA","SEMAPHORE_GIT_SHA","BUILDKITE_COMMIT"],e={};for(let r of t){let n=ye(r);n!==void 0&&(e[r]=n)}return Xs=e,e}a(fg,"getShas");function ou(){return ye("OTEL_ENABLED")==="true"||Z("OTEL_ENABLED")==="true"}a(ou,"getOtelEnabled");var cu=new Set(["langsmith","otel"]);function ri(t){if(t!==void 0)return t;let e=Z("TRACING_MODE");if(e!==void 0&&e!==""){let r=e.toLowerCase();if(!cu.has(r))throw new Error(`Invalid LANGSMITH_TRACING_MODE=${JSON.stringify(e)}. Must be one of: ${[...cu].sort().join(", ")}`);return ou()&&console.warn("Both LANGSMITH_TRACING_MODE and the legacy OTEL_ENABLED / LANGSMITH_OTEL_ENABLED env vars are set. LANGSMITH_TRACING_MODE takes precedence."),r}return ou()?"otel":"langsmith"}a(ri,"resolveTracingMode");var ra=class{static{a(this,"MockTracer")}constructor(){Object.defineProperty(this,"hasWarned",{enumerable:!0,configurable:!0,writable:!0,value:!1})}startActiveSpan(e,...r){!this.hasWarned&&ri()==="otel"&&(console.warn('OTel tracing mode is active (via LANGSMITH_TRACING_MODE, OTEL_ENABLED, or LANGSMITH_OTEL_ENABLED), but the required OTEL instances have not been initialized. Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'),this.hasWarned=!0);let n;if(r.length===1&&typeof r[0]=="function"?n=r[0]:r.length===2&&typeof r[1]=="function"?n=r[1]:r.length===3&&typeof r[2]=="function"&&(n=r[2]),typeof n=="function")return n()}},na=class{static{a(this,"MockOTELTrace")}constructor(){Object.defineProperty(this,"mockTracer",{enumerable:!0,configurable:!0,writable:!0,value:new ra})}getTracer(e,r){return this.mockTracer}getActiveSpan(){}setSpan(e,r){return e}getSpan(e){}setSpanContext(e,r){return e}getTracerProvider(){}setGlobalTracerProvider(e){return!1}},ia=class{static{a(this,"MockOTELContext")}active(){return{}}with(e,r){return r()}},ea=Symbol.for("ls:otel_trace"),ta=Symbol.for("ls:otel_context"),uu=Symbol.for("ls:otel_get_default_otlp_tracer_provider"),pg=new na,mg=new ia,sa=class{static{a(this,"OTELProvider")}getTraceInstance(){return globalThis[ea]??pg}getContextInstance(){return globalThis[ta]??mg}initializeGlobalInstances(e){globalThis[ea]===void 0&&(globalThis[ea]=e.trace),globalThis[ta]===void 0&&(globalThis[ta]=e.context)}setDefaultOTLPTracerComponents(e){globalThis[uu]=e}getDefaultOTLPTracerComponents(){return globalThis[uu]??void 0}},aa=new sa;function ni(){return aa.getTraceInstance()}a(ni,"getOTELTrace");function du(){return aa.getContextInstance()}a(du,"getOTELContext");function fu(){return aa.getDefaultOTLPTracerComponents()}a(fu,"getDefaultOTLPTracerComponents");var hg={llm:"chat",tool:"execute_tool",retriever:"embeddings",embedding:"embeddings",prompt:"chat"};function gg(t){return hg[t]||t}a(gg,"getOperationName");function yg(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"}a(yg,"isPrimitive");var ii=class{static{a(this,"LangSmithToOTELTranslator")}constructor(){Object.defineProperty(this,"spans",{enumerable:!0,configurable:!0,writable:!0,value:new Map})}exportBatch(e,r){for(let n of e)try{if(!n.run)continue;if(n.operation==="post"){let i=this.createSpanForRun(n,n.run,r.get(n.id));i&&!n.run.end_time&&this.spans.set(n.id,i)}else this.updateSpanForRun(n,n.run)}catch(i){console.error(`Error processing operation ${n.id}:`,i)}}createSpanForRun(e,r,n){let i=n&&ni().getSpan(n);if(i)try{return this.finishSpanSetup(i,r,e)}catch(s){console.error(`Failed to create span for run ${e.id}:`,s);return}}finishSpanSetup(e,r,n){return this.setSpanAttributes(e,r,n),r.error?(e.setStatus({code:2}),e.recordException(new Error(r.error))):e.setStatus({code:1}),r.end_time&&e.end(new Date(r.end_time)),e}updateSpanForRun(e,r){try{let n=this.spans.get(e.id);if(!n){console.debug(`No span found for run ${e.id} during update`);return}this.setSpanAttributes(n,r,e),r.error?(n.setStatus({code:2}),n.recordException(new Error(r.error))):n.setStatus({code:1});let i=r.end_time;i&&(n.end(new Date(i)),this.spans.delete(e.id))}catch(n){console.error(`Failed to update span for run ${e.id}:`,n)}}extractModelName(e){if(e.extra?.metadata){let r=e.extra.metadata;if(r.ls_model_name)return r.ls_model_name;if(r.invocation_params){let n=r.invocation_params;if(n.model)return n.model;if(n.model_name)return n.model_name}}}setSpanAttributes(e,r,n){if("run_type"in r&&r.run_type){e.setAttribute(Ol,r.run_type);let c=gg(r.run_type||"chain");e.setAttribute(ol,c)}"name"in r&&r.name&&e.setAttribute(kl,r.name),"session_id"in r&&r.session_id&&e.setAttribute(Cl,r.session_id),"session_name"in r&&r.session_name&&e.setAttribute(Rl,r.session_name),this.setGenAiSystem(e,r);let i=this.extractModelName(r);i&&e.setAttribute(Ls,i),r.extra?.metadata?.usage_metadata&&typeof r.extra.metadata.usage_metadata=="object"&&e.setAttribute(Bs,JSON.stringify(r.extra.metadata.usage_metadata)),"prompt_tokens"in r&&typeof r.prompt_tokens=="number"&&e.setAttribute(Ds,r.prompt_tokens),"completion_tokens"in r&&typeof r.completion_tokens=="number"&&e.setAttribute(Us,r.completion_tokens),"total_tokens"in r&&typeof r.total_tokens=="number"&&e.setAttribute($s,r.total_tokens),this.setInvocationParameters(e,r);let s=r.extra?.metadata||{};for(let[c,l]of Object.entries(s))l!=null&&e.setAttribute(`${Ml}.${c}`,yg(l)?String(l):JSON.stringify(l));let o=r.tags;if(o&&Array.isArray(o)?e.setAttribute(Fs,o.join(", ")):o&&e.setAttribute(Fs,String(o)),"serialized"in r&&typeof r.serialized=="object"){let c=r.serialized;c.name&&e.setAttribute(wl,String(c.name)),c.signature&&e.setAttribute(El,String(c.signature)),c.doc&&e.setAttribute(Tl,String(c.doc))}this.setIOAttributes(e,n)}setGenAiSystem(e,r){let n="langchain",i=this.extractModelName(r);if(i){let s=i.toLowerCase();s.includes("anthropic")||s.startsWith("claude")?n="anthropic":s.includes("bedrock")?n="aws.bedrock":s.includes("azure")&&s.includes("openai")?n="az.ai.openai":s.includes("azure")&&s.includes("inference")?n="az.ai.inference":s.includes("cohere")?n="cohere":s.includes("deepseek")?n="deepseek":s.includes("gemini")?n="gemini":s.includes("groq")?n="groq":s.includes("watson")||s.includes("ibm")?n="ibm.watsonx.ai":s.includes("mistral")?n="mistral_ai":s.includes("gpt")||s.includes("openai")?n="openai":s.includes("perplexity")||s.includes("sonar")?n="perplexity":s.includes("vertex")?n="vertex_ai":(s.includes("xai")||s.includes("grok"))&&(n="xai")}e.setAttribute(cl,n)}setInvocationParameters(e,r){if(!r.extra?.metadata?.invocation_params)return;let n=r.extra.metadata.invocation_params;n.max_tokens!==void 0&&e.setAttribute(ul,n.max_tokens),n.temperature!==void 0&&e.setAttribute(dl,n.temperature),n.top_p!==void 0&&e.setAttribute(fl,n.top_p),n.frequency_penalty!==void 0&&e.setAttribute(pl,n.frequency_penalty),n.presence_penalty!==void 0&&e.setAttribute(ml,n.presence_penalty)}setIOAttributes(e,r){if(r.run.inputs)try{let n=r.run.inputs;typeof n=="object"&&n!==null&&(n.model&&Array.isArray(n.messages)&&e.setAttribute(Ls,n.model),n.stream!==void 0&&e.setAttribute(Pl,n.stream),n.extra_headers&&e.setAttribute(Nl,JSON.stringify(n.extra_headers)),n.extra_query&&e.setAttribute(_l,JSON.stringify(n.extra_query)),n.extra_body&&e.setAttribute(bl,JSON.stringify(n.extra_body))),e.setAttribute(gl,JSON.stringify(n))}catch(n){console.debug(`Failed to process inputs for run ${r.id}`,n)}if(r.run.outputs)try{let n=r.run.outputs,i=this.getUnifiedRunTokens(n);if(i&&(e.setAttribute(Ds,i[0]),e.setAttribute(Us,i[1]),e.setAttribute($s,i[0]+i[1])),n&&typeof n=="object"){if(n.model&&e.setAttribute(ll,String(n.model)),n.id&&e.setAttribute(vl,n.id),n.choices&&Array.isArray(n.choices)){let s=n.choices.map(o=>o.finish_reason).filter(o=>o).map(String);s.length>0&&e.setAttribute(hl,s.join(", "))}if(n.service_tier&&e.setAttribute(Sl,n.service_tier),n.system_fingerprint&&e.setAttribute(xl,n.system_fingerprint),n.usage_metadata&&typeof n.usage_metadata=="object"){let s=n.usage_metadata;e.setAttribute(Bs,JSON.stringify(s)),s.input_token_details&&e.setAttribute(Il,JSON.stringify(s.input_token_details)),s.output_token_details&&e.setAttribute(Al,JSON.stringify(s.output_token_details))}}e.setAttribute(yl,JSON.stringify(n))}catch(n){console.debug(`Failed to process outputs for run ${r.id}`,n)}}getUnifiedRunTokens(e){if(!e)return null;let r=this.extractUnifiedRunTokens(e.usage_metadata);if(r)return r;let n=Object.keys(e);for(let o of n){let c=e[o];if(!(!c||typeof c!="object")&&(r=this.extractUnifiedRunTokens(c.usage_metadata),r||c.lc===1&&c.kwargs&&typeof c.kwargs=="object"&&(r=this.extractUnifiedRunTokens(c.kwargs.usage_metadata),r)))return r}let i=e.generations||[];if(!Array.isArray(i))return null;let s=Array.isArray(i[0])?i.flat():i;for(let o of s)if(typeof o=="object"&&o.message&&typeof o.message=="object"&&o.message.kwargs&&typeof o.message.kwargs=="object"&&(r=this.extractUnifiedRunTokens(o.message.kwargs.usage_metadata),r))return r;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 _g=Object.prototype.toString,bg=a(t=>_g.call(t)==="[object Error]","isError"),wg=new Set(["network error","Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed","fetch failed","terminated"," A network error occurred.","Network connection lost"]);function oa(t){if(!(t&&bg(t)&&t.name==="TypeError"&&typeof t.message=="string"))return!1;let{message:r,stack:n}=t;return r==="Load failed"?n===void 0||"__sentry_captured__"in t:r.startsWith("error sending request for url")?!0:wg.has(r)}a(oa,"isNetworkError");function Eg(t){if(typeof t=="number"){if(t<0)throw new TypeError("Expected `retries` to be a non-negative number.");if(Number.isNaN(t))throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN.")}else if(t!==void 0)throw new TypeError("Expected `retries` to be a number or Infinity.")}a(Eg,"validateRetries");function si(t,e,{min:r=0,allowInfinity:n=!1}={}){if(e!==void 0){if(typeof e!="number"||Number.isNaN(e))throw new TypeError(`Expected \`${t}\` to be a number${n?" or Infinity":""}.`);if(!n&&!Number.isFinite(e))throw new TypeError(`Expected \`${t}\` to be a finite number.`);if(e<r)throw new TypeError(`Expected \`${t}\` to be \u2265 ${r}.`)}}a(si,"validateNumberOption");var ca=class extends Error{static{a(this,"AbortError")}constructor(e){super(),e instanceof Error?(this.originalError=e,{message:e}=e):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}};function Tg(t,e){let r=Math.max(1,t+1),n=e.randomize?Math.random()+1:1,i=Math.round(n*e.minTimeout*e.factor**(r-1));return i=Math.min(i,e.maxTimeout),i}a(Tg,"calculateDelay");function pu(t,e){return Number.isFinite(e)?e-(performance.now()-t):e}a(pu,"calculateRemainingTime");async function vg({error:t,attemptNumber:e,retriesConsumed:r,startTime:n,options:i}){let s=t instanceof Error?t:new TypeError(`Non-error was thrown: "${t}". You should only throw errors.`);if(s instanceof ca)throw s.originalError;let o=Number.isFinite(i.retries)?Math.max(0,i.retries-r):i.retries,c=i.maxRetryTime??Number.POSITIVE_INFINITY,l=Object.freeze({error:s,attemptNumber:e,retriesLeft:o,retriesConsumed:r});if(await i.onFailedAttempt(l),pu(n,c)<=0)throw s;let u=await i.shouldConsumeRetry(l),d=pu(n,c);if(d<=0||o<=0)throw s;if(s instanceof TypeError&&!oa(s)){if(u)throw s;return i.signal?.throwIfAborted(),!1}if(!await i.shouldRetry(l))throw s;if(!u)return i.signal?.throwIfAborted(),!1;let f=Tg(r,i),y=Math.min(f,d);return y>0&&await new Promise((h,g)=>{let b=a(()=>{clearTimeout(w),i.signal?.removeEventListener("abort",b),g(i.signal.reason)},"onAbort"),w=setTimeout(()=>{i.signal?.removeEventListener("abort",b),h()},y);i.unref&&w.unref?.(),i.signal?.addEventListener("abort",b,{once:!0})}),i.signal?.throwIfAborted(),!0}a(vg,"onAttemptFailure");async function la(t,e={}){if(e={...e},Eg(e.retries),Object.hasOwn(e,"forever"))throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead.");e.retries??=10,e.factor??=2,e.minTimeout??=1e3,e.maxTimeout??=Number.POSITIVE_INFINITY,e.maxRetryTime??=Number.POSITIVE_INFINITY,e.randomize??=!1,e.onFailedAttempt??=()=>{},e.shouldRetry??=()=>!0,e.shouldConsumeRetry??=()=>!0,si("factor",e.factor,{min:0,allowInfinity:!1}),si("minTimeout",e.minTimeout,{min:0,allowInfinity:!1}),si("maxTimeout",e.maxTimeout,{min:0,allowInfinity:!0}),si("maxRetryTime",e.maxRetryTime,{min:0,allowInfinity:!0}),e.factor>0||(e.factor=1),e.signal?.throwIfAborted();let r=0,n=0,i=performance.now();for(;!Number.isFinite(e.retries)||n<=e.retries;){r++;try{e.signal?.throwIfAborted();let s=await t(r);return e.signal?.throwIfAborted(),s}catch(s){await vg({error:s,attemptNumber:r,retriesConsumed:n,startTime:i,options:e})&&n++}}throw new Error("Retry attempts exhausted without throwing an error.")}a(la,"pRetry");var ai=He(Hn(),1),mu="default"in ai.default?ai.default.default:ai.default;var Sg=[408,425,429,500,502,503,504],cn=class{static{a(this,"AsyncCaller")}constructor(e){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxQueueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queueSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),this.maxConcurrency=e.maxConcurrency??1/0,this.maxRetries=e.maxRetries??6,this.maxQueueSizeBytes=e.maxQueueSizeBytes,this.queue=new mu({concurrency:this.maxConcurrency}),this.onFailedResponseHook=e?.onFailedResponseHook}call(e,...r){return this.callWithOptions({},e,...r)}callWithOptions(e,r,...n){let i=e.sizeBytes??0;if(this.maxQueueSizeBytes!==void 0&&i>0&&this.queueSizeBytes+i>this.maxQueueSizeBytes)return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${i} bytes.`));i>0&&(this.queueSizeBytes+=i);let s=this.onFailedResponseHook,o=this.queue.add(()=>la(()=>r(...n).catch(c=>{throw c instanceof Error?c:new Error(c)}),{async onFailedAttempt({error:c}){if(typeof c!="object"||c==null)throw c;let l="message"in c&&typeof c.message=="string"?c.message:void 0;if(l?.startsWith("Cancel")||l?.startsWith("TimeoutError")||l?.startsWith("AbortError")||"name"in c&&c.name==="TimeoutError"||"code"in c&&c.code==="ECONNABORTED")throw c;let u="response"in c?c.response:void 0;if(s&&await s(u))return;let d=u?.status??("status"in c?c.status:void 0);if(d!=null&&(typeof d=="number"||typeof d=="string")&&!Sg.includes(+d))throw c},retries:this.maxRetries,randomize:!0}),{throwOnTimeout:!0});return i>0&&(o=o.finally(()=>{this.queueSizeBytes-=i})),e.signal?Promise.race([o,new Promise((c,l)=>{e.signal?.addEventListener("abort",()=>{l(new Error("AbortError"))})})]):o}};function ua(t){return typeof t?._getType=="function"}a(ua,"isLangChainMessage");function da(t){let e={type:t._getType(),data:{content:t.content}};return t?.additional_kwargs&&Object.keys(t.additional_kwargs).length>0&&(e.data.additional_kwargs={...t.additional_kwargs}),e}a(da,"convertLangChainMessageToExample");var fa=a(function(){let{crypto:t}=globalThis;if(t?.randomUUID)return fa=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))},"uuid4");var xg=/^[a-z][a-z0-9+.-]*:/i,hu=a(t=>xg.test(t),"isAbsoluteURL"),Ae=a(t=>(Ae=Array.isArray,Ae(t)),"isArray"),pa=Ae;function Cr(t){return typeof t!="object"?{}:t??{}}a(Cr,"maybeObj");function ma(t){if(!t)return!0;for(let e in t)return!1;return!0}a(ma,"isEmptyObj");function gu(t,e){return Object.prototype.hasOwnProperty.call(t,e)}a(gu,"hasOwn");var yu=a((t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new $e(`${t} must be an integer`);if(e<0)throw new $e(`${t} must be a positive integer`);return e},"validatePositiveInteger");var _u=a(t=>{try{return JSON.parse(t)}catch{return}},"safeJSON");var bu=a(t=>new Promise(e=>setTimeout(e,t)),"sleep");var Ot="0.0.1";function Ig(){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"}a(Ig,"getDetectedPlatform");var Ag=a(()=>{let t=Ig();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":Eu(Deno.build.os),"X-Stainless-Arch":wu(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":Ot,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"X-Stainless-OS":Eu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":wu(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};let e=Cg();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ot,"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":Ot,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}},"getPlatformProperties");function Cg(){if(typeof navigator>"u"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let i=n[1]||0,s=n[2]||0,o=n[3]||0;return{browser:e,version:`${i}.${s}.${o}`}}}return null}a(Cg,"getBrowserInfo");var wu=a(t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown","normalizeArch"),Eu=a(t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),"normalizePlatform"),Rg,Tu=a(()=>Rg??=Ag(),"getPlatformHeaders");function vu(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Langsmith({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}a(vu,"getDefaultFetch");function Og(...t){let e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}a(Og,"makeReadableStream");function ha(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Og({start(){},async pull(r){let{done:n,value:i}=await e.next();n?r.close():r.enqueue(i)},async cancel(){await e.return?.()}})}a(ha,"ReadableStreamFrom");async function Su(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}a(Su,"CancelReadableStream");var xu=a(({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),"FallbackEncoder");var ga="RFC3986",ya=a(t=>String(t),"default_formatter"),_a={RFC1738:a(t=>String(t).replace(/%20/g,"+"),"RFC1738"),RFC3986:ya},Iu="RFC1738";var oi=a((t,e)=>(oi=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),oi(t,e)),"has"),lt=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var ba=1024,Au=a((t,e,r,n,i)=>{if(t.length===0)return t;let s=t;if(typeof t=="symbol"?s=Symbol.prototype.toString.call(t):typeof t!="string"&&(s=String(t)),r==="iso-8859-1")return escape(s).replace(/%u[0-9a-f]{4}/gi,function(c){return"%26%23"+parseInt(c.slice(2),16)+"%3B"});let o="";for(let c=0;c<s.length;c+=ba){let l=s.length>=ba?s.slice(c,c+ba):s,u=[];for(let d=0;d<l.length;++d){let f=l.charCodeAt(d);if(f===45||f===46||f===95||f===126||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||i===Iu&&(f===40||f===41)){u[u.length]=l.charAt(d);continue}if(f<128){u[u.length]=lt[f];continue}if(f<2048){u[u.length]=lt[192|f>>6]+lt[128|f&63];continue}if(f<55296||f>=57344){u[u.length]=lt[224|f>>12]+lt[128|f>>6&63]+lt[128|f&63];continue}d+=1,f=65536+((f&1023)<<10|l.charCodeAt(d)&1023),u[u.length]=lt[240|f>>18]+lt[128|f>>12&63]+lt[128|f>>6&63]+lt[128|f&63]}o+=u.join("")}return o},"encode");function Cu(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}a(Cu,"is_buffer");function wa(t,e){if(Ae(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}a(wa,"maybe_map");var Ru={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Ou=a(function(t,e){Array.prototype.push.apply(t,Ae(e)?e:[e])},"push_to_array"),Pg,pe={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Au,encodeValuesOnly:!1,format:ga,formatter:ya,indices:!1,serializeDate(t){return(Pg??=Function.prototype.call.bind(Date.prototype.toISOString))(t)},skipNulls:!1,strictNullHandling:!1};function Ng(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}a(Ng,"is_non_nullish_primitive");var Ea={};function ku(t,e,r,n,i,s,o,c,l,u,d,f,y,h,g,b,w,v){let S=t,p=v,T=0,I=!1;for(;(p=p.get(Ea))!==void 0&&!I;){let D=p.get(t);if(T+=1,typeof D<"u"){if(D===T)throw new RangeError("Cyclic object value");I=!0}typeof p.get(Ea)>"u"&&(T=0)}if(typeof u=="function"?S=u(e,S):S instanceof Date?S=y?.(S):r==="comma"&&Ae(S)&&(S=wa(S,function(D){return D instanceof Date?y?.(D):D})),S===null){if(s)return l&&!b?l(e,pe.encoder,w,"key",h):e;S=""}if(Ng(S)||Cu(S)){if(l){let D=b?e:l(e,pe.encoder,w,"key",h);return[g?.(D)+"="+g?.(l(S,pe.encoder,w,"value",h))]}return[g?.(e)+"="+g?.(String(S))]}let C=[];if(typeof S>"u")return C;let k;if(r==="comma"&&Ae(S))b&&l&&(S=wa(S,l)),k=[{value:S.length>0?S.join(",")||null:void 0}];else if(Ae(u))k=u;else{let D=Object.keys(S);k=d?D.sort(d):D}let E=c?String(e).replace(/\./g,"%2E"):String(e),U=n&&Ae(S)&&S.length===1?E+"[]":E;if(i&&Ae(S)&&S.length===0)return U+"[]";for(let D=0;D<k.length;++D){let N=k[D],W=typeof N=="object"&&typeof N.value<"u"?N.value:S[N];if(o&&W===null)continue;let te=f&&c?N.replace(/\./g,"%2E"):N,Se=Ae(S)?typeof r=="function"?r(U,te):U:U+(f?"."+te:"["+te+"]");v.set(t,T);let nt=new WeakMap;nt.set(Ea,v),Ou(C,ku(W,Se,r,n,i,s,o,c,r==="comma"&&b&&Ae(S)?null:l,u,d,f,y,h,g,b,w,nt))}return C}a(ku,"inner_stringify");function Lg(t=pe){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||pe.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=ga;if(typeof t.format<"u"){if(!oi(_a,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=_a[r],i=pe.filter;(typeof t.filter=="function"||Ae(t.filter))&&(i=t.filter);let s;if(t.arrayFormat&&t.arrayFormat in Ru?s=t.arrayFormat:"indices"in t?s=t.indices?"indices":"repeat":s=pe.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let o=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:pe.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:pe.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:pe.allowEmptyArrays,arrayFormat:s,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:pe.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?pe.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:pe.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:pe.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:pe.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:pe.encodeValuesOnly,filter:i,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:pe.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:pe.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:pe.strictNullHandling}}a(Lg,"normalize_stringify_options");function Mu(t,e={}){let r=t,n=Lg(e),i,s;typeof n.filter=="function"?(s=n.filter,r=s("",r)):Ae(n.filter)&&(s=n.filter,i=s);let o=[];if(typeof r!="object"||r===null)return"";let c=Ru[n.arrayFormat],l=c==="comma"&&n.commaRoundTrip;i||(i=Object.keys(r)),n.sort&&i.sort(n.sort);let u=new WeakMap;for(let y=0;y<i.length;++y){let h=i[y];n.skipNulls&&r[h]===null||Ou(o,ku(r[h],h,c,l,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,u))}let d=o.join(n.delimiter),f=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?f+="utf8=%26%2310003%3B&":f+="utf8=%E2%9C%93&"),d.length>0?f+d:""}a(Mu,"stringify");function Pu(t){return Mu(t,{arrayFormat:"repeat"})}a(Pu,"stringifyQuery");var li={off:0,error:200,warn:300,info:400,debug:500},Ta=a((t,e,r)=>{if(t){if(gu(li,t))return t;Me(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(li))}`)}},"parseLogLevel");function ln(){}a(ln,"noop");function ci(t,e,r){return!e||li[t]>li[r]?ln:e[t].bind(e)}a(ci,"makeLogFn");var Ug={error:ln,warn:ln,info:ln,debug:ln},Nu=new WeakMap;function Me(t){let e=t.logger,r=t.logLevel??"off";if(!e)return Ug;let n=Nu.get(e);if(n&&n[0]===r)return n[1];let i={error:ci("error",e,r),warn:ci("warn",e,r),info:ci("info",e,r),debug:ci("debug",e,r)};return Nu.set(e,[r,i]),i}a(Me,"loggerFor");var _t=a(t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="api-key"||e.toLowerCase()==="x-api-key"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"||e.toLowerCase()==="x-tenant-id"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t),"formatRequestDetails");async function ui(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:i,startTime:s}=e,o=await(async()=>{if(r.status===204)return null;if(e.options.__binaryResponse)return r;let l=r.headers.get("content-type")?.split(";")[0]?.trim();return l?.includes("application/json")||l?.endsWith("+json")?r.headers.get("content-length")==="0"?void 0:await r.json():await r.text()})();return Me(t).debug(`[${n}] response parsed`,_t({retryOfRequestLogID:i,url:r.url,status:r.status,body:o,durationMs:Date.now()-s})),o}a(ui,"defaultParseResponse");var $g=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Lu=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},un,tr=class t extends Promise{static{a(this,"APIPromise")}constructor(e,r,n=ui){super(i=>{i(null)}),Object.defineProperty(this,"responsePromise",{enumerable:!0,configurable:!0,writable:!0,value:r}),Object.defineProperty(this,"parseResponse",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"parsedPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),un.set(this,void 0),$g(this,un,e,"f")}_thenUnwrap(e){return new t(Lu(this,un,"f"),this.responsePromise,async(r,n)=>e(await this.parseResponse(r,n),n))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(Lu(this,un,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};un=new WeakMap;var Fg=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Bg=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},di,rr=class{static{a(this,"AbstractPage")}constructor(e,r,n,i){di.set(this,void 0),Object.defineProperty(this,"options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"body",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Fg(this,di,e,"f"),this.options=i,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new $e("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await Bg(this,di,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(di=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},dn=class extends tr{static{a(this,"PagePromise")}constructor(e,r,n){super(e,r,async(i,s)=>new n(i,s.response,await ui(i,s),s.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},fi=class extends rr{static{a(this,"OffsetPaginationTopLevelArray")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...Cr(this.options.query),offset:n}}}},pi=class extends rr{static{a(this,"OffsetPaginationIssues")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n||[]}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...Cr(this.options.query),offset:n}}}};var mi=class extends rr{static{a(this,"OffsetPaginationOnlineEvaluators")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"evaluators",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"total",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.evaluators=n.evaluators||[],this.total=n.total||0}getPaginatedItems(){return this.evaluators??[]}nextPageRequestOptions(){let e=this.options.query.offset??0,r=this.getPaginatedItems().length,n=e+r;return{...this.options,query:{...Cr(this.options.query),offset:n}}}};var ut=class extends rr{static{a(this,"ItemsCursorPostPagination")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n.items||[],this.next_cursor=n.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,body:{...Cr(this.options.body),cursor:e}}:null}},Rr=class extends rr{static{a(this,"ItemsCursorGetPagination")}constructor(e,r,n,i){super(e,r,n,i),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"next_cursor",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.items=n.items||[],this.next_cursor=n.next_cursor||""}getPaginatedItems(){return this.items??[]}nextPageRequestOptions(){let e=this.next_cursor;return e?{...this.options,query:{...Cr(this.options.query),cursor:e}}:null}};var va=a(()=>{if(typeof File>"u"){let{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.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`.":""))}},"checkFileSupport");function hi(t,e,r){return va(),new File(t,e??"unknown_file",r)}a(hi,"makeFile");function Du(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}a(Du,"getName");var Uu=a(t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function","isAsyncIterable");var $u=a(t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function","isBlobLike"),Hg=a(t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&$u(t),"isFileLike"),zg=a(t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function","isResponseLike");async function gi(t,e,r){if(va(),t=await t,Hg(t))return t instanceof File?t:hi([await t.arrayBuffer()],t.name);if(zg(t)){let i=await t.blob();return e||=new URL(t.url).pathname.split(/[\\/]/).pop(),hi(await Sa(i),e,r)}let n=await Sa(t);if(e||=Du(t),!r?.type){let i=n.find(s=>typeof s=="object"&&"type"in s&&s.type);typeof i=="string"&&(r={...r,type:i})}return hi(n,e,r)}a(gi,"toFile");async function Sa(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if($u(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Uu(t))for await(let r of t)e.push(...await Sa(r));else{let r=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${r?`; constructor: ${r}`:""}${Gg(t)}`)}return e}a(Sa,"getBytes");function Gg(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}a(Gg,"propsForError");var G=class{static{a(this,"APIResource")}constructor(e){Object.defineProperty(this,"_client",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this._client=e}};function Bu(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}a(Bu,"encodeURIPath");var Fu=Object.freeze(Object.create(null)),Wg=a((t=Bu)=>a(function(r,...n){if(r.length===1)return r[0];let i=!1,s=[],o=r.reduce((d,f,y)=>{/[?#]/.test(f)&&(i=!0);let h=n[y],g=(i?encodeURIComponent:t)(""+h);return y!==n.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??Fu)??Fu)?.toString)&&(g=h+"",s.push({start:d.length+f.length,length:g.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),d+f+(y===n.length?"":g)},""),c=o.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,u;for(;(u=l.exec(c))!==null;)s.push({start:u.index,length:u[0].length,error:`Value "${u[0]}" can't be safely passed as a path parameter`});if(s.sort((d,f)=>d.start-f.start),s.length>0){let d=0,f=s.reduce((y,h)=>{let g=" ".repeat(h.start-d),b="^".repeat(h.length);return d=h.start+h.length,y+g+b},"");throw new $e(`Path parameters result in path with invalid segments:
10
+ ${s.map(y=>y.error).join(`
11
+ `)}
12
+ ${o}
13
+ ${f}`)}return o},"path"),"createPathTagFunction"),F=Wg(Bu);var Or=class extends G{static{a(this,"Items")}create(e,r,n){let{extend_trace_retention:i,...s}=r;return this._client.post(F`/api/v1/platform/annotation-queues/${e}/items`,{query:{extend_trace_retention:i},body:s,...n})}update(e,r,n){let{queue_id:i,...s}=r;return this._client.patch(F`/api/v1/platform/annotation-queues/${i}/items/${e}`,{body:s,...n})}list(e,r,n){return this._client.getAPIList(F`/api/v1/platform/annotation-queues/${e}/items`,Rr,{query:r,...n})}createStatus(e,r,n){return this._client.post(F`/api/v1/platform/annotation-queues/items/${e}/status`,{body:r,...n})}deleteAll(e,r,n){return this._client.post(F`/api/v1/platform/annotation-queues/${e}/items/delete`,{body:r,...n})}retrieveCount(e,r,n){return this._client.get(F`/api/v1/platform/annotation-queues/${e}/items/count`,{query:r,...n})}retrievePlacement(e,r,n){let{queue_id:i}=r;return this._client.get(F`/api/v1/platform/annotation-queues/${i}/items/${e}/placement`,n)}};var kr=class extends G{static{a(this,"Runs")}create(e,r,n){let{body:i,extend_trace_retention:s}=r;return this._client.post(F`/api/v1/annotation-queues/${e}/runs`,{query:{extend_trace_retention:s},body:i,...n})}update(e,r,n){let{queue_id:i,...s}=r;return this._client.patch(F`/api/v1/annotation-queues/${i}/runs/${e}`,{body:s,...n})}list(e,r={},n){return this._client.get(F`/api/v1/annotation-queues/${e}/runs`,{query:r,...n})}createByKey(e,r,n){let{body:i,extend_trace_retention:s}=r;return this._client.post(F`/api/v1/annotation-queues/${e}/runs/by-key`,{query:{extend_trace_retention:s},body:i,...n})}deleteAll(e,r,n){return this._client.post(F`/api/v1/annotation-queues/${e}/runs/delete`,{body:r,...n})}deleteQueue(e,r,n){let{queue_id:i}=r;return this._client.delete(F`/api/v1/annotation-queues/${i}/runs/${e}`,n)}};var bt=class extends G{static{a(this,"AnnotationQueues")}constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new kr(this._client)}),Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:new Or(this._client)})}retrieve(e,r){return this._client.get(F`/api/v1/annotation-queues/${e}`,r)}update(e,r,n){return this._client.patch(F`/api/v1/annotation-queues/${e}`,{body:r,...n})}delete(e,r){return this._client.delete(F`/api/v1/annotation-queues/${e}`,r)}annotationQueues(e,r){return this._client.post("/api/v1/annotation-queues",{body:e,...r})}createRunStatus(e,r,n){return this._client.post(F`/api/v1/annotation-queues/status/${e}`,{body:r,...n})}export(e,r,n){return this._client.post(F`/api/v1/annotation-queues/${e}/export`,{body:r,...n})}populate(e,r){return this._client.post("/api/v1/annotation-queues/populate",{body:e,...r})}retrieveAnnotationQueues(e={},r){return this._client.getAPIList("/api/v1/annotation-queues",fi,{query:e,...r})}retrieveQueues(e,r){return this._client.get(F`/api/v1/annotation-queues/${e}/queues`,r)}retrieveRun(e,r,n){let{queue_id:i,...s}=r;return this._client.get(F`/api/v1/annotation-queues/${i}/run/${e}`,{query:s,...n})}retrieveSize(e,r={},n){return this._client.get(F`/api/v1/annotation-queues/${e}/size`,{query:r,...n})}retrieveTotalArchived(e,r={},n){return this._client.get(F`/api/v1/annotation-queues/${e}/total_archived`,{query:r,...n})}retrieveTotalSize(e,r){return this._client.get(F`/api/v1/annotation-queues/${e}/total_size`,r)}};bt.Runs=kr;bt.Items=Or;var Mr=class extends G{static{a(this,"ExperimentRuns")}query(e,r,n){return this._client.getAPIList(F`/api/v2/datasets/${e}/experiment-runs`,ut,{body:r,method:"post",...n})}};var kt=class extends G{static{a(this,"Datasets")}constructor(){super(...arguments),Object.defineProperty(this,"experimentRuns",{enumerable:!0,configurable:!0,writable:!0,value:new Mr(this._client)})}};kt.ExperimentRuns=Mr;var nr=class extends G{static{a(this,"Info")}list(e){return this._client.get("/api/v1/info",e)}};var ir=class extends G{static{a(this,"Issues")}retrieve(e,r){return this._client.get(F`/api/v1/platform/issues/${e}`,r)}list(e={},r){return this._client.getAPIList("/api/v1/platform/issues",pi,{query:e,...r})}};var ju=Symbol("brand.privateNullableHeaders");function*Zg(t){if(!t)return;if(ju in t){let{values:n,nulls:i}=t;yield*n.entries();for(let s of i)yield[s,null];return}let e=!1,r;t instanceof Headers?r=t.entries():pa(t)?r=t:(e=!0,r=Object.entries(t??{}));for(let n of r){let i=n[0];if(typeof i!="string")throw new TypeError("expected header name to be a string");let s=pa(n[1])?n[1]:[n[1]],o=!1;for(let c of s)c!==void 0&&(e&&!o&&(o=!0,yield[i,null]),yield[i,c])}}a(Zg,"iterateHeaders");var ee=a(t=>{let e=new Headers,r=new Set;for(let n of t){let i=new Set;for(let[s,o]of Zg(n)){let c=s.toLowerCase();i.has(c)||(e.delete(s),i.add(c)),o===null?(e.delete(s),r.add(c)):(e.append(s,o),r.delete(c))}}return{[ju]:!0,values:e,nulls:r}},"buildHeaders");var sr=class extends G{static{a(this,"OnlineEvaluators")}create(e,r){return this._client.post("/api/v1/platform/evaluators",{body:e,...r})}retrieve(e,r){return this._client.get(F`/api/v1/platform/evaluators/${e}`,r)}update(e,r,n){return this._client.patch(F`/api/v1/platform/evaluators/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/api/v1/platform/evaluators",mi,{query:e,...r})}delete(e,r={},n){let{delete_run_rules:i}=r??{};return this._client.delete(F`/api/v1/platform/evaluators/${e}`,{query:{delete_run_rules:i},...n,headers:ee([{Accept:"*/*"},n?.headers])})}bulkDelete(e,r){let{evaluator_ids:n,delete_run_rules:i}=e;return this._client.delete("/api/v1/platform/evaluators",{query:{evaluator_ids:n,delete_run_rules:i},...r})}spend(e,r){return this._client.get("/api/v1/platform/evaluators/spend",{query:e,...r})}};var Pr=class extends G{static{a(this,"Runs")}retrieve(e,r,n){let{share_token:i,Accept:s,...o}=r;return this._client.get(F`/api/v2/public/${i}/run/${e}`,{query:o,...n,headers:ee([{...s!=null?{Accept:s}:void 0},n?.headers])})}query(e,r,n){let{Accept:i,...s}=r;return this._client.post(F`/api/v2/public/${e}/runs/query`,{body:s,...n,headers:ee([{...i!=null?{Accept:i}:void 0},n?.headers])})}};var Mt=class extends G{static{a(this,"Public")}constructor(){super(...arguments),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new Pr(this._client)})}};Mt.Runs=Pr;var Nr=class extends G{static{a(this,"Share")}create(e,r,n){return this._client.post(F`/api/v2/runs/${e}/share`,{body:r,...n})}delete(e,r,n){return this._client.delete(F`/api/v2/runs/${e}/share`,{body:r,...n,headers:ee([{Accept:"*/*"},n?.headers])})}};var Pt=class extends G{static{a(this,"Runs")}constructor(){super(...arguments),Object.defineProperty(this,"share",{enumerable:!0,configurable:!0,writable:!0,value:new Nr(this._client)}),Object.defineProperty(this,"retrieve",{enumerable:!0,configurable:!0,writable:!0,value:this.retrieveV2}),Object.defineProperty(this,"query",{enumerable:!0,configurable:!0,writable:!0,value:this.queryV2})}getURL(e,r,n){return this._client.get(F`/api/v2/runs/${e}/url`,{query:r,...n})}queryV2(e,r){let{Accept:n,...i}=e;return this._client.getAPIList("/api/v2/runs/query",ut,{body:i,method:"post",...r,headers:ee([{...n!=null?{Accept:n}:void 0},r?.headers])})}retrieveV2(e,r,n){let{Accept:i,...s}=r;return this._client.get(F`/api/v2/runs/${e}`,{query:s,...n,headers:ee([{...i!=null?{Accept:i}:void 0},n?.headers])})}};Pt.Share=Nr;var Lr=class extends G{static{a(this,"Boxes")}create(e,r){return this._client.post("/api/v2/sandboxes/boxes",{body:e,...r})}retrieve(e,r){return this._client.get(F`/api/v2/sandboxes/boxes/${e}`,r)}update(e,r,n){return this._client.patch(F`/api/v2/sandboxes/boxes/${e}`,{body:r,...n})}list(e={},r){return this._client.get("/api/v2/sandboxes/boxes",{query:e,...r})}delete(e,r){return this._client.delete(F`/api/v2/sandboxes/boxes/${e}`,{...r,headers:ee([{Accept:"*/*"},r?.headers])})}createSnapshot(e,r,n){return this._client.post(F`/api/v2/sandboxes/boxes/${e}/snapshot`,{body:r,...n})}generateServiceURL(e,r,n){return this._client.post(F`/api/v2/sandboxes/boxes/${e}/service-url`,{body:r,...n})}getStatus(e,r){return this._client.get(F`/api/v2/sandboxes/boxes/${e}/status`,r)}start(e,r){return this._client.post(F`/api/v2/sandboxes/boxes/${e}/start`,r)}stop(e,r){return this._client.post(F`/api/v2/sandboxes/boxes/${e}/stop`,{...r,headers:ee([{Accept:"*/*"},r?.headers])})}};var Dr=class extends G{static{a(this,"Registries")}create(e,r){return this._client.post("/api/v2/sandboxes/registries",{body:e,...r})}retrieve(e,r){return this._client.get(F`/api/v2/sandboxes/registries/${e}`,r)}update(e,r,n){return this._client.patch(F`/api/v2/sandboxes/registries/${e}`,{body:r,...n})}list(e={},r){return this._client.get("/api/v2/sandboxes/registries",{query:e,...r})}delete(e,r){return this._client.delete(F`/api/v2/sandboxes/registries/${e}`,{...r,headers:ee([{Accept:"*/*"},r?.headers])})}};var Ur=class extends G{static{a(this,"Snapshots")}create(e,r){return this._client.post("/api/v2/sandboxes/snapshots",{body:e,...r})}retrieve(e,r){return this._client.get(F`/api/v2/sandboxes/snapshots/${e}`,r)}list(e={},r){return this._client.get("/api/v2/sandboxes/snapshots",{query:e,...r})}delete(e,r){return this._client.delete(F`/api/v2/sandboxes/snapshots/${e}`,{...r,headers:ee([{Accept:"*/*"},r?.headers])})}};var dt=class extends G{static{a(this,"Sandboxes")}constructor(){super(...arguments),Object.defineProperty(this,"boxes",{enumerable:!0,configurable:!0,writable:!0,value:new Lr(this._client)}),Object.defineProperty(this,"registries",{enumerable:!0,configurable:!0,writable:!0,value:new Dr(this._client)}),Object.defineProperty(this,"snapshots",{enumerable:!0,configurable:!0,writable:!0,value:new Ur(this._client)})}};dt.Boxes=Lr;dt.Registries=Dr;dt.Snapshots=Ur;var ar=class extends G{static{a(this,"Threads")}listTraces(e,r,n){return this._client.getAPIList(F`/api/v2/threads/${e}/traces`,Rr,{query:r,...n})}query(e,r){return this._client.getAPIList("/api/v2/threads/query",ut,{body:e,method:"post",...r})}stats(e,r,n){return this._client.get(F`/api/v2/threads/${e}/stats`,{query:r,...n})}};var or=class extends G{static{a(this,"Traces")}listRuns(e,r,n){let{Accept:i,...s}=r;return this._client.get(F`/api/v2/traces/${e}/runs`,{query:s,...n,headers:ee([{...i!=null?{Accept:i}:void 0},n?.headers])})}query(e,r){return this._client.getAPIList("/api/v2/traces/query",ut,{body:e,method:"post",...r})}};var $r=a(t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()||void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()||void 0},"readEnv");var ny=function(t,e,r,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!i:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(t,r):i?i.value=r:e.set(t,r),r},Hu=function(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)},xa,Ia,yi,zu,K=class{static{a(this,"Langsmith")}constructor({baseURL:e=$r("LANGCHAIN_BASE_URL"),apiKey:r=$r("LANGSMITH_API_KEY")??null,tenantID:n=$r("LANGSMITH_TENANT_ID")??null,...i}={}){xa.add(this),Object.defineProperty(this,"apiKey",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tenantID",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"baseURL",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"timeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logger",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"logLevel",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetch",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),yi.set(this,void 0),Object.defineProperty(this,"idempotencyHeader",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_options",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"datasets",{enumerable:!0,configurable:!0,writable:!0,value:new kt(this)}),Object.defineProperty(this,"runs",{enumerable:!0,configurable:!0,writable:!0,value:new Pt(this)}),Object.defineProperty(this,"threads",{enumerable:!0,configurable:!0,writable:!0,value:new ar(this)}),Object.defineProperty(this,"traces",{enumerable:!0,configurable:!0,writable:!0,value:new or(this)}),Object.defineProperty(this,"onlineEvaluators",{enumerable:!0,configurable:!0,writable:!0,value:new sr(this)}),Object.defineProperty(this,"public",{enumerable:!0,configurable:!0,writable:!0,value:new Mt(this)}),Object.defineProperty(this,"annotationQueues",{enumerable:!0,configurable:!0,writable:!0,value:new bt(this)}),Object.defineProperty(this,"info",{enumerable:!0,configurable:!0,writable:!0,value:new nr(this)}),Object.defineProperty(this,"issues",{enumerable:!0,configurable:!0,writable:!0,value:new ir(this)}),Object.defineProperty(this,"sandboxes",{enumerable:!0,configurable:!0,writable:!0,value:new dt(this)});let s={apiKey:r,tenantID:n,...i,baseURL:e||"https://api.smith.langchain.com/"};this.baseURL=s.baseURL,this.timeout=s.timeout??Ia.DEFAULT_TIMEOUT,this.logger=s.logger??console;let o="warn";this.logLevel=o,this.logLevel=Ta(s.logLevel,"ClientOptions.logLevel",this)??Ta($r("LANGCHAIN_LOG"),"process.env['LANGCHAIN_LOG']",this)??o,this.fetchOptions=s.fetchOptions,this.maxRetries=s.maxRetries??2,this.fetch=s.fetch??vu(),ny(this,yi,xu,"f");let c=$r("LANGCHAIN_CUSTOM_HEADERS");if(c){let l={};for(let u of c.split(`
14
+ `)){let d=u.indexOf(":");d>=0&&(l[u.substring(0,d).trim()]=u.substring(d+1).trim())}s.defaultHeaders={...l,...s.defaultHeaders}}this._options=s,this.apiKey=r,this.tenantID=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,tenantID:this.tenantID,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.tenantID&&e.get("x-tenant-id"))&&!r.has("x-tenant-id"))throw new Error('Could not resolve authentication method. Expected either apiKey or tenantID to be set. Or for one of the "X-API-Key" or "X-Tenant-Id" headers to be explicitly omitted')}async authHeaders(e){return ee([await this.apiKeyAuth(e),await this.tenantIDAuth(e)])}async apiKeyAuth(e){if(this.apiKey!=null)return ee([{"X-API-Key":this.apiKey}])}async tenantIDAuth(e){if(this.tenantID!=null)return ee([{"X-Tenant-Id":this.tenantID}])}stringifyQuery(e){return Pu(e)}getUserAgent(){return`${this.constructor.name}/JS ${Ot}`}defaultIdempotencyKey(){return`stainless-node-retry-${fa()}`}makeStatusError(e,r,n,i){return Te.generate(e,r,n,i)}buildURL(e,r,n){let i=!Hu(this,xa,"m",zu).call(this)&&n||this.baseURL,s=hu(e)?new URL(e):new URL(i+(i.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),o=this.defaultQuery(),c=Object.fromEntries(s.searchParams);return(!ma(o)||!ma(c))&&(r={...c,...o,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(s.search=this.stringifyQuery(r)),s.toString()}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(i=>({method:e,path:r,...i})))}request(e,r=null){return new tr(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){let i=await e,s=i.maxRetries??this.maxRetries;r==null&&(r=s),await this.prepareOptions(i);let{req:o,url:c,timeout:l}=await this.buildRequest(i,{retryCount:s-r});await this.prepareRequest(o,{url:c,options:i});let u="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=n===void 0?"":`, retryOf: ${n}`,f=Date.now();if(Me(this).debug(`[${u}] sending request`,_t({retryOfRequestLogID:n,method:i.method,url:c,options:i,headers:o.headers})),i.signal?.aborted)throw new Ct;let y=new AbortController,h=await this.fetchWithTimeout(c,o,l,y).catch(an),g=Date.now();if(h instanceof globalThis.Error){let w=`retrying, ${r} attempts remaining`;if(i.signal?.aborted)throw new Ct;let v=au(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(r)return Me(this).info(`[${u}] connection ${v?"timed out":"failed"} - ${w}`),Me(this).debug(`[${u}] connection ${v?"timed out":"failed"} (${w})`,_t({retryOfRequestLogID:n,url:c,durationMs:g-f,message:h.message})),this.retryRequest(i,r,n??u);throw Me(this).info(`[${u}] connection ${v?"timed out":"failed"} - error; no more retries left`),Me(this).debug(`[${u}] connection ${v?"timed out":"failed"} (error; no more retries left)`,_t({retryOfRequestLogID:n,url:c,durationMs:g-f,message:h.message})),v?new Wt:new yt({cause:h})}let b=`[${u}${d}] ${o.method} ${c} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${g-f}ms`;if(!h.ok){let w=await this.shouldRetry(h);if(r&&w){let C=`retrying, ${r} attempts remaining`;return await Su(h.body),Me(this).info(`${b} - ${C}`),Me(this).debug(`[${u}] response error (${C})`,_t({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:g-f})),this.retryRequest(i,r,n??u,h.headers)}let v=w?"error; no more retries left":"error; not retryable";Me(this).info(`${b} - ${v}`);let S=await h.text().catch(C=>an(C).message),p=_u(S),T=p?void 0:S;throw Me(this).debug(`[${u}] response error (${v})`,_t({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:T,durationMs:Date.now()-f})),this.makeStatusError(h.status,p,T,h.headers)}return Me(this).info(b),Me(this).debug(`[${u}] response start`,_t({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:g-f})),{response:h,options:i,controller:y,requestLogID:u,retryOfRequestLogID:n,startTime:f}}getAPIList(e,r,n){return this.requestAPIList(r,n&&"then"in n?n.then(i=>({method:"get",path:e,...i})):{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new dn(this,n,e)}async fetchWithTimeout(e,r,n,i){let{signal:s,method:o,...c}=r||{},l=this._makeAbort(i);s&&s.addEventListener("abort",l,{once:!0});let u=setTimeout(l,n),d=globalThis.ReadableStream&&c.body instanceof globalThis.ReadableStream||typeof c.body=="object"&&c.body!==null&&Symbol.asyncIterator in c.body,f={signal:i.signal,...d?{duplex:"half"}:{},method:"GET",...c};o&&(f.method=o.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(u)}}async shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,i){let s,o=i?.get("retry-after-ms");if(o){let l=parseFloat(o);Number.isNaN(l)||(s=l)}let c=i?.get("retry-after");if(c&&!s){let l=parseFloat(c);Number.isNaN(l)?s=Date.parse(c)-Date.now():s=l*1e3}if(s===void 0){let l=e.maxRetries??this.maxRetries;s=this.calculateDefaultRetryTimeoutMillis(r,l)}return await bu(s),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let s=r-e,o=Math.min(.5*Math.pow(2,s),16),c=1-Math.random()*.25;return o*c*1e3}async buildRequest(e,{retryCount:r=0}={}){let n={...e},{method:i,path:s,query:o,defaultBaseURL:c}=n,l=this.buildURL(s,o,c);"timeout"in n&&yu("timeout",n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:u,body:d}=this.buildBody({options:n}),f=await this.buildHeaders({options:e,method:i,bodyHeaders:u,retryCount:r});return{req:{method:i,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...n.fetchOptions??{}},url:l,timeout:n.timeout}}async buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:i}){let s={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),s[this.idempotencyHeader]=e.idempotencyKey);let o=ee([s,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(i),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...Tu()},await this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(o),o.values}_makeAbort(e){return()=>e.abort()}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=ee([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ha(e)}:typeof e=="object"&&n.values.get("content-type")==="application/x-www-form-urlencoded"?{bodyHeaders:{"content-type":"application/x-www-form-urlencoded"},body:this.stringifyQuery(e)}:Hu(this,yi,"f").call(this,{body:e,headers:n})}};Ia=K,yi=new WeakMap,xa=new WeakSet,zu=a(function(){return this.baseURL!=="https://api.smith.langchain.com/"},"_Langsmith_baseURLOverridden");Object.defineProperty(K,"Langsmith",{enumerable:!0,configurable:!0,writable:!0,value:Ia});Object.defineProperty(K,"DEFAULT_TIMEOUT",{enumerable:!0,configurable:!0,writable:!0,value:9e4});Object.defineProperty(K,"LangsmithError",{enumerable:!0,configurable:!0,writable:!0,value:$e});Object.defineProperty(K,"APIError",{enumerable:!0,configurable:!0,writable:!0,value:Te});Object.defineProperty(K,"APIConnectionError",{enumerable:!0,configurable:!0,writable:!0,value:yt});Object.defineProperty(K,"APIConnectionTimeoutError",{enumerable:!0,configurable:!0,writable:!0,value:Wt});Object.defineProperty(K,"APIUserAbortError",{enumerable:!0,configurable:!0,writable:!0,value:Ct});Object.defineProperty(K,"NotFoundError",{enumerable:!0,configurable:!0,writable:!0,value:Zt});Object.defineProperty(K,"ConflictError",{enumerable:!0,configurable:!0,writable:!0,value:Yt});Object.defineProperty(K,"RateLimitError",{enumerable:!0,configurable:!0,writable:!0,value:Qt});Object.defineProperty(K,"BadRequestError",{enumerable:!0,configurable:!0,writable:!0,value:qt});Object.defineProperty(K,"AuthenticationError",{enumerable:!0,configurable:!0,writable:!0,value:Kt});Object.defineProperty(K,"InternalServerError",{enumerable:!0,configurable:!0,writable:!0,value:er});Object.defineProperty(K,"PermissionDeniedError",{enumerable:!0,configurable:!0,writable:!0,value:Jt});Object.defineProperty(K,"UnprocessableEntityError",{enumerable:!0,configurable:!0,writable:!0,value:Xt});Object.defineProperty(K,"toFile",{enumerable:!0,configurable:!0,writable:!0,value:gi});K.Datasets=kt;K.Runs=Pt;K.Threads=ar;K.Traces=or;K.OnlineEvaluators=sr;K.Public=Mt;K.AnnotationQueues=bt;K.Info=nr;K.Issues=ir;K.Sandboxes=dt;var fn={CLICKHOUSE_ONLY:"clickhouse_only",SMITHDB_ONLY:"smithdb_only",DUAL:"dual"};function Gu(t){let e=t??{},r=!!(e.ch_query_enabled??!0),n=!!(e.sdb_query_enabled??!1);return!r&&n?fn.SMITHDB_ONLY:r&&n?fn.DUAL:fn.CLICKHOUSE_ONLY}a(Gu,"getQueryBackend");function bi(t){return`Invalid prompt identifier format: "${t}". Expected one of:
10
15
  - "prompt-name" (for private prompts)
11
16
  - "owner/prompt-name" (for prompts with explicit owner)
12
17
  - "prompt-name:commit-hash" (with commit reference)
13
- - "owner/prompt-name:commit-hash" (with owner and commit)`}o(Bn,"getInvalidPromptIdentifierMsg");var Bi=class extends Error{static{o(this,"LangSmithConflictError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},ji=class extends Error{static{o(this,"LangSmithNotFoundError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function Hi(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}o(Hi,"isLangSmithNotFoundError");async function U(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let c=new Error(`${t.status} ${t.statusText}`);throw c.status=t?.status,c}if(n===void 0)try{n=await t.text()}catch{n=""}let s=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new ji(s);if(t.status===409)throw new Bi(s);let i=new Error(s);throw i.status=t.status,i}o(U,"raiseForStatus");var Ed="ERR_CONFLICTING_ENDPOINTS",Fn=class extends Error{static{o(this,"ConflictingEndpointsError")}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:Ed}),this.name="ConflictingEndpointsError"}};function wd(t){return typeof t=="object"&&t!==null&&t.code===Ed}o(wd,"isConflictingEndpointsError");function ct(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(Bn(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[s,i]=e.split("/",2);if(!s||!i)throw new Error(Bn(t));return[s,i,n]}else{if(!e)throw new Error(Bn(t));return["-",e,n]}}o(ct,"parsePromptIdentifier");var Td="[...]",jb={result:"[Circular]"},Hn=[],Qt=[],Hb=new TextEncoder;function Gb(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}o(Gb,"defaultOptions");function jn(t){return Hb.encode(t)}o(jn,"encodeString");function vd(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}o(vd,"serializeWellKnownTypes");function zb(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return vd(r)}}o(zb,"createDefaultReplacer");function Pe(t,e,r,n,s){try{let i=JSON.stringify(t,zb(r),n);return jn(i)}catch(i){if(!i.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
14
- Context: ${e}`:""}`),jn("[Unserializable]");te("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
15
- Context: ${e}`:""}`),typeof s>"u"&&(s=Gb()),zi(t,"",0,[],void 0,0,s);let a;try{Qt.length===0?a=JSON.stringify(t,r,n):a=JSON.stringify(t,Vb(r),n)}catch{return jn("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;Hn.length!==0;){let c=Hn.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return jn(a)}}o(Pe,"serialize");function Gi(t,e,r,n){var s=Object.getOwnPropertyDescriptor(n,r);s.get!==void 0?s.configurable?(Object.defineProperty(n,r,{value:t}),Hn.push([n,r,e,s])):Qt.push([e,r,t]):(n[r]=t,Hn.push([n,r,e]))}o(Gi,"setReplace");function zi(t,e,r,n,s,i,a){i+=1;var c;if(typeof t=="object"&&t!==null){for(c=0;c<n.length;c++)if(n[c]===t){Gi(jb,t,e,s);return}if(typeof a.depthLimit<"u"&&i>a.depthLimit){Gi(Td,t,e,s);return}if(typeof a.edgesLimit<"u"&&r+1>a.edgesLimit){Gi(Td,t,e,s);return}if(n.push(t),Array.isArray(t))for(c=0;c<t.length;c++)zi(t[c],c,c,n,t,i,a);else{t=vd(t);var l=Object.keys(t);for(c=0;c<l.length;c++){var u=l[c];zi(t[u],u,c,n,t,i,a)}}n.pop()}}o(zi,"decirc");function Vb(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Qt.length>0)for(var n=0;n<Qt.length;n++){var s=Qt[n];if(s[1]===e&&s[0]===r){r=s[2],Qt.splice(n,1);break}}return t.call(this,e,r)}}o(Vb,"replaceGetterValues");function Sd(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}o(Sd,"_ensureUTCTimestamp");function Or(t){return{...t,start_time:Sd(t.start_time),end_time:Sd(t.end_time)}}o(Or,"_normalizeRunTimestamps");function Id(t,e,r){if(r)return t;let n=wn(),s=e??ci(),i=t.extra??{},a=i.metadata;return t.extra={...i,runtime:{...n,...i?.runtime},metadata:{...s,...s.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??s.revision_id}:{},...a}},t}o(Id,"mergeRuntimeEnvIntoRun");var Wb=o(t=>{let e=t?.toString()??te("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},"getTracingSamplingRate"),qb=o(t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"},"isLocalhost");async function Kb(t){let e=[];for await(let r of t)e.push(r);return e}o(Kb,"toArray");function Gn(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}o(Gn,"trimQuotes");var Zb=o(async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1},"handle429");function xd(t){return typeof t=="number"?Number(t.toFixed(4)):t}o(xd,"_formatFeedbackScore");var Jb=24*1024*1024,Rd=1024*1024*1024,Yb=1e4,Xb=100,Ad="https://api.smith.langchain.com",Vi=class{static{o(this,"AutoBatchQueue")}constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??Rd}peek(){return this.items[0]}push(e){let r,n=new Promise(i=>{r=i}),s=Pe(e.item,`Serializing run with id: ${e.item.id}`).length;return this.sizeBytes+s>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${s} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,itemPromiseResolve:r,itemPromise:n,size:s}),this.sizeBytes+=s,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],s=0;for(;s+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let i=this.items.shift();i&&(n.push(i),s+=i.size,this.sizeBytes-=i.size)}if(n.length===0&&this.items.length>0){let i=this.items.shift();n.push(i),s+=i.size,this.sizeBytes-=i.size}return[n.map(i=>({action:i.action,item:i.payload,otelContext:i.otelContext,apiKey:i.apiKey,apiUrl:i.apiUrl,size:i.size})),()=>n.forEach(i=>i.itemPromiseResolve())]}},vt=class t{static{o(this,"Client")}get _fetch(){return this.fetchImplementation||rl(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,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"settings",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"blockOnRootRunFinalization",{enumerable:!0,configurable:!0,writable:!0,value:Be("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,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:te("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:Be("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig();if(this.tracingSampleRate=Wb(e.tracingSamplingRate),this.apiUrl=Gn(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1)),this.apiKey=Gn(e.apiKey??r.apiKey),this.webUrl=Gn(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Gn(e.workspaceId??te("WORKSPACE_ID")),this.timeout_ms=e.timeout_ms??9e4,this.caller=new Tr({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=te("FAILED_TRACES_DIR")||void 0;let n=te("FAILED_TRACES_MAX_MB");if(n){let i=parseInt(n,10);Number.isFinite(i)&&i>0&&(this.failedTracesMaxBytes=i*1024*1024)}let s=e.maxIngestMemoryBytes??Rd;this.batchIngestCaller=new Tr({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:Zb,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new Vi(s),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit,this.fetchOptions=e.fetchOptions||{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,Tn()&&(this.langSmithToOTELTranslator=new Sn),this.cachedLSEnvVarsForMetadata=ci(),e.cache!==void 0&&e.disablePromptCache&&Pt("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(Pt("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=bn:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=bn)}static getDefaultClientConfig(){let e=te("API_KEY"),r=te("ENDPOINT")??Ad,n=te("HIDE_INPUTS")==="true",s=te("HIDE_OUTPUTS")==="true";return{apiUrl:r,apiKey:e,webUrl:void 0,hideInputs:n,hideOutputs:s}}getHostUrl(){return this.webUrl?this.webUrl:qb(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get headers(){let e={"User-Agent":`langsmith-js/${En}`};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){let r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r}async _getResponse(e,r){let n=r?.toString()??"",s=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let a=await this._fetch(s,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,`fetch ${e}`),a})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let s=Number(r.get("offset"))||0,i=Number(r.get("limit"))||100;for(;;){r.set("offset",String(s)),r.set("limit",String(i));let a=`${this.apiUrl}${e}?${r}`,c=await this.caller.call(async()=>{let u=await this._fetch(a,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(u,`fetch ${e}`),u}),l=n?n(await c.json()):await c.json();if(l.length===0||(yield l,l.length<i))break;s+=l.length}}async*_getCursorPaginatedList(e,r=null,n="POST",s="runs"){let i=r?{...r}:{};for(;;){let a=JSON.stringify(i),l=await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(d,`fetch ${e}`),d})).json();if(!l||!l[s])break;yield l[s];let u=l.cursors;if(!u||!u.next)break;i.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){let n=[];for(let s of e)this.filteredPostUuids.has(s.trace_id)?s.id===s.trace_id&&this.filteredPostUuids.delete(s.trace_id):n.push(s);return n}else{let n=[];for(let s of e){let i=s.trace_id??s.id;this.filteredPostUuids.has(i)||(s.id===i?this._shouldSample()?n.push(s):this.filteredPostUuids.add(i):n.push(s))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Jb}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??Xb}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[s,i]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!s.length){i();break}let a=s.reduce((u,d)=>{let p=d.apiUrl??this.apiUrl,_=d.apiKey??this.apiKey,y=d.apiKey===this.apiKey&&d.apiUrl===this.apiUrl?"default":`${p}|${_}`;return u[y]||(u[y]=[]),u[y].push(d),u},{}),c=[];for(let[u,d]of Object.entries(a)){let p=this._processBatch(d,{apiUrl:u==="default"?void 0:u.split("|")[0],apiKey:u==="default"?void 0:u.split("|")[1]});c.push(p)}let l=Promise.all(c).finally(i);n.push(l)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,s,i){try{let a=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),c=JSON.stringify({version:1,endpoint:s,headers:n,body_base64:a.toString("base64")}),l=`trace_${Date.now()}_${kt().slice(0,8)}.json`,u=wr.join(e,l);if(t._fallbackDirsCreated.has(e)||(await gl(e),t._fallbackDirsCreated.add(e)),i!==void 0&&i>0)try{let p=(await _l(e)).filter(g=>g.startsWith("trace_")&&g.endsWith(".json")),_=0;for(let g of p){let{size:y}=await bl(wr.join(e,g));_+=y}if(_>=i){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${_} bytes >= ${i} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await yl(u,c),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(a){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,a)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((s,i)=>s+(i.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let s={runCreates:e.filter(c=>c.action==="create").map(c=>c.item),runUpdates:e.filter(c=>c.action==="update").map(c=>c.item)},i=await this._ensureServerInfo();if(!this._multipartDisabled&&(i?.batch_ingest_config?.use_multipart_endpoint??!0)){let c=!this._runCompressionDisabled&&i?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(s,{...r,useGzip:c,sizeBytes:n})}catch(l){if(Hi(l))this._multipartDisabled=!0,await this.batchIngestRuns(s,{...r,sizeBytes:n});else throw l}}else await this.batchIngestRuns(s,{...r,sizeBytes:n})}}catch(s){console.error("Error exporting batch:",s)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let s of e)s.item.id&&s.otelContext&&(r.set(s.item.id,s.otelContext),s.action==="create"?n.push({operation:"post",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}):n.push({operation:"patch",id:s.item.id,trace_id:s.item.trace_id??s.item.id,run:s.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=Id(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),s=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>s)&&this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s}),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:s})},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{Accept:"application/json"},signal:AbortSignal.timeout(Yb),...this.fetchOptions});return await U(n,"get server info"),n})).json();return this.debug&&console.log(`
18
+ - "owner/prompt-name:commit-hash" (with owner and commit)`}a(bi,"getInvalidPromptIdentifierMsg");var Aa=class extends Error{static{a(this,"LangSmithConflictError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithConflictError",this.status=409}},Ca=class extends Error{static{a(this,"LangSmithNotFoundError")}constructor(e){super(e),Object.defineProperty(this,"status",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name="LangSmithNotFoundError",this.status=404}};function wi(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithNotFoundError"}a(wi,"isLangSmithNotFoundError");function Vu(t){return t!=null&&typeof t=="object"&&"name"in t&&t?.name==="LangSmithConflictError"}a(Vu,"isLangSmithConflictError");async function L(t,e,r){let n;if(t.ok){r&&(n=await t.text());return}if(t.status===403)try{(await t.json())?.error==="org_scoped_key_requires_workspace"&&(n="This API key is org-scoped and requires workspace specification. Please provide 'workspaceId' parameter, or set LANGSMITH_WORKSPACE_ID environment variable.")}catch{let c=new Error(`${t.status} ${t.statusText}`);throw c.status=t?.status,c}if(n===void 0)try{n=await t.text()}catch{n=""}let i=`Failed to ${e}. Received status [${t.status}]: ${t.statusText}. Message: ${n}`;if(t.status===404)throw new Ca(i);if(t.status===409)throw new Aa(i);let s=new Error(i);throw s.status=t.status,s}a(L,"raiseForStatus");var Wu="ERR_CONFLICTING_ENDPOINTS",_i=class extends Error{static{a(this,"ConflictingEndpointsError")}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:Wu}),this.name="ConflictingEndpointsError"}};function qu(t){return typeof t=="object"&&t!==null&&t.code===Wu}a(qu,"isConflictingEndpointsError");function Ce(t){if(!t||t.split("/").length>2||t.startsWith("/")||t.endsWith("/")||t.split(":").length>2)throw new Error(bi(t));let[e,r]=t.split(":"),n=r||"latest";if(e.includes("/")){let[i,s]=e.split("/",2);if(!i||!s)throw new Error(bi(t));return[i,s,n]}else{if(!e)throw new Error(bi(t));return["-",e,n]}}a(Ce,"parseHubIdentifier");var iy=10,sy=1e4,Ku="created_at";function ay(t){return new Promise(e=>setTimeout(e,t))}a(ay,"sleep");function oy(t){return typeof t=="object"&&t!==null&&t.code==="EEXIST"}a(oy,"isEEXIST");function Ju(t){try{return Vt(Qe.join(t,Ku)).split(`
19
+ `)}catch{return}}a(Ju,"lockMetadataLines");function cy(t){let e=Ju(t);if(e&&e[0]&&e[0].trim()){let r=Date.parse(e[0].trim());if(!Number.isNaN(r))return r}return su(t)}a(cy,"lockCreatedAtMs");function ly(t){let e=Ju(t);if(e&&e.length>=2&&e[1].trim())return e[1].trim()}a(ly,"lockOwner");async function uy(t){let e=cy(t);return e===void 0||Date.now()-e<=sy?!1:(await Yn(t),!0)}a(uy,"removeStaleLock");async function Zu(t,e){let r=`${t}.oauth.lock.lock`,n=Qe.dirname(r);n&&await Zn(n);let i=globalThis.crypto.randomUUID();for(;;){try{await iu(r)}catch(s){if(!oy(s))throw s;if(!await uy(r)){if(Date.now()>=e)throw new Error("timed out acquiring OAuth refresh lock");await ay(Math.min(iy,Math.max(0,e-Date.now())))}continue}try{await Ir(Qe.join(r,Ku),`${new Date().toISOString()}
20
+ ${i}
21
+ `)}catch(s){throw await Yn(r),s}break}return{async release(){ly(r)===i&&await Yn(r)}}}a(Zu,"acquireOAuthRefreshLock");var Ei="https://api.smith.langchain.com",dy="langsmith-cli",fy=6e4,py=1e4;function my(){let t=on();return t==="browser"||t==="webworker"}a(my,"isBrowserLikeRuntime");function hy(){let t=ye("LANGSMITH_CONFIG_FILE");if(t)return t;let e=ye("HOME")??ye("USERPROFILE");if(e)return Qe.join(e,".langsmith","config.json")}a(hy,"getProfileConfigPath");function gy(t){let e=ye("LANGSMITH_PROFILE");if(e)return e;if(t.current_profile)return t.current_profile;if(t.profiles?.default)return"default"}a(gy,"resolveProfileName");function yy(){if(my())return;let t=hy();if(!(!t||!Ar(t)))try{let e=JSON.parse(Vt(t)),r=gy(e),n=r?e.profiles?.[r]:void 0;return!r||!n?void 0:{configPath:t,config:e,profileName:r,profile:n}}catch{return}}a(yy,"loadProfileState");function We(t){return t!=null&&t.trim()!==""}a(We,"hasValue");function Nt(t){return t?.trim().replace(/^["']|["']$/g,"")}a(Nt,"trimConfigValue");function Yu(t){let e=t.oauth;if(!e?.refresh_token)return!1;if(!e.access_token)return!0;if(!e.expires_at)return!1;let r=Date.parse(e.expires_at);return Number.isNaN(r)?!1:r<=Date.now()+fy}a(Yu,"shouldRefreshProfileToken");function _y(t){let e=t;for(;e.endsWith("/");)e=e.slice(0,-1);let r="/api/v1";return e.endsWith(r)?e.slice(0,-r.length):e}a(_y,"normalizeConfigUrl");function by(t,e){t.oauth??={},e.access_token&&(t.oauth.access_token=e.access_token),e.refresh_token&&(t.oauth.refresh_token=e.refresh_token),typeof e.expires_in=="number"&&e.expires_in>0&&(t.oauth.expires_at=new Date(Date.now()+e.expires_in*1e3).toISOString())}a(by,"applyTokenResponse");function Xu(t){return t.reason??new Error("The operation was aborted.")}a(Xu,"getAbortReason");async function wy(t,e){if(!e)return t;if(e.aborted)throw Xu(e);let r,n=new Promise((i,s)=>{let o=a(()=>{s(Xu(e))},"onAbort");e.addEventListener("abort",o,{once:!0}),r=a(()=>{e.removeEventListener("abort",o)},"cleanup")});try{return await Promise.race([t,n])}finally{r?.()}}a(wy,"waitForAbortSignal");function Qu(){let t=yy(),e=t?.profile;if(!t||!e)return{};let r=Nt(e.api_key),n=Nt(e.oauth?.access_token),i=Nt(e.oauth?.refresh_token);return{apiUrl:e.api_url,apiKey:r,workspaceId:e.workspace_id,oauthAccessToken:n,oauthRefreshToken:i,profileAuth:r||n||i?new Ra(t):void 0}}a(Qu,"loadProfileClientConfig");var Ra=class{static{a(this,"ProfileAuth")}constructor(e){Object.defineProperty(this,"state",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"refreshPromise",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"managedAuthorizationValue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.rememberProfileAuthHeader(this.currentAuthHeader())}currentAuthHeader(){let e=Ey(this.state.profile);return this.rememberProfileAuthHeader(e),e}async getAuthHeader(e,r){Yu(this.state.profile)&&(this.refreshPromise||(this.refreshPromise=this.refreshOAuthToken(e).finally(()=>{this.refreshPromise=void 0})),await wy(this.refreshPromise,r));let n=ed(this.state.profile);return this.rememberProfileAuthHeader(n),n}isProfileAuthorizationHeader(e){return e===this.managedAuthorizationValue}reloadProfile(){try{let e=JSON.parse(Vt(this.state.configPath)),r=e.profiles?.[this.state.profileName];return r?(this.state.config=e,this.state.profile=r,r):void 0}catch{return}}async refreshOAuthToken(e){let r=this.state.profile.oauth?.refresh_token;if(!r)return;let n=Nt(this.state.profile.api_url)??Ei,i=Date.now()+py,s;try{if(s=await Zu(this.state.configPath,i),this.reloadProfile()&&!Yu(this.state.profile))return;let c=new URLSearchParams({grant_type:"refresh_token",client_id:dy,refresh_token:this.state.profile.oauth?.refresh_token??r}),l=await e(`${_y(n)}/oauth/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:c.toString(),signal:AbortSignal.timeout(Math.max(0,i-Date.now()))});if(!l.ok)return;let u=await l.json();if(!u.access_token)return;by(this.state.profile,u),this.state.config.profiles??={},this.state.config.profiles[this.state.profileName]=this.state.profile,await Ir(this.state.configPath,`${JSON.stringify(this.state.config,null,2)}
22
+ `)}catch{return}finally{await s?.release()}}rememberProfileAuthHeader(e){this.managedAuthorizationValue=e?.name==="Authorization"?e.value:void 0}};function Ey(t){let e=Nt(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};if(!Nt(t.oauth?.refresh_token))return ed(t)}a(Ey,"currentAuthHeaderFromProfile");function ed(t){let e=Nt(t.oauth?.access_token);if(e)return{name:"Authorization",value:`Bearer ${e}`};let r=Nt(t.api_key);if(r)return{name:"x-api-key",value:r}}a(ed,"authHeaderFromProfile");var td="[...]",Ty={result:"[Circular]"},vi=[],Fr=[],vy=new TextEncoder;function Sy(){return{depthLimit:Number.MAX_SAFE_INTEGER,edgesLimit:Number.MAX_SAFE_INTEGER}}a(Sy,"defaultOptions");function Ti(t){return vy.encode(t)}a(Ti,"encodeString");function rd(t){if(t&&typeof t=="object"&&t!==null){if(t instanceof Map)return Object.fromEntries(t);if(t instanceof Set)return Array.from(t);if(t instanceof Date)return t.toISOString();if(t instanceof RegExp)return t.toString();if(t instanceof Error)return{name:t.name,message:t.message}}else if(typeof t=="bigint")return t.toString();return t}a(rd,"serializeWellKnownTypes");function xy(t){return function(e,r){if(t){let n=t.call(this,e,r);if(n!==void 0)return n}return rd(r)}}a(xy,"createDefaultReplacer");function nd(t){try{let i=function(d){let f=n(d);return f>r&&(r=f),f+2},s=function(d){return d===0?2:2+d*4},o=function(d){return d===void 0||typeof d=="function"||typeof d=="symbol"},c=function(d){return d===void 0||typeof d=="function"||typeof d=="symbol"?4:l(d)},l=function(d){if(d===null)return 4;if(d===void 0)return 0;let f=typeof d;if(f==="boolean")return 5;if(f==="number")return Number.isFinite(d)?d.toString().length:4;if(f==="bigint")return d.toString().length+2;if(f==="string")return i(d);if(f==="function"||f==="symbol")return 0;let y=d;if(y instanceof Date)return 26;if(y instanceof RegExp)return n(y.toString())+2;if(y instanceof Error){let g=y.name??"",b=y.message??"";return 22+n(g)+n(b)}if(typeof Buffer<"u"&&y instanceof Buffer)return 28+s(y.byteLength);if(ArrayBuffer.isView(y)){if(y instanceof DataView)return 2;let g=y.length??0,w=y instanceof Float32Array||y instanceof Float64Array?30:12;return 2+g*w}if(y instanceof ArrayBuffer)return 2;if(e.has(y))return 24;if(typeof y.toJSON=="function"){let g;try{g=y.toJSON("")}catch{return 16}e.add(y);let b=l(g);return e.delete(y),b}e.add(y);let h;if(Array.isArray(y)){h=2;let g=y.length;for(let b=0;b<g;b++)h+=c(y[b]),b<g-1&&(h+=1)}else if(y instanceof Map){h=2;let g=0;for(let[b,w]of y){if(o(w))continue;g>0&&(h+=1);let v=typeof b=="string"?b:String(b);h+=n(v)+3,h+=l(w),g++}}else if(y instanceof Set){h=2;let g=0;for(let b of y)g>0&&(h+=1),h+=c(b),g++}else{h=2;let g=0,b=Object.keys(y);for(let w=0;w<b.length;w++){let v=b[w],S=y[v];o(S)||(g>0&&(h+=1),h+=n(v)+3,h+=l(S),g++)}}return e.delete(y),h};a(i,"estimateString"),a(s,"estimateByteArrayJson"),a(o,"isDropped"),a(c,"estimateInArray"),a(l,"estimate");let e=new Set,r=0,n=typeof Buffer<"u"&&typeof Buffer.byteLength=="function"?d=>Buffer.byteLength(d,"utf8"):d=>d.length;return{size:l(t),maxStringLen:r}}catch{return{size:Re(t).length,maxStringLen:0}}}a(nd,"estimateSerializedSize");function Re(t,e,r,n,i){try{let s=JSON.stringify(t,xy(r),n);return Ti(s)}catch(s){if(!s.message?.includes("Converting circular structure to JSON"))return console.warn(`[WARNING]: LangSmith received unserializable value.${e?`
23
+ Context: ${e}`:""}`),Ti("[Unserializable]");Z("SUPPRESS_CIRCULAR_JSON_WARNINGS")!=="true"&&console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${e?`
24
+ Context: ${e}`:""}`),typeof i>"u"&&(i=Sy()),ka(t,"",0,[],void 0,0,i);let o;try{Fr.length===0?o=JSON.stringify(t,r,n):o=JSON.stringify(t,Iy(r),n)}catch{return Ti("[unable to serialize, circular reference is too complex to analyze]")}finally{for(;vi.length!==0;){let c=vi.pop();c.length===4?Object.defineProperty(c[0],c[1],c[3]):c[0][c[1]]=c[2]}}return Ti(o)}}a(Re,"serialize");function Oa(t,e,r,n){var i=Object.getOwnPropertyDescriptor(n,r);i.get!==void 0?i.configurable?(Object.defineProperty(n,r,{value:t}),vi.push([n,r,e,i])):Fr.push([e,r,t]):(n[r]=t,vi.push([n,r,e]))}a(Oa,"setReplace");function ka(t,e,r,n,i,s,o){s+=1;var c;if(typeof t=="object"&&t!==null){for(c=0;c<n.length;c++)if(n[c]===t){Oa(Ty,t,e,i);return}if(typeof o.depthLimit<"u"&&s>o.depthLimit){Oa(td,t,e,i);return}if(typeof o.edgesLimit<"u"&&r+1>o.edgesLimit){Oa(td,t,e,i);return}if(n.push(t),Array.isArray(t))for(c=0;c<t.length;c++)ka(t[c],c,c,n,t,s,o);else{t=rd(t);var l=Object.keys(t);for(c=0;c<l.length;c++){var u=l[c];ka(t[u],u,c,n,t,s,o)}}n.pop()}}a(ka,"decirc");function Iy(t){return t=typeof t<"u"?t:function(e,r){return r},function(e,r){if(Fr.length>0)for(var n=0;n<Fr.length;n++){var i=Fr[n];if(i[1]===e&&i[0]===r){r=i[2],Fr.splice(n,1);break}}return t.call(this,e,r)}}a(Iy,"replaceGetterValues");var id=require("node:worker_threads"),Ma=id.Worker,sd=!0;var Ay=`
25
+ const { parentPort } = require("worker_threads");
26
+
27
+ const CIRCULAR_REPLACE_NODE = { result: "[Circular]" };
28
+
29
+ function serializeWellKnownTypes(val) {
30
+ if (val && typeof val === "object") {
31
+ if (val instanceof Map) return Object.fromEntries(val);
32
+ if (val instanceof Set) return Array.from(val);
33
+ if (val instanceof Date) return val.toISOString();
34
+ if (val instanceof RegExp) return val.toString();
35
+ if (val instanceof Error) return { name: val.name, message: val.message };
36
+ } else if (typeof val === "bigint") {
37
+ return val.toString();
38
+ }
39
+ return val;
40
+ }
41
+
42
+ function defaultReplacer(_key, val) {
43
+ return serializeWellKnownTypes(val);
44
+ }
45
+
46
+ // Decirculate in-place: replace circular refs with { result: "[Circular]" }
47
+ // then restore after stringify. Mirrors fast-safe-stringify's decirc().
48
+ const restoreStack = [];
49
+ function decirc(val, k, stack, parent) {
50
+ if (typeof val === "object" && val !== null) {
51
+ for (let i = 0; i < stack.length; i++) {
52
+ if (stack[i] === val) {
53
+ const orig = parent[k];
54
+ parent[k] = CIRCULAR_REPLACE_NODE;
55
+ restoreStack.push([parent, k, orig]);
56
+ return;
57
+ }
58
+ }
59
+ stack.push(val);
60
+ if (Array.isArray(val)) {
61
+ for (let i = 0; i < val.length; i++) decirc(val[i], i, stack, val);
62
+ } else {
63
+ const normalized = serializeWellKnownTypes(val);
64
+ // Only recurse into normalized if it's still an object (arrays/objects),
65
+ // else it was replaced with a primitive (e.g. Date -> string).
66
+ if (normalized === val) {
67
+ const keys = Object.keys(val);
68
+ for (let i = 0; i < keys.length; i++) decirc(val[keys[i]], keys[i], stack, val);
69
+ }
70
+ }
71
+ stack.pop();
72
+ }
73
+ }
74
+
75
+ function serialize(obj) {
76
+ try {
77
+ return JSON.stringify(obj, defaultReplacer);
78
+ } catch (e) {
79
+ if (!String(e && e.message).includes("Converting circular structure to JSON")) {
80
+ return "[Unserializable]";
81
+ }
82
+ decirc(obj, "", [], { "": obj });
83
+ try {
84
+ return JSON.stringify(obj, defaultReplacer);
85
+ } catch (_) {
86
+ return "[unable to serialize, circular reference is too complex to analyze]";
87
+ } finally {
88
+ while (restoreStack.length) {
89
+ const [p, k, v] = restoreStack.pop();
90
+ p[k] = v;
91
+ }
92
+ }
93
+ }
94
+ }
95
+
96
+ parentPort.on("message", (msg) => {
97
+ const { id, op, payload } = msg;
98
+ try {
99
+ if (op === "serialize") {
100
+ const str = serialize(payload);
101
+ const buf = Buffer.from(str, "utf8");
102
+ // Slice into its own ArrayBuffer so we can transfer without dragging
103
+ // unrelated bytes from any shared pool buffer.
104
+ const ab = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
105
+ parentPort.postMessage({ id, bytes: ab, length: buf.byteLength }, [ab]);
106
+ } else if (op === "ping") {
107
+ parentPort.postMessage({ id });
108
+ } else {
109
+ parentPort.postMessage({ id, error: "unknown op: " + op });
110
+ }
111
+ } catch (e) {
112
+ parentPort.postMessage({ id, error: String((e && e.message) || e) });
113
+ }
114
+ });
115
+ `,Na=class{static{a(this,"SerializeWorker")}constructor(){Object.defineProperty(this,"worker",{enumerable:!0,configurable:!0,writable:!0,value:null}),Object.defineProperty(this,"nextId",{enumerable:!0,configurable:!0,writable:!0,value:1}),Object.defineProperty(this,"pending",{enumerable:!0,configurable:!0,writable:!0,value:new Map}),Object.defineProperty(this,"disabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"startPromise",{enumerable:!0,configurable:!0,writable:!0,value:null})}async ensureStarted(){if(this.disabled)return!1;if(this.worker!==null)return!0;if(this.startPromise!==null)return this.startPromise;this.startPromise=this._start();try{return await this.startPromise}finally{this.startPromise=null}}async _start(){if(!sd||Ma===null)return this.disabled=!0,!1;try{let e=new Ma(Ay,{eval:!0});return e.on("message",r=>{let n=this.pending.get(r.id);n&&(this.pending.delete(r.id),r.error?n.reject(new Error(r.error)):r.bytes&&typeof r.length=="number"?n.resolve(new Uint8Array(r.bytes,0,r.length)):n.reject(new Error("worker returned malformed message")))}),e.on("error",r=>{for(let[,n]of this.pending)n.reject(r);this.pending.clear(),this.disabled=!0,this.worker=null}),e.on("exit",r=>{for(let[,n]of this.pending)n.reject(new Error(`worker exited with code ${r}`));this.pending.clear(),this.worker=null}),e.unref(),this.worker=e,!0}catch{return this.disabled=!0,!1}}async serialize(e){if(!await this.ensureStarted())return null;let n=this.nextId++;return new Promise((i,s)=>{this.pending.set(n,{resolve:i,reject:s});try{this.worker.postMessage({id:n,op:"serialize",payload:e})}catch(o){this.pending.delete(n),s(o)}})}async terminate(){this.worker&&(await this.worker.terminate(),this.worker=null);for(let[,e]of this.pending)e.reject(new Error("worker terminated"));this.pending.clear()}},Pa=null;function ad(){return Pa===null&&(Pa=new Na),Pa}a(ad,"getSharedSerializeWorker");var Cy=64*1024,Ry=2048;function od(t,e=Cy,r=Ry){if(t===null||typeof t!="object")return typeof t=="string"&&t.length>=e;let n=[t],i=new Set,s=0;for(;n.length>0;){if(s++>=r)return!1;let o=n.pop();if(o==null)continue;let c=typeof o;if(c==="string"){if(o.length>=e)return!0;continue}if(c!=="object")continue;let l=o;if(i.has(l)||(i.add(l),l instanceof Date||l instanceof RegExp||l instanceof Error||l instanceof ArrayBuffer||ArrayBuffer.isView(l)))continue;if(Array.isArray(l)){for(let d=l.length-1;d>=0;d--)n.push(l[d]);continue}if(l instanceof Map){for(let[,d]of l)n.push(d);continue}if(l instanceof Set){for(let d of l)n.push(d);continue}let u=Object.keys(l);for(let d=u.length-1;d>=0;d--)n.push(l[u[d]])}return!1}a(od,"hasLargeString");function Oy(t,e){let[r]=Ce(t);if(r!=="-"&&!e)throw new Error("Pulling a public prompt by owner/name is disabled by default because prompts may contain untrusted serialized LangChain objects. If you trust this prompt, set `dangerouslyPullPublicPrompt: true` to acknowledge the risk.")}a(Oy,"assertPullPublicPromptAllowed");function cd(t){return typeof t=="string"&&t.length>0&&!t.includes("Z")&&!t.includes("+")&&!t.includes("-",10)?t+"Z":t}a(cd,"_ensureUTCTimestamp");function Br(t){return{...t,start_time:cd(t.start_time),end_time:cd(t.end_time)}}a(Br,"_normalizeRunTimestamps");function ld(t,e,r){if(r)return t;let n=ti(),i=e??Qs(),s=t.extra??{},o=s.metadata;return t.extra={...s,runtime:{...n,...s?.runtime},metadata:{...i,...i.revision_id||"revision_id"in t&&t.revision_id?{revision_id:("revision_id"in t?t.revision_id:void 0)??i.revision_id}:{},...o}},t}a(ld,"mergeRuntimeEnvIntoRun");var ky=a(t=>{let e=t?.toString()??Z("TRACING_SAMPLING_RATE");if(e===void 0)return;let r=parseFloat(e);if(r<0||r>1)throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${r}`);return r},"getTracingSamplingRate"),My=a(t=>{let r=t.replace("http://","").replace("https://","").split("/")[0].split(":")[0];return r==="localhost"||r==="127.0.0.1"||r==="::1"},"isLocalhost");async function Py(t){let e=[];for await(let r of t)e.push(r);return e}a(Py,"toArray");function Si(t){if(t!==void 0)return t.trim().replace(/^"(.*)"$/,"$1").replace(/^'(.*)'$/,"$1")}a(Si,"trimQuotes");var Ny=a(async t=>{if(t?.status===429){let e=parseInt(t.headers.get("retry-after")??"10",10)*1e3;if(e>0)return await new Promise(r=>setTimeout(r,e)),!0}return!1},"handle429");function ud(t){return typeof t=="number"?Number(t.toFixed(4)):t}a(ud,"_formatFeedbackScore");function Ly(t,e){if(!t)return;let r=a(u=>u.split(".").map(d=>parseInt(d,10)),"parse"),[n,i,s]=r(t),[o,c,l]=r(e);if(isNaN(n)||isNaN(i)||isNaN(s)||isNaN(o)||isNaN(c)||isNaN(l)){console.warn(`[LANGSMITH]: Could not parse backend version ${JSON.stringify(t)} for compatibility check.`);return}(n<o||n===o&&i<c||n===o&&i===c&&s<l)&&console.warn(`[LANGSMITH]: Backend version ${JSON.stringify(t)} is older than the minimum version required by this SDK (${JSON.stringify(e)}). Some features may not work as expected. See https://docs.langchain.com/langsmith/smithdb-sdk-migration`)}a(Ly,"_checkBackendVersion");var Dy=24*1024*1024,md=1024*1024*1024,Uy=1e4,$y=100;function hd(t,e){new Headers({[t]:e})}a(hd,"assertValidHeader");function dd(t){for(let[e,r]of Object.entries(t??{}))hd(e,r)}a(dd,"assertValidHeaders");function fd(t){if(!t)return{};let e=t instanceof Headers?[...t.entries()]:Array.isArray(t)?t.map(([i,s])=>[i,s]):Object.entries(t),r={},n=new Map;for(let[i,s]of e){hd(i,s);let o=i.toLowerCase(),c=n.get(o);c===void 0?(n.set(o,i),r[i]=s):r[c]=s}return r}a(fd,"normalizeHeaders");function Fy(t,e,r){let n={...t},i=new Map(Object.keys(n).map(s=>[s.toLowerCase(),s]));for(let[s,o]of Object.entries(e)){let c=s.toLowerCase();n[i.get(c)??s]=o}for(let s of Object.keys(n))r.has(s.toLowerCase())&&delete n[s];return n}a(Fy,"mergeCallerHeaders");var La=class{static{a(this,"AutoBatchQueue")}constructor(e){Object.defineProperty(this,"items",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"sizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:0}),Object.defineProperty(this,"maxSizeBytes",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxSizeBytes=e??md}peek(){return this.items[0]}push(e){let r,n=new Promise(s=>{r=s}),i=nd(e.item).size;return this.sizeBytes+i>this.maxSizeBytes&&this.items.length>0?(console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${e.item.id}. Current queue size: ${this.sizeBytes} bytes, attempted addition: ${i} bytes.`),r(),n):(this.items.push({action:e.action,payload:e.item,otelContext:e.otelContext,apiKey:e.apiKey,apiUrl:e.apiUrl,workspaceId:e.workspaceId,itemPromiseResolve:r,itemPromise:n,size:i}),this.sizeBytes+=i,n)}pop({upToSizeBytes:e,upToSize:r}){if(e<1)throw new Error("Number of bytes to pop off may not be less than 1.");let n=[],i=0;for(;i+(this.peek()?.size??0)<e&&this.items.length>0&&n.length<r;){let s=this.items.shift();s&&(n.push(s),i+=s.size,this.sizeBytes-=s.size)}if(n.length===0&&this.items.length>0){let s=this.items.shift();n.push(s),i+=s.size,this.sizeBytes-=s.size}return[n.map(s=>({action:s.action,item:s.payload,otelContext:s.otelContext,apiKey:s.apiKey,apiUrl:s.apiUrl,workspaceId:s.workspaceId,size:s.size})),()=>n.forEach(s=>s.itemPromiseResolve())]}},Rt=class t{static{a(this,"Client")}get tracingMode(){return this._tracingMode}get _fetch(){let e=this.fetchImplementation||Ul(this.debug);return(async(r,n)=>{let i,s=this.getProfileManagedAuthorizationHeader(n);return this.apiKey!==void 0?i={name:"x-api-key",value:`${this.apiKey}`}:this.hasExplicitAuthHeader(n,s)||(i=await this.profileAuth?.getAuthHeader(e,n?.signal)),e(r,this.applyCurrentAuthHeaders(n,i,s))})}getProfileManagedAuthorizationHeader(e){if(!e?.headers||!this.profileAuth)return;let r=new Headers(e.headers).get("Authorization");if(We(r))return this.profileAuth.isProfileAuthorizationHeader(r??"")?r??void 0:void 0}isProfileManagedAuthorizationHeader(e,r){return e===r||this.profileAuth?.isProfileAuthorizationHeader(e)===!0}hasExplicitAuthHeader(e,r){if(!e?.headers)return!1;let n=new Headers(e.headers);if(We(n.get("x-api-key")))return!0;let i=n.get("Authorization");return We(i)?!this.isProfileManagedAuthorizationHeader(i??"",r):!1}applyCurrentAuthHeaders(e,r,n){if(!r)return e;let i=a(f=>{if(this.apiKey!==void 0&&r.name==="x-api-key")return f.delete("Authorization"),f.has("x-api-key")||f.set("x-api-key",r.value),f;if(r.name==="Authorization"){if(We(f.get("x-api-key")))return f;let h=f.get("Authorization");return We(h)&&!this.isProfileManagedAuthorizationHeader(h??"",n)||f.set("Authorization",r.value),f}let y=f.get("Authorization");return We(y)&&!this.isProfileManagedAuthorizationHeader(y??"",n)||(We(y)&&f.delete("Authorization"),f.has("x-api-key")||f.set("x-api-key",r.value)),f},"applyAuth");if(!e)return{headers:{[r.name]:r.value}};if(e.headers instanceof Headers)return{...e,headers:i(new Headers(e.headers))};if(Array.isArray(e.headers))return{...e,headers:i(new Headers(e.headers))};let s={...e.headers??{}},o=a(f=>Object.keys(s).find(y=>y.toLowerCase()===f),"getHeaderKey"),c=a(f=>{let y=o(f);return y?s[y]:void 0},"getHeader"),l=We(c("x-api-key")),u=c("authorization"),d=We(u)&&!this.isProfileManagedAuthorizationHeader(u??"",n);if(this.apiKey!==void 0&&r.name==="x-api-key"){let f=o("authorization");return f&&delete s[f],l||(s["x-api-key"]=r.value),{...e,headers:s}}if(r.name==="Authorization"){if(!l&&!d){let f=o("authorization");f&&f!=="Authorization"&&delete s[f],s.Authorization=r.value}return{...e,headers:s}}if(!d){let f=o("authorization");f&&delete s[f],l||(s["x-api-key"]=r.value)}return{...e,headers:s}}_trackDrain(e){this._pendingDrains.add(e),e.finally(()=>{this._pendingDrains.delete(e)})}async _serializeBody(e,r){if(this.manualFlushMode)return Re(e,r);if(!od(e))return Re(e,r);if(this._serializeWorker===void 0&&(this._serializeWorker=ad()),this._serializeWorker===null)return Re(e,r);try{let n=await this._serializeWorker.serialize(e);return n===null?(this._serializeWorker=null,Re(e,r)):n}catch{return Re(e,r)}}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,"hideMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"anonymizer",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"omitTracedRuntimeInfo",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tracingSampleRate",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"filteredPostUuids",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"autoBatchTracing",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"autoBatchQueue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchTimeout",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"autoBatchAggregationDelayMs",{enumerable:!0,configurable:!0,writable:!0,value:250}),Object.defineProperty(this,"batchSizeBytesLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"batchSizeLimit",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"fetchOptions",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_fetchOptionsHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"_openAPIClient",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_openAPIClientSignature",{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:ye("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,"_stainlessVersionsChecked",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"manualFlushMode",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_serializeWorker",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_pendingDrains",{enumerable:!0,configurable:!0,writable:!0,value:new Set}),Object.defineProperty(this,"langSmithToOTELTranslator",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_tracingMode",{enumerable:!0,configurable:!0,writable:!0,value:"langsmith"}),Object.defineProperty(this,"fetchImplementation",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"cachedLSEnvVarsForMetadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_promptCache",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"profileAuth",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"multipartStreamingDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Z("DISABLE_MULTIPART_STREAMING")==="true"}),Object.defineProperty(this,"_multipartDisabled",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"_runCompressionDisabled",{enumerable:!0,configurable:!0,writable:!0,value:Z("DISABLE_RUN_COMPRESSION")==="true"}),Object.defineProperty(this,"failedTracesDir",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"failedTracesMaxBytes",{enumerable:!0,configurable:!0,writable:!0,value:100*1024*1024}),Object.defineProperty(this,"_customHeaders",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"debug",{enumerable:!0,configurable:!0,writable:!0,value:ye("LANGSMITH_DEBUG")==="true"});let r=t.getDefaultClientConfig();this.tracingSampleRate=ky(e.tracingSamplingRate),this.apiUrl=Si(e.apiUrl??r.apiUrl)??"",this.apiUrl.endsWith("/")&&(this.apiUrl=this.apiUrl.slice(0,-1));let n=Si(e.apiKey??r.apiKey);if(this.apiKey=We(n)?n:void 0,this.profileAuth=this.apiKey!==void 0?void 0:r.profileAuth,this.webUrl=Si(e.webUrl??r.webUrl),this.webUrl?.endsWith("/")&&(this.webUrl=this.webUrl.slice(0,-1)),this.workspaceId=Si(e.workspaceId??r.workspaceId),this.timeout_ms=e.timeout_ms??9e4,this.caller=new cn({...e.callerOptions??{},maxRetries:4,debug:e.debug??this.debug}),this.traceBatchConcurrency=e.traceBatchConcurrency??this.traceBatchConcurrency,this.traceBatchConcurrency<1)throw new Error("Trace batch concurrency must be positive.");this.debug=e.debug??this.debug,this.fetchImplementation=e.fetchImplementation,this.failedTracesDir=Z("FAILED_TRACES_DIR")||void 0;let i=Z("FAILED_TRACES_MAX_MB");if(i){let l=parseInt(i,10);Number.isFinite(l)&&l>0&&(this.failedTracesMaxBytes=l*1024*1024)}let s=e.maxIngestMemoryBytes??md;this.batchIngestCaller=new cn({maxRetries:4,maxConcurrency:this.traceBatchConcurrency,maxQueueSizeBytes:s,...e.callerOptions??{},onFailedResponseHook:Ny,debug:e.debug??this.debug}),this.hideInputs=e.hideInputs??e.anonymizer??r.hideInputs,this.hideOutputs=e.hideOutputs??e.anonymizer??r.hideOutputs,this.hideMetadata=e.hideMetadata??r.hideMetadata,this.anonymizer=e.anonymizer,this.omitTracedRuntimeInfo=e.omitTracedRuntimeInfo??!1,this.autoBatchTracing=e.autoBatchTracing??this.autoBatchTracing,this.autoBatchQueue=new La(s),this.blockOnRootRunFinalization=e.blockOnRootRunFinalization??this.blockOnRootRunFinalization,this.batchSizeBytesLimit=e.batchSizeBytesLimit,this.batchSizeLimit=e.batchSizeLimit;let{headers:o,...c}=e.fetchOptions||{};this.fetchOptions=c,this._fetchOptionsHeaders=fd(o),dd(e.headers),this._customHeaders=e.headers??{},this.manualFlushMode=e.manualFlushMode??this.manualFlushMode,this._tracingMode=ri(e.tracingMode),this._tracingMode==="otel"&&(this.langSmithToOTELTranslator=new ii),this.cachedLSEnvVarsForMetadata=Qs(),e.cache!==void 0&&e.disablePromptCache&&_e("Both 'cache' and 'disablePromptCache' were provided. The 'cache' parameter is deprecated and will be removed in a future version. Using 'cache' parameter value."),e.cache!==void 0?(_e("The 'cache' parameter is deprecated and will be removed in a future version. Use 'configureGlobalPromptCache()' to configure the global cache, or 'disablePromptCache: true' to disable caching for this client."),e.cache===!1?this._promptCache=void 0:e.cache===!0?this._promptCache=Qn:this._promptCache=e.cache):e.disablePromptCache||(this._promptCache=Qn)}static getDefaultClientConfig(){let e=Qu(),r=Z("API_KEY"),n=Z("ENDPOINT"),i=Z("WORKSPACE_ID"),s=We(r),o=n??e.apiUrl??Ei,c=i??e.workspaceId,l=Z("HIDE_INPUTS")==="true",u=Z("HIDE_OUTPUTS")==="true",d=Z("HIDE_METADATA")==="true";return{apiUrl:o,apiKey:r,webUrl:void 0,hideInputs:l,hideOutputs:u,hideMetadata:d,workspaceId:c,oauthAccessToken:s?void 0:e.oauthAccessToken,oauthRefreshToken:s?void 0:e.oauthRefreshToken,profileAuth:s?void 0:e.profileAuth}}getHostUrl(){return this.webUrl?this.webUrl:My(this.apiUrl)?(this.webUrl="http://localhost:3000",this.webUrl):this.apiUrl.endsWith("/api/v1")?(this.webUrl=this.apiUrl.replace("/api/v1",""),this.webUrl):this.apiUrl.includes("/api")&&!this.apiUrl.split(".",1)[0].endsWith("api")?(this.webUrl=this.apiUrl.replace("/api",""),this.webUrl):this.apiUrl.split(".",1)[0].includes("dev")?(this.webUrl="https://dev.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("eu")?(this.webUrl="https://eu.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("aws")?(this.webUrl="https://aws.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("apac")?(this.webUrl="https://apac.smith.langchain.com",this.webUrl):this.apiUrl.split(".",1)[0].includes("beta")?(this.webUrl="https://beta.smith.langchain.com",this.webUrl):(this.webUrl="https://smith.langchain.com",this.webUrl)}get _sdkControlledHeaders(){let e=new Set;if(this.apiKey!==void 0)e.add("x-api-key");else{let r=this.profileAuth?.currentAuthHeader();r&&e.add(r.name.toLowerCase())}return this.workspaceId&&e.add("x-tenant-id"),e}get _callerHeaders(){return Fy(fd(this._customHeaders),this._fetchOptionsHeaders,this._sdkControlledHeaders)}get _mergedHeaders(){let e={"User-Agent":`langsmith-js/${ei}`,...this._callerHeaders};if(this.apiKey!==void 0)e["x-api-key"]=`${this.apiKey}`;else{let r=this.profileAuth?.currentAuthHeader();r&&(e[r.name]=r.value)}return this.workspaceId&&(e["x-tenant-id"]=this.workspaceId),e}get _openAPIAuth(){let e={...this._callerHeaders},r=Object.keys(e).find(i=>i.toLowerCase()==="x-api-key"),n=this.apiKey;return n===void 0&&r!==void 0&&(n=e[r]??void 0,delete e[r]),n===void 0&&this.workspaceId===void 0&&(e["X-API-Key"]=null),{apiKey:n,defaultHeaders:Object.keys(e).length>0?e:void 0}}get headers(){return this._customHeaders}set headers(e){dd(e),this._customHeaders=e??{}}_getOpenAPIBaseUrl(){let e=this.apiUrl.replace(/\/$/,"");for(let r of["/api/v1","/api"])if(e.endsWith(r))return e.slice(0,-r.length);return e}get openAPIClient(){let e=this._openAPIAuth,r=JSON.stringify([e.apiKey,e.defaultHeaders]);return(this._openAPIClient===void 0||this._openAPIClientSignature!==r)&&(this._openAPIClientSignature=r,this._openAPIClient=this._newOpenAPIClient(e)),this._openAPIClient}_newOpenAPIClient(e=this._openAPIAuth){let{method:r,body:n,signal:i,...s}=this.fetchOptions;return new K({apiKey:e.apiKey,tenantID:this.workspaceId,baseURL:this._getOpenAPIBaseUrl(),timeout:this.timeout_ms,fetch:this._fetch,fetchOptions:s,defaultHeaders:e.defaultHeaders})}_getPlatformEndpointPath(e){return this.apiUrl.slice(-3)!=="/v1"&&this.apiUrl.slice(-4)!=="/v1/"?`/v1/platform/${e}`:`/platform/${e}`}get evaluators(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.onlineEvaluators}get runs(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.runs}get sandboxes(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.sandboxes}get datasets(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.datasets}get annotationQueues(){return this._checkStainlessVersion("0.16.14"),this.openAPIClient.annotationQueues}get threads(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.threads}get traces(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.traces}get public(){return this._checkStainlessVersion("0.16.0"),this.openAPIClient.public}async processInputs(e){return this.hideInputs===!1?e:this.hideInputs===!0?{}:typeof this.hideInputs=="function"?this.hideInputs(e):e}async processOutputs(e){return this.hideOutputs===!1?e:this.hideOutputs===!0?{}:typeof this.hideOutputs=="function"?this.hideOutputs(e):e}async processMetadata(e){return this.hideMetadata===!1?e:this.hideMetadata===!0?{}:typeof this.hideMetadata=="function"?this.hideMetadata(e):e}async processError(e){if(this.anonymizer==null)return e;let r=await this.anonymizer({error:e});return typeof r?.error=="string"?r.error:e}_filterNewTokenEvents(e){return!e||e.length===0?e:e.map(r=>{if(r.name==="new_token"){let{kwargs:n,...i}=r;return i}return r})}async prepareRunCreateOrUpdateInputs(e){let r={...e};return r.inputs!==void 0&&(r.inputs=await this.processInputs(r.inputs)),r.outputs!==void 0&&(r.outputs=await this.processOutputs(r.outputs)),r.error!==void 0&&(r.error=await this.processError(r.error)),r.extra!=null&&"metadata"in r.extra&&(r.extra={...r.extra,metadata:await this.processMetadata(r.extra.metadata)}),r.events!==void 0&&(r.events=this._filterNewTokenEvents(r.events)),r}async _getResponse(e,r){let n=r?.toString()??"",i=`${this.apiUrl}${e}?${n}`;return await this.caller.call(async()=>{let o=await this._fetch(i,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,`fetch ${e}`),o})}async _get(e,r){return(await this._getResponse(e,r)).json()}async*_getPaginated(e,r=new URLSearchParams,n){let i=Number(r.get("offset"))||0,s=Number(r.get("limit"))||100;for(;;){r.set("offset",String(i)),r.set("limit",String(s));let o=`${this.apiUrl}${e}?${r}`,c=await this.caller.call(async()=>{let u=await this._fetch(o,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(u,`fetch ${e}`),u}),l=n?n(await c.json()):await c.json();if(l.length===0||(yield l,l.length<s))break;i+=l.length}}async*_getCursorPaginatedList(e,r=null,n="POST",i="runs"){let s=r?{...r}:{};for(;;){let o=JSON.stringify(s),l=await(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}${e}`,{method:n,headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(d,`fetch ${e}`),d})).json();if(!l||!l[i])break;yield l[i];let u=l.cursors;if(!u||!u.next)break;s.cursor=u.next}}_shouldSample(){return this.tracingSampleRate===void 0?!0:Math.random()<this.tracingSampleRate}_filterForSampling(e,r=!1){if(this.tracingSampleRate===void 0)return e;if(r){let n=[];for(let i of e)this.filteredPostUuids.has(i.trace_id)?i.id===i.trace_id&&this.filteredPostUuids.delete(i.trace_id):n.push(i);return n}else{let n=[];for(let i of e){let s=i.trace_id??i.id;this.filteredPostUuids.has(s)||(i.id===s?this._shouldSample()?n.push(i):this.filteredPostUuids.add(s):n.push(i))}return n}}async _getBatchSizeLimitBytes(){let e=await this._ensureServerInfo();return this.batchSizeBytesLimit??e?.batch_ingest_config?.size_limit_bytes??Dy}async _getBatchSizeLimit(){let e=await this._ensureServerInfo();return this.batchSizeLimit??e?.batch_ingest_config?.size_limit??$y}async _getDatasetExamplesMultiPartSupport(){return(await this._ensureServerInfo()).instance_flags?.dataset_examples_multipart_enabled??!1}drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r}){let n=[];for(;this.autoBatchQueue.items.length>0;){let[i,s]=this.autoBatchQueue.pop({upToSizeBytes:e,upToSize:r});if(!i.length){s();break}let o=i.reduce((u,d)=>{let f=d.apiUrl??this.apiUrl,y=d.apiKey??this.apiKey,h=d.workspaceId??this.workspaceId,b=d.apiKey===this.apiKey&&d.apiUrl===this.apiUrl&&d.workspaceId===this.workspaceId?"default":`${f}|${y}|${h??""}`;return u[b]||(u[b]=[]),u[b].push(d),u},{}),c=[];for(let[u,d]of Object.entries(o)){let f=u==="default",y=f?[]:u.split("|"),h=y[2],g=this._processBatch(d,{apiUrl:f?void 0:y[0],apiKey:f?void 0:y[1],workspaceId:f||!h?void 0:h});c.push(g)}let l=Promise.all(c).finally(s);n.push(l)}return Promise.all(n)}static async _writeTraceToFallbackDir(e,r,n,i,s){try{let o=typeof r=="string"?Buffer.from(r,"utf8"):Buffer.from(r),c=JSON.stringify({version:1,endpoint:i,headers:n,body_base64:o.toString("base64")}),l=`trace_${Date.now()}_${zt().slice(0,8)}.json`,u=Qe.join(e,l);if(t._fallbackDirsCreated.has(e)||(await Zn(e),t._fallbackDirsCreated.add(e)),s!==void 0&&s>0)try{let f=(await Xl(e)).filter(h=>h.startsWith("trace_")&&h.endsWith(".json")),y=0;for(let h of f){let{size:g}=await Ql(Qe.join(e,h));y+=g}if(y>=s){console.warn(`Could not write trace to fallback dir ${e} as it's already over size limit (${y} bytes >= ${s} bytes). Increase LANGSMITH_FAILED_TRACES_MAX_MB if possible.`);return}}catch{}await Ir(u,c),console.warn(`LangSmith trace upload failed; data saved to ${u} for later replay.`)}catch(o){console.error(`LangSmith tracing error: could not write trace to fallback dir ${e}:`,o)}}async _processBatch(e,r){if(!e.length)return;let n=e.reduce((i,s)=>i+(s.size??0),0);try{if(this.langSmithToOTELTranslator!==void 0)this._sendBatchToOTELTranslator(e);else{let i={runCreates:e.filter(c=>c.action==="create").map(c=>c.item),runUpdates:e.filter(c=>c.action==="update").map(c=>c.item)},s=await this._ensureServerInfo();if(!this._multipartDisabled&&(s?.batch_ingest_config?.use_multipart_endpoint??!0)){let c=!this._runCompressionDisabled&&s?.instance_flags?.gzip_body_enabled;try{await this.multipartIngestRuns(i,{...r,useGzip:c,sizeBytes:n})}catch(l){if(wi(l))this._multipartDisabled=!0,await this.batchIngestRuns(i,{...r,sizeBytes:n});else throw l}}else await this.batchIngestRuns(i,{...r,sizeBytes:n})}}catch(i){console.error("Error exporting batch:",i)}}_sendBatchToOTELTranslator(e){if(this.langSmithToOTELTranslator!==void 0){let r=new Map,n=[];for(let i of e)i.item.id&&i.otelContext&&(r.set(i.item.id,i.otelContext),i.action==="create"?n.push({operation:"post",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}):n.push({operation:"patch",id:i.item.id,trace_id:i.item.trace_id??i.item.id,run:i.item}));this.langSmithToOTELTranslator.exportBatch(n,r)}}async processRunOperation(e){clearTimeout(this.autoBatchTimeout),this.autoBatchTimeout=void 0,e.item=ld(e.item,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);let r=this.autoBatchQueue.push(e);if(this.manualFlushMode)return r;let n=await this._getBatchSizeLimitBytes(),i=await this._getBatchSizeLimit();return(this.autoBatchQueue.sizeBytes>n||this.autoBatchQueue.items.length>i)&&this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i})),this.autoBatchQueue.items.length>0&&(this.autoBatchTimeout=setTimeout(()=>{this.autoBatchTimeout=void 0,this._trackDrain(this.drainAutoBatchQueue({batchSizeLimitBytes:n,batchSizeLimit:i}))},this.autoBatchAggregationDelayMs)),r}async _getServerInfo(){let r=await(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/info`,{method:"GET",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(Uy),...this.fetchOptions});return await L(n,"get server info"),n})).json();return this.debug&&console.log(`
16
116
  === LangSmith Server Configuration ===
17
117
  `+JSON.stringify(r,null,2)+`
18
- `),r}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(){let e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){let e=vn(),r=Al();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this.headers,"Content-Type":"application/json"},s=e.project_name;delete e.project_name;let i=await this.prepareRunCreateOrUpdateInputs({session_name:s,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:i,otelContext:l,apiKey:r?.apiKey,apiUrl:r?.apiUrl}).catch(console.error);return}let a=Id(i,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let c=Pe(a,`Creating run with id: ${a.id}`);await this.caller.call(async()=>{let l=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let s=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),i=await Promise.all(r?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(s.length>0&&i.length>0){let l=s.reduce((d,p)=>(p.id&&(d[p.id]=p),d),{}),u=[];for(let d of i)d.id!==void 0&&l[d.id]?l[d.id]={...l[d.id],...d}:u.push(d);s=Object.values(l),i=u}let a={post:s,patch:i};if(!a.post.length&&!a.patch.length)return;let c={post:[],patch:[]};for(let l of["post","patch"]){let u=l,d=a[u].reverse(),p=d.pop();for(;p!==void 0;)c[u].push(p),p=d.pop()}if(c.post.length>0||c.patch.length>0){let l=c.post.map(u=>u.id).concat(c.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(Pe(c,`Ingesting runs with ids: ${l}`),n)}}async _postBatchIngestRuns(e,r){let n={...this.headers,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let s=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await U(s,"batch create run",!0),s})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let s={},i=[];for(let p of e??[]){let _=await this.prepareRunCreateOrUpdateInputs(p);_.id!==void 0&&_.attachments!==void 0&&(s[_.id]=_.attachments),delete _.attachments,i.push(_)}let a=[];for(let p of r??[])a.push(await this.prepareRunCreateOrUpdateInputs(p));if(i.find(p=>p.trace_id===void 0||p.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run');if(a.find(p=>p.trace_id===void 0||p.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(i.length>0&&a.length>0){let p=i.reduce((g,y)=>(y.id&&(g[y.id]=y),g),{}),_=[];for(let g of a)g.id!==void 0&&p[g.id]?p[g.id]={...p[g.id],...g}:_.push(g);i=Object.values(p),a=_}if(i.length===0&&a.length===0)return;let u=[],d=[];for(let[p,_]of[["post",i],["patch",a]])for(let g of _){let{inputs:y,outputs:E,events:w,extra:S,error:I,serialized:m,attachments:T,...A}=g,N={inputs:y,outputs:E,events:w,extra:S,error:I,serialized:m},O=Pe(A,`Serializing for multipart ingestion of run with id: ${A.id}`);d.push({name:`${p}.${A.id}`,payload:new Blob([O],{type:`application/json; length=${O.length}`})});for(let[b,j]of Object.entries(N)){if(j===void 0)continue;let G=Pe(j,`Serializing ${b} for multipart ingestion of run with id: ${A.id}`);d.push({name:`${p}.${A.id}.${b}`,payload:new Blob([G],{type:`application/json; length=${G.length}`})})}if(A.id!==void 0){let b=s[A.id];if(b){delete s[A.id];for(let[j,G]of Object.entries(b)){let B,Z;if(Array.isArray(G)?[B,Z]=G:(B=G.mimeType,Z=G.data),j.includes(".")){console.warn(`Skipping attachment '${j}' for run ${A.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}d.push({name:`attachment.${A.id}.${j}`,payload:new Blob([Z],{type:`${B}; length=${Z.byteLength}`})})}}}u.push(`trace=${A.trace_id},id=${A.id}`)}await this._sendMultipartRequest(d,u.join("; "),n)}async _createNodeFetchBody(e,r){let n=[];for(let a of e)n.push(new Blob([`--${r}\r
19
- `])),n.push(new Blob([`Content-Disposition: form-data; name="${a.name}"\r
20
- `,`Content-Type: ${a.payload.type}\r
118
+ `),r}_checkStainlessVersion(e){this._stainlessVersionsChecked.has(e)||(this._stainlessVersionsChecked.add(e),this._ensureServerInfo().then(r=>{Ly(r?.version,e)}).catch(()=>{}))}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 _supportsSDBQuery(){return(await this._ensureServerInfo()).instance_flags?.sdb_query_enabled===!0}async _checkFeedbackSessionId(){let e="https://docs.langchain.com/langsmith/smithdb-sdk-migration#feedback-create",r=await this._ensureServerInfo();if(Gu(r.instance_flags)===fn.SMITHDB_ONLY)throw new Error(`sessionId must be provided when creating feedback for a run: this deployment cannot locate the run without it. See ${e}`);_e(`Creating feedback for a run without sessionId is deprecated and will stop working in a future release. See ${e}`)}async _getSettings(){return this.settings||(this.settings=this._get("/settings")),await this.settings}async flush(){let e=await this._getBatchSizeLimitBytes(),r=await this._getBatchSizeLimit();await this.drainAutoBatchQueue({batchSizeLimitBytes:e,batchSizeLimit:r})}_cloneCurrentOTELContext(){let e=ni(),r=du();if(this.langSmithToOTELTranslator!==void 0){let n=e.getActiveSpan();if(n)return e.setSpan(r.active(),n)}}async createRun(e,r){if(!this._filterForSampling([e]).length)return;let n={...this._mergedHeaders,"Content-Type":"application/json"},i=e.project_name;delete e.project_name;let s=await this.prepareRunCreateOrUpdateInputs({session_name:i,...e,start_time:e.start_time??Date.now()});if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let l=this._cloneCurrentOTELContext();this.processRunOperation({action:"create",item:s,otelContext:l,apiKey:r?.apiKey,apiUrl:r?.apiUrl,workspaceId:r?.workspaceId}).catch(console.error);return}let o=ld(s,this.cachedLSEnvVarsForMetadata,this.omitTracedRuntimeInfo);r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId);let c=Re(o,`Creating run with id: ${o.id}`);await this.caller.call(async()=>{let l=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await L(l,"create run",!0),l})}async batchIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i=await Promise.all(e?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]),s=await Promise.all(r?.map(l=>this.prepareRunCreateOrUpdateInputs(l))??[]);if(i.length>0&&s.length>0){let l=i.reduce((d,f)=>(f.id&&(d[f.id]=f),d),{}),u=[];for(let d of s)d.id!==void 0&&l[d.id]?l[d.id]={...l[d.id],...d}:u.push(d);i=Object.values(l),s=u}let o={post:i,patch:s};if(!o.post.length&&!o.patch.length)return;let c={post:[],patch:[]};for(let l of["post","patch"]){let u=l,d=o[u].reverse(),f=d.pop();for(;f!==void 0;)c[u].push(f),f=d.pop()}if(c.post.length>0||c.patch.length>0){let l=c.post.map(u=>u.id).concat(c.patch.map(u=>u.id)).join(",");await this._postBatchIngestRuns(await this._serializeBody(c,`Ingesting runs with ids: ${l}`),n)}}async _postBatchIngestRuns(e,r){let n={...this._mergedHeaders,"Content-Type":"application/json",Accept:"application/json"};r?.apiKey!==void 0&&(n["x-api-key"]=r.apiKey),r?.workspaceId!==void 0&&(n["x-tenant-id"]=r.workspaceId),await this.batchIngestCaller.callWithOptions({sizeBytes:r?.sizeBytes},async()=>{let i=await this._fetch(`${r?.apiUrl??this.apiUrl}/runs/batch`,{method:"POST",headers:n,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:e});return await L(i,"batch create run",!0),i})}async multipartIngestRuns({runCreates:e,runUpdates:r},n){if(e===void 0&&r===void 0)return;let i={},s=[];for(let f of e??[]){let y=await this.prepareRunCreateOrUpdateInputs(f);y.id!==void 0&&y.attachments!==void 0&&(i[y.id]=y.attachments),delete y.attachments,s.push(y)}let o=[];for(let f of r??[])o.push(await this.prepareRunCreateOrUpdateInputs(f));if(s.find(f=>f.trace_id===void 0||f.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(o.find(f=>f.trace_id===void 0||f.dotted_order===void 0)!==void 0)throw new Error('Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run');if(s.length>0&&o.length>0){let f=s.reduce((h,g)=>(g.id&&(h[g.id]=g),h),{}),y=[];for(let h of o)h.id!==void 0&&f[h.id]?f[h.id]={...f[h.id],...h}:y.push(h);s=Object.values(f),o=y}if(s.length===0&&o.length===0)return;let u=[],d=[];for(let[f,y]of[["post",s],["patch",o]])for(let h of y){let{inputs:g,outputs:b,events:w,extra:v,error:S,serialized:p,attachments:T,...I}=h,C={inputs:g,outputs:b,events:w,extra:v,error:S,serialized:p},k=await this._serializeBody(I,`Serializing for multipart ingestion of run with id: ${I.id}`);d.push({name:`${f}.${I.id}`,payload:new Blob([k],{type:`application/json; length=${k.length}`})});for(let[E,U]of Object.entries(C)){if(U===void 0)continue;let D=await this._serializeBody(U,`Serializing ${E} for multipart ingestion of run with id: ${I.id}`);d.push({name:`${f}.${I.id}.${E}`,payload:new Blob([D],{type:`application/json; length=${D.length}`})})}if(I.id!==void 0){let E=i[I.id];if(E){delete i[I.id];for(let[U,D]of Object.entries(E)){let N,W;if(Array.isArray(D)?[N,W]=D:(N=D.mimeType,W=D.data),U.includes(".")){console.warn(`Skipping attachment '${U}' for run ${I.id}: Invalid attachment name. Attachment names must not contain periods ('.'). Please rename the attachment and try again.`);continue}d.push({name:`attachment.${I.id}.${U}`,payload:new Blob([W],{type:`${N}; length=${W.byteLength}`})})}}}u.push(`trace=${I.trace_id},id=${I.id}`)}await this._sendMultipartRequest(d,u.join("; "),n)}async _createNodeFetchBody(e,r){let n=[];for(let o of e)n.push(new Blob([`--${r}\r
119
+ `])),n.push(new Blob([`Content-Disposition: form-data; name="${o.name}"\r
120
+ `,`Content-Type: ${o.payload.type}\r
21
121
  \r
22
- `])),n.push(a.payload),n.push(new Blob([`\r
122
+ `])),n.push(o.payload),n.push(new Blob([`\r
23
123
  `]));return n.push(new Blob([`--${r}--\r
24
- `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(i){let a=o(async c=>{typeof c=="string"?i.enqueue(n.encode(c)):i.enqueue(c)},"writeChunk");for(let c of e){await a(`--${r}\r
25
- `),await a(`Content-Disposition: form-data; name="${c.name}"\r
26
- `),await a(`Content-Type: ${c.payload.type}\r
124
+ `])),await new Blob(n).arrayBuffer()}async _createMultipartStream(e,r){let n=new TextEncoder;return new ReadableStream({async start(s){let o=a(async c=>{typeof c=="string"?s.enqueue(n.encode(c)):s.enqueue(c)},"writeChunk");for(let c of e){await o(`--${r}\r
125
+ `),await o(`Content-Disposition: form-data; name="${c.name}"\r
126
+ `),await o(`Content-Type: ${c.payload.type}\r
27
127
  \r
28
- `);let u=c.payload.stream().getReader();try{let d;for(;!(d=await u.read()).done;)i.enqueue(d.value)}finally{u.releaseLock()}await a(`\r
29
- `)}await a(`--${r}--\r
30
- `),i.close()}})}async _sendMultipartRequest(e,r,n){let s="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),i=o(()=>this._createNodeFetchBody(e,s),"buildBuffered"),a=o(()=>this._createMultipartStream(e,s),"buildStream"),c=o(async l=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let u=await l(),d={...this.headers,"Content-Type":`multipart/form-data; boundary=${s}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey);let p=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(p=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let _=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:p,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(_,"Failed to send multipart request",!0),_}),"sendWithRetry");try{let l,u=!1;tl()&&!this.multipartStreamingDisabled&&oi()!=="bun"?(u=!0,l=await c(a)):l=await c(i),(!this.multipartStreamingDisabled||u)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==Ad&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,l=await c(i))}catch(l){if(Hi(l))throw l;if(console.warn(`${l.message.trim()}
128
+ `);let u=c.payload.stream().getReader();try{let d;for(;!(d=await u.read()).done;)s.enqueue(d.value)}finally{u.releaseLock()}await o(`\r
129
+ `)}await o(`--${r}--\r
130
+ `),s.close()}})}async _sendMultipartRequest(e,r,n){let i="----LangSmithFormBoundary"+Math.random().toString(36).slice(2),s=a(()=>this._createNodeFetchBody(e,i),"buildBuffered"),o=a(()=>this._createMultipartStream(e,i),"buildStream"),c=a(async l=>this.batchIngestCaller.callWithOptions({sizeBytes:n?.sizeBytes},async()=>{let u=await l(),d={...this._mergedHeaders,"Content-Type":`multipart/form-data; boundary=${i}`};n?.apiKey!==void 0&&(d["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(d["x-tenant-id"]=n.workspaceId);let f=u;n?.useGzip&&typeof u=="object"&&"pipeThrough"in u&&(f=u.pipeThrough(new CompressionStream("gzip")),d["Content-Encoding"]="gzip");let y=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/multipart`,{method:"POST",headers:d,body:f,duplex:"half",signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(y,"Failed to send multipart request",!0),y}),"sendWithRetry");try{let l,u=!1;Dl()&&!this.multipartStreamingDisabled&&on()!=="bun"?(u=!0,l=await c(o)):l=await c(s),(!this.multipartStreamingDisabled||u)&&l.status===422&&(n?.apiUrl??this.apiUrl)!==Ei&&(console.warn(`Streaming multipart upload to ${n?.apiUrl??this.apiUrl}/runs/multipart failed. This usually means the host does not support chunked uploads. Retrying with a buffered upload for operation "${r}".`),this.multipartStreamingDisabled=!0,l=await c(s))}catch(l){if(wi(l))throw l;if(console.warn(`${l.message.trim()}
31
131
 
32
- Context: ${r}`),this.failedTracesDir){let u=await this._createNodeFetchBody(e,s).catch(()=>null);u&&await t._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${s}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){z(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs));let s={...r,id:e};if(!this._filterForSampling([s],!0).length)return;if(this.autoBatchTracing&&s.trace_id!==void 0&&s.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&s.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:s,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}else this.processRunOperation({action:"update",item:s,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl}).catch(console.error);return}let i={...this.headers,"Content-Type":"application/json"};n?.apiKey!==void 0&&(i["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(i["x-tenant-id"]=n.workspaceId);let a=Pe(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:i,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(c,"update run",!0),c})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){z(e);let n=Or(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(r!==void 0){let s;r.session_id?s=r.session_id:n?.projectName?s=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?s=n?.projectId:s=(await this.readProject({projectName:te("PROJECT")||"default"})).id;let i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${s}/r/${r.id}?poll=true`}else if(e!==void 0){let 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){let r=await Kb(this.listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},s={};r.sort((i,a)=>(i?.dotted_order??"").localeCompare(a?.dotted_order??""));for(let i of r){if(i.parent_run_id===null||i.parent_run_id===void 0)throw new Error(`Child run ${i.id} has no parent`);i.dotted_order?.startsWith(e.dotted_order??"")&&i.id!==e.id&&(i.parent_run_id in n||(n[i.parent_run_id]=[]),n[i.parent_run_id].push(i),s[i.id]=i)}e.child_runs=n[e.id]||[];for(let i in n)i!==e.id&&(s[i].child_runs=n[i]);return e}async*listRuns(e){let{projectId:r,projectName:n,parentRunId:s,traceId:i,referenceExampleId:a,startTime:c,executionOrder:l,isRoot:u,runType:d,error:p,id:_,query:g,filter:y,traceFilter:E,treeFilter:w,limit:S,select:I,order:m}=e,T=[];if(r&&(T=Array.isArray(r)?r:[r]),n){let b=Array.isArray(n)?n:[n],j=await Promise.all(b.map(G=>this.readProject({projectName:G}).then(B=>B.id)));T.push(...j)}let A=["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"],N={session:T.length?T:null,run_type:d,reference_example:a,query:g,filter:y,trace_filter:E,tree_filter:w,execution_order:l,parent_run:s,start_time:c?c.toISOString():null,error:p,id:_,limit:S,trace:i,select:I||A,is_root:u,order:m};N.select.includes("child_run_ids")&&Pt("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let O=0;for await(let b of this._getCursorPaginatedList("/runs/query",N)){let j=b.map(Or);if(S){if(O>=S)break;if(j.length+O>S){yield*j.slice(0,S-O);break}O+=j.length,yield*j}else yield*j}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:s,filter:i,startTime:a,endTime:c,limit:l,offset:u}=e,p={session_id:r||(await this.readProject({projectName:n})).id,group_by:s,filter:i,start_time:a?a.toISOString():null,end_time:c?c.toISOString():null,limit:Number(l)||100},_=Number(u)||0,g="/runs/group",y=`${this.apiUrl}${g}`;for(;;){let E={...p,offset:_},w=Object.fromEntries(Object.entries(E).filter(([N,O])=>O!==void 0)),S=JSON.stringify(w),m=await(await this.caller.call(async()=>{let N=await this._fetch(y,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:S});return await U(N,`Failed to fetch ${g}`),N})).json(),{groups:T,total:A}=m;if(T.length===0)break;for(let N of T)yield N;if(_+=T.length,_>=A)break}}async*readThread(e){let{threadId:r,projectId:n,projectName:s,isRoot:i=!0,limit:a,filter:c,order:l="asc"}=e;if(!n&&!s)throw new Error("threadId requires projectId or projectName");let u=`eq(thread_id, ${JSON.stringify(r)})`,d=c?`and(${u}, ${c})`:u;yield*this.listRuns({projectId:n??void 0,projectName:s??void 0,isRoot:i,limit:a,filter:d,order:l})}async listThreads(e){let{projectId:r,projectName:n,limit:s,offset:i=0,filter:a,startTime:c,isRoot:l=!0}=e;if(!r&&!n)throw new Error("Either projectId or projectName must be provided");if(r&&n)throw new Error("Provide exactly one of projectId or projectName");let u=r??(await this.readProject({projectName:n})).id,d=c??new Date(Date.now()-1440*60*1e3),_={session:[u],is_root:l,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:d.toISOString()};a!=null&&(_.filter=a);let g=new Map;for await(let S of this._getCursorPaginatedList("/runs/query",_))for(let I of S){let m=Or(I),T=m.thread_id;if(T){let A=g.get(T)??[];A.push(m),g.set(T,A)}}let y=[];for(let[S,I]of g.entries()){I.sort((O,b)=>{let j=O,G=b,B=j.start_time??"",Z=G.start_time??"";if(B!==Z)return B.localeCompare(Z);let ce=j.dotted_order??"",ke=G.dotted_order??"";return ce.localeCompare(ke)});let T=[...I.map(O=>O.start_time).filter(Boolean)].sort(),A=T.length?T[0]:"",N=T.length?T[T.length-1]:"";y.push({thread_id:S,runs:I,count:I.length,filter:"",total_tokens:0,total_cost:null,min_start_time:A,max_start_time:N,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}y.sort((S,I)=>{let m=S.max_start_time??"";return(I.max_start_time??"").localeCompare(m)});let E=i>0?y.slice(i):y;return s!==void 0?E.slice(0,s):E}async getRunStats({id:e,trace:r,parentRun:n,runType:s,projectNames:i,projectIds:a,referenceExampleIds:c,startTime:l,endTime:u,error:d,query:p,filter:_,traceFilter:g,treeFilter:y,isRoot:E,dataSourceType:w}){let S=a||[];i&&(S=[...a||[],...await Promise.all(i.map(O=>this.readProject({projectName:O}).then(b=>b.id)))]);let m=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:s,session:S,reference_example:c,start_time:l,end_time:u,error:d,query:p,filter:_,trace_filter:g,tree_filter:y,is_root:E,data_source_type:w}).filter(([O,b])=>b!==void 0)),T=JSON.stringify(m);return await(await this.caller.call(async()=>{let O=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:T});return await U(O,"get run stats"),O})).json()}async shareRun(e,{shareId:r}={}){let n={run_id:e,share_token:r||kt()};z(e);let s=JSON.stringify(n),a=await(await this.caller.call(async()=>{let c=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 U(c,"share run"),c})).json();if(a===null||!("share_token"in a))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${a.share_token}/r`}async unshareRun(e){z(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"unshare run",!0),r})}async readRunSharedLink(e){z(e);let n=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"read run shared link"),s})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){let n=new URLSearchParams({share_token:e});if(r!==void 0)for(let a of r)n.append("id",a);return z(e),(await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"list shared runs"),a})).json()).map(Or)}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),z(e);let s=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(i,"read dataset shared schema"),i})).json();return s.url=`${this.getHostUrl()}/public/${s.share_token}/d`,s}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);let n={dataset_id:e};z(e);let s=JSON.stringify(n),a=await(await this.caller.call(async()=>{let c=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 U(c,"share dataset"),c})).json();return a.url=`${this.getHostUrl()}/public/${a.share_token}/d`,a}async unshareDataset(e){z(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(r,"unshare dataset",!0),r})}async readSharedDataset(e){return z(e),await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"read shared dataset"),s})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let s=new URLSearchParams;Object.entries(n).forEach(([c,l])=>{Array.isArray(l)?l.forEach(u=>s.append(c,u)):s.append(c,l)});let i=await this.caller.call(async()=>{let c=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 U(c,"list shared examples"),c}),a=await i.json();if(!i.ok)throw"detail"in a?new Error(`Failed to list shared examples.
33
- Status: ${i.status}
34
- Message: ${Array.isArray(a.detail)?a.detail.join(`
35
- `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${i.status} ${i.statusText}`);return a.map(c=>({...c,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:s=!1,projectExtra:i=null,referenceDatasetId:a=null}){let c=s?"?upsert=true":"",l=`${this.apiUrl}/sessions${c}`,u=i||{};n&&(u.metadata=n);let d={name:e,extra:u,description:r};a!==null&&(d.reference_dataset_id=a);let p=JSON.stringify(d);return await(await this.caller.call(async()=>{let y=await this._fetch(l,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:p});return await U(y,"create project"),y})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:s=null,projectExtra:i=null,endTime:a=null}){let c=`${this.apiUrl}/sessions/${e}`,l=i;s&&(l={...l||{},metadata:s});let u=JSON.stringify({name:r,extra:l,description:n,end_time:a?new Date(a).toISOString():null});return await(await this.caller.call(async()=>{let _=await this._fetch(c,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(_,"update project"),_})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",s=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)z(e),n+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");let i=await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}?${s}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"has project"),a});try{let a=await i.json();return i.ok?Array.isArray(a)?a.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let s="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)z(e),s+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&i.append("include_stats",n.toString());let a=await this._get(s,i),c;if(Array.isArray(a)){if(a.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);c=a[0]}else c=a;return c}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:s,referenceDatasetName:i,includeStats:a,datasetVersion:c,referenceFree:l,metadata:u}={}){let d=new URLSearchParams;if(e!==void 0)for(let p of e)d.append("id",p);if(r!==void 0&&d.append("name",r),n!==void 0&&d.append("name_contains",n),s!==void 0)d.append("reference_dataset",s);else if(i!==void 0){let p=await this.readDataset({datasetName:i});d.append("reference_dataset",p.id)}a!==void 0&&d.append("include_stats",a.toString()),c!==void 0&&d.append("dataset_version",c),l!==void 0&&d.append("reference_free",l.toString()),u!==void 0&&d.append("metadata",JSON.stringify(u));for await(let p of this._getPaginated("/sessions",d))yield*p}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,z(n),await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,`delete session ${n} (${r})`,!0),s})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:s,description:i,dataType:a,name:c}){let l=`${this.apiUrl}/datasets/upload`,u=new FormData,d=new Blob([e],{type:"text/csv"});return u.append("file",d,r),n.forEach(g=>{u.append("input_keys",g)}),s.forEach(g=>{u.append("output_keys",g)}),i&&u.append("description",i),a&&u.append("data_type",a),c&&u.append("name",c),await(await this.caller.call(async()=>{let g=await this._fetch(l,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(g,"upload CSV"),g})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:s,outputsSchema:i,metadata:a}={}){let c={name:e,description:r,extra:{source:"sdk",...a?{metadata:a}:{}}};n&&(c.data_type=n),s&&(c.inputs_schema_definition=s),i&&(c.outputs_schema_definition=i);let l=JSON.stringify(c);return await(await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(p,"create dataset"),p})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets",s=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)z(e),n+=`/${e}`;else if(r)s.append("name",r);else throw new Error("Must provide datasetName or datasetId");let i=await this._get(n,s),a;if(Array.isArray(i)){if(i.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);a=i[0]}else a=i;return a}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:s}){let i=e;if(i===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:r})).id);let a=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof s=="string"?s:s.toISOString()});return await this._get(`/datasets/${i}/versions/diff`,a)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){let n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
36
- `).map(c=>JSON.parse(c))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:s,datasetNameContains:i,metadata:a}={}){let c="/datasets",l=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)l.append("id",u);s!==void 0&&l.append("name",s),i!==void 0&&l.append("name_contains",i),a!==void 0&&l.append("metadata",JSON.stringify(a));for await(let u of this._getPaginated(c,l))yield*u}async updateDataset(e){let{datasetId:r,datasetName:n,...s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let i=r??(await this.readDataset({datasetName:n})).id;z(i);let a=JSON.stringify(s);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:s,tag:i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let a=r??(await this.readDataset({datasetName:n})).id;z(a);let c=JSON.stringify({as_of:typeof s=="string"?s:s.toISOString(),tag:i});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${a}/tags`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await U(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",s=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(s=(await this.readDataset({datasetName:r})).id),s!==void 0)z(s),n+=`/${s}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let i=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(i,`delete ${n}`,!0),i})}async indexDataset({datasetId:e,datasetName:r,tag:n}){let s=e;if(!s&&!r)throw new Error("Must provide either datasetName or datasetId");if(s&&r)throw new Error("Must provide either datasetName or datasetId, not both");s||(s=(await this.readDataset({datasetName:r})).id),z(s);let a=JSON.stringify({tag:n});await(await this.caller.call(async()=>{let l=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:a});return await U(l,"index dataset"),l})).json()}async similarExamples(e,r,n,{filter:s}={}){let i={limit:n,inputs:e};s!==void 0&&(i.filter=s),z(r);let a=JSON.stringify(i);return(await(await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${r}/search`,{headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,method:"POST",body:a});return await U(u,"fetch similar examples"),u})).json()).examples}async createExample(e,r,n){if(Cd(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let s=r?n?.datasetId:e.dataset_id,i=r?n?.datasetName:e.dataset_name;if(s===void 0&&i===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&i!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:i})).id);let a=(r?n?.createdAt:e.created_at)||new Date,c;Cd(e)?c=e:c={inputs:e,outputs:r,created_at:a?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let l=await this._uploadExamplesMultipart(s,[c]);return await this.readExample(l.example_ids?.[0]??kt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let I=e,m=I[0].dataset_id,T=I[0].dataset_name;if(m===void 0&&T===void 0)throw new Error("Must provide either datasetName or datasetId");if(m!==void 0&&T!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");m===void 0&&(m=(await this.readDataset({datasetName:T})).id);let A=await this._uploadExamplesMultipart(m,I);return await Promise.all(A.example_ids.map(O=>this.readExample(O)))}let{inputs:r,outputs:n,metadata:s,splits:i,sourceRunIds:a,useSourceRunIOs:c,useSourceRunAttachments:l,attachments:u,exampleIds:d,datasetId:p,datasetName:_}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let g=p,y=_;if(g===void 0&&y===void 0)throw new Error("Must provide either datasetName or datasetId");if(g!==void 0&&y!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");g===void 0&&(g=(await this.readDataset({datasetName:y})).id);let E=r.map((I,m)=>({dataset_id:g,inputs:I,outputs:n?.[m],metadata:s?.[m],split:i?.[m],id:d?.[m],attachments:u?.[m],source_run_id:a?.[m],use_source_run_io:c?.[m],use_source_run_attachments:l?.[m]})),w=await this._uploadExamplesMultipart(g,E);return await Promise.all(w.example_ids.map(I=>this.readExample(I)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let s=e.map(a=>bi(a)?Ei(a):a),i=bi(r)?Ei(r):r;return this.createExample({input:s},{output:i},n)}async readExample(e){z(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:s,...i}=n,a=i;return s&&(a.attachments=Object.entries(s).reduce((c,[l,u])=>(c[l.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},c),{})),a}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:s,splits:i,inlineS3Urls:a,metadata:c,limit:l,offset:u,filter:d,includeAttachments:p}={}){let _;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)_=e;else if(r!==void 0)_=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let g=new URLSearchParams({dataset:_}),y=s?typeof s=="string"?s:s?.toISOString():void 0;y&&g.append("as_of",y);let E=a??!0;if(g.append("inline_s3_urls",E.toString()),n!==void 0)for(let S of n)g.append("id",S);if(i!==void 0)for(let S of i)g.append("splits",S);if(c!==void 0){let S=JSON.stringify(c);g.append("metadata",S)}l!==void 0&&g.append("limit",l.toString()),u!==void 0&&g.append("offset",u.toString()),d!==void 0&&g.append("filter",d),p===!0&&["attachment_urls","outputs","metadata"].forEach(S=>g.append("select",S));let w=0;for await(let S of this._getPaginated("/examples",g)){for(let I of S){let{attachment_urls:m,...T}=I,A=T;m&&(A.attachments=Object.entries(m).reduce((N,[O,b])=>(N[O.slice(11)]={presigned_url:b.presigned_url,mime_type:b.mime_type||void 0},N),{})),yield A,w++}if(l!==void 0&&w>=l)break}}async deleteExample(e){z(e);let r=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>z(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"hard delete examples",!0),s})}else{let n=new URLSearchParams;e.forEach(s=>n.append("example_ids",s)),await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(s,"delete examples",!0),s})}}async updateExample(e,r){let n;r?n=e:n=e.id,z(n);let s;r?s={id:n,...r}:s=e;let i;return s.dataset_id!==void 0?i=s.dataset_id:i=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(i,[s])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:s}){let i;if(e?i=e:i=(await this.readDataset({datasetName:r})).id,z(i),n&&s||!n&&!s)throw new Error("Exactly one of asOf and tag must be specified.");let a=new URLSearchParams;return n!==void 0&&a.append("as_of",typeof n=="string"?n:n.toISOString()),s!==void 0&&a.append("tag",s),await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${i}/version?${a.toString()}`,{method:"GET",headers:{...this.headers},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(l,"read dataset version"),l})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let s;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?s=(await this.readDataset({datasetName:r})).id:s=e,z(s);let i=new URLSearchParams,a=n?typeof n=="string"?n:n?.toISOString():void 0;return a&&i.append("as_of",a),await this._get(`/datasets/${s}/splits`,i)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:s,remove:i=!1}){let a;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?a=(await this.readDataset({datasetName:r})).id:a=e,z(a);let c={split_name:n,examples:s.map(u=>(z(u),u)),remove:i},l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${a}/splits`,{method:"PUT",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(u,"update dataset splits",!0),u})}async createFeedback(e,r,{score:n,value:s,correction:i,comment:a,sourceInfo:c,feedbackSourceType:l="api",sourceRunId:u,feedbackId:d,feedbackConfig:p,projectId:_,comparativeExperimentId:g,sessionId:y,startTime:E}){if(!e&&!_)throw new Error("One of runId or projectId must be provided");if(e&&_)throw new Error("Only one of runId or projectId can be provided");let w={type:l??"api",metadata:c??{}};u!==void 0&&w?.metadata!==void 0&&!w.metadata.__run&&(w.metadata.__run={run_id:u}),w?.metadata!==void 0&&w.metadata.__run?.run_id!==void 0&&z(w.metadata.__run.run_id);let S={id:d??_r(),run_id:e,key:r,score:xd(n),value:s,correction:i,comment:a,feedback_source:w,comparative_experiment_id:g,feedbackConfig:p,session_id:y??_,start_time:E},I=JSON.stringify(S),m=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let T=await this._fetch(m,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:I});return await U(T,"create feedback",!0),T}),S}async updateFeedback(e,{score:r,value:n,correction:s,comment:i}){let a={};r!=null&&(a.score=xd(r)),n!=null&&(a.value=n),s!=null&&(a.correction=s),i!=null&&(a.comment=i),z(e);let c=JSON.stringify(a);await this.caller.call(async()=>{let l=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:c});return await U(l,"update feedback",!0),l})}async readFeedback(e){z(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){z(e);let r=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let s=new URLSearchParams;if(e)for(let i of e)z(i),s.append("run",i);if(r)for(let i of r)s.append("key",i);if(n)for(let i of n)s.append("source",i);for await(let i of this._getPaginated("/feedback",s))yield*i}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:s}={}){let i={run_id:e,feedback_key:r,feedback_config:s};n?typeof n=="string"?i.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(i.expires_in=n):i.expires_in={hours:3};let a=JSON.stringify(i);return await(await this.caller.call(async()=>{let l=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:a});return await U(l,"create presigned feedback token"),l})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:s,description:i,metadata:a,id:c}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let l={id:c,name:e,experiment_ids:r,reference_dataset_id:n,description:i,created_at:(s??new Date)?.toISOString(),extra:{}};a&&(l.extra.metadata=a);let u=JSON.stringify(l);return(await this.caller.call(async()=>{let p=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:u});return await U(p,"create comparative experiment"),p})).json()}async*listPresignedFeedbackTokens(e){z(e);let r=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n){let s=this._selectEvalResults(e),i=[];for(let a of s){let c=n||{};a.evaluatorInfo&&(c={...a.evaluatorInfo,...c});let l=null;a.targetRunId?l=a.targetRunId:r&&(l=r.id),i.push(await this.createFeedback(l,a.key,{score:a.score,value:a.value,comment:a.comment,correction:a.correction,sourceInfo:c,sourceRunId:a.sourceRunId,feedbackConfig:a.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id,startTime:r?.start_time}))}return[s,i]}async logEvaluationFeedback(e,r,n){let[s]=await this._logEvaluationFeedback(e,r,n);return s}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:s=!1}=e,i={feedback_key:r,feedback_config:n,is_lower_score_better:s};return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await U(c,"create feedback config"),c})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:s}=e,i=new URLSearchParams;r&&r.forEach(c=>{i.append("key",c)}),n&&i.append("name_contains",n),i.append("limit",(s!==void 0?Math.min(s,100):100).toString());let a=0;for await(let c of this._getPaginated("/feedback-configs",i))if(yield*c,a+=c.length,s!==void 0&&a>=s)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:s}=r,i={feedback_key:e};return n!==void 0&&(i.feedback_config=n),s!==void 0&&(i.is_lower_score_better=s),(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await U(c,"update feedback config"),c})).json()}async deleteFeedbackConfig(e){let r=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/feedback-configs?${r}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:s,limit:i}=e,a=new URLSearchParams;r&&r.forEach((l,u)=>{z(l,`queueIds[${u}]`),a.append("ids",l)}),n&&a.append("name",n),s&&a.append("name_contains",s),a.append("limit",(i!==void 0?Math.min(i,100):100).toString());let c=0;for await(let l of this._getPaginated("/annotation-queues",a))if(yield*l,c++,i!==void 0&&c>=i)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:s,rubricInstructions:i,rubricItems:a}=e,c={name:r,description:n,id:s||kt(),rubric_instructions:i,rubric_items:a},l=JSON.stringify(Object.fromEntries(Object.entries(c).filter(([d,p])=>p!==void 0)));return(await this.caller.call(async()=>{let d=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:l});return await U(d,"create annotation queue"),d})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=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 U(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:s,rubricInstructions:i,rubricItems:a}=r,c={};n!==void 0&&(c.name=n),s!==void 0&&(c.description=s),i!==void 0&&(c.rubric_instructions=i),a!==void 0&&(c.rubric_items=a);let l=JSON.stringify(c);await this.caller.call(async()=>{let u=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:l});return await U(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=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 U(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=JSON.stringify(r.map((s,i)=>z(s,`runIds[${i}]`).toString()));await this.caller.call(async()=>{let 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:n});return await U(s,"add runs to annotation queue",!0),s})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${z(e,"queueId")}/run`,i=await(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"get run from annotation queue"),a})).json();return Or(i)}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${z(e,"queueId")}/runs/${z(r,"queueRunId")}`,{method:"DELETE",headers:{...this.headers,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=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 U(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
132
+ Context: ${r}`),this.failedTracesDir){let u=await this._createNodeFetchBody(e,i).catch(()=>null);u&&await t._writeTraceToFallbackDir(this.failedTracesDir,u,{"Content-Type":`multipart/form-data; boundary=${i}`},"runs/multipart",this.failedTracesMaxBytes)}}}async updateRun(e,r,n){H(e),r.inputs&&(r.inputs=await this.processInputs(r.inputs)),r.outputs&&(r.outputs=await this.processOutputs(r.outputs)),r.error&&(r.error=await this.processError(r.error)),r.extra!=null&&"metadata"in r.extra&&(r.extra={...r.extra,metadata:await this.processMetadata(r.extra.metadata)}),r.events&&(r.events=this._filterNewTokenEvents(r.events));let i={...r,id:e};if(!this._filterForSampling([i],!0).length)return;if(this.autoBatchTracing&&i.trace_id!==void 0&&i.dotted_order!==void 0){let c=this._cloneCurrentOTELContext();if(r.end_time!==void 0&&i.parent_run_id===void 0&&this.blockOnRootRunFinalization&&!this.manualFlushMode){await this.processRunOperation({action:"update",item:i,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}else this.processRunOperation({action:"update",item:i,otelContext:c,apiKey:n?.apiKey,apiUrl:n?.apiUrl,workspaceId:n?.workspaceId}).catch(console.error);return}let s={...this._mergedHeaders,"Content-Type":"application/json"};n?.apiKey!==void 0&&(s["x-api-key"]=n.apiKey),n?.workspaceId!==void 0&&(s["x-tenant-id"]=n.workspaceId);let o=Re(r,`Serializing payload to update run with id: ${e}`);await this.caller.call(async()=>{let c=await this._fetch(`${n?.apiUrl??this.apiUrl}/runs/${e}`,{method:"PATCH",headers:s,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(c,"update run",!0),c})}async readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){return _e("readRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-retrieve for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN"}),this._readRun(e,{loadChildRuns:r})}async _readRun(e,{loadChildRuns:r}={loadChildRuns:!1}){H(e);let n=Br(await this._get(`/runs/${e}`));return r&&(n=await this._loadChildRuns(n)),n}async getRunUrl({runId:e,run:r,projectOpts:n}){if(_e("getRunUrl() is deprecated and will be removed after Jan 31, 2027. Use client.runs.getURL() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-get-url for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_GET_RUN_URL"}),r!==void 0){let i;r.session_id?i=r.session_id:n?.projectName?i=(await this.readProject({projectName:n?.projectName})).id:n?.projectId?i=n?.projectId:i=(await this.readProject({projectName:Z("PROJECT")||"default"})).id;let s=await this._getTenantId();return`${this.getHostUrl()}/o/${s}/projects/p/${i}/r/${r.id}?poll=true`}else if(e!==void 0){let i=await this._readRun(e);if(!i.app_path)throw new Error(`Run ${e} has no app_path`);return`${this.getHostUrl()}${i.app_path}`}else throw new Error("Must provide either runId or run")}async _loadChildRuns(e){let r=await Py(this._listRuns({isRoot:!1,projectId:e.session_id,traceId:e.trace_id})),n={},i={};r.sort((s,o)=>(s?.dotted_order??"").localeCompare(o?.dotted_order??""));for(let s of r){if(s.parent_run_id===null||s.parent_run_id===void 0)throw new Error(`Child run ${s.id} has no parent`);s.dotted_order?.startsWith(e.dotted_order??"")&&s.id!==e.id&&(s.parent_run_id in n||(n[s.parent_run_id]=[]),n[s.parent_run_id].push(s),i[s.id]=s)}e.child_runs=n[e.id]||[];for(let s in n)s!==e.id&&(i[s].child_runs=n[s]);return e}async*listRuns(e){_e("listRuns() is deprecated and will be removed after Jan 31, 2027. Use client.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#runs-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_RUNS"}),yield*this._listRuns(e)}async*_listRuns(e){let{projectId:r,projectName:n,parentRunId:i,traceId:s,referenceExampleId:o,startTime:c,executionOrder:l,isRoot:u,runType:d,error:f,id:y,query:h,filter:g,traceFilter:b,treeFilter:w,limit:v,select:S,order:p}=e,T=[];if(r&&(T=Array.isArray(r)?r:[r]),n){let E=Array.isArray(n)?n:[n],U=await Promise.all(E.map(D=>this.readProject({projectName:D}).then(N=>N.id)));T.push(...U)}let I=["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"],C={session:T.length?T:null,run_type:d,reference_example:o,query:h,filter:g,trace_filter:b,tree_filter:w,execution_order:l,parent_run:i,start_time:c?c.toISOString():null,error:f,id:y,limit:v,trace:s,select:S||I,is_root:u,order:p};C.select.includes("child_run_ids")&&_e("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version.");let k=0;for await(let E of this._getCursorPaginatedList("/runs/query",C)){let U=E.map(Br);if(v){if(k>=v)break;if(U.length+k>v){yield*U.slice(0,v-k);break}k+=U.length,yield*U}else yield*U}}async*listGroupRuns(e){let{projectId:r,projectName:n,groupBy:i,filter:s,startTime:o,endTime:c,limit:l,offset:u}=e,f={session_id:r||(await this.readProject({projectName:n})).id,group_by:i,filter:s,start_time:o?o.toISOString():null,end_time:c?c.toISOString():null,limit:Number(l)||100},y=Number(u)||0,h="/runs/group",g=`${this.apiUrl}${h}`;for(;;){let b={...f,offset:y},w=Object.fromEntries(Object.entries(b).filter(([C,k])=>k!==void 0)),v=JSON.stringify(w),p=await(await this.caller.call(async()=>{let C=await this._fetch(g,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:v});return await L(C,`Failed to fetch ${h}`),C})).json(),{groups:T,total:I}=p;if(T.length===0)break;for(let C of T)yield C;if(y+=T.length,y>=I)break}}async*readThread(e){_e("readThread() is deprecated and will be removed after Jan 31, 2027. Use client.threads.listTraces() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#threads-list-traces for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_THREAD"});let{threadId:r,projectId:n,projectName:i,isRoot:s=!0,limit:o,filter:c,order:l="asc"}=e;if(!n&&!i)throw new Error("threadId requires projectId or projectName");let u=`eq(thread_id, ${JSON.stringify(r)})`,d=c?`and(${u}, ${c})`:u;yield*this._listRuns({projectId:n??void 0,projectName:i??void 0,isRoot:s,limit:o,filter:d,order:l})}async listThreads(e){_e("listThreads() is deprecated and will be removed after Jan 31, 2027. Use client.threads.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#threads-query for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_THREADS"});let{projectId:r,projectName:n,limit:i,offset:s=0,filter:o,startTime:c,isRoot:l=!0}=e;if(!r&&!n)throw new Error("Either projectId or projectName must be provided");if(r&&n)throw new Error("Provide exactly one of projectId or projectName");let u=r??(await this.readProject({projectName:n})).id,d=c??new Date(Date.now()-1440*60*1e3),y={session:[u],is_root:l,limit:100,order:"desc",select:["id","name","status","start_time","end_time","thread_id","trace_id","run_type","error","tags","session_id","parent_run_id","total_tokens","total_cost","dotted_order","reference_example_id","feedback_stats","app_path","completion_cost","completion_tokens","prompt_cost","prompt_tokens","first_token_time"],start_time:d.toISOString()};o!=null&&(y.filter=o);let h=new Map;for await(let v of this._getCursorPaginatedList("/runs/query",y))for(let S of v){let p=Br(S),T=p.thread_id;if(T){let I=h.get(T)??[];I.push(p),h.set(T,I)}}let g=[];for(let[v,S]of h.entries()){S.sort((k,E)=>{let U=k,D=E,N=U.start_time??"",W=D.start_time??"";if(N!==W)return N.localeCompare(W);let te=U.dotted_order??"",Se=D.dotted_order??"";return te.localeCompare(Se)});let T=[...S.map(k=>k.start_time).filter(Boolean)].sort(),I=T.length?T[0]:"",C=T.length?T[T.length-1]:"";g.push({thread_id:v,runs:S,count:S.length,filter:"",total_tokens:0,total_cost:null,min_start_time:I,max_start_time:C,latency_p50:0,latency_p99:0,feedback_stats:null,first_inputs:"",last_outputs:"",last_error:null})}g.sort((v,S)=>{let p=v.max_start_time??"";return(S.max_start_time??"").localeCompare(p)});let b=s>0?g.slice(s):g;return i!==void 0?b.slice(0,i):b}async getRunStats({id:e,trace:r,parentRun:n,runType:i,projectNames:s,projectIds:o,referenceExampleIds:c,startTime:l,endTime:u,error:d,query:f,filter:y,traceFilter:h,treeFilter:g,isRoot:b,dataSourceType:w}){let v=o||[];if(s&&(v=[...o||[],...await Promise.all(s.map(k=>this.readProject({projectName:k}).then(E=>E.id)))]),v.length===0)throw new Error("At least one of projectNames or projectIds must be provided.");let p=Object.fromEntries(Object.entries({id:e,trace:r,parent_run:n,run_type:i,session:v,reference_example:c,start_time:l,end_time:u,error:d,query:f,filter:y,trace_filter:h,tree_filter:g,is_root:b,data_source_type:w}).filter(([k,E])=>E!==void 0)),T=JSON.stringify(p);return await(await this.caller.call(async()=>{let k=await this._fetch(`${this.apiUrl}/runs/stats`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:T});return await L(k,"get run stats"),k})).json()}async shareRun(e,{shareId:r}={}){_e("shareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.create() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_SHARE_RUN"});let n={run_id:e,share_token:r||zt()};H(e);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(c,"share run"),c})).json();if(o===null||!("share_token"in o))throw new Error("Invalid response from server");return`${this.getHostUrl()}/public/${o.share_token}/r`}async unshareRun(e){_e("unshareRun() is deprecated and will be removed after Jan 31, 2027. Use client.runs.share.delete() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_UNSHARE_RUN"}),H(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(r,"unshare run",!0),r})}async readRunSharedLink(e){_e('readRunSharedLink() is deprecated and will be removed after Jan 31, 2027. Use client.runs.retrieve({ selects: ["SHARE_URL"] }) instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.',{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_READ_RUN_SHARED_LINK"}),H(e);let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/runs/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"read run shared link"),i})).json();if(!(n===null||!("share_token"in n)))return`${this.getHostUrl()}/public/${n.share_token}/r`}async listSharedRuns(e,{runIds:r}={}){_e("listSharedRuns() is deprecated and will be removed after Jan 31, 2027. Use client.public.runs.query() instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#share-and-read-public-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_LIST_SHARED_RUNS"});let n=new URLSearchParams({share_token:e});if(r!==void 0)for(let o of r)n.append("id",o);return H(e),(await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/public/${e}/runs${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,"list shared runs"),o})).json()).map(Br)}async readDatasetSharedSchema(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id),H(e);let i=await(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(s,"read dataset shared schema"),s})).json();return i.url=`${this.getHostUrl()}/public/${i.share_token}/d`,i}async shareDataset(e,r){if(!e&&!r)throw new Error("Either datasetId or datasetName must be given");e||(e=(await this.readDataset({datasetName:r})).id);let n={dataset_id:e};H(e);let i=JSON.stringify(n),o=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"PUT",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:i});return await L(c,"share dataset"),c})).json();return o.url=`${this.getHostUrl()}/public/${o.share_token}/d`,o}async unshareDataset(e){H(e),await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/datasets/${e}/share`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(r,"unshare dataset",!0),r})}async readSharedDataset(e){return H(e),await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/public/${e}/datasets`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"read shared dataset"),i})).json()}async listSharedExamples(e,r){let n={};r?.exampleIds&&(n.id=r.exampleIds);let i=new URLSearchParams;Object.entries(n).forEach(([c,l])=>{Array.isArray(l)?l.forEach(u=>i.append(c,u)):i.append(c,l)});let s=await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/public/${e}/examples?${i.toString()}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(c,"list shared examples"),c}),o=await s.json();if(!s.ok)throw"detail"in o?new Error(`Failed to list shared examples.
133
+ Status: ${s.status}
134
+ Message: ${Array.isArray(o.detail)?o.detail.join(`
135
+ `):"Unspecified error"}`):new Error(`Failed to list shared examples: ${s.status} ${s.statusText}`);return o.map(c=>({...c,_hostUrl:this.getHostUrl()}))}async createProject({projectName:e,description:r=null,metadata:n=null,upsert:i=!1,projectExtra:s=null,referenceDatasetId:o=null,numExamples:c=null,numRepetitions:l=null,evaluatorKeys:u=null}){let d=i?"?upsert=true":"",f=`${this.apiUrl}/sessions${d}`,y=s||{};n&&(y.metadata=n);let h={name:e,extra:y,description:r};o!==null&&(h.reference_dataset_id=o),c!=null&&(h.num_examples=c),l!=null&&(h.num_repetitions=l),u!=null&&u.length>0&&(h.evaluator_keys=u);let g=JSON.stringify(h);return await(await this.caller.call(async()=>{let v=await this._fetch(f,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:g});return await L(v,"create project"),v})).json()}async updateProject(e,{name:r=null,description:n=null,metadata:i=null,projectExtra:s=null,endTime:o=null}){let c=`${this.apiUrl}/sessions/${e}`,l=s;i&&(l={...l||{},metadata:i});let u=JSON.stringify({name:r,extra:l,description:n,end_time:o?new Date(o).toISOString():null});return await(await this.caller.call(async()=>{let y=await this._fetch(c,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(y,"update project"),y})).json()}async hasProject({projectId:e,projectName:r}){let n="/sessions",i=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)H(e),n+=`/${e}`;else if(r!==void 0)i.append("name",r);else throw new Error("Must provide projectName or projectId");let s=await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${n}?${i}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,"has project"),o});try{let o=await s.json();return s.ok?Array.isArray(o)?o.length>0:!0:!1}catch{return!1}}async readProject({projectId:e,projectName:r,includeStats:n}){let i="/sessions",s=new URLSearchParams;if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(e!==void 0)H(e),i+=`/${e}`;else if(r!==void 0)s.append("name",r);else throw new Error("Must provide projectName or projectId");n!==void 0&&s.append("include_stats",n.toString());let o=await this._get(i,s),c;if(Array.isArray(o)){if(o.length===0)throw new Error(`Project[id=${e}, name=${r}] not found`);c=o[0]}else c=o;return c}async getProjectUrl({projectId:e,projectName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either projectName or projectId");let n=await this.readProject({projectId:e,projectName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/projects/p/${n.id}`}async getDatasetUrl({datasetId:e,datasetName:r}){if(e===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");let n=await this.readDataset({datasetId:e,datasetName:r}),i=await this._getTenantId();return`${this.getHostUrl()}/o/${i}/datasets/${n.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let e=new URLSearchParams({limit:"1"});for await(let r of this._getPaginated("/sessions",e))return this._tenantId=r[0].tenant_id,r[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:e,name:r,nameContains:n,referenceDatasetId:i,referenceDatasetName:s,includeStats:o,datasetVersion:c,referenceFree:l,metadata:u}={}){let d=new URLSearchParams;if(e!==void 0)for(let f of e)d.append("id",f);if(r!==void 0&&d.append("name",r),n!==void 0&&d.append("name_contains",n),i!==void 0)d.append("reference_dataset",i);else if(s!==void 0){let f=await this.readDataset({datasetName:s});d.append("reference_dataset",f.id)}o!==void 0&&d.append("include_stats",o.toString()),c!==void 0&&d.append("dataset_version",c),l!==void 0&&d.append("reference_free",l.toString()),u!==void 0&&d.append("metadata",JSON.stringify(u));for await(let f of this._getPaginated("/sessions",d))yield*f}async deleteProject({projectId:e,projectName:r}){let n;if(e===void 0&&r===void 0)throw new Error("Must provide projectName or projectId");if(e!==void 0&&r!==void 0)throw new Error("Must provide either projectName or projectId, not both");e===void 0?n=(await this.readProject({projectName:r})).id:n=e,H(n),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/sessions/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,`delete session ${n} (${r})`,!0),i})}async uploadCsv({csvFile:e,fileName:r,inputKeys:n,outputKeys:i,description:s,dataType:o,name:c}){let l=`${this.apiUrl}/datasets/upload`,u=new FormData,d=new Blob([e],{type:"text/csv"});return u.append("file",d,r),n.forEach(h=>{u.append("input_keys",h)}),i.forEach(h=>{u.append("output_keys",h)}),s&&u.append("description",s),o&&u.append("data_type",o),c&&u.append("name",c),await(await this.caller.call(async()=>{let h=await this._fetch(l,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(h,"upload CSV"),h})).json()}async createDataset(e,{description:r,dataType:n,inputsSchema:i,outputsSchema:s,metadata:o}={}){let c={name:e,description:r,extra:{source:"sdk",...o?{metadata:o}:{}}};n&&(c.data_type=n),i&&(c.inputs_schema_definition=i),s&&(c.outputs_schema_definition=s);let l=JSON.stringify(c);return await(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/datasets`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(f,"create dataset"),f})).json()}async readDataset({datasetId:e,datasetName:r}){let n="/datasets",i=new URLSearchParams({limit:"1"});if(e&&r)throw new Error("Must provide either datasetName or datasetId, not both");if(e)H(e),n+=`/${e}`;else if(r)i.append("name",r);else throw new Error("Must provide datasetName or datasetId");let s=await this._get(n,i),o;if(Array.isArray(s)){if(s.length===0)throw new Error(`Dataset[id=${e}, name=${r}] not found`);o=s[0]}else o=s;return o}async hasDataset({datasetId:e,datasetName:r}){try{return await this.readDataset({datasetId:e,datasetName:r}),!0}catch(n){if(n instanceof Error&&n.message.toLocaleLowerCase().includes("not found"))return!1;throw n}}async diffDatasetVersions({datasetId:e,datasetName:r,fromVersion:n,toVersion:i}){let s=e;if(s===void 0&&r===void 0)throw new Error("Must provide either datasetName or datasetId");if(s!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");s===void 0&&(s=(await this.readDataset({datasetName:r})).id);let o=new URLSearchParams({from_version:typeof n=="string"?n:n.toISOString(),to_version:typeof i=="string"?i:i.toISOString()});return await this._get(`/datasets/${s}/versions/diff`,o)}async readDatasetOpenaiFinetuning({datasetId:e,datasetName:r}){let n="/datasets";if(e===void 0)if(r!==void 0)e=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide either datasetName or datasetId");return(await(await this._getResponse(`${n}/${e}/openai_ft`)).text()).trim().split(`
136
+ `).map(c=>JSON.parse(c))}async*listDatasets({limit:e=100,offset:r=0,datasetIds:n,datasetName:i,datasetNameContains:s,metadata:o}={}){let c="/datasets",l=new URLSearchParams({limit:e.toString(),offset:r.toString()});if(n!==void 0)for(let u of n)l.append("id",u);i!==void 0&&l.append("name",i),s!==void 0&&l.append("name_contains",s),o!==void 0&&l.append("metadata",JSON.stringify(o));for await(let u of this._getPaginated(c,l))yield*u}async updateDataset(e){let{datasetId:r,datasetName:n,...i}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let s=r??(await this.readDataset({datasetName:n})).id;H(s);let o=JSON.stringify(i);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(l,"update dataset"),l})).json()}async updateDatasetTag(e){let{datasetId:r,datasetName:n,asOf:i,tag:s}=e;if(!r&&!n)throw new Error("Must provide either datasetName or datasetId");let o=r??(await this.readDataset({datasetName:n})).id;H(o);let c=JSON.stringify({as_of:typeof i=="string"?i:i.toISOString(),tag:s});await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${o}/tags`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await L(l,"update dataset tags",!0),l})}async deleteDataset({datasetId:e,datasetName:r}){let n="/datasets",i=e;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(r!==void 0&&(i=(await this.readDataset({datasetName:r})).id),i!==void 0)H(i),n+=`/${i}`;else throw new Error("Must provide datasetName or datasetId");await this.caller.call(async()=>{let s=await this._fetch(this.apiUrl+n,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(s,`delete ${n}`,!0),s})}async createExample(e,r,n){if(pd(e)&&(r!==void 0||n!==void 0))throw new Error("Cannot provide outputs or options when using ExampleCreate object");let i=r?n?.datasetId:e.dataset_id,s=r?n?.datasetName:e.dataset_name;if(i===void 0&&s===void 0)throw new Error("Must provide either datasetName or datasetId");if(i!==void 0&&s!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");i===void 0&&(i=(await this.readDataset({datasetName:s})).id);let o=(r?n?.createdAt:e.created_at)||new Date,c;pd(e)?c=e:c={inputs:e,outputs:r,created_at:o?.toISOString(),id:n?.exampleId,metadata:n?.metadata,split:n?.split,source_run_id:n?.sourceRunId,use_source_run_io:n?.useSourceRunIO,use_source_run_attachments:n?.useSourceRunAttachments,attachments:n?.attachments};let l=await this._uploadExamplesMultipart(i,[c]);return await this.readExample(l.example_ids?.[0]??zt())}async createExamples(e){if(Array.isArray(e)){if(e.length===0)return[];let S=e,p=S[0].dataset_id,T=S[0].dataset_name;if(p===void 0&&T===void 0)throw new Error("Must provide either datasetName or datasetId");if(p!==void 0&&T!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");p===void 0&&(p=(await this.readDataset({datasetName:T})).id);let I=await this._uploadExamplesMultipart(p,S);return await Promise.all(I.example_ids.map(k=>this.readExample(k)))}let{inputs:r,outputs:n,metadata:i,splits:s,sourceRunIds:o,useSourceRunIOs:c,useSourceRunAttachments:l,attachments:u,exampleIds:d,datasetId:f,datasetName:y}=e;if(r===void 0)throw new Error("Must provide inputs when using legacy parameters");let h=f,g=y;if(h===void 0&&g===void 0)throw new Error("Must provide either datasetName or datasetId");if(h!==void 0&&g!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");h===void 0&&(h=(await this.readDataset({datasetName:g})).id);let b=r.map((S,p)=>({dataset_id:h,inputs:S,outputs:n?.[p],metadata:i?.[p],split:s?.[p],id:d?.[p],attachments:u?.[p],source_run_id:o?.[p],use_source_run_io:c?.[p],use_source_run_attachments:l?.[p]})),w=await this._uploadExamplesMultipart(h,b);return await Promise.all(w.example_ids.map(S=>this.readExample(S)))}async createLLMExample(e,r,n){return this.createExample({input:e},{output:r},n)}async createChatExample(e,r,n){let i=e.map(o=>ua(o)?da(o):o),s=ua(r)?da(r):r;return this.createExample({input:i},{output:s},n)}async readExample(e){H(e);let r=`/examples/${e}`,n=await this._get(r),{attachment_urls:i,...s}=n,o=s;return i&&(o.attachments=Object.entries(i).reduce((c,[l,u])=>(c[l.slice(11)]={presigned_url:u.presigned_url,mime_type:u.mime_type},c),{})),o}async*listExamples({datasetId:e,datasetName:r,exampleIds:n,asOf:i,splits:s,inlineS3Urls:o,metadata:c,limit:l,offset:u,filter:d,includeAttachments:f}={}){let y;if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0)y=e;else if(r!==void 0)y=(await this.readDataset({datasetName:r})).id;else throw new Error("Must provide a datasetName or datasetId");let h=new URLSearchParams({dataset:y}),g=i?typeof i=="string"?i:i?.toISOString():void 0;g&&h.append("as_of",g);let b=o??!0;if(h.append("inline_s3_urls",b.toString()),n!==void 0)for(let v of n)h.append("id",v);if(s!==void 0)for(let v of s)h.append("splits",v);if(c!==void 0){let v=JSON.stringify(c);h.append("metadata",v)}l!==void 0&&h.append("limit",l.toString()),u!==void 0&&h.append("offset",u.toString()),d!==void 0&&h.append("filter",d),f===!0&&["attachment_urls","outputs","metadata"].forEach(v=>h.append("select",v));let w=0;for await(let v of this._getPaginated("/examples",h)){for(let S of v){let{attachment_urls:p,...T}=S,I=T;p&&(I.attachments=Object.entries(p).reduce((C,[k,E])=>(C[k.slice(11)]={presigned_url:E.presigned_url,mime_type:E.mime_type||void 0},C),{})),yield I,w++}if(l!==void 0&&w>=l)break}}async deleteExample(e){H(e);let r=`/examples/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,`delete ${r}`,!0),n})}async deleteExamples(e,r){if(e.forEach(n=>H(n)),r?.hardDelete){let n=this._getPlatformEndpointPath("datasets/examples/delete");await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${n}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},body:JSON.stringify({example_ids:e,hard_delete:!0}),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"hard delete examples",!0),i})}else{let n=new URLSearchParams;e.forEach(i=>n.append("example_ids",i)),await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/examples?${n.toString()}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"delete examples",!0),i})}}async updateExample(e,r){let n;r?n=e:n=e.id,H(n);let i;r?i={id:n,...r}:i=e;let s;return i.dataset_id!==void 0?s=i.dataset_id:s=(await this.readExample(n)).dataset_id,this._updateExamplesMultipart(s,[i])}async updateExamples(e){let r;return e[0].dataset_id===void 0?r=(await this.readExample(e[0].id)).dataset_id:r=e[0].dataset_id,this._updateExamplesMultipart(r,e)}async readDatasetVersion({datasetId:e,datasetName:r,asOf:n,tag:i}){let s;if(e?s=e:s=(await this.readDataset({datasetName:r})).id,H(s),n&&i||!n&&!i)throw new Error("Exactly one of asOf and tag must be specified.");let o=new URLSearchParams;return n!==void 0&&o.append("as_of",typeof n=="string"?n:n.toISOString()),i!==void 0&&o.append("tag",i),await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/datasets/${s}/version?${o.toString()}`,{method:"GET",headers:{...this._mergedHeaders},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(l,"read dataset version"),l})).json()}async listDatasetSplits({datasetId:e,datasetName:r,asOf:n}){let i;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?i=(await this.readDataset({datasetName:r})).id:i=e,H(i);let s=new URLSearchParams,o=n?typeof n=="string"?n:n?.toISOString():void 0;return o&&s.append("as_of",o),await this._get(`/datasets/${i}/splits`,s)}async updateDatasetSplits({datasetId:e,datasetName:r,splitName:n,exampleIds:i,remove:s=!1}){let o;if(e===void 0&&r===void 0)throw new Error("Must provide dataset name or ID");if(e!==void 0&&r!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");e===void 0?o=(await this.readDataset({datasetName:r})).id:o=e,H(o);let c={split_name:n,examples:i.map(u=>(H(u),u)),remove:s},l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/datasets/${o}/splits`,{method:"PUT",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(u,"update dataset splits",!0),u})}async createFeedback(e,r,n){let{runId:i=null,key:s,score:o,value:c,correction:l,comment:u,sourceInfo:d,feedbackSourceType:f="api",sourceRunId:y,feedbackId:h,feedbackConfig:g,projectId:b,comparativeExperimentId:w,sessionId:v,startTime:S,extendTraceRetention:p}=typeof e=="object"&&e!==null?e:{runId:e,key:r,...n};if(!i&&!b)throw new Error("One of runId or projectId must be provided");if(i&&b)throw new Error("Only one of runId or projectId can be provided");i&&v===void 0&&await this._checkFeedbackSessionId();let T={type:f??"api",metadata:d??{}};y!==void 0&&T?.metadata!==void 0&&!T.metadata.__run&&(T.metadata.__run={run_id:y}),T?.metadata!==void 0&&T.metadata.__run?.run_id!==void 0&&H(T.metadata.__run.run_id);let I={id:h??Er(),run_id:i,key:s,score:ud(o),value:c,correction:l,comment:u,feedback_source:T,comparative_experiment_id:w,feedbackConfig:g,session_id:v??b,start_time:S,extend_trace_retention:p},C=JSON.stringify(I),k=`${this.apiUrl}/feedback`;return await this.caller.call(async()=>{let E=await this._fetch(k,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:C});return await L(E,"create feedback",!0),E}),I}async updateFeedback(e,{score:r,value:n,correction:i,comment:s}){let o={};r!=null&&(o.score=ud(r)),n!=null&&(o.value=n),i!=null&&(o.correction=i),s!=null&&(o.comment=s),H(e);let c=JSON.stringify(o);await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/${e}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:c});return await L(l,"update feedback",!0),l})}async readFeedback(e){H(e);let r=`/feedback/${e}`;return await this._get(r)}async deleteFeedback(e){H(e);let r=`/feedback/${e}`;await this.caller.call(async()=>{let n=await this._fetch(this.apiUrl+r,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,`delete ${r}`,!0),n})}async*listFeedback({runIds:e,feedbackKeys:r,feedbackSourceTypes:n}={}){let i=new URLSearchParams;if(e)for(let s of e)H(s),i.append("run",s);if(r)for(let s of r)i.append("key",s);if(n)for(let s of n)i.append("source",s);for await(let s of this._getPaginated("/feedback",i))yield*s}async createPresignedFeedbackToken(e,r,{expiration:n,feedbackConfig:i}={}){let s={run_id:e,feedback_key:r,feedback_config:i};n?typeof n=="string"?s.expires_at=n:(n?.hours||n?.minutes||n?.days)&&(s.expires_in=n):s.expires_in={hours:3};let o=JSON.stringify(s);return await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/feedback/tokens`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(l,"create presigned feedback token"),l})).json()}async createComparativeExperiment({name:e,experimentIds:r,referenceDatasetId:n,createdAt:i,description:s,metadata:o,id:c}){if(r.length===0)throw new Error("At least one experiment is required");if(n||(n=(await this.readProject({projectId:r[0]})).reference_dataset_id),!n==null)throw new Error("A reference dataset is required");let l={id:c,name:e,experiment_ids:r,reference_dataset_id:n,description:s,created_at:(i??new Date)?.toISOString(),extra:{}};o&&(l.extra.metadata=o);let u=JSON.stringify(l);return(await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/datasets/comparative`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(f,"create comparative experiment"),f})).json()}async*listPresignedFeedbackTokens(e){H(e);let r=new URLSearchParams({run_id:e});for await(let n of this._getPaginated("/feedback/tokens",r))yield*n}_selectEvalResults(e){let r;return"results"in e?r=e.results:Array.isArray(e)?r=e:r=[e],r}async _logEvaluationFeedback(e,r,n,i){let s=this._selectEvalResults(e),o=[];for(let c of s){let l=n||{};c.evaluatorInfo&&(l={...c.evaluatorInfo,...l});let u=null;c.targetRunId?u=c.targetRunId:r&&(u=r.id),o.push(await this.createFeedback(u,c.key,{score:c.score,value:c.value,comment:c.comment,correction:c.correction,sourceInfo:l,sourceRunId:c.sourceRunId,feedbackConfig:c.feedbackConfig,feedbackSourceType:"model",sessionId:r?.session_id??i,startTime:r?.start_time}))}return[s,o]}async logEvaluationFeedback(e,r,n,i){if(e!=null&&typeof e=="object"&&"evaluatorResponse"in e){let[o]=await this._logEvaluationFeedback(e.evaluatorResponse,e.run,e.sourceInfo,e.projectId);return o}let[s]=await this._logEvaluationFeedback(e,r,n,i);return s}async createFeedbackConfig(e){let{feedbackKey:r,feedbackConfig:n,isLowerScoreBetter:i=!1}=e,s={feedback_key:r,feedback_config:n,is_lower_score_better:i};return(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await L(c,"create feedback config"),c})).json()}async*listFeedbackConfigs(e={}){let{feedbackKeys:r,nameContains:n,limit:i}=e,s=new URLSearchParams;r&&r.forEach(c=>{s.append("key",c)}),n&&s.append("name_contains",n),s.append("limit",(i!==void 0?Math.min(i,100):100).toString());let o=0;for await(let c of this._getPaginated("/feedback-configs",s))if(yield*c,o+=c.length,i!==void 0&&o>=i)break}async updateFeedbackConfig(e,r={}){let{feedbackConfig:n,isLowerScoreBetter:i}=r,s={feedback_key:e};return n!==void 0&&(s.feedback_config=n),i!==void 0&&(s.is_lower_score_better=i),(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/feedback-configs`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(s)});return await L(c,"update feedback config"),c})).json()}async deleteFeedbackConfig(e){let r=new URLSearchParams({feedback_key:e});await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/feedback-configs?${r}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"delete feedback config",!0),n})}async*listAnnotationQueues(e={}){let{queueIds:r,name:n,nameContains:i,limit:s}=e,o=new URLSearchParams;r&&r.forEach((l,u)=>{H(l,`queueIds[${u}]`),o.append("ids",l)}),n&&o.append("name",n),i&&o.append("name_contains",i),o.append("limit",(s!==void 0?Math.min(s,100):100).toString());let c=0;for await(let l of this._getPaginated("/annotation-queues",o))if(yield*l,c++,s!==void 0&&c>=s)break}async createAnnotationQueue(e){let{name:r,description:n,queueId:i,rubricInstructions:s,rubricItems:o}=e,c={name:r,description:n,id:i||zt(),rubric_instructions:s,rubric_items:o},l=JSON.stringify(Object.fromEntries(Object.entries(c).filter(([d,f])=>f!==void 0)));return(await this.caller.call(async()=>{let d=await this._fetch(`${this.apiUrl}/annotation-queues`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(d,"create annotation queue"),d})).json()}async readAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"read annotation queue"),n})).json()}async updateAnnotationQueue(e,r){let{name:n,description:i,rubricInstructions:s,rubricItems:o}=r,c={};n!==void 0&&(c.name=n),i!==void 0&&(c.description=i),s!==void 0&&(c.rubric_instructions=s),o!==void 0&&(c.rubric_items=o);let l=JSON.stringify(c);await this.caller.call(async()=>{let u=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(u,"update annotation queue",!0),u})}async deleteAnnotationQueue(e){await this.caller.call(async()=>{let r=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(r,"delete annotation queue",!0),r})}async addRunsToAnnotationQueue(e,r){let n=`${this.apiUrl}/annotation-queues/${H(e,"queueId")}/runs`,i=r.every(c=>typeof c=="string"),s,o;i?(_e("Passing run IDs as strings to addRunsToAnnotationQueue() is deprecated and will be removed after Jan 31, 2027. Use RunKey[] instead. See https://docs.langchain.com/langsmith/smithdb-sdk-migration#annotation-queues-add-runs for the migration guide.",{type:"DeprecationWarning",code:"LANGSMITH_DEPRECATED_ADD_RUNS_STRING_IDS"}),s=n,o=JSON.stringify(r.map((c,l)=>H(c,`runs[${l}]`).toString()))):(s=`${n}/by-key`,o=JSON.stringify(r.map((c,l)=>{let u={run_id:H(c.runId,`runs[${l}].runId`).toString(),session_id:H(c.sessionId,`runs[${l}].sessionId`).toString(),start_time:typeof c.startTime=="string"?c.startTime:new Date(c.startTime).toISOString()};return c.sourceProposedExampleId!=null&&(u.source_proposed_example_id=H(c.sourceProposedExampleId,`runs[${l}].sourceProposedExampleId`).toString()),u}))),await this.caller.call(async()=>{let c=await this._fetch(s,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(c,"add runs to annotation queue",!0),c})}async getRunFromAnnotationQueue(e,r){let n=`/annotation-queues/${H(e,"queueId")}/run`,s=await(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${n}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,"get run from annotation queue"),o})).json();return Br(s)}async*listRunsFromAnnotationQueue(e,r={}){let{status:n,limit:i}=r,s=new URLSearchParams,o=i!==void 0&&Number.isFinite(i)?Math.min(i,100):100;n&&s.append("status",n),s.append("limit",o.toString());let c=0,l=`/annotation-queues/${H(e,"queueId")}/runs`;for await(let u of this._getPaginated(l,s))for(let d of u)if(yield Br(d),c++,c>=o)return}async deleteRunFromAnnotationQueue(e,r){await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}/runs/${H(r,"queueRunId")}`,{method:"DELETE",headers:{...this._mergedHeaders,Accept:"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"delete run from annotation queue",!0),n})}async getSizeFromAnnotationQueue(e){return(await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/annotation-queues/${H(e,"queueId")}/size`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"get size from annotation queue"),n})).json()}async _currentTenantIsOwner(e){let r=await this._getSettings();return e=="-"||r.tenant_handle===e}async _ownerConflictError(e,r){let n=await this._getSettings();return new Error(`Cannot ${e} for another tenant.
37
137
 
38
138
  Current tenant: ${n.tenant_handle}
39
139
 
40
- Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let 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 U(s,"get latest commit hash"),s})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _likeOrUnlikePrompt(e,r){let[n,s,i]=ct(e),a=JSON.stringify({like:r});return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/likes/${n}/${s}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,`${r?"like":"unlike"} prompt`),l})).json()}async _getPromptUrl(e){let[r,n,s]=ct(e);if(await this._currentTenantIsOwner(r)){let i=await this._getSettings();return s!=="latest"?`${this.getHostUrl()}/prompts/${n}/${s.substring(0,8)}?organizationId=${i.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${i.id}`}else return s!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${s.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}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){let[r,n,s]=ct(e);for await(let i of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,a=>a.commits))yield*i}async*listPrompts(e){let r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(let n of this._getPaginated("/repos",r,s=>s.repos))yield*n}async getPrompt(e){let[r,n,s]=ct(e),a=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return c?.status===404?null:(await U(c,"get prompt"),c)}))?.json();return a?.repo?a.repo:null}async createPrompt(e,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
140
+ Requested tenant: ${r}`)}async _getLatestCommitHash(e){let n=await(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}/commits/${e}/?limit=1&offset=0`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"get latest commit hash"),i})).json();if(n.commits.length!==0)return n.commits[0].commit_hash}async _createCommitTags(e,r,n){let i=typeof n=="string"?[n]:n;await Promise.all(i.map(async s=>this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${e}/tags`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify({tag_name:s,commit_id:r})});return await L(o,"create commit tag"),o})))}async _likeOrUnlikePrompt(e,r){let[n,i,s]=Ce(e),o=JSON.stringify({like:r});return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/likes/${n}/${i}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(l,`${r?"like":"unlike"} prompt`),l})).json()}async _getPromptUrl(e){let[r,n,i]=Ce(e);if(await this._currentTenantIsOwner(r)){let s=await this._getSettings();return i!=="latest"?`${this.getHostUrl()}/prompts/${n}/${i.substring(0,8)}?organizationId=${s.id}`:`${this.getHostUrl()}/prompts/${n}?organizationId=${s.id}`}else return i!=="latest"?`${this.getHostUrl()}/hub/${r}/${n}/${i.substring(0,8)}`:`${this.getHostUrl()}/hub/${r}/${n}`}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){let[r,n,i]=Ce(e);for await(let s of this._getPaginated(`/commits/${r}/${n}/`,new URLSearchParams,o=>o.commits))yield*s}async*listPrompts(e){let r=new URLSearchParams;r.append("sort_field",e?.sortField??"updated_at"),r.append("sort_direction","desc"),r.append("is_archived",(!!e?.isArchived).toString()),e?.isPublic!==void 0&&r.append("is_public",e.isPublic.toString()),e?.query&&r.append("query",e.query);for await(let n of this._getPaginated("/repos",r,i=>i.repos))yield*n}async getPrompt(e){let[r,n,i]=Ce(e),o=await(await this.caller.call(async()=>{let c=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return c?.status===404?null:(await L(c,"get prompt"),c)}))?.json();return o?.repo?o.repo:null}async createPrompt(e,r){let n=await this._getSettings();if(r?.isPublic&&!n.tenant_handle)throw new Error(`Cannot create a public prompt without first
41
141
 
42
142
  creating a LangChain Hub handle.
43
143
  You can add a handle by creating a public prompt at:
44
144
 
45
- https://smith.langchain.com/prompts`);let[s,i,a]=ct(e);if(!await this._currentTenantIsOwner(s))throw await this._ownerConflictError("create a prompt",s);let c={repo_handle:i,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},l=JSON.stringify(c),u=await this.caller.call(async()=>{let p=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await U(p,"create prompt"),p}),{repo:d}=await u.json();return d}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[s,i,a]=ct(e),c=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${s}/${i}`):n?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(r)),parent_commit:c},u=JSON.stringify(l),p=await(await this.caller.call(async()=>{let _=await this._fetch(`${this.apiUrl}/commits/${s}/${i}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await U(_,"create commit"),_})).json();return this._getPromptUrl(`${s}/${i}${p.commit_hash?`:${p.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){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.");let n=new FormData;for(let a of r){let c=a.id,l={...a.metadata&&{metadata:a.metadata},...a.split&&{split:a.split}},u=Pe(l,`Serializing body for example with id: ${c}`),d=new Blob([u],{type:"application/json"});if(n.append(c,d),a.inputs){let p=Pe(a.inputs,`Serializing inputs for example with id: ${c}`),_=new Blob([p],{type:"application/json"});n.append(`${c}.inputs`,_)}if(a.outputs){let p=Pe(a.outputs,`Serializing outputs whle updating example with id: ${c}`),_=new Blob([p],{type:"application/json"});n.append(`${c}.outputs`,_)}if(a.attachments)for(let[p,_]of Object.entries(a.attachments)){let g,y;Array.isArray(_)?[g,y]=_:(g=_.mimeType,y=_.data);let E=new Blob([y],{type:`${g}; length=${y.byteLength}`});n.append(`${c}.attachment.${p}`,E)}if(a.attachments_operations){let p=Pe(a.attachments_operations,`Serializing attachments while updating example with id: ${c}`),_=new Blob([p],{type:"application/json"});n.append(`${c}.attachments_operations`,_)}}let s=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${s}/examples`)}`,{method:"PATCH",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(a,"update examples"),a})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){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.");let n=new FormData;for(let i of r){let a=(i.id??kt()).toString(),c={created_at:i.created_at,...i.metadata&&{metadata:i.metadata},...i.split&&{split:i.split},...i.source_run_id&&{source_run_id:i.source_run_id},...i.use_source_run_io&&{use_source_run_io:i.use_source_run_io},...i.use_source_run_attachments&&{use_source_run_attachments:i.use_source_run_attachments}},l=Pe(c,`Serializing body for uploaded example with id: ${a}`),u=new Blob([l],{type:"application/json"});if(n.append(a,u),i.inputs){let d=Pe(i.inputs,`Serializing inputs for uploaded example with id: ${a}`),p=new Blob([d],{type:"application/json"});n.append(`${a}.inputs`,p)}if(i.outputs){let d=Pe(i.outputs,`Serializing outputs for uploaded example with id: ${a}`),p=new Blob([d],{type:"application/json"});n.append(`${a}.outputs`,p)}if(i.attachments)for(let[d,p]of Object.entries(i.attachments)){let _,g;Array.isArray(p)?[_,g]=p:(_=p.mimeType,g=p.data);let y=new Blob([g],{type:`${_}; length=${g.byteLength}`});n.append(`${a}.attachment.${d}`,y)}}return(await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await U(i,"upload examples"),i})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,s]=ct(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let i={};if(r?.description!==void 0&&(i.description=r.description),r?.readme!==void 0&&(i.readme=r.readme),r?.tags!==void 0&&(i.tags=r.tags),r?.isPublic!==void 0&&(i.is_public=r.isPublic),r?.isArchived!==void 0&&(i.is_archived=r.isArchived),Object.keys(i).length===0)throw new Error("No valid update options provided");let a=JSON.stringify(i);return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${n}/${s}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:a});return await U(l,"update prompt"),l})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,s]=ct(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let a=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(a,"delete prompt"),a})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,s,i]=ct(e),c=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/commits/${n}/${s}/${i}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await U(l,"pull prompt commit"),l})).json();return{owner:n,repo:s,commit_hash:c.commit_hash,manifest:c.manifest,examples:c.examples}}async pullPromptCommit(e,r){let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let s=this._getPromptCacheKey(e,r?.includeModel),i=this._promptCache.get(s,n);if(i)return i;let a=await n();return this._promptCache.set(s,a,n),a}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){let n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&Object.keys(r).some(s=>s!=="object")&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash}):await this._getPromptUrl(e)}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:s}=r,[i,a]=this.parseTokenOrUrl(e,n),c=new t({apiUrl:i,apiKey:"placeholder"}),l=await c.readSharedDataset(a),u=s||l.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let d=await c.listSharedExamples(a),p=await this.createDataset(u,{description:l.description,dataType:l.data_type||"kv",inputsSchema:l.inputs_schema_definition??void 0,outputsSchema:l.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(_=>_.inputs),outputs:d.flatMap(_=>_.outputs?[_.outputs]:[]),datasetId:p.id})}catch(_){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),_}}parseTokenOrUrl(e,r,n=2,s="dataset"){try{return z(e),[r,e]}catch{}try{let a=new URL(e).pathname.split("/").filter(c=>c!=="");if(a.length>=n){let c=a[a.length-n];return[r,c]}else throw new Error(`Invalid public ${s} URL: ${e}`)}catch{throw new Error(`Invalid public ${s} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}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 new Promise(e=>setTimeout(e,1)),await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await Cl()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}};Object.defineProperty(vt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function Cd(t){return"dataset_id"in t||"dataset_name"in t}o(Cd,"isExampleCreate");var Od=o(t=>t!==void 0?t:!!["TRACING_V2","TRACING"].find(r=>te(r)==="true"),"isTracingEnabled");var lt=Symbol.for("lc:context_variables");var zn=Symbol.for("langsmith:replica_trace_roots");function Wi(t,e){if(lt in t)return t[lt][e]}o(Wi,"getContextVar");function Nd(t,e,r){let n=lt in t?t[lt]:{};n[e]=r,t[lt]=n}o(Nd,"setContextVar");var Nr=36,Qb="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function Md(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Zs(r,Qb)}o(Md,"getReplicaKey");function eE(t){return t.replace(/[-:.]/g,"")}o(eE,"stripNonAlphanumeric");function Pd(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}o(Pd,"getMicrosecondPrecisionDatestring");function qi(t,e,r=1){let n=Pd(t,r);return{dottedOrder:eE(n)+e,microsecondPrecisionDatestring:n}}o(qi,"convertToDottedOrderFormat");var tE=new Set(["projectName","updates","reroot"]);function rE(t){let e={};for(let r of Object.keys(t))tE.has(r)&&(e[r]=t[r]);return e}o(rE,"filterReplicaForHeaders");var Vn=class t{static{o(this,"Baggage")}constructor(e,r,n,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=r,this.project_name=n,this.replicas=s}static fromHeader(e){let r=e.split(","),n={},s=[],i,a;for(let c of r){let[l,u]=c.split("="),d=decodeURIComponent(u);l==="langsmith-metadata"?n=JSON.parse(d):l==="langsmith-tags"?s=d.split(","):l==="langsmith-project"?i=d:l==="langsmith-replicas"&&(a=JSON.parse(d).map(_=>Array.isArray(_)?_:rE(_)))}return new t(n,s,i,a)}toHeader(){let 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(",")}},Qe=class t{static{o(this,"RunTree")}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,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Ld(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...s}=e,i=s.client??t.getSharedClient(),a={...n,...s?.extra?.metadata};if(s.extra={...s.extra,metadata:a},"id"in s&&s.id==null&&delete s.id,Object.assign(this,{...r,...s,client:i}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=Pd(this.start_time,this.execution_order)),this.id||(this.id=gn(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=aE(this.replicas),!this.dotted_order){let{dottedOrder:c}=qi(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+c:this.dotted_order=c}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:br(),child_runs:[],api_url:Be("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:Be("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new vt),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(_=>{let{reroot:g,...y}=_;return y}),s=e.replicas??n,i=new t({...e,parent_run:this,project_name:this.project_name,replicas:s,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),a=this.extra?.metadata??{},c=i.extra?.metadata??{};Object.keys(a).length>0&&(i.extra={...i.extra,metadata:{...a,...c}}),lt in this&&(i[lt]=this[lt]);let l=Symbol.for("lc:child_config"),u=e.extra?.[l]??this.extra[l];if(sE(u)){let _={...u},g=nE(_.callbacks)?_.callbacks.copy?.():void 0;g&&(Object.assign(g,{_parentRunId:i.id}),g.handlers?.find(Dd)?.updateFromRunTree?.(i),_.callbacks=g),i.extra[l]=_}let d=new Set,p=this;for(;p!=null&&!d.has(p.id);)d.add(p.id),p.child_execution_order=Math.max(p.child_execution_order,r),p=p.parent_run;return this.child_runs.push(i),i}async end(e,r,n=Date.now(),s){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,s&&Object.keys(s).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...s}}:{metadata:s})}_convertToCreate(e,r,n=!0){let s=e.extra??{};if(s?.runtime?.library===void 0&&(s.runtime||(s.runtime={}),r))for(let[c,l]of Object.entries(r))s.runtime[c]||(s.runtime[c]=l);let i=e.parent_run?.id??e.parent_run_id,a;return n?a=[]:a=e.child_runs.map(c=>this._convertToCreate(c,r,n)),{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}}_sliceParentId(e,r){if(r.dotted_order){let n=r.dotted_order.split("."),s=null;for(let i=0;i<n.length;i++)if(n[i].slice(-Nr)===e){s=i;break}if(s!==null){let i=n.slice(s+1);r.dotted_order=i.join("."),i.length>0?r.trace_id=i[0].slice(-Nr):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=Wi(this,zn)??{};n[e]=r,Nd(this,zn,n);for(let s of this.child_runs)s._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,runtimeEnv:n,excludeChildRuns:s=!0,reroot:i=!1,distributedParentId:a,apiUrl:c,apiKey:l,workspaceId:u}=e,d=this._convertToCreate(this,n,s);if(r===this.project_name)return{...d,session_name:r};if(i){if(a)this._sliceParentId(a,d);else if(d.parent_run_id=void 0,d.dotted_order){let I=d.dotted_order.split(".");I.length>0&&(d.dotted_order=I[I.length-1],d.trace_id=d.id)}let S=Md({projectName:r,apiUrl:c,apiKey:l,workspaceId:u});this._setReplicaTraceRoot(S,d.id)}let p;if(!i){let S=Wi(this,zn)??{},I=Md({projectName:r,apiUrl:c,apiKey:l,workspaceId:u});if(p=S[I],p&&(d.trace_id=p,d.dotted_order)){let m=d.dotted_order.split("."),T=null;for(let A=0;A<m.length;A++)if(m[A].slice(-Nr)===p){T=A;break}if(T!==null){let A=m.slice(T);d.dotted_order=A.join(".")}}}let _=d.id,g=Er(_,r),y;d.trace_id?y=Er(d.trace_id,r):y=g;let E;d.parent_run_id&&(E=Er(d.parent_run_id,r));let w;return d.dotted_order&&(w=d.dotted_order.split(".").map(m=>{let T=m.slice(-Nr),A=Er(T,r);return m.slice(0,-Nr)+A}).join(".")),{...d,id:g,trace_id:y,parent_run_id:E,dotted_order:w,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=wn();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,apiKey:s,apiUrl:i,workspaceId:a,reroot:c}of this.replicas){let l=this._remapForProject({projectName:n??this.project_name,runtimeEnv:r,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:i,apiKey:s,workspaceId:a});await this.client.createRun(l,{apiKey:s,apiUrl:i,workspaceId:a})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){Pt("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,apiKey:n,apiUrl:s,workspaceId:i,updates:a,reroot:c}of this.replicas){let l=this._remapForProject({projectName:r??this.project_name,runtimeEnv:void 0,excludeChildRuns:!0,reroot:c,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:n,workspaceId:i}),u={id:l.id,name:l.name,run_type:l.run_type,start_time:l.start_time,outputs:l.outputs,error:l.error,parent_run_id:l.parent_run_id,session_name:l.session_name,reference_example_id:l.reference_example_id,end_time:l.end_time,dotted_order:l.dotted_order,trace_id:l.trace_id,events:l.events,tags:l.tags,extra:l.extra,attachments:this.attachments,...a};e?.excludeInputs||(u.inputs=l.inputs),await this.client.updateRun(l.id,u,{apiKey:n,apiUrl:s,workspaceId:i})}else try{let r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id: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||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){let n=e?.callbacks,s,i,a,c=Od();if(n){let u=n?.getParentRunId?.()??"",d=n?.handlers?.find(p=>p?.name=="langchain_tracer");s=d?.getRun?.(u),i=d?.projectName,a=d?.client,c=c||!!d}return s?new t({name:s.name,id:s.id,trace_id:s.trace_id,dotted_order:s.dotted_order,client:a,tracingEnabled:c,project_name:i,tags:[...new Set((s?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...s?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:a,tracingEnabled:c,project_name:i})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,s=n["langsmith-trace"];if(!s||typeof s!="string")return;let i=s.trim(),a=i.split(".").map(d=>{let[p,_]=d.split("Z");return{strTime:p,time:Date.parse(p+"Z"),uuid:_}}),c=a[0].uuid,l={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:a.at(-1)?.uuid,trace_id:c,dotted_order:i};if(n.baggage&&typeof n.baggage=="string"){let d=Vn.fromHeader(n.baggage);l.metadata=d.metadata,l.tags=d.tags,l.project_name=d.project_name,l.replicas=d.replicas}let u=new t(l);return u.distributedParentId=u.id,u}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new Vn(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,s]of Object.entries(r))e.set(n,s);return r}};Object.defineProperty(Qe,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function Ld(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}o(Ld,"isRunTree");function Dd(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}o(Dd,"isLangChainTracerLike");function kd(t){return Array.isArray(t)&&t.some(e=>Dd(e))}o(kd,"containsLangChainTracerLike");function nE(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}o(nE,"isCallbackManagerLike");function sE(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(kd(e?.handlers)||kd(e))}o(sE,"isRunnableConfigLike");function iE(){let t=Be("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let r=[];for(let n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key})}return r}else if(typeof e=="object"&&e!==null){oE(e);let r=[];for(let[n,s]of Object.entries(e)){let i=n.replace(/\/$/,"");if(typeof s=="string")r.push({apiUrl:i,apiKey:s});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof s}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 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(wd(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}o(iE,"_getWriteReplicasFromEnv");function aE(t){return t?t.map(e=>Array.isArray(e)?{projectName:e[0],updates:e[1]}:e):iE()}o(aE,"_ensureWriteReplicas");function oE(t){if(Object.keys(t).length>0&&te("ENDPOINT"))throw new Fn}o(oE,"_checkEndpointEnvUnset");var cE=o(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function Zi(t,e){if(t)return new Qe({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Zi(e),child_runs:t.child_runs.map(r=>Zi(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:hc()},tracingEnabled:!1})}o(Zi,"convertRunToRunTree");function Ki(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}o(Ki,"_coerceToDict");function er(t){return typeof t._addRunToRunMap=="function"}o(er,"isBaseTracer");var $t=class extends qt{static{o(this,"BaseTracer")}runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?cE(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
46
-
47
- ${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=qi(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},s=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?s?(this._addChildRun(s,n),s.child_execution_order=Math.max(s.child_execution_order,n.child_execution_order),n.trace_id=s.trace_id,s.dotted_order!==void 0&&(n.dotted_order=[s.dotted_order,e].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){let i=Zi(n,s);i!==void 0&&this.runTreeMap.set(n.id,i)}else this.runMap.set(n.id,n);return n}async _endTrace(t){let e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){let e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,s,i,a,c){let l=this._getExecutionOrder(n),u=Date.now(),d=a?{...s,metadata:a}:s,p={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(p)}async handleLLMStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(t,e,r,n,s,i,a,c){let l=this._getExecutionOrder(n),u=Date.now(),d=a?{...s,metadata:a}:s,p={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:i||[]};return this._addRunToRunMap(p)}async handleChatModelStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(t,e,r,n,s){let i=this.getRunById(e);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.outputs=t,i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await this.onLLMEnd?.(i),await this._endTrace(i),i}async handleLLMError(t,e,r,n,s){let i=this.getRunById(e);if(!i||i?.run_type!=="llm")throw new Error("No LLM run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(t),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),i.extra={...i.extra,...s},await this.onLLMError?.(i),await this._endTrace(i),i}_createRunForChainStart(t,e,r,n,s,i,a,c,l){let u=this._getExecutionOrder(n),d=Date.now(),p={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:d,serialized:t,events:[{name:"start",time:new Date(d).toISOString()}],inputs:e,execution_order:u,child_execution_order:u,run_type:a??"chain",child_runs:[],extra:i?{...l,metadata:i}:{...l},tags:s||[]};return this._addRunToRunMap(p)}async handleChainStart(t,e,r,n,s,i,a,c){let l=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,s,i,a,c);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(t,e,r,n,s){let i=this.getRunById(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.outputs=Ki(t,"output"),i.events.push({name:"end",time:new Date(i.end_time).toISOString()}),s?.inputs!==void 0&&(i.inputs=Ki(s.inputs,"input")),await this.onChainEnd?.(i),await this._endTrace(i),i}async handleChainError(t,e,r,n,s){let i=this.getRunById(e);if(!i)throw new Error("No chain run to end.");return i.end_time=Date.now(),i.error=this.stringifyError(t),i.events.push({name:"error",time:new Date(i.end_time).toISOString()}),s?.inputs!==void 0&&(i.inputs=Ki(s.inputs,"input")),await this.onChainError?.(i),await this._endTrace(i),i}_createRunForToolStart(t,e,r,n,s,i,a){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:e},execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,s,i,a){let c=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,s,i,a);return await this.onRunCreate?.(c),await this.onToolStart?.(c),c}async handleToolEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,s,i,a){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:a??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:e},execution_order:c,child_execution_order:c,run_type:"retriever",child_runs:[],extra:i?{metadata:i}:{},tags:s||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,s,i,a){let c=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,s,i,a);return await this.onRunCreate?.(c),await this.onRetrieverStart?.(c),c}async handleRetrieverEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,s,i){let a=this.getRunById(r);if(!a||a?.run_type!=="llm")throw new Error('Invalid "runId" provided to "handleLLMNewToken" callback.');return a.events.push({name:"new_token",time:new Date().toISOString(),kwargs:{token:t,idx:e,chunk:i?.chunk}}),await this.onLLMNewToken?.(a,t,{chunk:i?.chunk}),a}};var Ud={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};function Oe(t,e){return`${t.open}${e}${t.close}`}o(Oe,"wrap");function Ve(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}o(Ve,"tryJsonStringify");function $d(t){return typeof t=="string"?t.trim():t==null?t:Ve(t,t.toString())}o($d,"formatKVMapItem");function St(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}o(St,"elapsed");var{color:Le}=Ud,Ji=class extends $t{static{o(this,"ConsoleCallbackHandler")}name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){let e=[],r=t;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){let e=[...this.getParents(t).reverse(),t].map((r,n,s)=>{let i=`${r.execution_order}:${r.run_type}:${r.name}`;return n===s.length-1?Oe(Ud.bold,i):i}).join(" > ");return Oe(Le.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[chain/start]")} [${e}] Entering Chain run with input: ${Ve(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[chain/end]")} [${e}] [${St(t)}] Exiting Chain run with output: ${Ve(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[chain/error]")} [${e}] [${St(t)}] Chain run errored with error: ${Ve(t.error,"[error]")}`)}onLLMStart(t){let e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${Oe(Le.green,"[llm/start]")} [${e}] Entering LLM run with input: ${Ve(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[llm/end]")} [${e}] [${St(t)}] Exiting LLM run with output: ${Ve(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[llm/error]")} [${e}] [${St(t)}] LLM run errored with error: ${Ve(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[tool/start]")} [${e}] Entering Tool run with input: "${$d(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[tool/end]")} [${e}] [${St(t)}] Exiting Tool run with output: "${$d(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[tool/error]")} [${e}] [${St(t)}] Tool run errored with error: ${Ve(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${Ve(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.cyan,"[retriever/end]")} [${e}] [${St(t)}] Exiting Retriever run with output: ${Ve(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${Oe(Le.red,"[retriever/error]")} [${e}] [${St(t)}] Retriever run errored with error: ${Ve(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${Oe(Le.blue,"[agent/action]")} [${r}] Agent selected action: ${Ve(e.actions[e.actions.length-1],"[action]")}`)}};var Yi,Xi=o(()=>(Yi===void 0&&(Yi=new vt(Je("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),Yi),"getDefaultLangChainClientSingleton");var ea=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(e,r){return r()}},Qi=Symbol.for("ls:tracing_async_local_storage"),lE=new ea,ta=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return globalThis[Qi]??lE}initializeGlobalInstance(e){globalThis[Qi]===void 0&&(globalThis[Qi]=e)}},uE=new ta;function Fd(t=!1){let e=uE.getInstance().getStore();if(!t&&e===void 0)throw new Error(`Could not get the current run tree.
145
+ https://smith.langchain.com/prompts`);let[i,s,o]=Ce(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError("create a prompt",i);let c={repo_handle:s,...r?.description&&{description:r.description},...r?.readme&&{readme:r.readme},...r?.tags&&{tags:r.tags},is_public:!!r?.isPublic},l=JSON.stringify(c),u=await this.caller.call(async()=>{let f=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:l});return await L(f,"create prompt"),f}),{repo:d}=await u.json();return d}async createCommit(e,r,n){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[i,s,o]=Ce(e),c=n?.parentCommitHash==="latest"||!n?.parentCommitHash?await this._getLatestCommitHash(`${i}/${s}`):n?.parentCommitHash,l={manifest:JSON.parse(JSON.stringify(r)),parent_commit:c,...n?.description!==void 0&&{description:n.description}},u=JSON.stringify(l),f=await(await this.caller.call(async()=>{let h=await this._fetch(`${this.apiUrl}/commits/${i}/${s}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:u});return await L(h,"create commit"),h})).json(),y=f.commit??f;return n?.tags&&await this._createCommitTags(`${i}/${s}`,y.id,n.tags),this._getPromptUrl(`${i}/${s}${y.commit_hash?`:${y.commit_hash}`:""}`)}async updateExamplesMultipart(e,r=[]){return this._updateExamplesMultipart(e,r)}async _updateExamplesMultipart(e,r=[]){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.");let n=new FormData;for(let o of r){let c=o.id,l={...o.metadata&&{metadata:o.metadata},...o.split&&{split:o.split}},u=Re(l,`Serializing body for example with id: ${c}`),d=new Blob([u],{type:"application/json"});if(n.append(c,d),o.inputs){let f=Re(o.inputs,`Serializing inputs for example with id: ${c}`),y=new Blob([f],{type:"application/json"});n.append(`${c}.inputs`,y)}if(o.outputs){let f=Re(o.outputs,`Serializing outputs whle updating example with id: ${c}`),y=new Blob([f],{type:"application/json"});n.append(`${c}.outputs`,y)}if(o.attachments)for(let[f,y]of Object.entries(o.attachments)){let h,g;Array.isArray(y)?[h,g]=y:(h=y.mimeType,g=y.data);let b=new Blob([g],{type:`${h}; length=${g.byteLength}`});n.append(`${c}.attachment.${f}`,b)}if(o.attachments_operations){let f=Re(o.attachments_operations,`Serializing attachments while updating example with id: ${c}`),y=new Blob([f],{type:"application/json"});n.append(`${c}.attachments_operations`,y)}}let i=e??r[0]?.dataset_id;return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${i}/examples`)}`,{method:"PATCH",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await L(o,"update examples"),o})).json()}async uploadExamplesMultipart(e,r=[]){return this._uploadExamplesMultipart(e,r)}async _uploadExamplesMultipart(e,r=[]){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.");let n=new FormData;for(let s of r){let o=(s.id??zt()).toString(),c={created_at:s.created_at,...s.metadata&&{metadata:s.metadata},...s.split&&{split:s.split},...s.source_run_id&&{source_run_id:s.source_run_id},...s.use_source_run_io&&{use_source_run_io:s.use_source_run_io},...s.use_source_run_attachments&&{use_source_run_attachments:s.use_source_run_attachments}},l=Re(c,`Serializing body for uploaded example with id: ${o}`),u=new Blob([l],{type:"application/json"});if(n.append(o,u),s.inputs){let d=Re(s.inputs,`Serializing inputs for uploaded example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.inputs`,f)}if(s.outputs){let d=Re(s.outputs,`Serializing outputs for uploaded example with id: ${o}`),f=new Blob([d],{type:"application/json"});n.append(`${o}.outputs`,f)}if(s.attachments)for(let[d,f]of Object.entries(s.attachments)){let y,h;Array.isArray(f)?[y,h]=f:(y=f.mimeType,h=f.data);let g=new Blob([h],{type:`${y}; length=${h.byteLength}`});n.append(`${o}.attachment.${d}`,g)}}return(await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${e}/examples`)}`,{method:"POST",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:n});return await L(s,"upload examples"),s})).json()}async updatePrompt(e,r){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[n,i]=Ce(e);if(!await this._currentTenantIsOwner(n))throw await this._ownerConflictError("update a prompt",n);let s={};if(r?.description!==void 0&&(s.description=r.description),r?.readme!==void 0&&(s.readme=r.readme),r?.tags!==void 0&&(s.tags=r.tags),r?.isPublic!==void 0&&(s.is_public=r.isPublic),r?.isArchived!==void 0&&(s.is_archived=r.isArchived),Object.keys(s).length===0)throw new Error("No valid update options provided");let o=JSON.stringify(s);return(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/repos/${n}/${i}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:o});return await L(l,"update prompt"),l})).json()}async deletePrompt(e){if(!await this.promptExists(e))throw new Error("Prompt does not exist, you must create it first.");let[r,n,i]=Ce(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete a prompt",r);return(await this.caller.call(async()=>{let o=await this._fetch(`${this.apiUrl}/repos/${r}/${n}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(o,"delete prompt"),o})).json()}_getPromptCacheKey(e,r){return`${e}${r?":with_model":""}`}async _fetchPromptFromApi(e,r){let[n,i,s]=Ce(e),c=await(await this.caller.call(async()=>{let l=await this._fetch(`${this.apiUrl}/commits/${n}/${i}/${s}${r?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(l,"pull prompt commit"),l})).json();return{owner:n,repo:i,commit_hash:c.commit_hash,manifest:c.manifest,examples:c.examples,hub_model_config:c.model_config,hub_model_provider:c.model_provider}}async pullPromptCommit(e,r){Oy(e,r?.dangerouslyPullPublicPrompt);let n=this._fetchPromptFromApi.bind(this,e,r);if(!r?.skipCache&&this._promptCache){let i=this._getPromptCacheKey(e,r?.includeModel),s=this._promptCache.get(i,n);if(s)return s;let o=await n();return this._promptCache.set(i,o,n),o}return this._fetchPromptFromApi(e,r)}async _pullPrompt(e,r){let n=await this.pullPromptCommit(e,{includeModel:r?.includeModel,skipCache:r?.skipCache,dangerouslyPullPublicPrompt:r?.dangerouslyPullPublicPrompt});return JSON.stringify(n.manifest)}async pushPrompt(e,r){return await this.promptExists(e)?r&&["description","readme","tags","isPublic"].some(i=>r[i]!==void 0)&&await this.updatePrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}):await this.createPrompt(e,{description:r?.description,readme:r?.readme,tags:r?.tags,isPublic:r?.isPublic}),r?.object?await this.createCommit(e,r?.object,{parentCommitHash:r?.parentCommitHash,tags:r?.commitTags,description:r?.commitDescription}):await this._getPromptUrl(e)}async agentExists(e){let[r,n]=Ce(e);return this._repoExists(r,n)}async skillExists(e){let[r,n]=Ce(e);return this._repoExists(r,n)}async pullAgent(e,r){return await this._pullDirectory(e,"agent",r?.version)}async pullSkill(e,r){return await this._pullDirectory(e,"skill",r?.version)}async pushAgent(e,r){return this._pushDirectory(e,"agent",r)}async pushSkill(e,r){return this._pushDirectory(e,"skill",r)}async deleteAgent(e){return this._deleteDirectory(e)}async deleteSkill(e){return this._deleteDirectory(e)}async*listAgents(e){yield*this._listReposByType("agent",e)}async*listSkills(e){yield*this._listReposByType("skill",e)}async*_listReposByType(e,r){let n=new URLSearchParams;n.append("repo_type",e),n.append("is_archived",(!!r?.isArchived).toString()),r?.isPublic!==void 0&&n.append("is_public",r.isPublic.toString()),r?.query&&n.append("query",r.query);for await(let i of this._getPaginated("/repos",n,s=>s.repos))yield*i}async _pullDirectory(e,r,n){let[i,s,o]=Ce(e),c=n??(o!=="latest"?o:void 0),l=new URL(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${s}/directories`)}`);return l.searchParams.set("repo_type",r),c&&l.searchParams.set("commit",c),await(await this.caller.call(async()=>{let d=await this._fetch(l.toString(),{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(d,"pull directory"),d})).json()}async _pushDirectory(e,r,n){if(n.parentCommit!==void 0&&(n.parentCommit.length<8||n.parentCommit.length>64))throw new Error("parent_commit must be 8-64 characters");let[i,s]=Ce(e);if(!await this._currentTenantIsOwner(i))throw await this._ownerConflictError(`push ${r}`,i);if(await this._repoExists(i,s))(n.description!==void 0||n.readme!==void 0||n.tags!==void 0||n.isPublic!==void 0)&&await this._updateRepoMetadata(i,s,n);else{let y=/^[a-z][a-z0-9-_]*$/;if(!y.test(s))throw new Error(`Invalid repo_handle ${JSON.stringify(s)}: must match ${y}`);await this._createRepo(s,r,n)}let o={files:n.files};n.parentCommit&&(o.parent_commit=n.parentCommit);let u=(await(await this.caller.call(async()=>{let y=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${i}/${s}/directories/commits`)}`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(o)});return await L(y,`push ${r}`),y})).json()).commit.commit_hash,d=await this._getSettings(),f=new URLSearchParams({organizationId:d.id});return`${this.getHostUrl()}/context/${s}/${u.slice(0,8)}?${f.toString()}`}async _deleteDirectory(e){let[r,n]=Ce(e);if(!await this._currentTenantIsOwner(r))throw await this._ownerConflictError("delete",r);await this.caller.call(async()=>{let i=await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`hub/repos/${r}/${n}/directories`)}`,{method:"DELETE",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(i,"delete directory"),i})}async _repoExists(e,r){try{return await this.caller.call(async()=>{let n=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"GET",headers:this._mergedHeaders,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await L(n,"check repo exists"),n}),!0}catch(n){if(wi(n))return!1;throw n}}async _createRepo(e,r,n){let i={repo_handle:e,repo_type:r,is_public:!!n.isPublic};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags);try{await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/`,{method:"POST",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await L(s,`create ${r}`),s})}catch(s){if(Vu(s))return;throw s}}async _updateRepoMetadata(e,r,n){let i={};n.description!==void 0&&(i.description=n.description),n.readme!==void 0&&(i.readme=n.readme),n.tags!==void 0&&(i.tags=n.tags),n.isPublic!==void 0&&(i.is_public=n.isPublic),Object.keys(i).length!==0&&await this.caller.call(async()=>{let s=await this._fetch(`${this.apiUrl}/repos/${e}/${r}`,{method:"PATCH",headers:{...this._mergedHeaders,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions,body:JSON.stringify(i)});return await L(s,"update repo metadata"),s})}async clonePublicDataset(e,r={}){let{sourceApiUrl:n=this.apiUrl,datasetName:i}=r,[s,o]=this.parseTokenOrUrl(e,n),c=new t({apiUrl:s,apiKey:"placeholder"}),l=await c.readSharedDataset(o),u=i||l.name;try{if(await this.hasDataset({datasetId:u})){console.log(`Dataset ${u} already exists in your tenant. Skipping.`);return}}catch{}let d=await c.listSharedExamples(o),f=await this.createDataset(u,{description:l.description,dataType:l.data_type||"kv",inputsSchema:l.inputs_schema_definition??void 0,outputsSchema:l.outputs_schema_definition??void 0});try{await this.createExamples({inputs:d.map(y=>y.inputs),outputs:d.flatMap(y=>y.outputs?[y.outputs]:[]),datasetId:f.id})}catch(y){throw console.error(`An error occurred while creating dataset ${u}. You should delete it manually.`),y}}parseTokenOrUrl(e,r,n=2,i="dataset"){try{return H(e),[r,e]}catch{}try{let o=new URL(e).pathname.split("/").filter(c=>c!=="");if(o.length>=n){let c=o[o.length-n];return[r,c]}else throw new Error(`Invalid public ${i} URL: ${e}`)}catch{throw new Error(`Invalid public ${i} URL or token: ${e}`)}}cleanup(){this._promptCache&&this._promptCache.stop()}async awaitPendingTraceBatches(){if(this.manualFlushMode)return console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."),Promise.resolve();for(await new Promise(e=>setTimeout(e,1));this._pendingDrains.size>0;)await Promise.all([...this._pendingDrains]);await Promise.all([...this.autoBatchQueue.items.map(({itemPromise:e})=>e),this.batchIngestCaller.queue.onIdle()]),this.langSmithToOTELTranslator!==void 0&&await fu()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush()}toString(){let e=[`apiUrl=${JSON.stringify(this.apiUrl)}`];return this.webUrl!==void 0&&e.push(`webUrl=${JSON.stringify(this.webUrl)}`),this.workspaceId!==void 0&&e.push(`workspaceId=${JSON.stringify(this.workspaceId)}`),`[LangSmithClient ${e.join(" ")}]`}[Symbol.for("nodejs.util.inspect.custom")](){return this.toString()}};Object.defineProperty(Rt,"_fallbackDirsCreated",{enumerable:!0,configurable:!0,writable:!0,value:new Set});function pd(t){return"dataset_id"in t||"dataset_name"in t}a(pd,"isExampleCreate");var ft=Symbol.for("lc:context_variables");var xi=Symbol.for("langsmith:replica_trace_roots");function Da(t,e){if(ft in t)return t[ft][e]}a(Da,"getContextVar");function gd(t,e,r){let n=ft in t?t[ft]:{};n[e]=r,t[ft]=n}a(gd,"setContextVar");var pn=36,By="6ba7b810-9dad-11d1-80b4-00c04fd430c8";function yd(t){let r=Object.keys(t).sort().map(n=>`${n}:${t[n]??""}`).join("|");return Ps(r,By)}a(yd,"getReplicaKey");function jy(t){return t.replace(/[-:.]/g,"")}a(jy,"stripNonAlphanumeric");function bd(t,e=1){let r=e.toFixed(0).slice(0,3).padStart(3,"0");return`${new Date(t).toISOString().slice(0,-1)}${r}Z`}a(bd,"getMicrosecondPrecisionDatestring");function Ua(t,e,r=1){let n=bd(t,r);return{dottedOrder:jy(n)+e,microsecondPrecisionDatestring:n}}a(Ua,"convertToDottedOrderFormat");var Hy=new Set(["projectName","primary","updates","reroot"]);function zy(t){let e={};for(let r of Object.keys(t))r==="primary"&&typeof t[r]!="boolean"||Hy.has(r)&&(e[r]=t[r]);return e}a(zy,"filterReplicaForHeaders");var Ii=class t{static{a(this,"Baggage")}constructor(e,r,n,i){Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"project_name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"replicas",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.metadata=e,this.tags=r,this.project_name=n,this.replicas=i}static fromHeader(e){let r=e.split(","),n={},i=[],s,o;for(let c of r){let[l,u]=c.split("="),d=decodeURIComponent(u);l==="langsmith-metadata"?n=JSON.parse(d):l==="langsmith-tags"?i=d.split(","):l==="langsmith-project"?s=d:l==="langsmith-replicas"&&(o=JSON.parse(d).map(y=>Array.isArray(y)?y:zy(y)))}return new t(n,i,s,o)}toHeader(){let 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(",")}},et=class t{static{a(this,"RunTree")}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,"distributedParentId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_serialized_start_time",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_awaitInputsOnPost",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),wd(e)){Object.assign(this,{...e});return}let r=t.getDefaultConfig(),{metadata:n,...i}=e,s=i.client??t.getSharedClient(),o={...n,...i?.extra?.metadata};if(i.extra={...i.extra,metadata:o},"id"in i&&i.id==null&&delete i.id,Object.assign(this,{...r,...i,client:s}),this.execution_order??=1,this.child_execution_order??=1,this.dotted_order||(this._serialized_start_time=bd(this.start_time,this.execution_order)),this.id||(this.id=Jn(this._serialized_start_time??this.start_time)),this.trace_id||(this.parent_run?this.trace_id=this.parent_run.trace_id??this.id:this.trace_id=this.id),this.replicas=qy(this.replicas),!this.dotted_order){let{dottedOrder:c}=Ua(this.start_time,this.id,this.execution_order);this.parent_run?this.dotted_order=this.parent_run.dotted_order+"."+c:this.dotted_order=c}}set metadata(e){this.extra={...this.extra,metadata:{...this.extra?.metadata,...e}}}get metadata(){return this.extra?.metadata}static getDefaultConfig(){let e=Date.now();return{run_type:"chain",project_name:sn(),child_runs:[],api_url:ye("LANGCHAIN_ENDPOINT")??"http://localhost:1984",api_key:ye("LANGCHAIN_API_KEY"),caller_options:{},start_time:e,serialized:{},inputs:{},extra:{}}}static getSharedClient(){return t.sharedClient||(t.sharedClient=new Rt),t.sharedClient}createChild(e){let r=this.child_execution_order+1,n=this.replicas?.map(y=>{let{reroot:h,...g}=y;return g}),i=e.replicas??n,s=new t({...e,parent_run:this,project_name:this.project_name,replicas:i,client:this.client,tracingEnabled:this.tracingEnabled,execution_order:r,child_execution_order:r}),o=this.extra?.metadata??{},c=s.extra?.metadata??{};Object.keys(o).length>0&&(s.extra={...s.extra,metadata:{...o,...c}}),ft in this&&(s[ft]=this[ft]);let l=Symbol.for("lc:child_config"),u=e.extra?.[l]??this.extra[l];if(Vy(u)){let y={...u},h=Gy(y.callbacks)?y.callbacks.copy?.():void 0;h&&(Object.assign(h,{_parentRunId:s.id}),h.handlers?.find(Ed)?.updateFromRunTree?.(s),y.callbacks=h),s.extra[l]=y}let d=new Set,f=this;for(;f!=null&&!d.has(f.id);)d.add(f.id),f.child_execution_order=Math.max(f.child_execution_order,r),f=f.parent_run;return this.child_runs.push(s),s}async end(e,r,n=Date.now(),i){this.outputs=this.outputs??e,this.error=this.error??r,this.end_time=this.end_time??n,i&&Object.keys(i).length>0&&(this.extra=this.extra?{...this.extra,metadata:{...this.extra.metadata,...i}}:{metadata:i})}_convertToCreate(e,r,n=!0){let i=e.extra??{};if(i?.runtime?.library===void 0&&(i.runtime||(i.runtime={}),r))for(let[c,l]of Object.entries(r))i.runtime[c]||(i.runtime[c]=l);let s=e.parent_run?.id??e.parent_run_id,o;return n?o=[]:o=e.child_runs.map(c=>this._convertToCreate(c,r,n)),{id:e.id,name:e.name,start_time:e._serialized_start_time??e.start_time,end_time:e.end_time,run_type:e.run_type,reference_example_id:e.reference_example_id,extra:i,serialized:e.serialized,error:e.error,inputs:e.inputs,outputs:e.outputs,session_name:e.project_name,child_runs:o,parent_run_id:s,trace_id:e.trace_id,dotted_order:e.dotted_order,tags:e.tags,attachments:e.attachments,events:e.events}}_sliceParentId(e,r){if(r.dotted_order){let n=r.dotted_order.split("."),i=null;for(let s=0;s<n.length;s++)if(n[s].slice(-pn)===e){i=s;break}if(i!==null){let s=n.slice(i+1);r.dotted_order=s.join("."),s.length>0?r.trace_id=s[0].slice(-pn):r.trace_id=r.id}}r.parent_run_id===e&&(r.parent_run_id=void 0)}_setReplicaTraceRoot(e,r){let n=Da(this,xi)??{};n[e]=r,gd(this,xi,n);for(let i of this.child_runs)i._setReplicaTraceRoot(e,r)}_remapForProject(e){let{projectName:r,primary:n,runtimeEnv:i,excludeChildRuns:s=!0,reroot:o=!1,distributedParentId:c,apiUrl:l,apiKey:u,workspaceId:d}=e,f=this._convertToCreate(this,i,s);if(n===void 0&&r===this.project_name)return{...f,session_name:r};if(o){if(c)this._sliceParentId(c,f);else if(f.parent_run_id=void 0,f.dotted_order){let p=f.dotted_order.split(".");p.length>0&&(f.dotted_order=p[p.length-1],f.trace_id=f.id)}let S=yd({projectName:r,apiUrl:l,apiKey:u,workspaceId:d});this._setReplicaTraceRoot(S,f.id)}let y;if(!o){let S=Da(this,xi)??{},p=yd({projectName:r,apiUrl:l,apiKey:u,workspaceId:d});if(y=S[p],y&&(f.trace_id=y,f.dotted_order)){let T=f.dotted_order.split("."),I=null;for(let C=0;C<T.length;C++)if(T[C].slice(-pn)===y){I=C;break}if(I!==null){let C=T.slice(I);f.dotted_order=C.join(".")}}}if(n)return{...f,session_name:r};let h=f.id,g=xr(h,r),b;f.trace_id?b=xr(f.trace_id,r):b=g;let w;f.parent_run_id&&(w=xr(f.parent_run_id,r));let v;return f.dotted_order&&(v=f.dotted_order.split(".").map(T=>{let I=T.slice(-pn),C=xr(I,r);return T.slice(0,-pn)+C}).join(".")),{...f,id:g,trace_id:b,parent_run_id:w,dotted_order:v,session_name:r}}async postRun(e=!0){this._awaitInputsOnPost&&(this.inputs=await this.inputs);try{let r=ti();if(this.replicas&&this.replicas.length>0)for(let{projectName:n,primary:i,apiKey:s,apiUrl:o,workspaceId:c,reroot:l,client:u}of this.replicas){let d=this._remapForProject({projectName:n??this.project_name,primary:i,runtimeEnv:r,excludeChildRuns:!0,reroot:l,distributedParentId:this.distributedParentId,apiUrl:o,apiKey:s,workspaceId:c});await(u??this.client).createRun(d,{apiKey:s,apiUrl:o,workspaceId:c})}else{let n=this._convertToCreate(this,r,e);await this.client.createRun(n)}if(!e){_e("Posting with excludeChildRuns=false is deprecated and will be removed in a future version.");for(let n of this.child_runs)await n.postRun(!1)}this.child_runs=[]}catch(r){console.error(`Error in postRun for run ${this.id}:`,r)}}async patchRun(e){if(this.replicas&&this.replicas.length>0)for(let{projectName:r,primary:n,apiKey:i,apiUrl:s,workspaceId:o,updates:c,reroot:l,client:u}of this.replicas){let d=this._remapForProject({projectName:r??this.project_name,primary:n,runtimeEnv:void 0,excludeChildRuns:!0,reroot:l,distributedParentId:this.distributedParentId,apiUrl:s,apiKey:i,workspaceId:o}),f={id:d.id,name:d.name,run_type:d.run_type,start_time:d.start_time,outputs:d.outputs,error:d.error,parent_run_id:d.parent_run_id,session_name:d.session_name,reference_example_id:d.reference_example_id,end_time:d.end_time,dotted_order:d.dotted_order,trace_id:d.trace_id,events:d.events,tags:d.tags,extra:d.extra,attachments:this.attachments,...c};e?.excludeInputs||(f.inputs=d.inputs),await(u??this.client).updateRun(d.id,f,{apiKey:i,apiUrl:s,workspaceId:o})}else try{let r={name:this.name,run_type:this.run_type,start_time:this._serialized_start_time??this.start_time,end_time:this.end_time,error:this.error,outputs:this.outputs,parent_run_id: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||(r.inputs=this.inputs),await this.client.updateRun(this.id,r)}catch(r){console.error(`Error in patchRun for run ${this.id}`,r)}this.child_runs=[]}toJSON(){return this._convertToCreate(this,void 0,!1)}addEvent(e){this.events||(this.events=[]),typeof e=="string"?this.events.push({name:"event",time:new Date().toISOString(),message:e}):this.events.push({...e,time:e.time??new Date().toISOString()})}static fromRunnableConfig(e,r){let n=e?.callbacks,i,s,o,c=Vs();if(n){let u=n?.getParentRunId?.()??"",d=n?.handlers?.find(f=>f?.name=="langchain_tracer");i=d?.getRun?.(u),s=d?.projectName,o=d?.client,c=c||!!d}return i?new t({name:i.name,id:i.id,trace_id:i.trace_id,dotted_order:i.dotted_order,client:o,tracingEnabled:c,project_name:s,tags:[...new Set((i?.tags??[]).concat(e?.tags??[]))],extra:{metadata:{...i?.extra?.metadata,...e?.metadata}}}).createChild(r):new t({...r,client:o,tracingEnabled:c,project_name:s})}static fromDottedOrder(e){return this.fromHeaders({"langsmith-trace":e})}static fromHeaders(e,r){let n="get"in e&&typeof e.get=="function"?{"langsmith-trace":e.get("langsmith-trace"),baggage:e.get("baggage")}:e,i=n["langsmith-trace"];if(!i||typeof i!="string")return;let s=i.trim(),o=s.split(".").map(d=>{let[f,y]=d.split("Z");return{strTime:f,time:Date.parse(f+"Z"),uuid:y}}),c=o[0].uuid,l={...r,name:r?.name??"parent",run_type:r?.run_type??"chain",start_time:r?.start_time??Date.now(),id:o.at(-1)?.uuid,trace_id:c,dotted_order:s};if(n.baggage&&typeof n.baggage=="string"){let d=Ii.fromHeader(n.baggage);l.metadata=d.metadata,l.tags=d.tags,l.project_name=d.project_name,l.replicas=d.replicas}let u=new t(l);return u.distributedParentId=u.id,u}toHeaders(e){let r={"langsmith-trace":this.dotted_order,baggage:new Ii(this.extra?.metadata,this.tags,this.project_name,this.replicas).toHeader()};if(e)for(let[n,i]of Object.entries(r))e.set(n,i);return r}};Object.defineProperty(et,"sharedClient",{enumerable:!0,configurable:!0,writable:!0,value:null});function wd(t){return t!=null&&typeof t.createChild=="function"&&typeof t.postRun=="function"}a(wd,"isRunTree");function Ed(t){return typeof t=="object"&&t!=null&&typeof t.name=="string"&&t.name==="langchain_tracer"}a(Ed,"isLangChainTracerLike");function _d(t){return Array.isArray(t)&&t.some(e=>Ed(e))}a(_d,"containsLangChainTracerLike");function Gy(t){return typeof t=="object"&&t!=null&&Array.isArray(t.handlers)}a(Gy,"isCallbackManagerLike");function Vy(t){let e=t?.callbacks;return t!=null&&typeof e=="object"&&(_d(e?.handlers)||_d(e))}a(Vy,"isRunnableConfigLike");function Wy(){let t=ye("LANGSMITH_RUNS_ENDPOINTS");if(!t)return[];try{let e=JSON.parse(t);if(Array.isArray(e)){let r=[];for(let n of e){if(typeof n!="object"||n===null){console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: expected object, got ${typeof n}`);continue}if(typeof n.api_url!="string"){console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_url}`);continue}if(typeof n.api_key!="string"){console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.api_key}`);continue}if(n.project_name!==void 0&&n.project_name!==null&&typeof n.project_name!="string"){console.warn(`Invalid project_name type in LANGSMITH_RUNS_ENDPOINTS: expected string, got ${typeof n.project_name}`);continue}if(n.primary!==void 0&&typeof n.primary!="boolean"){console.warn(`Invalid primary type in LANGSMITH_RUNS_ENDPOINTS: expected boolean, got ${typeof n.primary}`);continue}r.push({apiUrl:n.api_url.replace(/\/$/,""),apiKey:n.api_key,projectName:n.project_name??void 0,primary:n.primary??void 0})}return r}else if(typeof e=="object"&&e!==null){Ky(e);let r=[];for(let[n,i]of Object.entries(e)){let s=n.replace(/\/$/,"");if(typeof i=="string")r.push({apiUrl:s,apiKey:i});else{console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${n}: expected string, got ${typeof i}`);continue}}return r}else return console.warn(`Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 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(qu(e))throw e;return console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS \u2013 must be valid JSON array of objects with api_url and api_key properties, or object mapping url->apiKey"),[]}}a(Wy,"_getWriteReplicasFromEnv");function qy(t){let e=t?t.map(r=>Array.isArray(r)?{projectName:r[0],updates:r[1]}:r):Wy();if(e.filter(r=>r.primary===!0).length>1)throw new Error("Only one replica can be marked as primary.");return e}a(qy,"_ensureWriteReplicas");function Ky(t){if(Object.keys(t).length>0&&Z("ENDPOINT"))throw new _i}a(Ky,"_checkEndpointEnvUnset");var Jy=a(t=>{if(t)return t.events=t.events??[],t.child_runs=t.child_runs??[],t},"convertRunTreeToRun");function Fa(t,e){if(t)return new et({...t,start_time:t._serialized_start_time??t.start_time,parent_run:Fa(e),child_runs:t.child_runs.map(r=>Fa(r)).filter(r=>r!==void 0),extra:{...t.extra,runtime:rl()},tracingEnabled:!1})}a(Fa,"convertRunToRunTree");function $a(t,e){return t&&!Array.isArray(t)&&typeof t=="object"?t:{[e]:t}}a($a,"_coerceToDict");function jr(t){return typeof t._addRunToRunMap=="function"}a(jr,"isBaseTracer");var cr=class extends _r{static{a(this,"BaseTracer")}runMap=new Map;runTreeMap=new Map;usesRunTreeMap=!1;constructor(t){super(...arguments)}copy(){return this}getRunById(t){if(t!==void 0)return this.usesRunTreeMap?Jy(this.runTreeMap.get(t)):this.runMap.get(t)}stringifyError(t){return t instanceof Error?t.message+(t?.stack?`
48
146
 
49
- Please make sure you are calling this method within a traceable function and that tracing is enabled.`);return e}o(Fd,"getCurrentRunTree");var jd=new Set(["ls_agent_type"]);function dE(t){let e;for(let r of t)for(let n of r)bt.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Xr(e,n.message.usage_metadata));return e}o(dE,"_getUsageMetadataFromGenerations");var Mr=class ra extends $t{static{o(this,"LangChainTracer")}name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(e={}){super(e),this.fields=e;let{exampleId:r,projectName:n,client:s,replicas:i,metadata:a,tags:c}=e;this.projectName=n??br(),this.replicas=i,this.exampleId=r,this.client=s??Xi(),this.tracingMetadata=a?{...a}:void 0,this.tracingTags=c??[];let l=ra.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(e){}async onRunCreate(e){Bd(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){Bd(this,e);let r=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(e){let r=e.outputs;if(r?.generations){let n=dE(r.generations);if(n!==void 0){e.extra=e.extra??{};let s=e.extra.metadata??{};s.usage_metadata=n,e.extra.metadata=s}}}copyWithTracingConfig({metadata:e,tags:r}){let n;if(e===void 0)n=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)n={...e};else{n={...this.tracingMetadata};for(let[a,c]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,a)||jd.has(a))&&(n[a]=c)}let s=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],i=new ra({...this.fields,metadata:n,tags:s});return i.runMap=this.runMap,i.runTreeMap=this.runTreeMap,i}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let s=[r];for(;s.length>0;){let i=s.shift();!i||n.has(i.id)||(n.add(i.id),this.runTreeMap.set(i.id,i),i.child_runs&&s.push(...i.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,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let r=this.runTreeMap.get(e);if(r)return new Qe({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Fd(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!="object"||e===null)return!1;let r=e;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function Bd(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[s,i]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,s)||jd.has(s))&&r[s]!==i&&(r[s]=i,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}o(Bd,"_patchMissingTracingDefaults");var Wn=_e(cn(),1);var kr;function fE(){return new("default"in Wn.default?Wn.default.default:Wn.default)({autoStart:!0,concurrency:1})}o(fE,"createQueue");function pE(){return typeof kr>"u"&&(kr=fE()),kr}o(pE,"getQueue");async function re(t,e){if(e===!0){let r=wt();r!==void 0?await r.run(void 0,async()=>t()):await t()}else kr=pE(),kr.add(async()=>{let r=wt();r!==void 0?await r.run(void 0,async()=>t()):await t()})}o(re,"consumeCallback");var Hd=o(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Je(e)==="true"),"isTracingEnabled");function na(t){let e=wt();if(e!==void 0)return e.getStore()?.[Mt]?.[t]}o(na,"getContextVariable");var mE=Symbol("lc:configure_hooks"),Gd=o(()=>na(mE)||[],"_getConfigureHooks");var hE=class{static{o(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},qn=class{static{o(this,"BaseRunManager")}constructor(t,e,r,n,s,i,a,c){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=s,this.metadata=i,this.inheritableMetadata=a,this._parentRunId=c}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>re(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{try{await i.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleCustomEvent: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}},gE=class extends qn{static{o(this,"CallbackManagerForRetrieverRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},zd=class extends qn{static{o(this,"CallbackManagerForLLMRun")}async handleLLMNewToken(t,e,r,n,s,i){await Promise.all(this.handlers.map(a=>re(async()=>{if(!a.ignoreLLM)try{await a.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,i)}catch(c){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleLLMNewToken: ${c}`),a.raiseError)throw c}},a.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreLLM)try{await e.handleChatModelStreamEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleLLMError(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreLLM)try{await i.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMError: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleLLMEnd(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreLLM)try{await i.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleLLMEnd: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}},yE=class extends qn{static{o(this,"CallbackManagerForChainRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreChain)try{await i.handleChainError?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainError: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleChainEnd(t,e,r,n,s){await Promise.all(this.handlers.map(i=>re(async()=>{if(!i.ignoreChain)try{await i.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,s)}catch(a){if((i.raiseError?console.error:console.warn)(`Error in handler ${i.constructor.name}, handleChainEnd: ${a}`),i.raiseError)throw a}},i.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},_E=class extends qn{static{o(this,"CallbackManagerForToolRun")}getChild(t){let e=new Ut(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>re(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},Ut=class Pr extends hE{static{o(this,"CallbackManager")}handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:nt();return await Promise.all(this.handlers.map(_=>{if(!_.ignoreLLM)return er(_)&&_._createRunForLLMStart(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l),re(async()=>{try{await _.handleLLMStart?.(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l)}catch(g){if((_.raiseError?console.error:console.warn)(`Error in handler ${_.constructor.name}, handleLLMStart: ${g}`),_.raiseError)throw g}},_.awaitHandlers)})),new zd(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let p=d===0&&n?n:nt();return await Promise.all(this.handlers.map(_=>{if(!_.ignoreLLM)return er(_)&&_._createRunForChatModelStart(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l),re(async()=>{try{if(_.handleChatModelStart)await _.handleChatModelStart?.(e,[u],p,this._parentRunId,i,this.tags,this.metadata,l);else if(_.handleLLMStart){let g=tn(u);await _.handleLLMStart?.(e,[g],p,this._parentRunId,i,this.tags,this.metadata,l)}}catch(g){if((_.raiseError?console.error:console.warn)(`Error in handler ${_.constructor.name}, handleLLMStart: ${g}`),_.raiseError)throw g}},_.awaitHandlers)})),new zd(p,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=nt(),s=void 0,i=void 0,a=void 0,c=void 0,l=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return er(d)&&d._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,s,c,u),re(async()=>{try{await d.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,s,c,u)}catch(p){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${p}`),d.raiseError)throw p}},d.awaitHandlers)})),new yE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=nt(),s=void 0,i=void 0,a=void 0,c=void 0,l=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return er(u)&&u._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),re(async()=>{try{await u.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c,l)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new _E(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=nt(),s=void 0,i=void 0,a=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreRetriever)return er(l)&&l._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),re(async()=>{try{await l.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c)}catch(u){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleRetrieverStart: ${u}`),l.raiseError)throw u}},l.awaitHandlers)})),new gE(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,s,i){await Promise.all(this.handlers.map(a=>re(async()=>{if(!a.ignoreCustomEvent)try{await a.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(c){if((a.raiseError?console.error:console.warn)(`Error in handler ${a.constructor.name}, handleCustomEvent: ${c}`),a.raiseError)throw c}},a.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){let n=new Pr(this._parentRunId);for(let s of this.handlers){let i=this.inheritableHandlers.includes(s);n.addHandler(s,i)}for(let s of this.tags){let i=this.inheritableTags.includes(s);n.addTags([s],i)}for(let s of Object.keys(this.metadata)){let i=Object.keys(this.inheritableMetadata).includes(s);n.addMetadata({[s]:this.metadata[s]},i)}for(let s of e)n.handlers.filter(i=>i.name==="console_callback_handler").some(i=>i.name===s.name)||n.addHandler(s,r);return n}static fromHandlers(e){class r extends qt{static{o(this,"Handler")}name=nt();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,s,i,a,c){return this._configureSync(e,r,n,s,i,a,c)}static _configureSync(e,r,n,s,i,a,c){let l;(e||r)&&(Array.isArray(e)||!e?(l=new Pr,l.setHandlers(e?.map(sa)??[],!0)):l=e,l=l.copy(Array.isArray(r)?r.map(sa):r?.handlers,!1));let u=Je("LANGCHAIN_VERBOSE")==="true"||c?.verbose,d=Mr.getTraceableRunTree(),p=d?.tracingEnabled??Hd();if(d?.tracingEnabled===!1&&l){let E=l.handlers.filter(w=>w.name==="langchain_tracer");for(let w of E)l.removeHandler(w)}let _=p||(Je("LANGCHAIN_TRACING")??!1);if(u||_){if(l||(l=new Pr),u&&!l.handlers.some(E=>E.name===Ji.prototype.name)){let E=new Ji;l.addHandler(E,!0)}if(_&&!l.handlers.some(E=>E.name==="langchain_tracer")&&p){let E=new Mr;l.addHandler(E,!0)}p&&d&&l._parentRunId===void 0&&(l._parentRunId=d.id,l.handlers.find(E=>E.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:E,inheritable:w=!0,handlerClass:S,envVar:I}of Gd()){let m=I&&Je(I)==="true"&&S,T,A=E!==void 0?na(E):void 0;A&&gc(A)?T=A:m&&(T=new S({})),T!==void 0&&(l||(l=new Pr),l.handlers.some(N=>N.name===T.name)||l.addHandler(T,w))}(n||s)&&l&&(l.addTags(n??[]),l.addTags(s??[],!1)),(i||a)&&l&&(l.addMetadata(i??{}),l.addMetadata(a??{},!1));let g=c?.tracerInheritableMetadata,y=c?.tracerInheritableTags;return l&&(g||y)&&(l.handlers=l.handlers.map(E=>E instanceof Mr?E.copyWithTracingConfig({metadata:g,tags:y}):E),l.inheritableHandlers=l.inheritableHandlers.map(E=>E instanceof Mr?E.copyWithTracingConfig({metadata:g,tags:y}):E)),l}};function sa(t){return"name"in t?t:qt.fromMethods(t)}o(sa,"ensureHandler");var Wd=class{static{o(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},bE=new Wd,Vd=Symbol.for("lc:child_config"),EE=class{static{o(this,"AsyncLocalStorageProvider")}getInstance(){return wt()??bE}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Vd]}runWithConfig(t,e,r){let n=Ut._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),s=this.getInstance(),i=s.getStore(),a=n?.getParentRunId(),c=n?.handlers?.find(u=>u?.name==="langchain_tracer"),l;return c&&a?l=c.getRunTreeWithTracingConfig(a):r||(l=new Qe({name:"<runnable_lambda>",tracingEnabled:!1})),l&&(l.extra={...l.extra,[Vd]:t}),i!==void 0&&i[Mt]!==void 0&&(l===void 0&&(l={}),l[Mt]=i[Mt]),s.run(l,e)}initializeGlobalInstance(t){wt()===void 0&&mc(t)}},Lr=new EE;var wE=Object.prototype.hasOwnProperty;function Zd(t,e){return wE.call(t,e)}o(Zd,"hasOwnProperty");function Jd(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)Zd(t,r)&&e.push(r);return e}o(Jd,"_objectKeys");function mt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}o(mt,"_deepClone");function Zn(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}o(Zn,"isInteger");function Yd(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}o(Yd,"unescapePathComponent");function Kn(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Kn(t[r]))return!0}else if(typeof t=="object"){let r=Jd(t),n=r.length;for(var e=0;e<n;e++)if(Kn(t[r[e]]))return!0}}return!1}o(Kn,"hasUndefined");function Kd(t,e){let r=[t];for(let n in e){let s=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof s<"u"&&r.push(`${n}: ${s}`)}return r.join(`
50
- `)}o(Kd,"patchErrorMessageFormatter");var Xd=class extends Error{static{o(this,"PatchError")}constructor(t,e,r,n,s){super(Kd(t,{name:e,index:r,operation:n,tree:s})),this.name=e,this.index=r,this.operation=n,this.tree=s,Object.setPrototypeOf(this,new.target.prototype),this.message=Kd(t,{name:e,index:r,operation:n,tree:s})}};var Qd=q({JsonPatchError:o(()=>se,"JsonPatchError"),_areEquals:o(()=>Dr,"_areEquals"),applyOperation:o(()=>Ft,"applyOperation"),applyPatch:o(()=>Xn,"applyPatch"),applyReducer:o(()=>SE,"applyReducer"),deepClone:o(()=>TE,"deepClone"),getValueByPointer:o(()=>Jn,"getValueByPointer"),validate:o(()=>ef,"validate"),validator:o(()=>Yn,"validator")}),se=Xd,TE=mt,tr={add:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:r}},"add"),remove:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return delete t[e],{newDocument:r,removed:n}},"remove"),replace:o(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:o(function(t,e,r){let n=Jn(r,this.path);n&&(n=mt(n));let s=Ft(r,{op:"remove",path:this.from}).removed;return Ft(r,{op:"add",path:this.path,value:s}),{newDocument:r,removed:n}},"move"),copy:o(function(t,e,r){let n=Jn(r,this.from);return Ft(r,{op:"add",path:this.path,value:mt(n)}),{newDocument:r}},"copy"),test:o(function(t,e,r){return{newDocument:r,test:Dr(t[e],this.value)}},"test"),_get:o(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},vE={add:o(function(t,e,r){return Zn(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},"add"),remove:o(function(t,e,r){return{newDocument:r,removed:t.splice(e,1)[0]}},"remove"),replace:o(function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:tr.move,copy:tr.copy,test:tr.test,_get:tr._get};function Jn(t,e){if(e=="")return t;var r={op:"_get",path:e};return Ft(t,r),r.value}o(Jn,"getValueByPointer");function Ft(t,e,r=!1,n=!0,s=!0,i=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Yn(e,0)),e.path===""){let a={newDocument:t};if(e.op==="add")return a.newDocument=e.value,a;if(e.op==="replace")return a.newDocument=e.value,a.removed=t,a;if(e.op==="move"||e.op==="copy")return a.newDocument=Jn(t,e.from),e.op==="move"&&(a.removed=t),a;if(e.op==="test"){if(a.test=Dr(t,e.value),a.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return a.newDocument=t,a}else{if(e.op==="remove")return a.removed=t,a.newDocument=null,a;if(e.op==="_get")return e.value=t,a;if(r)throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",i,e,t);return a}}else{n||(t=mt(t));let a=(e.path||"").split("/"),c=t,l=1,u=a.length,d,p,_;for(typeof r=="function"?_=r:_=Yn;;){if(p=a[l],p&&p.indexOf("~")!=-1&&(p=Yd(p)),s&&(p=="__proto__"||p=="prototype"&&l>0&&a[l-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(r&&d===void 0&&(c[p]===void 0?d=a.slice(0,l).join("/"):l==u-1&&(d=e.path),d!==void 0&&_(e,0,t,d)),l++,Array.isArray(c)){if(p==="-")p=c.length;else{if(r&&!Zn(p))throw new se("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",i,e,t);Zn(p)&&(p=~~p)}if(l>=u){if(r&&e.op==="add"&&p>c.length)throw new se("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",i,e,t);let g=vE[e.op].call(e,c,p,t);if(g.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return g}}else if(l>=u){let g=tr[e.op].call(e,c,p,t);if(g.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",i,e,t);return g}if(c=c[p],r&&l<u&&(!c||typeof c!="object"))throw new se("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",i,e,t)}}}o(Ft,"applyOperation");function Xn(t,e,r,n=!0,s=!0){if(r&&!Array.isArray(e))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=mt(t));let i=new Array(e.length);for(let a=0,c=e.length;a<c;a++)i[a]=Ft(t,e[a],r,!0,s,a),t=i[a].newDocument;return i.newDocument=t,i}o(Xn,"applyPatch");function SE(t,e,r){let n=Ft(t,e);if(n.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}o(SE,"applyReducer");function Yn(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new se("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(tr[t.op]){if(typeof t.path!="string")throw new se("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new se('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new se("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Kn(t.value))throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var s=t.path.split("/").length,i=n.split("/").length;if(s!==i+1&&s!==i)throw new se("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new se("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var a=ef([{op:"_get",path:t.from,value:void 0}],r);if(a&&a.name==="OPERATION_PATH_UNRESOLVABLE")throw new se("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}o(Yn,"validator");function ef(t,e,r){try{if(!Array.isArray(t))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Xn(mt(e),mt(t),r||!0);else{r=r||Yn;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(s){if(s instanceof se)return s;throw s}}o(ef,"validate");function Dr(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),s,i,a;if(r&&n){if(i=t.length,i!=e.length)return!1;for(s=i;s--!==0;)if(!Dr(t[s],e[s]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(i=c.length,i!==Object.keys(e).length)return!1;for(s=i;s--!==0;)if(!e.hasOwnProperty(c[s]))return!1;for(s=i;s--!==0;)if(a=c[s],!Dr(t[a],e[a]))return!1;return!0}return t!==t&&e!==e}o(Dr,"_areEquals");({...Qd});var cU=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var NE=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,ME=[0,31,28,31,30,31,30,31,31,30,31,30,31],kE=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,PE=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,LE=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,DE=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,$E=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,UE=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,FE=/^(?:\/(?:[^~/]|~0|~1)*)*$/,BE=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,jE=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,HE=o(t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(s=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(s))},"EMAIL"),GE=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,zE=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,VE=o(t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),"DURATION");function ut(t){return t.test.bind(t)}o(ut,"bind");var WE={date:tf,time:rf.bind(void 0,!1),"date-time":ZE,duration:VE,uri:XE,"uri-reference":ut(LE),"uri-template":ut(DE),url:ut($E),email:HE,hostname:ut(PE),ipv4:ut(GE),ipv6:ut(zE),regex:ew,uuid:ut(UE),"json-pointer":ut(FE),"json-pointer-uri-fragment":ut(BE),"relative-json-pointer":ut(jE)};function qE(t){return t%4===0&&(t%100!==0||t%400===0)}o(qE,"isLeapYear");function tf(t){let e=t.match(NE);if(!e)return!1;let r=+e[1],n=+e[2],s=+e[3];return n>=1&&n<=12&&s>=1&&s<=(n==2&&qE(r)?29:ME[n])}o(tf,"date");function rf(t,e){let r=e.match(kE);if(!r)return!1;let n=+r[1],s=+r[2],i=+r[3],a=!!r[5];return(n<=23&&s<=59&&i<=59||n==23&&s==59&&i==60)&&(!t||a)}o(rf,"time");var KE=/t|\s/i;function ZE(t){let e=t.split(KE);return e.length==2&&tf(e[0])&&rf(!0,e[1])}o(ZE,"date_time");var JE=/\/|:/,YE=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function XE(t){return JE.test(t)&&YE.test(t)}o(XE,"uri");var QE=/[^\\]\\Z/;function ew(t){if(QE.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}o(ew,"regex");var nf;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(nf||(nf={}));var gf=_e(hf(),1);var gw=Object.defineProperty,yw=o((t,e,r)=>e in t?gw(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),_w=o((t,e,r)=>(yw(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function bw(t,e){let r=Array.from({length:t.length},(n,s)=>({start:s,end:s+1}));for(;r.length>1;){let n=null;for(let s=0;s<r.length-1;s++){let i=t.slice(r[s].start,r[s+1].end),a=e.get(i.join(","));a!=null&&(n==null||a<n[0])&&(n=[a,s])}if(n!=null){let s=n[1];r[s]={start:r[s].start,end:r[s+1].end},r.splice(s+1,1)}else break}return r}o(bw,"bytePairMerge");function Ew(t,e){return t.length===1?[e.get(t.join(","))]:bw(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}o(Ew,"bytePairEncode");function ww(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}o(ww,"escapeRegex");var ua=class{static{o(this,"_Tiktoken")}specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;let r=t.bpe_ranks.split(`
51
- `).filter(Boolean).reduce((n,s)=>{let[i,a,...c]=s.split(" "),l=Number.parseInt(a,10);return c.forEach((u,d)=>n[u]=l+d),n},{});for(let[n,s]of Object.entries(r)){let i=gf.default.toByteArray(n);this.rankMap.set(i.join(","),s),this.textMap.set(s,i)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[s,i])=>(n[i]=this.textEncoder.encode(s),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),s=ua.specialTokenRegex(Object.keys(this.specialTokens)),i=[],a=new Set(e==="all"?Object.keys(this.specialTokens):e),c=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!a.has(u)):r);if(c.size>0){let u=ua.specialTokenRegex([...c]),d=t.match(u);if(d!=null)throw new Error(`The text contains a special token that is not allowed: ${d[0]}`)}let l=0;for(;;){let u=null,d=l;for(;s.lastIndex=d,u=s.exec(t),!(u==null||a.has(u[0]));)d=u.index+1;let p=u?.index??t.length;for(let g of t.substring(l,p).matchAll(n)){let y=this.textEncoder.encode(g[0]),E=this.rankMap.get(y.join(","));if(E!=null){i.push(E);continue}i.push(...Ew(y,this.rankMap))}if(u==null)break;let _=this.specialTokens[u[0]];i.push(_),l=u.index+u[0].length}return i}decode(t){let e=[],r=0;for(let i=0;i<t.length;++i){let a=t[i],c=this.textMap.get(a)??this.inverseSpecialTokens[a];c!=null&&(e.push(c),r+=c.length)}let n=new Uint8Array(r),s=0;for(let i of e)n.set(i,s),s+=i.length;return this.textDecoder.decode(n)}},da=ua;_w(da,"specialTokenRegex",t=>new RegExp(t.map(e=>ww(e)).join("|"),"g"));var Ef=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var wf=["image","video","audio","text-plain","file"];var Sw=["text","reasoning",...Ef,...wf];var Mw=o(function(){let t={};t.parser=function(h,f){return new r(h,f)},t.SAXParser=r,t.SAXStream=u,t.createStream=l,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(h,f){if(!(this instanceof r))return new r(h,f);var C=this;s(C),C.q=C.c="",C.bufferCheckPosition=t.MAX_BUFFER_LENGTH,C.opt=f||{},C.opt.lowercase=C.opt.lowercase||C.opt.lowercasetags,C.looseCase=C.opt.lowercase?"toLowerCase":"toUpperCase",C.tags=[],C.closed=C.closedRoot=C.sawRoot=!1,C.tag=C.error=null,C.strict=!!h,C.noscript=!!(h||C.opt.noscript),C.state=b.BEGIN,C.strictEntities=C.opt.strictEntities,C.ENTITIES=C.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),C.attribList=[],C.opt.xmlns&&(C.ns=Object.create(y)),C.trackPosition=C.opt.position!==!1,C.trackPosition&&(C.position=C.line=C.column=0),G(C,"onready")}o(r,"SAXParser"),Object.create||(Object.create=function(h){function f(){}return o(f,"F"),f.prototype=h,new f}),Object.keys||(Object.keys=function(h){var f=[];for(var C in h)h.hasOwnProperty(C)&&f.push(C);return f});function n(h){for(var f=Math.max(t.MAX_BUFFER_LENGTH,10),C=0,v=0,J=e.length;v<J;v++){var le=h[e[v]].length;if(le>f)switch(e[v]){case"textNode":Z(h);break;case"cdata":B(h,"oncdata",h.cdata),h.cdata="";break;case"script":B(h,"onscript",h.script),h.script="";break;default:ke(h,"Max buffer length exceeded: "+e[v])}C=Math.max(C,le)}h.bufferCheckPosition=t.MAX_BUFFER_LENGTH-C+h.position}o(n,"checkBufferLength");function s(h){for(var f=0,C=e.length;f<C;f++)h[e[f]]=""}o(s,"clearBuffers");function i(h){Z(h),h.cdata!==""&&(B(h,"oncdata",h.cdata),h.cdata=""),h.script!==""&&(B(h,"onscript",h.script),h.script="")}o(i,"flushBuffers"),r.prototype={end:o(function(){xt(this)},"end"),write:Am,resume:o(function(){return this.error=null,this},"resume"),close:o(function(){return this.write(null)},"close"),flush:o(function(){i(this)},"flush")};var a=ReadableStream;a||(a=o(function(){},"Stream"));var c=t.EVENTS.filter(function(h){return h!=="error"&&h!=="end"});function l(h,f){return new u(h,f)}o(l,"createStream");function u(h,f){if(!(this instanceof u))return new u(h,f);a.apply(this),this._parser=new r(h,f),this.writable=!0,this.readable=!0;var C=this;this._parser.onend=function(){C.emit("end")},this._parser.onerror=function(v){C.emit("error",v),C._parser.error=null},this._decoder=null,c.forEach(function(v){Object.defineProperty(C,"on"+v,{get:o(function(){return C._parser["on"+v]},"get"),set:o(function(J){if(!J)return C.removeAllListeners(v),C._parser["on"+v]=J,J;C.on(v,J)},"set"),enumerable:!0,configurable:!1})})}o(u,"SAXStream"),u.prototype=Object.create(a.prototype,{constructor:{value:u}}),u.prototype.write=function(h){return this._parser.write(h.toString()),this.emit("data",h),!0},u.prototype.end=function(h){return h&&h.length&&this.write(h),this._parser.end(),!0},u.prototype.on=function(h,f){var C=this;return!C._parser["on"+h]&&c.indexOf(h)!==-1&&(C._parser["on"+h]=function(){var v=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);v.splice(0,0,h),C.emit.apply(C,v)}),a.prototype.on.call(C,h,f)};var d="[CDATA[",p="DOCTYPE",_="http://www.w3.org/XML/1998/namespace",g="http://www.w3.org/2000/xmlns/",y={xml:_,xmlns:g},E=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,w=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,S=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,I=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function m(h){return h===" "||h===`
52
- `||h==="\r"||h===" "}o(m,"isWhitespace");function T(h){return h==='"'||h==="'"}o(T,"isQuote");function A(h){return h===">"||m(h)}o(A,"isAttribEnd");function N(h,f){return h.test(f)}o(N,"isMatch");function O(h,f){return!N(h,f)}o(O,"notMatch");var b=0;t.STATE={BEGIN:b++,BEGIN_WHITESPACE:b++,TEXT:b++,TEXT_ENTITY:b++,OPEN_WAKA:b++,SGML_DECL:b++,SGML_DECL_QUOTED:b++,DOCTYPE:b++,DOCTYPE_QUOTED:b++,DOCTYPE_DTD:b++,DOCTYPE_DTD_QUOTED:b++,COMMENT_STARTING:b++,COMMENT:b++,COMMENT_ENDING:b++,COMMENT_ENDED:b++,CDATA:b++,CDATA_ENDING:b++,CDATA_ENDING_2:b++,PROC_INST:b++,PROC_INST_BODY:b++,PROC_INST_ENDING:b++,OPEN_TAG:b++,OPEN_TAG_SLASH:b++,ATTRIB:b++,ATTRIB_NAME:b++,ATTRIB_NAME_SAW_WHITE:b++,ATTRIB_VALUE:b++,ATTRIB_VALUE_QUOTED:b++,ATTRIB_VALUE_CLOSED:b++,ATTRIB_VALUE_UNQUOTED:b++,ATTRIB_VALUE_ENTITY_Q:b++,ATTRIB_VALUE_ENTITY_U:b++,CLOSE_TAG:b++,CLOSE_TAG_SAW_WHITE:b++,SCRIPT:b++,SCRIPT_ENDING:b++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(h){var f=t.ENTITIES[h],C=typeof f=="number"?String.fromCharCode(f):f;t.ENTITIES[h]=C});for(var j in t.STATE)t.STATE[t.STATE[j]]=j;b=t.STATE;function G(h,f,C){h[f]&&h[f](C)}o(G,"emit");function B(h,f,C){h.textNode&&Z(h),G(h,f,C)}o(B,"emitNode");function Z(h){h.textNode=ce(h.opt,h.textNode),h.textNode&&G(h,"ontext",h.textNode),h.textNode=""}o(Z,"closeText");function ce(h,f){return h.trim&&(f=f.trim()),h.normalize&&(f=f.replace(/\s+/g," ")),f}o(ce,"textopts");function ke(h,f){return Z(h),h.trackPosition&&(f+=`
53
- Line: `+h.line+`
54
- Column: `+h.column+`
55
- Char: `+h.c),f=new Error(f),h.error=f,G(h,"onerror",f),h}o(ke,"error");function xt(h){return h.sawRoot&&!h.closedRoot&&K(h,"Unclosed root tag"),h.state!==b.BEGIN&&h.state!==b.BEGIN_WHITESPACE&&h.state!==b.TEXT&&ke(h,"Unexpected end"),Z(h),h.c="",h.closed=!0,G(h,"onend"),r.call(h,h.strict,h.opt),h}o(xt,"end");function K(h,f){if(typeof h!="object"||!(h instanceof r))throw new Error("bad call to strictFail");h.strict&&ke(h,f)}o(K,"strictFail");function xm(h){h.strict||(h.tagName=h.tagName[h.looseCase]());var f=h.tags[h.tags.length-1]||h,C=h.tag={name:h.tagName,attributes:{}};h.opt.xmlns&&(C.ns=f.ns),h.attribList.length=0,B(h,"onopentagstart",C)}o(xm,"newTag");function vs(h,f){var C=h.indexOf(":")<0?["",h]:h.split(":"),v=C[0],J=C[1];return f&&h==="xmlns"&&(v="xmlns",J=""),{prefix:v,local:J}}o(vs,"qname");function Ss(h){if(h.strict||(h.attribName=h.attribName[h.looseCase]()),h.attribList.indexOf(h.attribName)!==-1||h.tag.attributes.hasOwnProperty(h.attribName)){h.attribName=h.attribValue="";return}if(h.opt.xmlns){var f=vs(h.attribName,!0),C=f.prefix,v=f.local;if(C==="xmlns")if(v==="xml"&&h.attribValue!==_)K(h,"xml: prefix must be bound to "+_+`
56
- Actual: `+h.attribValue);else if(v==="xmlns"&&h.attribValue!==g)K(h,"xmlns: prefix must be bound to "+g+`
57
- Actual: `+h.attribValue);else{var J=h.tag,le=h.tags[h.tags.length-1]||h;J.ns===le.ns&&(J.ns=Object.create(le.ns)),J.ns[v]=h.attribValue}h.attribList.push([h.attribName,h.attribValue])}else h.tag.attributes[h.attribName]=h.attribValue,B(h,"onattribute",{name:h.attribName,value:h.attribValue});h.attribName=h.attribValue=""}o(Ss,"attrib");function At(h,f){if(h.opt.xmlns){var C=h.tag,v=vs(h.tagName);C.prefix=v.prefix,C.local=v.local,C.uri=C.ns[v.prefix]||"",C.prefix&&!C.uri&&(K(h,"Unbound namespace prefix: "+JSON.stringify(h.tagName)),C.uri=v.prefix);var J=h.tags[h.tags.length-1]||h;C.ns&&J.ns!==C.ns&&Object.keys(C.ns).forEach(function(Qa){B(h,"onopennamespace",{prefix:Qa,uri:C.ns[Qa]})});for(var le=0,$e=h.attribList.length;le<$e;le++){var xe=h.attribList[le],Ke=xe[0],Ct=xe[1],Te=vs(Ke,!0),Rt=Te.prefix,Cm=Te.local,Xa=Rt===""?"":C.ns[Rt]||"",xs={name:Ke,value:Ct,prefix:Rt,local:Cm,uri:Xa};Rt&&Rt!=="xmlns"&&!Xa&&(K(h,"Unbound namespace prefix: "+JSON.stringify(Rt)),xs.uri=Rt),h.tag.attributes[Ke]=xs,B(h,"onattribute",xs)}h.attribList.length=0}h.tag.isSelfClosing=!!f,h.sawRoot=!0,h.tags.push(h.tag),B(h,"onopentag",h.tag),f||(!h.noscript&&h.tagName.toLowerCase()==="script"?h.state=b.SCRIPT:h.state=b.TEXT,h.tag=null,h.tagName=""),h.attribName=h.attribValue="",h.attribList.length=0}o(At,"openTag");function Is(h){if(!h.tagName){K(h,"Weird empty close tag."),h.textNode+="</>",h.state=b.TEXT;return}if(h.script){if(h.tagName!=="script"){h.script+="</"+h.tagName+">",h.tagName="",h.state=b.SCRIPT;return}B(h,"onscript",h.script),h.script=""}var f=h.tags.length,C=h.tagName;h.strict||(C=C[h.looseCase]());for(var v=C;f--&&h.tags[f].name!==v;)K(h,"Unexpected close tag");if(f<0){K(h,"Unmatched closing tag: "+h.tagName),h.textNode+="</"+h.tagName+">",h.state=b.TEXT;return}h.tagName=C;for(var J=h.tags.length;J-- >f;){var le=h.tag=h.tags.pop();h.tagName=h.tag.name,B(h,"onclosetag",h.tagName);var $e={};for(var xe in le.ns)$e[xe]=le.ns[xe];var Ke=h.tags[h.tags.length-1]||h;h.opt.xmlns&&le.ns!==Ke.ns&&Object.keys(le.ns).forEach(function(Ct){var Te=le.ns[Ct];B(h,"onclosenamespace",{prefix:Ct,uri:Te})})}f===0&&(h.closedRoot=!0),h.tagName=h.attribValue=h.attribName="",h.attribList.length=0,h.state=b.TEXT}o(Is,"closeTag");function Za(h){var f=h.entity,C=f.toLowerCase(),v,J="";return h.ENTITIES[f]?h.ENTITIES[f]:h.ENTITIES[C]?h.ENTITIES[C]:(f=C,f.charAt(0)==="#"&&(f.charAt(1)==="x"?(f=f.slice(2),v=parseInt(f,16),J=v.toString(16)):(f=f.slice(1),v=parseInt(f,10),J=v.toString(10))),f=f.replace(/^0+/,""),isNaN(v)||J.toLowerCase()!==f?(K(h,"Invalid character entity"),"&"+h.entity+";"):String.fromCodePoint(v))}o(Za,"parseEntity");function Ja(h,f){f==="<"?(h.state=b.OPEN_WAKA,h.startTagPosition=h.position):m(f)||(K(h,"Non-whitespace before first tag."),h.textNode=f,h.state=b.TEXT)}o(Ja,"beginWhiteSpace");function Ya(h,f){var C="";return f<h.length&&(C=h.charAt(f)),C}o(Ya,"charAt");function Am(h){var f=this;if(this.error)throw this.error;if(f.closed)return ke(f,"Cannot write after close. Assign an onready handler.");if(h===null)return xt(f);typeof h=="object"&&(h=h.toString());for(var C=0,v="";v=Ya(h,C++),f.c=v,!!v;)switch(f.trackPosition&&(f.position++,v===`
58
- `?(f.line++,f.column=0):f.column++),f.state){case b.BEGIN:if(f.state=b.BEGIN_WHITESPACE,v==="\uFEFF")continue;Ja(f,v);continue;case b.BEGIN_WHITESPACE:Ja(f,v);continue;case b.TEXT:if(f.sawRoot&&!f.closedRoot){for(var J=C-1;v&&v!=="<"&&v!=="&";)v=Ya(h,C++),v&&f.trackPosition&&(f.position++,v===`
59
- `?(f.line++,f.column=0):f.column++);f.textNode+=h.substring(J,C-1)}v==="<"&&!(f.sawRoot&&f.closedRoot&&!f.strict)?(f.state=b.OPEN_WAKA,f.startTagPosition=f.position):(!m(v)&&(!f.sawRoot||f.closedRoot)&&K(f,"Text data outside of root node."),v==="&"?f.state=b.TEXT_ENTITY:f.textNode+=v);continue;case b.SCRIPT:v==="<"?f.state=b.SCRIPT_ENDING:f.script+=v;continue;case b.SCRIPT_ENDING:v==="/"?f.state=b.CLOSE_TAG:(f.script+="<"+v,f.state=b.SCRIPT);continue;case b.OPEN_WAKA:if(v==="!")f.state=b.SGML_DECL,f.sgmlDecl="";else if(!m(v))if(N(E,v))f.state=b.OPEN_TAG,f.tagName=v;else if(v==="/")f.state=b.CLOSE_TAG,f.tagName="";else if(v==="?")f.state=b.PROC_INST,f.procInstName=f.procInstBody="";else{if(K(f,"Unencoded <"),f.startTagPosition+1<f.position){var le=f.position-f.startTagPosition;v=new Array(le).join(" ")+v}f.textNode+="<"+v,f.state=b.TEXT}continue;case b.SGML_DECL:(f.sgmlDecl+v).toUpperCase()===d?(B(f,"onopencdata"),f.state=b.CDATA,f.sgmlDecl="",f.cdata=""):f.sgmlDecl+v==="--"?(f.state=b.COMMENT,f.comment="",f.sgmlDecl=""):(f.sgmlDecl+v).toUpperCase()===p?(f.state=b.DOCTYPE,(f.doctype||f.sawRoot)&&K(f,"Inappropriately located doctype declaration"),f.doctype="",f.sgmlDecl=""):v===">"?(B(f,"onsgmldeclaration",f.sgmlDecl),f.sgmlDecl="",f.state=b.TEXT):(T(v)&&(f.state=b.SGML_DECL_QUOTED),f.sgmlDecl+=v);continue;case b.SGML_DECL_QUOTED:v===f.q&&(f.state=b.SGML_DECL,f.q=""),f.sgmlDecl+=v;continue;case b.DOCTYPE:v===">"?(f.state=b.TEXT,B(f,"ondoctype",f.doctype),f.doctype=!0):(f.doctype+=v,v==="["?f.state=b.DOCTYPE_DTD:T(v)&&(f.state=b.DOCTYPE_QUOTED,f.q=v));continue;case b.DOCTYPE_QUOTED:f.doctype+=v,v===f.q&&(f.q="",f.state=b.DOCTYPE);continue;case b.DOCTYPE_DTD:f.doctype+=v,v==="]"?f.state=b.DOCTYPE:T(v)&&(f.state=b.DOCTYPE_DTD_QUOTED,f.q=v);continue;case b.DOCTYPE_DTD_QUOTED:f.doctype+=v,v===f.q&&(f.state=b.DOCTYPE_DTD,f.q="");continue;case b.COMMENT:v==="-"?f.state=b.COMMENT_ENDING:f.comment+=v;continue;case b.COMMENT_ENDING:v==="-"?(f.state=b.COMMENT_ENDED,f.comment=ce(f.opt,f.comment),f.comment&&B(f,"oncomment",f.comment),f.comment=""):(f.comment+="-"+v,f.state=b.COMMENT);continue;case b.COMMENT_ENDED:v!==">"?(K(f,"Malformed comment"),f.comment+="--"+v,f.state=b.COMMENT):f.state=b.TEXT;continue;case b.CDATA:v==="]"?f.state=b.CDATA_ENDING:f.cdata+=v;continue;case b.CDATA_ENDING:v==="]"?f.state=b.CDATA_ENDING_2:(f.cdata+="]"+v,f.state=b.CDATA);continue;case b.CDATA_ENDING_2:v===">"?(f.cdata&&B(f,"oncdata",f.cdata),B(f,"onclosecdata"),f.cdata="",f.state=b.TEXT):v==="]"?f.cdata+="]":(f.cdata+="]]"+v,f.state=b.CDATA);continue;case b.PROC_INST:v==="?"?f.state=b.PROC_INST_ENDING:m(v)?f.state=b.PROC_INST_BODY:f.procInstName+=v;continue;case b.PROC_INST_BODY:if(!f.procInstBody&&m(v))continue;v==="?"?f.state=b.PROC_INST_ENDING:f.procInstBody+=v;continue;case b.PROC_INST_ENDING:v===">"?(B(f,"onprocessinginstruction",{name:f.procInstName,body:f.procInstBody}),f.procInstName=f.procInstBody="",f.state=b.TEXT):(f.procInstBody+="?"+v,f.state=b.PROC_INST_BODY);continue;case b.OPEN_TAG:N(w,v)?f.tagName+=v:(xm(f),v===">"?At(f):v==="/"?f.state=b.OPEN_TAG_SLASH:(m(v)||K(f,"Invalid character in tag name"),f.state=b.ATTRIB));continue;case b.OPEN_TAG_SLASH:v===">"?(At(f,!0),Is(f)):(K(f,"Forward-slash in opening tag not followed by >"),f.state=b.ATTRIB);continue;case b.ATTRIB:if(m(v))continue;v===">"?At(f):v==="/"?f.state=b.OPEN_TAG_SLASH:N(E,v)?(f.attribName=v,f.attribValue="",f.state=b.ATTRIB_NAME):K(f,"Invalid attribute name");continue;case b.ATTRIB_NAME:v==="="?f.state=b.ATTRIB_VALUE:v===">"?(K(f,"Attribute without value"),f.attribValue=f.attribName,Ss(f),At(f)):m(v)?f.state=b.ATTRIB_NAME_SAW_WHITE:N(w,v)?f.attribName+=v:K(f,"Invalid attribute name");continue;case b.ATTRIB_NAME_SAW_WHITE:if(v==="=")f.state=b.ATTRIB_VALUE;else{if(m(v))continue;K(f,"Attribute without value"),f.tag.attributes[f.attribName]="",f.attribValue="",B(f,"onattribute",{name:f.attribName,value:""}),f.attribName="",v===">"?At(f):N(E,v)?(f.attribName=v,f.state=b.ATTRIB_NAME):(K(f,"Invalid attribute name"),f.state=b.ATTRIB)}continue;case b.ATTRIB_VALUE:if(m(v))continue;T(v)?(f.q=v,f.state=b.ATTRIB_VALUE_QUOTED):(K(f,"Unquoted attribute value"),f.state=b.ATTRIB_VALUE_UNQUOTED,f.attribValue=v);continue;case b.ATTRIB_VALUE_QUOTED:if(v!==f.q){v==="&"?f.state=b.ATTRIB_VALUE_ENTITY_Q:f.attribValue+=v;continue}Ss(f),f.q="",f.state=b.ATTRIB_VALUE_CLOSED;continue;case b.ATTRIB_VALUE_CLOSED:m(v)?f.state=b.ATTRIB:v===">"?At(f):v==="/"?f.state=b.OPEN_TAG_SLASH:N(E,v)?(K(f,"No whitespace between attributes"),f.attribName=v,f.attribValue="",f.state=b.ATTRIB_NAME):K(f,"Invalid attribute name");continue;case b.ATTRIB_VALUE_UNQUOTED:if(!A(v)){v==="&"?f.state=b.ATTRIB_VALUE_ENTITY_U:f.attribValue+=v;continue}Ss(f),v===">"?At(f):f.state=b.ATTRIB;continue;case b.CLOSE_TAG:if(f.tagName)v===">"?Is(f):N(w,v)?f.tagName+=v:f.script?(f.script+="</"+f.tagName,f.tagName="",f.state=b.SCRIPT):(m(v)||K(f,"Invalid tagname in closing tag"),f.state=b.CLOSE_TAG_SAW_WHITE);else{if(m(v))continue;O(E,v)?f.script?(f.script+="</"+v,f.state=b.SCRIPT):K(f,"Invalid tagname in closing tag."):f.tagName=v}continue;case b.CLOSE_TAG_SAW_WHITE:if(m(v))continue;v===">"?Is(f):K(f,"Invalid characters in closing tag");continue;case b.TEXT_ENTITY:case b.ATTRIB_VALUE_ENTITY_Q:case b.ATTRIB_VALUE_ENTITY_U:var $e,xe;switch(f.state){case b.TEXT_ENTITY:$e=b.TEXT,xe="textNode";break;case b.ATTRIB_VALUE_ENTITY_Q:$e=b.ATTRIB_VALUE_QUOTED,xe="attribValue";break;case b.ATTRIB_VALUE_ENTITY_U:$e=b.ATTRIB_VALUE_UNQUOTED,xe="attribValue";break}if(v===";")if(f.opt.unparsedEntities){var Ke=Za(f);f.entity="",f.state=$e,f.write(Ke)}else f[xe]+=Za(f),f.entity="",f.state=$e;else N(f.entity.length?I:S,v)?f.entity+=v:(K(f,"Invalid character in entity name"),f[xe]+="&"+f.entity+v,f.entity="",f.state=$e);continue;default:throw new Error(f,"Unknown state: "+f.state)}return f.position>=f.bufferCheckPosition&&n(f),f}o(Am,"write");return String.fromCodePoint||(function(){var h=String.fromCharCode,f=Math.floor,C=o(function(){var v=16384,J=[],le,$e,xe=-1,Ke=arguments.length;if(!Ke)return"";for(var Ct="";++xe<Ke;){var Te=Number(arguments[xe]);if(!isFinite(Te)||Te<0||Te>1114111||f(Te)!==Te)throw RangeError("Invalid code point: "+Te);Te<=65535?J.push(Te):(Te-=65536,le=(Te>>10)+55296,$e=Te%1024+56320,J.push(le,$e)),(xe+1===Ke||J.length>v)&&(Ct+=h.apply(null,J),J.length=0)}return Ct},"fromCodePoint");Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:C,configurable:!0,writable:!0}):String.fromCodePoint=C})(),t},"initializeSax"),kw=Mw();var s5=require("@playwright/test");var K3={openai_gpt_4_1:{model:"gpt-4.1-2025-04-14",type:"openai"},openai_gpt_4_1_mini:{model:"gpt-4.1-mini-2025-04-14",type:"openai"},openai_gpt_4_1_nano:{model:"gpt-4.1-nano-2025-04-14",type:"openai"},gemini_2_0_flash:{model:"gemini-2.0-flash",type:"gemini"},gemini_2_5_pro_exp:{model:"gemini-2.5-pro-exp-03-25",type:"gemini"},gemini_2_5_flash:{model:"gemini-2.5-flash",type:"gemini"},gemini_2_5_pro_preview_05_06:{model:"gemini-2.5-pro-preview-05-06",type:"gemini"},claude_sonnet_4:{model:"claude-sonnet-4@20250514",type:"anthropic-vertexai"},claude_sonnet_4_6:{model:"claude-sonnet-4-6",type:"anthropic-vertexai"},claude_sonnet_5:{model:"claude-sonnet-5",type:"anthropic-vertexai"},claude_opus_4_8:{model:"claude-opus-4-8",type:"anthropic-vertexai"},gemini_2_5_flash_lite:{model:"gemini-2.5-flash-lite",type:"gemini"},gemini_3_5_flash:{model:"gemini-3.5-flash",type:"gemini"},gemini_3_1_flash_lite:{model:"gemini-3.1-flash-lite",type:"gemini"}};var Pf=_e(kf());Pf.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var e0="claude_4",t0={gemini20flash:{name:"google-vertexai/gemini-2.0-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt41:{name:"openai/gpt-4.1",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25flash:{name:"google-vertexai/gemini-2.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:.7},gemini25flash_lite:{name:"google-vertexai/gemini-2.5-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt4onano:{name:"openai/gpt-4o-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41nano:{name:"openai/gpt-4.1-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41mini:{name:"openai/gpt-4.1-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o3mini:{name:"openai/o3-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o4mini:{name:"openai/o4-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25pro:{name:"google-vertexai/gemini-2.5-pro-preview-05-06",inputTokenLimit:8e5,provider:"gemini",temperature:0},claude37sonnet:{name:"google-vertexai/claude-3-7-sonnet@20250219",inputTokenLimit:15e4,provider:"anthropic",temperature:0},claude4sonnet:{name:"google-vertexai/claude-sonnet-4@20250514",inputTokenLimit:15e4,provider:"anthropic",temperature:1},claudeSonnet46:{name:"google-vertexai/claude-sonnet-4-6",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeSonnet5:{name:"google-vertexai/claude-sonnet-5",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeOpus48:{name:"google-vertexai/claude-opus-4-8",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},gemini35flash:{name:"google-vertexai/gemini-3.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gemini31flashLite:{name:"google-vertexai/gemini-3.1-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gpt4omini:{name:"openai/gpt-4o-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5mini:{name:"openai/gpt-5-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5nano:{name:"openai/gpt-5-nano",inputTokenLimit:8e5,provider:"openai",temperature:0}},r0=o(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:e0},models:t0,langsmith:{enabled:process.env.LANGSMITH_TRACING==="true",endpoint:process.env.LANGSMITH_ENDPOINT??"",apiKey:process.env.LANGSMITH_API_KEY??"",project:process.env.LANGSMITH_PROJECT??""}}),"make"),ue=r0();var t5={claude_4:ue.models.claude4sonnet,"claude_3.7":ue.models.claude37sonnet,claude_sonnet_4_6:ue.models.claudeSonnet46,claude_sonnet_5:ue.models.claudeSonnet5,claude_opus_4_8:ue.models.claudeOpus48,"gemini_2.5_pro":ue.models.gemini25pro,"gemini_2.0_flash":ue.models.gemini20flash,"gemini_2.5_flash_lite":ue.models.gemini25flash_lite,"gemini_2.5_flash":ue.models.gemini25flash,"gemini_3.5_flash":ue.models.gemini35flash,"gemini_3.1_flash_lite":ue.models.gemini31flashLite,gpt_4o_mini:ue.models.gpt4omini,gpt_4o_nano:ue.models.gpt4onano,gpt_41_nano:ue.models.gpt41nano,gpt_5_mini:ue.models.gpt5mini,gpt_5_nano:ue.models.gpt5nano,gpt_41_mini:ue.models.gpt41mini,gpt_41:ue.models.gpt41,o4_mini:ue.models.o4mini,o3_mini:ue.models.o3mini};var bm=require("child_process"),Vr=require("crypto"),oe=require("fs"),Em=require("fs/promises"),wm=require("stream/promises"),Tm=require("http"),vm=_e(require("net")),Sm=require("os"),De=require("path");function n0(t){if(t)return{...t,...t.tests?{tests:t.tests.map(e=>{let{errorMessage:r,...n}=e;return n})}:{}}}o(n0,"projectReportStatsForTelemetry");function Lf(t,e,r){t.emit({outcome:e,stats:n0(r)})}o(Lf,"emitReportProcessingStatsTelemetry");var Df=["script","template"],$f='<script id="playwrightReportBase64" type="application/zip">',Uf="</script>";var Vp=require("htmlparser2"),Wp=_e(yp()),ye=require("node:fs"),Ht=require("node:path"),qp=require("node:os"),Kp=require("node:crypto");var _t=_e(require("path")),Ia=require("fs");var Ta=require("path"),as=require("fs");function v0(t,e,r=10){let n=t;for(let s=0;s<r;s++){let i=(0,Ta.join)(n,"package.json");if((0,as.existsSync)(i))try{if(JSON.parse((0,as.readFileSync)(i,"utf8")).name===e)return n}catch{}n=(0,Ta.join)(n,"..")}}o(v0,"findRepositoryRoot");function _p(t,e=10){return v0(t,"checksum-customer-engineering-workspace",e)}o(_p,"findCustomerEngineeringRoot");var xa=_e(Sp());var Me=o((t,e)=>{if(t==null||t==="")return e?.default??!1;let r=t.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:e?.default??!1},"parseBoolean");function Ip(t){if(t===void 0||t.trim()==="")return 5e7;let e=Number(t);return!Number.isInteger(e)||e<0?5e7:e}o(Ip,"resolveMaxRRwebBytes");var F0=__dirname,xp=_t.join(__dirname,".."),Cp=(0,Ia.existsSync)(xp)?xp:F0;(0,xa.config)({path:_t.resolve(Cp,".env")});var Ap=Me(process.env.CHECKSUM_RUNTIME_DEV_MODE);function B0(){let t=__dirname;for(;!(0,Ia.existsSync)(_t.join(t,"package.json"));)t=_t.join(t,"..");return t}o(B0,"findRoot");var Hr=B0(),j0=_p(Hr,10);(0,xa.config)({path:[Cp,j0].filter(t=>!!t).map(t=>_t.resolve(t,".env")),override:!1});var Sa=Me(process.env.CHECKSUM_RUNTIME_REPO_MODE),H0=Sa?_t.join(Hr,"package","pw-report-template.html"):_t.join(Hr,"pw-report-template.html"),G0=Me(process.env.CHECKSUM_DEBUG_ANALYTICS),z0=Me(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),V0=Ip(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),cs={isDevMode:Ap,isRepoMode:Sa,CI:!!process.env.CI,checksumRootFolderBypass:Sa&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(Ap?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:Hr+"/checksumlib.js"},runtimeRoot:Hr,playwrightReporter:{htmlReportTemplatePath:H0},bypassProxyForLocalhost:Me(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),useCLIDebug:Me(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Me(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Me(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Me(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0}),maxRRwebBytes:V0},monitoring:{debugAnalytics:G0,logToConsole:z0,segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Me(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Me(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Me(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),disableTimeMachine:Me(process.env.CHECKSUM_RUNTIME_DISABLE_TIME_MACHINE),disableRrwebRecording:Me(process.env.CHECKSUM_RUNTIME_DISABLE_RRWEB_RECORDING),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown"};var RH=require("@playwright/test/reporter");var ar=require("path");var Aa=o((t,e,r)=>`v2:${W0(t)}::${JSON.stringify([...e,r])}`,"computeVariantKey"),W0=o(t=>(t??"").replace(/\\/g,"/"),"normalizeFilePath");var ls=require("fs"),he=_e(require("typescript"));var q0=/^[0-9a-zA-Z]+$/,K0=5;function Rp(t){return t?t.length===K0&&q0.test(t):!1}o(Rp,"isValidChecksumTestId");var Ca=class{static{o(this,"FileNameExtractionStrategy")}extract(e,r){if(!e)return;let n=e.split("/"),s=n[n.length-1];if(!s||!s.endsWith(".checksum.spec.ts"))return;let a=s.replace(".checksum.spec.ts","").split(" - ").pop();return Rp(a)?a:void 0}},Ra=class{static{o(this,"FileContentExtractionStrategy")}extract(e,r){if(!(!e||!(0,ls.existsSync)(e)))try{let n=(0,ls.readFileSync)(e,"utf-8"),s=he.createSourceFile(e,n,he.ScriptTarget.Latest,!0),i=new Map,a=o(c=>{if(he.isCallExpression(c)&&this.isTestCall(c.expression)){let l=c.arguments[0];if(l&&he.isCallExpression(l)&&he.isIdentifier(l.expression)&&l.expression.text==="defineChecksumTest"){let u=this.extractDefineChecksumTestArgs(l);u&&Rp(u.checksumTestId)&&i.set(u.testTitle,u.checksumTestId)}}he.forEachChild(c,a)},"visit");return a(s),r&&i.has(r)?i.get(r):i.size>0?Array.from(i.values())[0]:void 0}catch{return}}isTestCall(e){return he.isIdentifier(e)&&e.text==="test"?!0:he.isPropertyAccessExpression(e)?he.isIdentifier(e.expression)&&e.expression.text==="test":!1}extractDefineChecksumTestArgs(e){let r=e.arguments;if(r.length<2)return;let n=r[0],s=r[1];if(!n||!s)return;let i=this.extractStringLiteral(n),a=this.extractStringLiteral(s);if(i&&a)return{testTitle:i,checksumTestId:a}}extractStringLiteral(e){if(he.isStringLiteral(e)||he.isNoSubstitutionTemplateLiteral(e))return e.text}},Oa=class{static{o(this,"ChecksumTestIdExtractor")}constructor(e){this.strategies=e??[new Ra,new Ca]}extract(e,r){for(let n of this.strategies){let s=n.extract(e,r);if(s)return s}}};var Op=new Oa;function us(t,e){return e.pwTestIdToChecksumTestId[t.playwrightTestId]||(t.filePath!==void 0?Op.extract(t.filePath,t.title):void 0)}o(us,"resolveChecksumTestId");var Ma=o((t,e)=>Object.values(e[t]??{}).some(r=>r.autoRecoveryMetadata?.data?.autoRecovered),"isAutoRecovered"),Na=o(t=>typeof t=="number"&&!isNaN(t)?t:0,"getStat");function ka(t,e,r){let n=[],s=0,i=0,a=Na(e.expected)+Na(e.flaky),c=Na(e.unexpected);for(let l of t){let u=Z0(l,r);n.push(u),u.recovered&&i++,u.bug&&(s++,u.outcome==="expected"||u.outcome==="flaky"?a--:u.outcome==="unexpected"&&c--)}return{passed:a,failed:c,bug:s,recovered:i,tests:n}}o(ka,"computeReportStats");function Z0(t,e){let r=us({playwrightTestId:t.playwrightTestId,filePath:t.filePath,title:t.title},e),n=J0(t),s=Y0(t.annotations),i=Ma(t.playwrightTestId,e.playwrightIdToMetadata),a=X0(r,t,e),c=e.toRelativeFilePath(t.filePath);return{checksumTestId:r,playwrightTestId:t.playwrightTestId,success:t.ok,recovered:i,bug:n,annotations:s,tags:t.tags,outcome:t.outcome,variantKey:Aa(t.filePath,t.titlePath,t.title),...t.filePath!==void 0?{filePath:t.filePath}:{},...c!==void 0?{relativeFilePath:c}:{},...t.projectName?{project:t.projectName}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{},...a!==void 0?{usingChecksumTestIdPlaceholder:a}:{}}}o(Z0,"rowToTestWithMetadata");function Np(t,e){let r=t.files,n=o(c=>{let u=us({playwrightTestId:c.testId,filePath:c.location.file,title:c.title},e)??`${c.location.file}::${c.title}`,d=Aa(c.location.file,c.path??[],c.title);return`${u}::${c.projectName}::${d}`},"keyFor"),s=new Map;for(let c of r)for(let l of c.tests)s.set(n(l),l);let i=new Set(s.values()),a={total:0,expected:0,unexpected:0,flaky:0,skipped:0};for(let c of r){c.tests=c.tests.filter(l=>i.has(l));for(let l of c.tests)a.total++,l.outcome==="expected"?a.expected++:l.outcome==="unexpected"?a.unexpected++:l.outcome==="flaky"?a.flaky++:a.skipped++}t.files=r.filter(c=>c.tests.length>0),t.stats={...t.stats,...a}}o(Np,"dedupeReportByChecksumTestId");var J0=o(t=>t.tags.includes("bug")||t.annotations.some(e=>e.type==="bug")||t.title.includes("@bug"),"detectBug"),Y0=o(t=>t.filter(e=>!!e?.type).map(e=>({type:e.type,description:e.description||""})),"normalizeAnnotations"),X0=o((t,e,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[e.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[t]||!1},"computeUsingPlaceholder");var Mp=o((t,e,r)=>{if(!t)return;let n=r||e,s;if((0,ar.isAbsolute)(t))s=t;else{let i=(0,ar.dirname)(e);s=(0,ar.resolve)(i,t)}return s.replace(n+"/","")},"toRelativeFilePath");var kp=require("node:util");var or=8*1024,Gr=`
60
- \u2026 [truncated]`,Q0=/[\u001b\u0080-\u009f]/g;function Pa(t){let e=t.replaceAll("\0","");return eT((0,kp.stripVTControlCharacters)(e))}o(Pa,"sanitizeTestErrorMessage");function eT(t){return t.replace(Q0,"")}o(eT,"removeResidualVTControls");function ds(t){let e=Pa(t);if(Buffer.byteLength(e,"utf8")<=or)return{value:e,truncated:!1};let r=or-Buffer.byteLength(Gr,"utf8"),n="",s=0;for(let i of e){let a=Buffer.byteLength(i,"utf8");if(s+a>r)break;n+=i,s+=a}return{value:n+Gr,truncated:!0}}o(ds,"boundTestErrorMessage");var Lp=require("node:crypto");var tT=new Set(["failed","timedOut","interrupted"]),La=new WeakMap;function Dp(){let t={messages:new Map,ambiguousKeys:new Set,truncatedCount:0,identityConflictCount:0};return La.set(t,new Map),t}o(Dp,"createErrorDetailIndex");function $p(t,e){try{let r=rT(t);if(!r||nT(r.tests))return!1;for(let n of r.tests){if(!cr(n))continue;let s=Hp(n.projectName),i=n.testId;if(s===void 0||!fs(i))continue;let a=sT(n);if(!a)continue;let c=aT(a);c.truncated&&(e.truncatedCount+=1),lT(e,jp(r.fileId,s,i),c.value,cT(a))}return!0}catch{return!1}}o($p,"addTestFileErrorDetails");function Up(t){return cr(t)&&Object.prototype.hasOwnProperty.call(t,"fileId")&&Object.prototype.hasOwnProperty.call(t,"tests")}o(Up,"isTestFileErrorDetailCandidate");function Fp(t,e,r,n){let s=Hp(r);if(!fs(e)||s===void 0||!fs(n))return;let i=jp(e,s,n);if(!t.ambiguousKeys.has(i))return t.messages.get(i)}o(Fp,"getTestErrorMessage");function rT(t){if(!cr(t))return;let e=t.fileId,r=t.tests;if(!(!fs(e)||!Array.isArray(r)))return{fileId:e,tests:r}}o(rT,"parseTestFile");function nT(t){return t.length>0&&!t.some(cr)}o(nT,"hasOnlyMalformedTests");function sT(t){let e=t.results;if(!Array.isArray(e))return;let r=e.at(-1);if(!cr(r))return;let n=r.status;if(typeof n!="string"||!tT.has(n))return;let s=r.errors;if(Array.isArray(s))for(let i of s){let a=iT(i);if(a)return a}}o(sT,"extractFinalErrorDetail");function iT(t){if(typeof t=="string"){let n=Bp(t);return n?{message:n}:void 0}if(!cr(t))return;let e=Pp(t.message,t.value),r=Pp(t.codeframe,t.snippet);return e?!r||e.includes(r)?{message:e}:{message:e,frame:r}:r?{frame:r}:void 0}o(iT,"normalizeError");function aT(t){let{message:e,frame:r}=t;if(!e)return ds(r??"");if(!r)return ds(e);let n=Buffer.byteLength(e,"utf8");if(n>or)return ds(e);let s=`
147
+ ${t.stack}`:""):typeof t=="string"?t:`${t}`}_addChildRun(t,e){t.child_runs.push(e)}_addRunToRunMap(t){let{dottedOrder:e,microsecondPrecisionDatestring:r}=Ua(new Date(t.start_time).getTime(),t.id,t.execution_order),n={...t},i=this.getRunById(n.parent_run_id);if(n.parent_run_id!==void 0?i?(this._addChildRun(i,n),i.child_execution_order=Math.max(i.child_execution_order,n.child_execution_order),n.trace_id=i.trace_id,i.dotted_order!==void 0&&(n.dotted_order=[i.dotted_order,e].join("."),n._serialized_start_time=r)):n.parent_run_id=void 0:(n.trace_id=n.id,n.dotted_order=e,n._serialized_start_time=r),this.usesRunTreeMap){let s=Fa(n,i);s!==void 0&&this.runTreeMap.set(n.id,s)}else this.runMap.set(n.id,n);return n}async _endTrace(t){let e=t.parent_run_id!==void 0&&this.getRunById(t.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,t.child_execution_order):await this.persistRun(t),await this.onRunUpdate?.(t),this.usesRunTreeMap?this.runTreeMap.delete(t.id):this.runMap.delete(t.id)}_getExecutionOrder(t){let e=t!==void 0&&this.getRunById(t);return e?e.child_execution_order+1:1}_createRunForLLMStart(t,e,r,n,i,s,o,c){let l=this._getExecutionOrder(n),u=Date.now(),d=o?{...i,metadata:o}:i,f={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{prompts:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleLLMStart(t,e,r,n,i,s,o,c){let l=this.getRunById(r)??this._createRunForLLMStart(t,e,r,n,i,s,o,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}_createRunForChatModelStart(t,e,r,n,i,s,o,c){let l=this._getExecutionOrder(n),u=Date.now(),d=o?{...i,metadata:o}:i,f={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:u,serialized:t,events:[{name:"start",time:new Date(u).toISOString()}],inputs:{messages:e},execution_order:l,child_runs:[],child_execution_order:l,run_type:"llm",extra:d??{},tags:s||[]};return this._addRunToRunMap(f)}async handleChatModelStart(t,e,r,n,i,s,o,c){let l=this.getRunById(r)??this._createRunForChatModelStart(t,e,r,n,i,s,o,c);return await this.onRunCreate?.(l),await this.onLLMStart?.(l),l}async handleLLMEnd(t,e,r,n,i){let s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.outputs=t,s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMEnd?.(s),await this._endTrace(s),s}async handleLLMError(t,e,r,n,i){let s=this.getRunById(e);if(!s||s?.run_type!=="llm")throw new Error("No LLM run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),s.extra={...s.extra,...i},await this.onLLMError?.(s),await this._endTrace(s),s}_createRunForChainStart(t,e,r,n,i,s,o,c,l){let u=this._getExecutionOrder(n),d=Date.now(),f={id:r,name:c??t.id[t.id.length-1],parent_run_id:n,start_time:d,serialized:t,events:[{name:"start",time:new Date(d).toISOString()}],inputs:e,execution_order:u,child_execution_order:u,run_type:o??"chain",child_runs:[],extra:s?{...l,metadata:s}:{...l},tags:i||[]};return this._addRunToRunMap(f)}async handleChainStart(t,e,r,n,i,s,o,c){let l=this.getRunById(r)??this._createRunForChainStart(t,e,r,n,i,s,o,c);return await this.onRunCreate?.(l),await this.onChainStart?.(l),l}async handleChainEnd(t,e,r,n,i){let s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.outputs=$a(t,"output"),s.events.push({name:"end",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=$a(i.inputs,"input")),await this.onChainEnd?.(s),await this._endTrace(s),s}async handleChainError(t,e,r,n,i){let s=this.getRunById(e);if(!s)throw new Error("No chain run to end.");return s.end_time=Date.now(),s.error=this.stringifyError(t),s.events.push({name:"error",time:new Date(s.end_time).toISOString()}),i?.inputs!==void 0&&(s.inputs=$a(i.inputs,"input")),await this.onChainError?.(s),await this._endTrace(s),s}_createRunForToolStart(t,e,r,n,i,s,o){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{input:e},execution_order:c,child_execution_order:c,run_type:"tool",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleToolStart(t,e,r,n,i,s,o){let c=this.getRunById(r)??this._createRunForToolStart(t,e,r,n,i,s,o);return await this.onRunCreate?.(c),await this.onToolStart?.(c),c}async handleToolEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.outputs={output:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onToolEnd?.(r),await this._endTrace(r),r}async handleToolError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="tool")throw new Error("No tool run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onToolError?.(r),await this._endTrace(r),r}async handleAgentAction(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="chain")return;let n=r;n.actions=n.actions||[],n.actions.push(t),n.events.push({name:"agent_action",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentAction?.(r)}async handleAgentEnd(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"agent_end",time:new Date().toISOString(),kwargs:{action:t}}),await this.onAgentEnd?.(r))}_createRunForRetrieverStart(t,e,r,n,i,s,o){let c=this._getExecutionOrder(n),l=Date.now(),u={id:r,name:o??t.id[t.id.length-1],parent_run_id:n,start_time:l,serialized:t,events:[{name:"start",time:new Date(l).toISOString()}],inputs:{query:e},execution_order:c,child_execution_order:c,run_type:"retriever",child_runs:[],extra:s?{metadata:s}:{},tags:i||[]};return this._addRunToRunMap(u)}async handleRetrieverStart(t,e,r,n,i,s,o){let c=this.getRunById(r)??this._createRunForRetrieverStart(t,e,r,n,i,s,o);return await this.onRunCreate?.(c),await this.onRetrieverStart?.(c),c}async handleRetrieverEnd(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.outputs={documents:t},r.events.push({name:"end",time:new Date(r.end_time).toISOString()}),await this.onRetrieverEnd?.(r),await this._endTrace(r),r}async handleRetrieverError(t,e){let r=this.getRunById(e);if(!r||r?.run_type!=="retriever")throw new Error("No retriever run to end");return r.end_time=Date.now(),r.error=this.stringifyError(t),r.events.push({name:"error",time:new Date(r.end_time).toISOString()}),await this.onRetrieverError?.(r),await this._endTrace(r),r}async handleText(t,e){let r=this.getRunById(e);!r||r?.run_type!=="chain"||(r.events.push({name:"text",time:new Date().toISOString(),kwargs:{text:t}}),await this.onText?.(r))}async handleLLMNewToken(t,e,r,n,i,s){let 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:t,idx:e,chunk:s?.chunk}}),await this.onLLMNewToken?.(o,t,{chunk:s?.chunk}),o}};var vd={bold:{open:"\x1B[1m",close:"\x1B[22m"},color:{grey:{open:"\x1B[90m",close:"\x1B[39m"},green:{open:"\x1B[32m",close:"\x1B[39m"},cyan:{open:"\x1B[36m",close:"\x1B[39m"},red:{open:"\x1B[31m",close:"\x1B[39m"},blue:{open:"\x1B[34m",close:"\x1B[39m"}}};function Pe(t,e){return`${t.open}${e}${t.close}`}a(Pe,"wrap");function qe(t,e){try{return JSON.stringify(t,null,2)}catch{return e}}a(qe,"tryJsonStringify");function Td(t){return typeof t=="string"?t.trim():t==null?t:qe(t,t.toString())}a(Td,"formatKVMapItem");function Lt(t){if(!t.end_time)return"";let e=t.end_time-t.start_time;return e<1e3?`${e}ms`:`${(e/1e3).toFixed(2)}s`}a(Lt,"elapsed");var{color:Fe}=vd,Ba=class extends cr{static{a(this,"ConsoleCallbackHandler")}name="console_callback_handler";persistRun(t){return Promise.resolve()}getParents(t){let e=[],r=t;for(;r.parent_run_id;){let n=this.runMap.get(r.parent_run_id);if(n)e.push(n),r=n;else break}return e}getBreadcrumbs(t){let e=[...this.getParents(t).reverse(),t].map((r,n,i)=>{let s=`${r.execution_order}:${r.run_type}:${r.name}`;return n===i.length-1?Pe(vd.bold,s):s}).join(" > ");return Pe(Fe.grey,e)}onChainStart(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.green,"[chain/start]")} [${e}] Entering Chain run with input: ${qe(t.inputs,"[inputs]")}`)}onChainEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.cyan,"[chain/end]")} [${e}] [${Lt(t)}] Exiting Chain run with output: ${qe(t.outputs,"[outputs]")}`)}onChainError(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.red,"[chain/error]")} [${e}] [${Lt(t)}] Chain run errored with error: ${qe(t.error,"[error]")}`)}onLLMStart(t){let e=this.getBreadcrumbs(t),r="prompts"in t.inputs?{prompts:t.inputs.prompts.map(n=>n.trim())}:t.inputs;console.log(`${Pe(Fe.green,"[llm/start]")} [${e}] Entering LLM run with input: ${qe(r,"[inputs]")}`)}onLLMEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.cyan,"[llm/end]")} [${e}] [${Lt(t)}] Exiting LLM run with output: ${qe(t.outputs,"[response]")}`)}onLLMError(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.red,"[llm/error]")} [${e}] [${Lt(t)}] LLM run errored with error: ${qe(t.error,"[error]")}`)}onToolStart(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.green,"[tool/start]")} [${e}] Entering Tool run with input: "${Td(t.inputs.input)}"`)}onToolEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.cyan,"[tool/end]")} [${e}] [${Lt(t)}] Exiting Tool run with output: "${Td(t.outputs?.output)}"`)}onToolError(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.red,"[tool/error]")} [${e}] [${Lt(t)}] Tool run errored with error: ${qe(t.error,"[error]")}`)}onRetrieverStart(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.green,"[retriever/start]")} [${e}] Entering Retriever run with input: ${qe(t.inputs,"[inputs]")}`)}onRetrieverEnd(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.cyan,"[retriever/end]")} [${e}] [${Lt(t)}] Exiting Retriever run with output: ${qe(t.outputs,"[outputs]")}`)}onRetrieverError(t){let e=this.getBreadcrumbs(t);console.log(`${Pe(Fe.red,"[retriever/error]")} [${e}] [${Lt(t)}] Retriever run errored with error: ${qe(t.error,"[error]")}`)}onAgentAction(t){let e=t,r=this.getBreadcrumbs(t);console.log(`${Pe(Fe.blue,"[agent/action]")} [${r}] Agent selected action: ${qe(e.actions[e.actions.length-1],"[action]")}`)}};var ja,Ha=a(()=>(ja===void 0&&(ja=new Rt(Xe("LANGCHAIN_CALLBACKS_BACKGROUND")==="false"?{blockOnRootRunFinalization:!0}:{})),ja),"getDefaultLangChainClientSingleton");var xd=new Set(["ls_agent_type"]);function Zy(t){let e;for(let r of t)for(let n of r)St.isInstance(n.message)&&n.message.usage_metadata!==void 0&&(e=Pn(e,n.message.usage_metadata));return e}a(Zy,"_getUsageMetadataFromGenerations");var mn=class za extends cr{static{a(this,"LangChainTracer")}name="langchain_tracer";projectName;exampleId;client;replicas;usesRunTreeMap=!0;tracingMetadata;tracingTags=[];constructor(e={}){super(e),this.fields=e;let{exampleId:r,projectName:n,client:i,replicas:s,metadata:o,tags:c}=e;this.projectName=n??sn(),this.replicas=s,this.exampleId=r,this.client=i??Ha(),this.tracingMetadata=o?{...o}:void 0,this.tracingTags=c??[];let l=za.getTraceableRunTree();l&&this.updateFromRunTree(l)}async persistRun(e){}async onRunCreate(e){Sd(this,e),e.extra?.lc_defers_inputs||await this.getRunTreeWithTracingConfig(e.id)?.postRun()}async onRunUpdate(e){Sd(this,e);let r=this.getRunTreeWithTracingConfig(e.id);e.extra?.lc_defers_inputs?await r?.postRun():await r?.patchRun()}onLLMEnd(e){let r=e.outputs;if(r?.generations){let n=Zy(r.generations);if(n!==void 0){e.extra=e.extra??{};let i=e.extra.metadata??{};i.usage_metadata=n,e.extra.metadata=i}}}copyWithTracingConfig({metadata:e,tags:r}){let n;if(e===void 0)n=this.tracingMetadata?{...this.tracingMetadata}:void 0;else if(this.tracingMetadata===void 0)n={...e};else{n={...this.tracingMetadata};for(let[o,c]of Object.entries(e))(!Object.prototype.hasOwnProperty.call(n,o)||xd.has(o))&&(n[o]=c)}let i=r?Array.from(new Set([...this.tracingTags,...r])):[...this.tracingTags],s=new za({...this.fields,metadata:n,tags:i});return s.runMap=this.runMap,s.runTreeMap=this.runTreeMap,s}getRun(e){return this.runTreeMap.get(e)}updateFromRunTree(e){this.runTreeMap.set(e.id,e);let r=e,n=new Set;for(;r.parent_run&&!(n.has(r.id)||(n.add(r.id),!r.parent_run));)r=r.parent_run;n.clear();let i=[r];for(;i.length>0;){let s=i.shift();!s||n.has(s.id)||(n.add(s.id),this.runTreeMap.set(s.id,s),s.child_runs&&i.push(...s.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,this.fields={...this.fields,client:this.client,replicas:this.replicas,projectName:this.projectName,exampleId:this.exampleId}}getRunTreeWithTracingConfig(e){let r=this.runTreeMap.get(e);if(r)return new et({...r,client:this.client,project_name:this.projectName,replicas:this.replicas,reference_example_id:this.exampleId,tracingEnabled:!0})}static getTraceableRunTree(){try{return Js(!0)}catch{return}}static[Symbol.hasInstance](e){if(typeof e!="object"||e===null)return!1;let r=e;return"name"in r&&r.name==="langchain_tracer"&&"copyWithTracingConfig"in r&&typeof r.copyWithTracingConfig=="function"&&"getRunTreeWithTracingConfig"in r&&typeof r.getRunTreeWithTracingConfig=="function"}};function Sd(t,e){if(t.tracingMetadata){e.extra??={};let r=e.extra.metadata??{},n=!1;for(let[i,s]of Object.entries(t.tracingMetadata))(!Object.prototype.hasOwnProperty.call(r,i)||xd.has(i))&&r[i]!==s&&(r[i]=s,n=!0);n&&(e.extra.metadata=r)}t.tracingTags.length>0&&(e.tags=Array.from(new Set([...e.tags??[],...t.tracingTags])))}a(Sd,"_patchMissingTracingDefaults");var Ai=He(Hn(),1);var hn;function Yy(){return new("default"in Ai.default?Ai.default.default:Ai.default)({autoStart:!0,concurrency:1})}a(Yy,"createQueue");function Xy(){return typeof hn>"u"&&(hn=Yy()),hn}a(Xy,"getQueue");async function ne(t,e){if(e===!0){let r=It();r!==void 0?await r.run(void 0,async()=>t()):await t()}else hn=Xy(),hn.add(async()=>{let r=It();r!==void 0?await r.run(void 0,async()=>t()):await t()})}a(ne,"consumeCallback");var Id=a(t=>t!==void 0?t:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>Xe(e)==="true"),"isTracingEnabled");function Ga(t){let e=It();if(e!==void 0)return e.getStore()?.[Ht]?.[t]}a(Ga,"getContextVariable");var Qy=Symbol("lc:configure_hooks"),Ad=a(()=>Ga(Qy)||[],"_getConfigureHooks");var e_=class{static{a(this,"BaseCallbackManager")}setHandler(t){return this.setHandlers([t])}},Ci=class{static{a(this,"BaseRunManager")}constructor(t,e,r,n,i,s,o,c){this.runId=t,this.handlers=e,this.inheritableHandlers=r,this.tags=n,this.inheritableTags=i,this.metadata=s,this.inheritableMetadata=o,this._parentRunId=c}get parentRunId(){return this._parentRunId}async handleText(t){await Promise.all(this.handlers.map(e=>ne(async()=>{try{await e.handleText?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleCustomEvent(t,e,r,n,i){await Promise.all(this.handlers.map(s=>ne(async()=>{try{await s.handleCustomEvent?.(t,e,this.runId,this.tags,this.metadata)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleCustomEvent: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},t_=class extends Ci{static{a(this,"CallbackManagerForRetrieverRun")}getChild(t){let e=new lr(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleRetrieverEnd(t){await Promise.all(this.handlers.map(e=>ne(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetriever`),e.raiseError)throw r}},e.awaitHandlers)))}async handleRetrieverError(t){await Promise.all(this.handlers.map(e=>ne(async()=>{if(!e.ignoreRetriever)try{await e.handleRetrieverError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleRetrieverError: ${r}`),e.raiseError)throw t}},e.awaitHandlers)))}},Cd=class extends Ci{static{a(this,"CallbackManagerForLLMRun")}async handleLLMNewToken(t,e,r,n,i,s){await Promise.all(this.handlers.map(o=>ne(async()=>{if(!o.ignoreLLM)try{await o.handleLLMNewToken?.(t,e??{prompt:0,completion:0},this.runId,this._parentRunId,this.tags,s)}catch(c){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleLLMNewToken: ${c}`),o.raiseError)throw c}},o.awaitHandlers)))}async handleChatModelStreamEvent(t){await Promise.all(this.handlers.map(e=>ne(async()=>{if(!e.ignoreLLM)try{await e.handleChatModelStreamEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleChatModelStreamEvent: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleLLMError(t,e,r,n,i){await Promise.all(this.handlers.map(s=>ne(async()=>{if(!s.ignoreLLM)try{await s.handleLLMError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleLLMEnd(t,e,r,n,i){await Promise.all(this.handlers.map(s=>ne(async()=>{if(!s.ignoreLLM)try{await s.handleLLMEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleLLMEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}},r_=class extends Ci{static{a(this,"CallbackManagerForChainRun")}getChild(t){let e=new lr(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleChainError(t,e,r,n,i){await Promise.all(this.handlers.map(s=>ne(async()=>{if(!s.ignoreChain)try{await s.handleChainError?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainError: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleChainEnd(t,e,r,n,i){await Promise.all(this.handlers.map(s=>ne(async()=>{if(!s.ignoreChain)try{await s.handleChainEnd?.(t,this.runId,this._parentRunId,this.tags,i)}catch(o){if((s.raiseError?console.error:console.warn)(`Error in handler ${s.constructor.name}, handleChainEnd: ${o}`),s.raiseError)throw o}},s.awaitHandlers)))}async handleAgentAction(t){await Promise.all(this.handlers.map(e=>ne(async()=>{if(!e.ignoreAgent)try{await e.handleAgentAction?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentAction: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleAgentEnd(t){await Promise.all(this.handlers.map(e=>ne(async()=>{if(!e.ignoreAgent)try{await e.handleAgentEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleAgentEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},n_=class extends Ci{static{a(this,"CallbackManagerForToolRun")}getChild(t){let e=new lr(this.runId);return e.setHandlers(this.inheritableHandlers),e.addTags(this.inheritableTags),e.addMetadata(this.inheritableMetadata),t&&e.addTags([t],!1),e}async handleToolError(t){await Promise.all(this.handlers.map(e=>ne(async()=>{if(!e.ignoreAgent)try{await e.handleToolError?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolError: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEvent(t){await Promise.all(this.handlers.map(e=>ne(async()=>{if(!e.ignoreAgent)try{await e.handleToolEvent?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if(e.raiseError)throw r}},e.awaitHandlers)))}async handleToolEnd(t){await Promise.all(this.handlers.map(e=>ne(async()=>{if(!e.ignoreAgent)try{await e.handleToolEnd?.(t,this.runId,this._parentRunId,this.tags)}catch(r){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleToolEnd: ${r}`),e.raiseError)throw r}},e.awaitHandlers)))}},lr=class gn extends e_{static{a(this,"CallbackManager")}handlers=[];inheritableHandlers=[];tags=[];inheritableTags=[];metadata={};inheritableMetadata={};name="callback_manager";_parentRunId;constructor(e,r){super(),this.handlers=r?.handlers??this.handlers,this.inheritableHandlers=r?.inheritableHandlers??this.inheritableHandlers,this.tags=r?.tags??this.tags,this.inheritableTags=r?.inheritableTags??this.inheritableTags,this.metadata=r?.metadata??this.metadata,this.inheritableMetadata=r?.inheritableMetadata??this.inheritableMetadata,this._parentRunId=e}getParentRunId(){return this._parentRunId}async handleLLMStart(e,r,n=void 0,i=void 0,s=void 0,o=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&n?n:st();return await Promise.all(this.handlers.map(y=>{if(!y.ignoreLLM)return jr(y)&&y._createRunForLLMStart(e,[u],f,this._parentRunId,s,this.tags,this.metadata,l),ne(async()=>{try{await y.handleLLMStart?.(e,[u],f,this._parentRunId,s,this.tags,this.metadata,l)}catch(h){if((y.raiseError?console.error:console.warn)(`Error in handler ${y.constructor.name}, handleLLMStart: ${h}`),y.raiseError)throw h}},y.awaitHandlers)})),new Cd(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChatModelStart(e,r,n=void 0,i=void 0,s=void 0,o=void 0,c=void 0,l=void 0){return Promise.all(r.map(async(u,d)=>{let f=d===0&&n?n:st();return await Promise.all(this.handlers.map(y=>{if(!y.ignoreLLM)return jr(y)&&y._createRunForChatModelStart(e,[u],f,this._parentRunId,s,this.tags,this.metadata,l),ne(async()=>{try{if(y.handleChatModelStart)await y.handleChatModelStart?.(e,[u],f,this._parentRunId,s,this.tags,this.metadata,l);else if(y.handleLLMStart){let h=Dn(u);await y.handleLLMStart?.(e,[h],f,this._parentRunId,s,this.tags,this.metadata,l)}}catch(h){if((y.raiseError?console.error:console.warn)(`Error in handler ${y.constructor.name}, handleLLMStart: ${h}`),y.raiseError)throw h}},y.awaitHandlers)})),new Cd(f,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}))}async handleChainStart(e,r,n=st(),i=void 0,s=void 0,o=void 0,c=void 0,l=void 0,u=void 0){return await Promise.all(this.handlers.map(d=>{if(!d.ignoreChain)return jr(d)&&d._createRunForChainStart(e,r,n,this._parentRunId,this.tags,this.metadata,i,c,u),ne(async()=>{try{await d.handleChainStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,i,c,u)}catch(f){if((d.raiseError?console.error:console.warn)(`Error in handler ${d.constructor.name}, handleChainStart: ${f}`),d.raiseError)throw f}},d.awaitHandlers)})),new r_(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleToolStart(e,r,n=st(),i=void 0,s=void 0,o=void 0,c=void 0,l=void 0){return await Promise.all(this.handlers.map(u=>{if(!u.ignoreAgent)return jr(u)&&u._createRunForToolStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),ne(async()=>{try{await u.handleToolStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c,l)}catch(d){if((u.raiseError?console.error:console.warn)(`Error in handler ${u.constructor.name}, handleToolStart: ${d}`),u.raiseError)throw d}},u.awaitHandlers)})),new n_(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleRetrieverStart(e,r,n=st(),i=void 0,s=void 0,o=void 0,c=void 0){return await Promise.all(this.handlers.map(l=>{if(!l.ignoreRetriever)return jr(l)&&l._createRunForRetrieverStart(e,r,n,this._parentRunId,this.tags,this.metadata,c),ne(async()=>{try{await l.handleRetrieverStart?.(e,r,n,this._parentRunId,this.tags,this.metadata,c)}catch(u){if((l.raiseError?console.error:console.warn)(`Error in handler ${l.constructor.name}, handleRetrieverStart: ${u}`),l.raiseError)throw u}},l.awaitHandlers)})),new t_(n,this.handlers,this.inheritableHandlers,this.tags,this.inheritableTags,this.metadata,this.inheritableMetadata,this._parentRunId)}async handleCustomEvent(e,r,n,i,s){await Promise.all(this.handlers.map(o=>ne(async()=>{if(!o.ignoreCustomEvent)try{await o.handleCustomEvent?.(e,r,n,this.tags,this.metadata)}catch(c){if((o.raiseError?console.error:console.warn)(`Error in handler ${o.constructor.name}, handleCustomEvent: ${c}`),o.raiseError)throw c}},o.awaitHandlers)))}addHandler(e,r=!0){this.handlers.push(e),r&&this.inheritableHandlers.push(e)}removeHandler(e){this.handlers=this.handlers.filter(r=>r!==e),this.inheritableHandlers=this.inheritableHandlers.filter(r=>r!==e)}setHandlers(e,r=!0){this.handlers=[],this.inheritableHandlers=[];for(let n of e)this.addHandler(n,r)}addTags(e,r=!0){this.removeTags(e),this.tags.push(...e),r&&this.inheritableTags.push(...e)}removeTags(e){this.tags=this.tags.filter(r=>!e.includes(r)),this.inheritableTags=this.inheritableTags.filter(r=>!e.includes(r))}addMetadata(e,r=!0){this.metadata={...this.metadata,...e},r&&(this.inheritableMetadata={...this.inheritableMetadata,...e})}removeMetadata(e){for(let r of Object.keys(e))delete this.metadata[r],delete this.inheritableMetadata[r]}copy(e=[],r=!0){let n=new gn(this._parentRunId);for(let i of this.handlers){let s=this.inheritableHandlers.includes(i);n.addHandler(i,s)}for(let i of this.tags){let s=this.inheritableTags.includes(i);n.addTags([i],s)}for(let i of Object.keys(this.metadata)){let s=Object.keys(this.inheritableMetadata).includes(i);n.addMetadata({[i]:this.metadata[i]},s)}for(let i of e)n.handlers.filter(s=>s.name==="console_callback_handler").some(s=>s.name===i.name)||n.addHandler(i,r);return n}static fromHandlers(e){class r extends _r{static{a(this,"Handler")}name=st();constructor(){super(),Object.assign(this,e)}}let n=new this;return n.addHandler(new r),n}static configure(e,r,n,i,s,o,c){return this._configureSync(e,r,n,i,s,o,c)}static _configureSync(e,r,n,i,s,o,c){let l;(e||r)&&(Array.isArray(e)||!e?(l=new gn,l.setHandlers(e?.map(Va)??[],!0)):l=e,l=l.copy(Array.isArray(r)?r.map(Va):r?.handlers,!1));let u=Xe("LANGCHAIN_VERBOSE")==="true"||c?.verbose,d=mn.getTraceableRunTree(),f=d?.tracingEnabled??Id();if(d?.tracingEnabled===!1&&l){let b=l.handlers.filter(w=>w.name==="langchain_tracer");for(let w of b)l.removeHandler(w)}let y=f||(Xe("LANGCHAIN_TRACING")??!1);if(u||y){if(l||(l=new gn),u&&!l.handlers.some(b=>b.name===Ba.prototype.name)){let b=new Ba;l.addHandler(b,!0)}if(y&&!l.handlers.some(b=>b.name==="langchain_tracer")&&f){let b=new mn;l.addHandler(b,!0)}f&&d&&l._parentRunId===void 0&&(l._parentRunId=d.id,l.handlers.find(b=>b.name==="langchain_tracer")?.updateFromRunTree(d))}for(let{contextVar:b,inheritable:w=!0,handlerClass:v,envVar:S}of Ad()){let p=S&&Xe(S)==="true"&&v,T,I=b!==void 0?Ga(b):void 0;I&&nl(I)?T=I:p&&(T=new v({})),T!==void 0&&(l||(l=new gn),l.handlers.some(C=>C.name===T.name)||l.addHandler(T,w))}(n||i)&&l&&(l.addTags(n??[]),l.addTags(i??[],!1)),(s||o)&&l&&(l.addMetadata(s??{}),l.addMetadata(o??{},!1));let h=c?.tracerInheritableMetadata,g=c?.tracerInheritableTags;return l&&(h||g)&&(l.handlers=l.handlers.map(b=>b instanceof mn?b.copyWithTracingConfig({metadata:h,tags:g}):b),l.inheritableHandlers=l.inheritableHandlers.map(b=>b instanceof mn?b.copyWithTracingConfig({metadata:h,tags:g}):b)),l}};function Va(t){return"name"in t?t:_r.fromMethods(t)}a(Va,"ensureHandler");var Od=class{static{a(this,"MockAsyncLocalStorage")}getStore(){}run(t,e){return e()}enterWith(t){}},i_=new Od,Rd=Symbol.for("lc:child_config"),s_=class{static{a(this,"AsyncLocalStorageProvider")}getInstance(){return It()??i_}getRunnableConfig(){return this.getInstance().getStore()?.extra?.[Rd]}runWithConfig(t,e,r){let n=lr._configureSync(t?.callbacks,void 0,t?.tags,void 0,t?.metadata),i=this.getInstance(),s=i.getStore(),o=n?.getParentRunId(),c=n?.handlers?.find(u=>u?.name==="langchain_tracer"),l;return c&&o?l=c.getRunTreeWithTracingConfig(o):r||(l=new et({name:"<runnable_lambda>",tracingEnabled:!1})),l&&(l.extra={...l.extra,[Rd]:t}),s!==void 0&&s[Ht]!==void 0&&(l===void 0&&(l={}),l[Ht]=s[Ht]),i.run(l,e)}initializeGlobalInstance(t){It()===void 0&&tl(t)}},yn=new s_;var a_=Object.prototype.hasOwnProperty;function Pd(t,e){return a_.call(t,e)}a(Pd,"hasOwnProperty");function Nd(t){if(Array.isArray(t)){let r=new Array(t.length);for(let n=0;n<r.length;n++)r[n]=""+n;return r}if(Object.keys)return Object.keys(t);let e=[];for(let r in t)Pd(t,r)&&e.push(r);return e}a(Nd,"_objectKeys");function wt(t){switch(typeof t){case"object":return JSON.parse(JSON.stringify(t));case"undefined":return null;default:return t}}a(wt,"_deepClone");function Oi(t){let e=0,r=t.length,n;for(;e<r;){if(n=t.charCodeAt(e),n>=48&&n<=57){e++;continue}return!1}return!0}a(Oi,"isInteger");function Ld(t){return t.replace(/~1/g,"/").replace(/~0/g,"~")}a(Ld,"unescapePathComponent");function Ri(t){if(t===void 0)return!0;if(t){if(Array.isArray(t)){for(let r=0,n=t.length;r<n;r++)if(Ri(t[r]))return!0}else if(typeof t=="object"){let r=Nd(t),n=r.length;for(var e=0;e<n;e++)if(Ri(t[r[e]]))return!0}}return!1}a(Ri,"hasUndefined");function Md(t,e){let r=[t];for(let n in e){let i=typeof e[n]=="object"?JSON.stringify(e[n],null,2):e[n];typeof i<"u"&&r.push(`${n}: ${i}`)}return r.join(`
148
+ `)}a(Md,"patchErrorMessageFormatter");var Dd=class extends Error{static{a(this,"PatchError")}constructor(t,e,r,n,i){super(Md(t,{name:e,index:r,operation:n,tree:i})),this.name=e,this.index=r,this.operation=n,this.tree=i,Object.setPrototypeOf(this,new.target.prototype),this.message=Md(t,{name:e,index:r,operation:n,tree:i})}};var Ud=V({JsonPatchError:a(()=>se,"JsonPatchError"),_areEquals:a(()=>_n,"_areEquals"),applyOperation:a(()=>ur,"applyOperation"),applyPatch:a(()=>Pi,"applyPatch"),applyReducer:a(()=>l_,"applyReducer"),deepClone:a(()=>o_,"deepClone"),getValueByPointer:a(()=>ki,"getValueByPointer"),validate:a(()=>$d,"validate"),validator:a(()=>Mi,"validator")}),se=Dd,o_=wt,Hr={add:a(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");return t[e]=this.value,{newDocument:r}},"add"),remove:a(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return delete t[e],{newDocument:r,removed:n}},"remove"),replace:a(function(t,e,r){if(e==="__proto__"||e==="constructor")throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor` prop is banned for security reasons");var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:a(function(t,e,r){let n=ki(r,this.path);n&&(n=wt(n));let i=ur(r,{op:"remove",path:this.from}).removed;return ur(r,{op:"add",path:this.path,value:i}),{newDocument:r,removed:n}},"move"),copy:a(function(t,e,r){let n=ki(r,this.from);return ur(r,{op:"add",path:this.path,value:wt(n)}),{newDocument:r}},"copy"),test:a(function(t,e,r){return{newDocument:r,test:_n(t[e],this.value)}},"test"),_get:a(function(t,e,r){return this.value=t[e],{newDocument:r}},"_get")},c_={add:a(function(t,e,r){return Oi(e)?t.splice(e,0,this.value):t[e]=this.value,{newDocument:r,index:e}},"add"),remove:a(function(t,e,r){return{newDocument:r,removed:t.splice(e,1)[0]}},"remove"),replace:a(function(t,e,r){var n=t[e];return t[e]=this.value,{newDocument:r,removed:n}},"replace"),move:Hr.move,copy:Hr.copy,test:Hr.test,_get:Hr._get};function ki(t,e){if(e=="")return t;var r={op:"_get",path:e};return ur(t,r),r.value}a(ki,"getValueByPointer");function ur(t,e,r=!1,n=!0,i=!0,s=0){if(r&&(typeof r=="function"?r(e,0,t,e.path):Mi(e,0)),e.path===""){let o={newDocument:t};if(e.op==="add")return o.newDocument=e.value,o;if(e.op==="replace")return o.newDocument=e.value,o.removed=t,o;if(e.op==="move"||e.op==="copy")return o.newDocument=ki(t,e.from),e.op==="move"&&(o.removed=t),o;if(e.op==="test"){if(o.test=_n(t,e.value),o.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return o.newDocument=t,o}else{if(e.op==="remove")return o.removed=t,o.newDocument=null,o;if(e.op==="_get")return e.value=t,o;if(r)throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",s,e,t);return o}}else{n||(t=wt(t));let o=(e.path||"").split("/"),c=t,l=1,u=o.length,d,f,y;for(typeof r=="function"?y=r:y=Mi;;){if(f=o[l],f&&f.indexOf("~")!=-1&&(f=Ld(f)),i&&(f=="__proto__"||f=="prototype"&&l>0&&o[l-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(r&&d===void 0&&(c[f]===void 0?d=o.slice(0,l).join("/"):l==u-1&&(d=e.path),d!==void 0&&y(e,0,t,d)),l++,Array.isArray(c)){if(f==="-")f=c.length;else{if(r&&!Oi(f))throw new se("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",s,e,t);Oi(f)&&(f=~~f)}if(l>=u){if(r&&e.op==="add"&&f>c.length)throw new se("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",s,e,t);let h=c_[e.op].call(e,c,f,t);if(h.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return h}}else if(l>=u){let h=Hr[e.op].call(e,c,f,t);if(h.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",s,e,t);return h}if(c=c[f],r&&l<u&&(!c||typeof c!="object"))throw new se("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",s,e,t)}}}a(ur,"applyOperation");function Pi(t,e,r,n=!0,i=!0){if(r&&!Array.isArray(e))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");n||(t=wt(t));let s=new Array(e.length);for(let o=0,c=e.length;o<c;o++)s[o]=ur(t,e[o],r,!0,i,o),t=s[o].newDocument;return s.newDocument=t,s}a(Pi,"applyPatch");function l_(t,e,r){let n=ur(t,e);if(n.test===!1)throw new se("Test operation failed","TEST_OPERATION_FAILED",r,e,t);return n.newDocument}a(l_,"applyReducer");function Mi(t,e,r,n){if(typeof t!="object"||t===null||Array.isArray(t))throw new se("Operation is not an object","OPERATION_NOT_AN_OBJECT",e,t,r);if(Hr[t.op]){if(typeof t.path!="string")throw new se("Operation `path` property is not a string","OPERATION_PATH_INVALID",e,t,r);if(t.path.indexOf("/")!==0&&t.path.length>0)throw new se('Operation `path` property must start with "/"',"OPERATION_PATH_INVALID",e,t,r);if((t.op==="move"||t.op==="copy")&&typeof t.from!="string")throw new se("Operation `from` property is not present (applicable in `move` and `copy` operations)","OPERATION_FROM_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&t.value===void 0)throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_REQUIRED",e,t,r);if((t.op==="add"||t.op==="replace"||t.op==="test")&&Ri(t.value))throw new se("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)","OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED",e,t,r);if(r){if(t.op=="add"){var i=t.path.split("/").length,s=n.split("/").length;if(i!==s+1&&i!==s)throw new se("Cannot perform an `add` operation at the desired path","OPERATION_PATH_CANNOT_ADD",e,t,r)}else if(t.op==="replace"||t.op==="remove"||t.op==="_get"){if(t.path!==n)throw new se("Cannot perform the operation at a path that does not exist","OPERATION_PATH_UNRESOLVABLE",e,t,r)}else if(t.op==="move"||t.op==="copy"){var o=$d([{op:"_get",path:t.from,value:void 0}],r);if(o&&o.name==="OPERATION_PATH_UNRESOLVABLE")throw new se("Cannot perform the operation from a path that does not exist","OPERATION_FROM_UNRESOLVABLE",e,t,r)}}}else throw new se("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",e,t,r)}a(Mi,"validator");function $d(t,e,r){try{if(!Array.isArray(t))throw new se("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");if(e)Pi(wt(e),wt(t),r||!0);else{r=r||Mi;for(var n=0;n<t.length;n++)r(t[n],n,e,void 0)}}catch(i){if(i instanceof se)return i;throw i}}a($d,"validate");function _n(t,e){if(t===e)return!0;if(t&&e&&typeof t=="object"&&typeof e=="object"){var r=Array.isArray(t),n=Array.isArray(e),i,s,o;if(r&&n){if(s=t.length,s!=e.length)return!1;for(i=s;i--!==0;)if(!_n(t[i],e[i]))return!1;return!0}if(r!=n)return!1;var c=Object.keys(t);if(s=c.length,s!==Object.keys(e).length)return!1;for(i=s;i--!==0;)if(!e.hasOwnProperty(c[i]))return!1;for(i=s;i--!==0;)if(o=c[i],!_n(t[o],e[o]))return!1;return!0}return t!==t&&e!==e}a(_n,"_areEquals");({...Ud});var p$=typeof self<"u"&&self.location&&self.location.origin!=="null"?new URL(self.location.origin+self.location.pathname+location.search):new URL("https://github.com/cfworker");var g_=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,y_=[0,31,28,31,30,31,30,31,31,30,31,30,31],__=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,b_=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,w_=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,E_=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,T_=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,v_=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,S_=/^(?:\/(?:[^~/]|~0|~1)*)*$/,x_=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,I_=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,A_=a(t=>{if(t[0]==='"')return!1;let[e,r,...n]=t.split("@");return!e||!r||n.length!==0||e.length>64||r.length>253||e[0]==="."||e.endsWith(".")||e.includes("..")||!/^[a-z0-9.-]+$/i.test(r)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(e)?!1:r.split(".").every(i=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(i))},"EMAIL"),C_=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,R_=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,O_=a(t=>t.length>1&&t.length<80&&(/^P\d+([.,]\d+)?W$/.test(t)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(t)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(t)),"DURATION");function pt(t){return t.test.bind(t)}a(pt,"bind");var k_={date:Fd,time:Bd.bind(void 0,!1),"date-time":N_,duration:O_,uri:U_,"uri-reference":pt(w_),"uri-template":pt(E_),url:pt(T_),email:A_,hostname:pt(b_),ipv4:pt(C_),ipv6:pt(R_),regex:F_,uuid:pt(v_),"json-pointer":pt(S_),"json-pointer-uri-fragment":pt(x_),"relative-json-pointer":pt(I_)};function M_(t){return t%4===0&&(t%100!==0||t%400===0)}a(M_,"isLeapYear");function Fd(t){let e=t.match(g_);if(!e)return!1;let r=+e[1],n=+e[2],i=+e[3];return n>=1&&n<=12&&i>=1&&i<=(n==2&&M_(r)?29:y_[n])}a(Fd,"date");function Bd(t,e){let r=e.match(__);if(!r)return!1;let n=+r[1],i=+r[2],s=+r[3],o=!!r[5];return(n<=23&&i<=59&&s<=59||n==23&&i==59&&s==60)&&(!t||o)}a(Bd,"time");var P_=/t|\s/i;function N_(t){let e=t.split(P_);return e.length==2&&Fd(e[0])&&Bd(!0,e[1])}a(N_,"date_time");var L_=/\/|:/,D_=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function U_(t){return L_.test(t)&&D_.test(t)}a(U_,"uri");var $_=/[^\\]\\Z/;function F_(t){if($_.test(t))return!1;try{return new RegExp(t,"u"),!0}catch{return!1}}a(F_,"regex");var jd;(function(t){t[t.Flag=1]="Flag",t[t.Basic=2]="Basic",t[t.Detailed=4]="Detailed"})(jd||(jd={}));var Qd=He(Xd(),1);var tb=Object.defineProperty,rb=a((t,e,r)=>e in t?tb(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,"__defNormalProp"),nb=a((t,e,r)=>(rb(t,typeof e!="symbol"?e+"":e,r),r),"__publicField");function ib(t,e){let r=Array.from({length:t.length},(n,i)=>({start:i,end:i+1}));for(;r.length>1;){let n=null;for(let i=0;i<r.length-1;i++){let s=t.slice(r[i].start,r[i+1].end),o=e.get(s.join(","));o!=null&&(n==null||o<n[0])&&(n=[o,i])}if(n!=null){let i=n[1];r[i]={start:r[i].start,end:r[i+1].end},r.splice(i+1,1)}else break}return r}a(ib,"bytePairMerge");function sb(t,e){return t.length===1?[e.get(t.join(","))]:ib(t,e).map(r=>e.get(t.slice(r.start,r.end).join(","))).filter(r=>r!=null)}a(sb,"bytePairEncode");function ab(t){return t.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}a(ab,"escapeRegex");var Ya=class{static{a(this,"_Tiktoken")}specialTokens;inverseSpecialTokens;patStr;textEncoder=new TextEncoder;textDecoder=new TextDecoder("utf-8");rankMap=new Map;textMap=new Map;constructor(t,e){this.patStr=t.pat_str;let r=t.bpe_ranks.split(`
149
+ `).filter(Boolean).reduce((n,i)=>{let[s,o,...c]=i.split(" "),l=Number.parseInt(o,10);return c.forEach((u,d)=>n[u]=l+d),n},{});for(let[n,i]of Object.entries(r)){let s=Qd.default.toByteArray(n);this.rankMap.set(s.join(","),i),this.textMap.set(i,s)}this.specialTokens={...t.special_tokens,...e},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((n,[i,s])=>(n[s]=this.textEncoder.encode(i),n),{})}encode(t,e=[],r="all"){let n=new RegExp(this.patStr,"ug"),i=Ya.specialTokenRegex(Object.keys(this.specialTokens)),s=[],o=new Set(e==="all"?Object.keys(this.specialTokens):e),c=new Set(r==="all"?Object.keys(this.specialTokens).filter(u=>!o.has(u)):r);if(c.size>0){let u=Ya.specialTokenRegex([...c]),d=t.match(u);if(d!=null)throw new Error(`The text contains a special token that is not allowed: ${d[0]}`)}let l=0;for(;;){let u=null,d=l;for(;i.lastIndex=d,u=i.exec(t),!(u==null||o.has(u[0]));)d=u.index+1;let f=u?.index??t.length;for(let h of t.substring(l,f).matchAll(n)){let g=this.textEncoder.encode(h[0]),b=this.rankMap.get(g.join(","));if(b!=null){s.push(b);continue}s.push(...sb(g,this.rankMap))}if(u==null)break;let y=this.specialTokens[u[0]];s.push(y),l=u.index+u[0].length}return s}decode(t){let e=[],r=0;for(let s=0;s<t.length;++s){let o=t[s],c=this.textMap.get(o)??this.inverseSpecialTokens[o];c!=null&&(e.push(c),r+=c.length)}let n=new Uint8Array(r),i=0;for(let s of e)n.set(s,i),i+=s.length;return this.textDecoder.decode(n)}},Xa=Ya;nb(Xa,"specialTokenRegex",t=>new RegExp(t.map(e=>ab(e)).join("|"),"g"));var nf=["tool_call","tool_call_chunk","invalid_tool_call","server_tool_call","server_tool_call_chunk","server_tool_call_result"];var sf=["image","video","audio","text-plain","file"];var lb=["text","reasoning",...nf,...sf];var yb=a(function(){let t={};t.parser=function(_,m){return new r(_,m)},t.SAXParser=r,t.SAXStream=u,t.createStream=l,t.MAX_BUFFER_LENGTH=65536;let e=["comment","sgmlDecl","textNode","tagName","doctype","procInstName","procInstBody","entity","attribName","attribValue","cdata","script"];t.EVENTS=["text","processinginstruction","sgmldeclaration","doctype","comment","opentagstart","attribute","opentag","closetag","opencdata","cdata","closecdata","error","end","ready","script","opennamespace","closenamespace"];function r(_,m){if(!(this instanceof r))return new r(_,m);var R=this;i(R),R.q=R.c="",R.bufferCheckPosition=t.MAX_BUFFER_LENGTH,R.opt=m||{},R.opt.lowercase=R.opt.lowercase||R.opt.lowercasetags,R.looseCase=R.opt.lowercase?"toLowerCase":"toUpperCase",R.tags=[],R.closed=R.closedRoot=R.sawRoot=!1,R.tag=R.error=null,R.strict=!!_,R.noscript=!!(_||R.opt.noscript),R.state=E.BEGIN,R.strictEntities=R.opt.strictEntities,R.ENTITIES=R.strictEntities?Object.create(t.XML_ENTITIES):Object.create(t.ENTITIES),R.attribList=[],R.opt.xmlns&&(R.ns=Object.create(g)),R.trackPosition=R.opt.position!==!1,R.trackPosition&&(R.position=R.line=R.column=0),D(R,"onready")}a(r,"SAXParser"),Object.create||(Object.create=function(_){function m(){}return a(m,"F"),m.prototype=_,new m}),Object.keys||(Object.keys=function(_){var m=[];for(var R in _)_.hasOwnProperty(R)&&m.push(R);return m});function n(_){for(var m=Math.max(t.MAX_BUFFER_LENGTH,10),R=0,x=0,J=e.length;x<J;x++){var le=_[e[x]].length;if(le>m)switch(e[x]){case"textNode":W(_);break;case"cdata":N(_,"oncdata",_.cdata),_.cdata="";break;case"script":N(_,"onscript",_.script),_.script="";break;default:Se(_,"Max buffer length exceeded: "+e[x])}R=Math.max(R,le)}_.bufferCheckPosition=t.MAX_BUFFER_LENGTH-R+_.position}a(n,"checkBufferLength");function i(_){for(var m=0,R=e.length;m<R;m++)_[e[m]]=""}a(i,"clearBuffers");function s(_){W(_),_.cdata!==""&&(N(_,"oncdata",_.cdata),_.cdata=""),_.script!==""&&(N(_,"onscript",_.script),_.script="")}a(s,"flushBuffers"),r.prototype={end:a(function(){nt(this)},"end"),write:im,resume:a(function(){return this.error=null,this},"resume"),close:a(function(){return this.write(null)},"close"),flush:a(function(){s(this)},"flush")};var o=ReadableStream;o||(o=a(function(){},"Stream"));var c=t.EVENTS.filter(function(_){return _!=="error"&&_!=="end"});function l(_,m){return new u(_,m)}a(l,"createStream");function u(_,m){if(!(this instanceof u))return new u(_,m);o.apply(this),this._parser=new r(_,m),this.writable=!0,this.readable=!0;var R=this;this._parser.onend=function(){R.emit("end")},this._parser.onerror=function(x){R.emit("error",x),R._parser.error=null},this._decoder=null,c.forEach(function(x){Object.defineProperty(R,"on"+x,{get:a(function(){return R._parser["on"+x]},"get"),set:a(function(J){if(!J)return R.removeAllListeners(x),R._parser["on"+x]=J,J;R.on(x,J)},"set"),enumerable:!0,configurable:!1})})}a(u,"SAXStream"),u.prototype=Object.create(o.prototype,{constructor:{value:u}}),u.prototype.write=function(_){return this._parser.write(_.toString()),this.emit("data",_),!0},u.prototype.end=function(_){return _&&_.length&&this.write(_),this._parser.end(),!0},u.prototype.on=function(_,m){var R=this;return!R._parser["on"+_]&&c.indexOf(_)!==-1&&(R._parser["on"+_]=function(){var x=arguments.length===1?[arguments[0]]:Array.apply(null,arguments);x.splice(0,0,_),R.emit.apply(R,x)}),o.prototype.on.call(R,_,m)};var d="[CDATA[",f="DOCTYPE",y="http://www.w3.org/XML/1998/namespace",h="http://www.w3.org/2000/xmlns/",g={xml:y,xmlns:h},b=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,w=/[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/,v=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/,S=/[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/;function p(_){return _===" "||_===`
150
+ `||_==="\r"||_===" "}a(p,"isWhitespace");function T(_){return _==='"'||_==="'"}a(T,"isQuote");function I(_){return _===">"||p(_)}a(I,"isAttribEnd");function C(_,m){return _.test(m)}a(C,"isMatch");function k(_,m){return!C(_,m)}a(k,"notMatch");var E=0;t.STATE={BEGIN:E++,BEGIN_WHITESPACE:E++,TEXT:E++,TEXT_ENTITY:E++,OPEN_WAKA:E++,SGML_DECL:E++,SGML_DECL_QUOTED:E++,DOCTYPE:E++,DOCTYPE_QUOTED:E++,DOCTYPE_DTD:E++,DOCTYPE_DTD_QUOTED:E++,COMMENT_STARTING:E++,COMMENT:E++,COMMENT_ENDING:E++,COMMENT_ENDED:E++,CDATA:E++,CDATA_ENDING:E++,CDATA_ENDING_2:E++,PROC_INST:E++,PROC_INST_BODY:E++,PROC_INST_ENDING:E++,OPEN_TAG:E++,OPEN_TAG_SLASH:E++,ATTRIB:E++,ATTRIB_NAME:E++,ATTRIB_NAME_SAW_WHITE:E++,ATTRIB_VALUE:E++,ATTRIB_VALUE_QUOTED:E++,ATTRIB_VALUE_CLOSED:E++,ATTRIB_VALUE_UNQUOTED:E++,ATTRIB_VALUE_ENTITY_Q:E++,ATTRIB_VALUE_ENTITY_U:E++,CLOSE_TAG:E++,CLOSE_TAG_SAW_WHITE:E++,SCRIPT:E++,SCRIPT_ENDING:E++},t.XML_ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'"},t.ENTITIES={amp:"&",gt:">",lt:"<",quot:'"',apos:"'",AElig:198,Aacute:193,Acirc:194,Agrave:192,Aring:197,Atilde:195,Auml:196,Ccedil:199,ETH:208,Eacute:201,Ecirc:202,Egrave:200,Euml:203,Iacute:205,Icirc:206,Igrave:204,Iuml:207,Ntilde:209,Oacute:211,Ocirc:212,Ograve:210,Oslash:216,Otilde:213,Ouml:214,THORN:222,Uacute:218,Ucirc:219,Ugrave:217,Uuml:220,Yacute:221,aacute:225,acirc:226,aelig:230,agrave:224,aring:229,atilde:227,auml:228,ccedil:231,eacute:233,ecirc:234,egrave:232,eth:240,euml:235,iacute:237,icirc:238,igrave:236,iuml:239,ntilde:241,oacute:243,ocirc:244,ograve:242,oslash:248,otilde:245,ouml:246,szlig:223,thorn:254,uacute:250,ucirc:251,ugrave:249,uuml:252,yacute:253,yuml:255,copy:169,reg:174,nbsp:160,iexcl:161,cent:162,pound:163,curren:164,yen:165,brvbar:166,sect:167,uml:168,ordf:170,laquo:171,not:172,shy:173,macr:175,deg:176,plusmn:177,sup1:185,sup2:178,sup3:179,acute:180,micro:181,para:182,middot:183,cedil:184,ordm:186,raquo:187,frac14:188,frac12:189,frac34:190,iquest:191,times:215,divide:247,OElig:338,oelig:339,Scaron:352,scaron:353,Yuml:376,fnof:402,circ:710,tilde:732,Alpha:913,Beta:914,Gamma:915,Delta:916,Epsilon:917,Zeta:918,Eta:919,Theta:920,Iota:921,Kappa:922,Lambda:923,Mu:924,Nu:925,Xi:926,Omicron:927,Pi:928,Rho:929,Sigma:931,Tau:932,Upsilon:933,Phi:934,Chi:935,Psi:936,Omega:937,alpha:945,beta:946,gamma:947,delta:948,epsilon:949,zeta:950,eta:951,theta:952,iota:953,kappa:954,lambda:955,mu:956,nu:957,xi:958,omicron:959,pi:960,rho:961,sigmaf:962,sigma:963,tau:964,upsilon:965,phi:966,chi:967,psi:968,omega:969,thetasym:977,upsih:978,piv:982,ensp:8194,emsp:8195,thinsp:8201,zwnj:8204,zwj:8205,lrm:8206,rlm:8207,ndash:8211,mdash:8212,lsquo:8216,rsquo:8217,sbquo:8218,ldquo:8220,rdquo:8221,bdquo:8222,dagger:8224,Dagger:8225,bull:8226,hellip:8230,permil:8240,prime:8242,Prime:8243,lsaquo:8249,rsaquo:8250,oline:8254,frasl:8260,euro:8364,image:8465,weierp:8472,real:8476,trade:8482,alefsym:8501,larr:8592,uarr:8593,rarr:8594,darr:8595,harr:8596,crarr:8629,lArr:8656,uArr:8657,rArr:8658,dArr:8659,hArr:8660,forall:8704,part:8706,exist:8707,empty:8709,nabla:8711,isin:8712,notin:8713,ni:8715,prod:8719,sum:8721,minus:8722,lowast:8727,radic:8730,prop:8733,infin:8734,ang:8736,and:8743,or:8744,cap:8745,cup:8746,int:8747,there4:8756,sim:8764,cong:8773,asymp:8776,ne:8800,equiv:8801,le:8804,ge:8805,sub:8834,sup:8835,nsub:8836,sube:8838,supe:8839,oplus:8853,otimes:8855,perp:8869,sdot:8901,lceil:8968,rceil:8969,lfloor:8970,rfloor:8971,lang:9001,rang:9002,loz:9674,spades:9824,clubs:9827,hearts:9829,diams:9830},Object.keys(t.ENTITIES).forEach(function(_){var m=t.ENTITIES[_],R=typeof m=="number"?String.fromCharCode(m):m;t.ENTITIES[_]=R});for(var U in t.STATE)t.STATE[t.STATE[U]]=U;E=t.STATE;function D(_,m,R){_[m]&&_[m](R)}a(D,"emit");function N(_,m,R){_.textNode&&W(_),D(_,m,R)}a(N,"emitNode");function W(_){_.textNode=te(_.opt,_.textNode),_.textNode&&D(_,"ontext",_.textNode),_.textNode=""}a(W,"closeText");function te(_,m){return _.trim&&(m=m.trim()),_.normalize&&(m=m.replace(/\s+/g," ")),m}a(te,"textopts");function Se(_,m){return W(_),_.trackPosition&&(m+=`
151
+ Line: `+_.line+`
152
+ Column: `+_.column+`
153
+ Char: `+_.c),m=new Error(m),_.error=m,D(_,"onerror",m),_}a(Se,"error");function nt(_){return _.sawRoot&&!_.closedRoot&&q(_,"Unclosed root tag"),_.state!==E.BEGIN&&_.state!==E.BEGIN_WHITESPACE&&_.state!==E.TEXT&&Se(_,"Unexpected end"),W(_),_.c="",_.closed=!0,D(_,"onend"),r.call(_,_.strict,_.opt),_}a(nt,"end");function q(_,m){if(typeof _!="object"||!(_ instanceof r))throw new Error("bad call to strictFail");_.strict&&Se(_,m)}a(q,"strictFail");function nm(_){_.strict||(_.tagName=_.tagName[_.looseCase]());var m=_.tags[_.tags.length-1]||_,R=_.tag={name:_.tagName,attributes:{}};_.opt.xmlns&&(R.ns=m.ns),_.attribList.length=0,N(_,"onopentagstart",R)}a(nm,"newTag");function is(_,m){var R=_.indexOf(":")<0?["",_]:_.split(":"),x=R[0],J=R[1];return m&&_==="xmlns"&&(x="xmlns",J=""),{prefix:x,local:J}}a(is,"qname");function ss(_){if(_.strict||(_.attribName=_.attribName[_.looseCase]()),_.attribList.indexOf(_.attribName)!==-1||_.tag.attributes.hasOwnProperty(_.attribName)){_.attribName=_.attribValue="";return}if(_.opt.xmlns){var m=is(_.attribName,!0),R=m.prefix,x=m.local;if(R==="xmlns")if(x==="xml"&&_.attribValue!==y)q(_,"xml: prefix must be bound to "+y+`
154
+ Actual: `+_.attribValue);else if(x==="xmlns"&&_.attribValue!==h)q(_,"xmlns: prefix must be bound to "+h+`
155
+ Actual: `+_.attribValue);else{var J=_.tag,le=_.tags[_.tags.length-1]||_;J.ns===le.ns&&(J.ns=Object.create(le.ns)),J.ns[x]=_.attribValue}_.attribList.push([_.attribName,_.attribValue])}else _.tag.attributes[_.attribName]=_.attribValue,N(_,"onattribute",{name:_.attribName,value:_.attribValue});_.attribName=_.attribValue=""}a(ss,"attrib");function Ut(_,m){if(_.opt.xmlns){var R=_.tag,x=is(_.tagName);R.prefix=x.prefix,R.local=x.local,R.uri=R.ns[x.prefix]||"",R.prefix&&!R.uri&&(q(_,"Unbound namespace prefix: "+JSON.stringify(_.tagName)),R.uri=x.prefix);var J=_.tags[_.tags.length-1]||_;R.ns&&J.ns!==R.ns&&Object.keys(R.ns).forEach(function(jo){N(_,"onopennamespace",{prefix:jo,uri:R.ns[jo]})});for(var le=0,je=_.attribList.length;le<je;le++){var Oe=_.attribList[le],Ze=Oe[0],$t=Oe[1],xe=is(Ze,!0),Ft=xe.prefix,sm=xe.local,Bo=Ft===""?"":R.ns[Ft]||"",os={name:Ze,value:$t,prefix:Ft,local:sm,uri:Bo};Ft&&Ft!=="xmlns"&&!Bo&&(q(_,"Unbound namespace prefix: "+JSON.stringify(Ft)),os.uri=Ft),_.tag.attributes[Ze]=os,N(_,"onattribute",os)}_.attribList.length=0}_.tag.isSelfClosing=!!m,_.sawRoot=!0,_.tags.push(_.tag),N(_,"onopentag",_.tag),m||(!_.noscript&&_.tagName.toLowerCase()==="script"?_.state=E.SCRIPT:_.state=E.TEXT,_.tag=null,_.tagName=""),_.attribName=_.attribValue="",_.attribList.length=0}a(Ut,"openTag");function as(_){if(!_.tagName){q(_,"Weird empty close tag."),_.textNode+="</>",_.state=E.TEXT;return}if(_.script){if(_.tagName!=="script"){_.script+="</"+_.tagName+">",_.tagName="",_.state=E.SCRIPT;return}N(_,"onscript",_.script),_.script=""}var m=_.tags.length,R=_.tagName;_.strict||(R=R[_.looseCase]());for(var x=R;m--&&_.tags[m].name!==x;)q(_,"Unexpected close tag");if(m<0){q(_,"Unmatched closing tag: "+_.tagName),_.textNode+="</"+_.tagName+">",_.state=E.TEXT;return}_.tagName=R;for(var J=_.tags.length;J-- >m;){var le=_.tag=_.tags.pop();_.tagName=_.tag.name,N(_,"onclosetag",_.tagName);var je={};for(var Oe in le.ns)je[Oe]=le.ns[Oe];var Ze=_.tags[_.tags.length-1]||_;_.opt.xmlns&&le.ns!==Ze.ns&&Object.keys(le.ns).forEach(function($t){var xe=le.ns[$t];N(_,"onclosenamespace",{prefix:$t,uri:xe})})}m===0&&(_.closedRoot=!0),_.tagName=_.attribValue=_.attribName="",_.attribList.length=0,_.state=E.TEXT}a(as,"closeTag");function Uo(_){var m=_.entity,R=m.toLowerCase(),x,J="";return _.ENTITIES[m]?_.ENTITIES[m]:_.ENTITIES[R]?_.ENTITIES[R]:(m=R,m.charAt(0)==="#"&&(m.charAt(1)==="x"?(m=m.slice(2),x=parseInt(m,16),J=x.toString(16)):(m=m.slice(1),x=parseInt(m,10),J=x.toString(10))),m=m.replace(/^0+/,""),isNaN(x)||J.toLowerCase()!==m?(q(_,"Invalid character entity"),"&"+_.entity+";"):String.fromCodePoint(x))}a(Uo,"parseEntity");function $o(_,m){m==="<"?(_.state=E.OPEN_WAKA,_.startTagPosition=_.position):p(m)||(q(_,"Non-whitespace before first tag."),_.textNode=m,_.state=E.TEXT)}a($o,"beginWhiteSpace");function Fo(_,m){var R="";return m<_.length&&(R=_.charAt(m)),R}a(Fo,"charAt");function im(_){var m=this;if(this.error)throw this.error;if(m.closed)return Se(m,"Cannot write after close. Assign an onready handler.");if(_===null)return nt(m);typeof _=="object"&&(_=_.toString());for(var R=0,x="";x=Fo(_,R++),m.c=x,!!x;)switch(m.trackPosition&&(m.position++,x===`
156
+ `?(m.line++,m.column=0):m.column++),m.state){case E.BEGIN:if(m.state=E.BEGIN_WHITESPACE,x==="\uFEFF")continue;$o(m,x);continue;case E.BEGIN_WHITESPACE:$o(m,x);continue;case E.TEXT:if(m.sawRoot&&!m.closedRoot){for(var J=R-1;x&&x!=="<"&&x!=="&";)x=Fo(_,R++),x&&m.trackPosition&&(m.position++,x===`
157
+ `?(m.line++,m.column=0):m.column++);m.textNode+=_.substring(J,R-1)}x==="<"&&!(m.sawRoot&&m.closedRoot&&!m.strict)?(m.state=E.OPEN_WAKA,m.startTagPosition=m.position):(!p(x)&&(!m.sawRoot||m.closedRoot)&&q(m,"Text data outside of root node."),x==="&"?m.state=E.TEXT_ENTITY:m.textNode+=x);continue;case E.SCRIPT:x==="<"?m.state=E.SCRIPT_ENDING:m.script+=x;continue;case E.SCRIPT_ENDING:x==="/"?m.state=E.CLOSE_TAG:(m.script+="<"+x,m.state=E.SCRIPT);continue;case E.OPEN_WAKA:if(x==="!")m.state=E.SGML_DECL,m.sgmlDecl="";else if(!p(x))if(C(b,x))m.state=E.OPEN_TAG,m.tagName=x;else if(x==="/")m.state=E.CLOSE_TAG,m.tagName="";else if(x==="?")m.state=E.PROC_INST,m.procInstName=m.procInstBody="";else{if(q(m,"Unencoded <"),m.startTagPosition+1<m.position){var le=m.position-m.startTagPosition;x=new Array(le).join(" ")+x}m.textNode+="<"+x,m.state=E.TEXT}continue;case E.SGML_DECL:(m.sgmlDecl+x).toUpperCase()===d?(N(m,"onopencdata"),m.state=E.CDATA,m.sgmlDecl="",m.cdata=""):m.sgmlDecl+x==="--"?(m.state=E.COMMENT,m.comment="",m.sgmlDecl=""):(m.sgmlDecl+x).toUpperCase()===f?(m.state=E.DOCTYPE,(m.doctype||m.sawRoot)&&q(m,"Inappropriately located doctype declaration"),m.doctype="",m.sgmlDecl=""):x===">"?(N(m,"onsgmldeclaration",m.sgmlDecl),m.sgmlDecl="",m.state=E.TEXT):(T(x)&&(m.state=E.SGML_DECL_QUOTED),m.sgmlDecl+=x);continue;case E.SGML_DECL_QUOTED:x===m.q&&(m.state=E.SGML_DECL,m.q=""),m.sgmlDecl+=x;continue;case E.DOCTYPE:x===">"?(m.state=E.TEXT,N(m,"ondoctype",m.doctype),m.doctype=!0):(m.doctype+=x,x==="["?m.state=E.DOCTYPE_DTD:T(x)&&(m.state=E.DOCTYPE_QUOTED,m.q=x));continue;case E.DOCTYPE_QUOTED:m.doctype+=x,x===m.q&&(m.q="",m.state=E.DOCTYPE);continue;case E.DOCTYPE_DTD:m.doctype+=x,x==="]"?m.state=E.DOCTYPE:T(x)&&(m.state=E.DOCTYPE_DTD_QUOTED,m.q=x);continue;case E.DOCTYPE_DTD_QUOTED:m.doctype+=x,x===m.q&&(m.state=E.DOCTYPE_DTD,m.q="");continue;case E.COMMENT:x==="-"?m.state=E.COMMENT_ENDING:m.comment+=x;continue;case E.COMMENT_ENDING:x==="-"?(m.state=E.COMMENT_ENDED,m.comment=te(m.opt,m.comment),m.comment&&N(m,"oncomment",m.comment),m.comment=""):(m.comment+="-"+x,m.state=E.COMMENT);continue;case E.COMMENT_ENDED:x!==">"?(q(m,"Malformed comment"),m.comment+="--"+x,m.state=E.COMMENT):m.state=E.TEXT;continue;case E.CDATA:x==="]"?m.state=E.CDATA_ENDING:m.cdata+=x;continue;case E.CDATA_ENDING:x==="]"?m.state=E.CDATA_ENDING_2:(m.cdata+="]"+x,m.state=E.CDATA);continue;case E.CDATA_ENDING_2:x===">"?(m.cdata&&N(m,"oncdata",m.cdata),N(m,"onclosecdata"),m.cdata="",m.state=E.TEXT):x==="]"?m.cdata+="]":(m.cdata+="]]"+x,m.state=E.CDATA);continue;case E.PROC_INST:x==="?"?m.state=E.PROC_INST_ENDING:p(x)?m.state=E.PROC_INST_BODY:m.procInstName+=x;continue;case E.PROC_INST_BODY:if(!m.procInstBody&&p(x))continue;x==="?"?m.state=E.PROC_INST_ENDING:m.procInstBody+=x;continue;case E.PROC_INST_ENDING:x===">"?(N(m,"onprocessinginstruction",{name:m.procInstName,body:m.procInstBody}),m.procInstName=m.procInstBody="",m.state=E.TEXT):(m.procInstBody+="?"+x,m.state=E.PROC_INST_BODY);continue;case E.OPEN_TAG:C(w,x)?m.tagName+=x:(nm(m),x===">"?Ut(m):x==="/"?m.state=E.OPEN_TAG_SLASH:(p(x)||q(m,"Invalid character in tag name"),m.state=E.ATTRIB));continue;case E.OPEN_TAG_SLASH:x===">"?(Ut(m,!0),as(m)):(q(m,"Forward-slash in opening tag not followed by >"),m.state=E.ATTRIB);continue;case E.ATTRIB:if(p(x))continue;x===">"?Ut(m):x==="/"?m.state=E.OPEN_TAG_SLASH:C(b,x)?(m.attribName=x,m.attribValue="",m.state=E.ATTRIB_NAME):q(m,"Invalid attribute name");continue;case E.ATTRIB_NAME:x==="="?m.state=E.ATTRIB_VALUE:x===">"?(q(m,"Attribute without value"),m.attribValue=m.attribName,ss(m),Ut(m)):p(x)?m.state=E.ATTRIB_NAME_SAW_WHITE:C(w,x)?m.attribName+=x:q(m,"Invalid attribute name");continue;case E.ATTRIB_NAME_SAW_WHITE:if(x==="=")m.state=E.ATTRIB_VALUE;else{if(p(x))continue;q(m,"Attribute without value"),m.tag.attributes[m.attribName]="",m.attribValue="",N(m,"onattribute",{name:m.attribName,value:""}),m.attribName="",x===">"?Ut(m):C(b,x)?(m.attribName=x,m.state=E.ATTRIB_NAME):(q(m,"Invalid attribute name"),m.state=E.ATTRIB)}continue;case E.ATTRIB_VALUE:if(p(x))continue;T(x)?(m.q=x,m.state=E.ATTRIB_VALUE_QUOTED):(q(m,"Unquoted attribute value"),m.state=E.ATTRIB_VALUE_UNQUOTED,m.attribValue=x);continue;case E.ATTRIB_VALUE_QUOTED:if(x!==m.q){x==="&"?m.state=E.ATTRIB_VALUE_ENTITY_Q:m.attribValue+=x;continue}ss(m),m.q="",m.state=E.ATTRIB_VALUE_CLOSED;continue;case E.ATTRIB_VALUE_CLOSED:p(x)?m.state=E.ATTRIB:x===">"?Ut(m):x==="/"?m.state=E.OPEN_TAG_SLASH:C(b,x)?(q(m,"No whitespace between attributes"),m.attribName=x,m.attribValue="",m.state=E.ATTRIB_NAME):q(m,"Invalid attribute name");continue;case E.ATTRIB_VALUE_UNQUOTED:if(!I(x)){x==="&"?m.state=E.ATTRIB_VALUE_ENTITY_U:m.attribValue+=x;continue}ss(m),x===">"?Ut(m):m.state=E.ATTRIB;continue;case E.CLOSE_TAG:if(m.tagName)x===">"?as(m):C(w,x)?m.tagName+=x:m.script?(m.script+="</"+m.tagName,m.tagName="",m.state=E.SCRIPT):(p(x)||q(m,"Invalid tagname in closing tag"),m.state=E.CLOSE_TAG_SAW_WHITE);else{if(p(x))continue;k(b,x)?m.script?(m.script+="</"+x,m.state=E.SCRIPT):q(m,"Invalid tagname in closing tag."):m.tagName=x}continue;case E.CLOSE_TAG_SAW_WHITE:if(p(x))continue;x===">"?as(m):q(m,"Invalid characters in closing tag");continue;case E.TEXT_ENTITY:case E.ATTRIB_VALUE_ENTITY_Q:case E.ATTRIB_VALUE_ENTITY_U:var je,Oe;switch(m.state){case E.TEXT_ENTITY:je=E.TEXT,Oe="textNode";break;case E.ATTRIB_VALUE_ENTITY_Q:je=E.ATTRIB_VALUE_QUOTED,Oe="attribValue";break;case E.ATTRIB_VALUE_ENTITY_U:je=E.ATTRIB_VALUE_UNQUOTED,Oe="attribValue";break}if(x===";")if(m.opt.unparsedEntities){var Ze=Uo(m);m.entity="",m.state=je,m.write(Ze)}else m[Oe]+=Uo(m),m.entity="",m.state=je;else C(m.entity.length?S:v,x)?m.entity+=x:(q(m,"Invalid character in entity name"),m[Oe]+="&"+m.entity+x,m.entity="",m.state=je);continue;default:throw new Error(m,"Unknown state: "+m.state)}return m.position>=m.bufferCheckPosition&&n(m),m}a(im,"write");return String.fromCodePoint||(function(){var _=String.fromCharCode,m=Math.floor,R=a(function(){var x=16384,J=[],le,je,Oe=-1,Ze=arguments.length;if(!Ze)return"";for(var $t="";++Oe<Ze;){var xe=Number(arguments[Oe]);if(!isFinite(xe)||xe<0||xe>1114111||m(xe)!==xe)throw RangeError("Invalid code point: "+xe);xe<=65535?J.push(xe):(xe-=65536,le=(xe>>10)+55296,je=xe%1024+56320,J.push(le,je)),(Oe+1===Ze||J.length>x)&&($t+=_.apply(null,J),J.length=0)}return $t},"fromCodePoint");Object.defineProperty?Object.defineProperty(String,"fromCodePoint",{value:R,configurable:!0,writable:!0}):String.fromCodePoint=R})(),t},"initializeSax"),_b=yb();var l3=require("@playwright/test");var Q6={openai_gpt_4_1:{model:"gpt-4.1-2025-04-14",type:"openai"},openai_gpt_4_1_mini:{model:"gpt-4.1-mini-2025-04-14",type:"openai"},openai_gpt_4_1_nano:{model:"gpt-4.1-nano-2025-04-14",type:"openai"},gemini_2_0_flash:{model:"gemini-2.0-flash",type:"gemini"},gemini_2_5_pro_exp:{model:"gemini-2.5-pro-exp-03-25",type:"gemini"},gemini_2_5_flash:{model:"gemini-2.5-flash",type:"gemini"},gemini_2_5_pro_preview_05_06:{model:"gemini-2.5-pro-preview-05-06",type:"gemini"},claude_sonnet_4:{model:"claude-sonnet-4@20250514",type:"anthropic-vertexai"},claude_sonnet_4_6:{model:"claude-sonnet-4-6",type:"anthropic-vertexai"},claude_sonnet_5:{model:"claude-sonnet-5",type:"anthropic-vertexai"},claude_opus_4_8:{model:"claude-opus-4-8",type:"anthropic-vertexai"},gemini_2_5_flash_lite:{model:"gemini-2.5-flash-lite",type:"gemini"},gemini_3_5_flash:{model:"gemini-3.5-flash",type:"gemini"},gemini_3_1_flash_lite:{model:"gemini-3.1-flash-lite",type:"gemini"}};var yf=He(io());yf.default.config({path:[`${__dirname}/.env`,`${__dirname}/../../.env`]});var Fb="claude_4",Bb={gemini20flash:{name:"google-vertexai/gemini-2.0-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt41:{name:"openai/gpt-4.1",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25flash:{name:"google-vertexai/gemini-2.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:.7},gemini25flash_lite:{name:"google-vertexai/gemini-2.5-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0},gpt4onano:{name:"openai/gpt-4o-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41nano:{name:"openai/gpt-4.1-nano",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt41mini:{name:"openai/gpt-4.1-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o3mini:{name:"openai/o3-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},o4mini:{name:"openai/o4-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gemini25pro:{name:"google-vertexai/gemini-2.5-pro-preview-05-06",inputTokenLimit:8e5,provider:"gemini",temperature:0},claude37sonnet:{name:"google-vertexai/claude-3-7-sonnet@20250219",inputTokenLimit:15e4,provider:"anthropic",temperature:0},claude4sonnet:{name:"google-vertexai/claude-sonnet-4@20250514",inputTokenLimit:15e4,provider:"anthropic",temperature:1},claudeSonnet46:{name:"google-vertexai/claude-sonnet-4-6",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeSonnet5:{name:"google-vertexai/claude-sonnet-5",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},claudeOpus48:{name:"google-vertexai/claude-opus-4-8",inputTokenLimit:15e4,provider:"anthropic",temperature:1,location:"global"},gemini35flash:{name:"google-vertexai/gemini-3.5-flash",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gemini31flashLite:{name:"google-vertexai/gemini-3.1-flash-lite",inputTokenLimit:8e5,provider:"gemini",temperature:0,location:"global"},gpt4omini:{name:"openai/gpt-4o-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5mini:{name:"openai/gpt-5-mini",inputTokenLimit:8e5,provider:"openai",temperature:0},gpt5nano:{name:"openai/gpt-5-nano",inputTokenLimit:8e5,provider:"openai",temperature:0}},jb=a(()=>({nodeEnv:process.env.NODE_ENV??"production",selectedModel:{name:Fb},models:Bb,langsmith:{enabled:process.env.LANGSMITH_TRACING==="true",endpoint:process.env.LANGSMITH_ENDPOINT??"",apiKey:process.env.LANGSMITH_API_KEY??"",project:process.env.LANGSMITH_PROJECT??""}}),"make"),ue=jb();var a3={claude_4:ue.models.claude4sonnet,"claude_3.7":ue.models.claude37sonnet,claude_sonnet_4_6:ue.models.claudeSonnet46,claude_sonnet_5:ue.models.claudeSonnet5,claude_opus_4_8:ue.models.claudeOpus48,"gemini_2.5_pro":ue.models.gemini25pro,"gemini_2.0_flash":ue.models.gemini20flash,"gemini_2.5_flash_lite":ue.models.gemini25flash_lite,"gemini_2.5_flash":ue.models.gemini25flash,"gemini_3.5_flash":ue.models.gemini35flash,"gemini_3.1_flash_lite":ue.models.gemini31flashLite,gpt_4o_mini:ue.models.gpt4omini,gpt_4o_nano:ue.models.gpt4onano,gpt_41_nano:ue.models.gpt41nano,gpt_5_mini:ue.models.gpt5mini,gpt_5_nano:ue.models.gpt5nano,gpt_41_mini:ue.models.gpt41mini,gpt_41:ue.models.gpt41,o4_mini:ue.models.o4mini,o3_mini:ue.models.o3mini};var Zp=require("child_process"),In=require("crypto"),ce=require("fs"),Yp=require("fs/promises"),Xp=require("stream/promises"),Qp=require("http"),em=He(require("net")),tm=require("os"),Be=require("path");function Hb(t){if(t)return{...t,...t.tests?{tests:t.tests.map(e=>{let{errorMessage:r,...n}=e;return n})}:{}}}a(Hb,"projectReportStatsForTelemetry");function _f(t,e,r){t.emit({outcome:e,stats:Hb(r)})}a(_f,"emitReportProcessingStatsTelemetry");var bf=["script","template"],wf='<script id="playwrightReportBase64" type="application/zip">',Ef="</script>";var Tp=require("htmlparser2"),vp=He(ep()),be=require("node:fs"),pr=require("node:path"),Sp=require("node:os"),xp=require("node:crypto");var vt=He(require("path")),po=require("fs");var uo=require("path"),ji=require("fs");function cw(t,e,r=10){let n=t;for(let i=0;i<r;i++){let s=(0,uo.join)(n,"package.json");if((0,ji.existsSync)(s))try{if(JSON.parse((0,ji.readFileSync)(s,"utf8")).name===e)return n}catch{}n=(0,uo.join)(n,"..")}}a(cw,"findRepositoryRoot");function tp(t,e=10){return cw(t,"checksum-customer-engineering-workspace",e)}a(tp,"findCustomerEngineeringRoot");var mo=He(io());var Le=a((t,e)=>{if(t==null||t==="")return e?.default??!1;let r=t.toLowerCase().trim();return r==="true"?!0:r==="false"?!1:e?.default??!1},"parseBoolean");function rp(t){if(t===void 0||t.trim()==="")return 5e7;let e=Number(t);return!Number.isInteger(e)||e<0?5e7:e}a(rp,"resolveMaxRRwebBytes");var lw=__dirname,np=vt.join(__dirname,".."),sp=(0,po.existsSync)(np)?np:lw;(0,mo.config)({path:vt.resolve(sp,".env")});var ip=Le(process.env.CHECKSUM_RUNTIME_DEV_MODE);function uw(){let t=__dirname;for(;!(0,po.existsSync)(vt.join(t,"package.json"));)t=vt.join(t,"..");return t}a(uw,"findRoot");var vn=uw(),dw=tp(vn,10);(0,mo.config)({path:[sp,dw].filter(t=>!!t).map(t=>vt.resolve(t,".env")),override:!1});var fo=Le(process.env.CHECKSUM_RUNTIME_REPO_MODE),fw=fo?vt.join(vn,"package","pw-report-template.html"):vt.join(vn,"pw-report-template.html"),pw=Le(process.env.CHECKSUM_DEBUG_ANALYTICS),mw=Le(process.env.CHECKSUM_LOG_ANALYTICS_TO_CONSOLE),hw=rp(process.env.CHECKSUM_RUNTIME_RRWEB_MAX_BYTES),Hi={isDevMode:ip,isRepoMode:fo,CI:!!process.env.CI,checksumRootFolderBypass:fo&&process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE?process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS_FOR_REPO_MODE:process.env.CHECKSUM_RUNTIME_ROOT_FOLDER_BYPASS,logLevel:process.env.CHECKSUM_RUNTIME_LOG_LEVEL??"warnings",checksumScript:{source:process.env.CHECKSUM_RUNTIME_SCRIPT_SOURCE??(ip?"url":"file"),url:process.env.CHECKSUM_RUNTIME_SCRIPT_URL,path:vn+"/checksumlib.js"},runtimeRoot:vn,playwrightReporter:{htmlReportTemplatePath:fw},bypassProxyForLocalhost:Le(process.env.CHECKSUM_RUNTIME_BYPASS_PROXY_FOR_LOCALHOST),useCLIDebug:Le(process.env.CHECKSUM_RUNTIME_USE_CLI_DEBUG),useRemoteDebugging:{enabled:Le(process.env.CHECKSUM_RUNTIME_USE_REMOTE_DEBUGGING),port:parseInt(process.env.CHECKSUM_AGENT_RUNTIME_REMOTE_DEBUGGING_PORT??"9500")},testRun:{timeMachine:{active:!0,headless:!Le(process.env.CHECKSUM_RUNTIME_SHOW_RUNTIME_TIME_MACHINE),recordRRwebEventsToFile:Le(process.env.CHECKSUM_RUNTIME_RECORD_RRWEB_EVENTS_TO_FILE,{default:!0}),maxRRwebBytes:hw},monitoring:{debugAnalytics:pw,logToConsole:mw,segment:{writeKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_WRITE_KEY??"TMuP8uorDj4QzJfNs0gEHDO7kHozVBOo",devWriteKey:process.env.CHECKSUM_RUNTIME_MONITORING_SEGMENT_DEV_WRITE_KEY??"gofHHwvdNHJNmb7KqACUmypZclVHEQ2l"}},autoRecovery:{verboseConsoleLog:Le(process.env.CHECKSUM_RUNTIME_AUTO_RECOVERY_CONSOLE_LOG,{default:!1}),sessionTimeout:18e4},disableAutoRecovery:Le(process.env.CHECKSUM_RUNTIME_DISABLE_AUTO_RECOVERY),disableHostReports:Le(process.env.CHECKSUM_RUNTIME_DISABLE_HOST_REPORTS),disableTimeMachine:Le(process.env.CHECKSUM_RUNTIME_DISABLE_TIME_MACHINE),disableRrwebRecording:Le(process.env.CHECKSUM_RUNTIME_DISABLE_RRWEB_RECORDING),request:{userEmail:process.env.CHECKSUM_RUNTIME_REQUEST_USER_EMAIL,reason:process.env.CHECKSUM_RUNTIME_REQUEST_REASON},platform:{name:process.env.CHECKSUM_RUNTIME_PLATFORM_NAME,jobURL:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_URL,jobName:process.env.CHECKSUM_RUNTIME_PLATFORM_JOB_NAME},runType:process.env.CHECKSUM_RUNTIME_RUN_TYPE},buildTime:process.env.CHECKSUM_RUNTIME_BUILD_TIME??"unknown"};var M5=require("@playwright/test/reporter");var Wr=require("path");var ho=a((t,e,r)=>`v2:${gw(t)}::${JSON.stringify([...e,r])}`,"computeVariantKey"),gw=a(t=>(t??"").replace(/\\/g,"/"),"normalizeFilePath");var zi=require("fs"),he=He(require("typescript"));var yw=/^[0-9a-zA-Z]+$/,_w=5;function ap(t){return t?t.length===_w&&yw.test(t):!1}a(ap,"isValidChecksumTestId");var go=class{static{a(this,"FileNameExtractionStrategy")}extract(e,r){if(!e)return;let n=e.split("/"),i=n[n.length-1];if(!i||!i.endsWith(".checksum.spec.ts"))return;let o=i.replace(".checksum.spec.ts","").split(" - ").pop();return ap(o)?o:void 0}},yo=class{static{a(this,"FileContentExtractionStrategy")}extract(e,r){if(!(!e||!(0,zi.existsSync)(e)))try{let n=(0,zi.readFileSync)(e,"utf-8"),i=he.createSourceFile(e,n,he.ScriptTarget.Latest,!0),s=new Map,o=a(c=>{if(he.isCallExpression(c)&&this.isTestCall(c.expression)){let l=c.arguments[0];if(l&&he.isCallExpression(l)&&he.isIdentifier(l.expression)&&l.expression.text==="defineChecksumTest"){let u=this.extractDefineChecksumTestArgs(l);u&&ap(u.checksumTestId)&&s.set(u.testTitle,u.checksumTestId)}}he.forEachChild(c,o)},"visit");return o(i),r&&s.has(r)?s.get(r):s.size>0?Array.from(s.values())[0]:void 0}catch{return}}isTestCall(e){return he.isIdentifier(e)&&e.text==="test"?!0:he.isPropertyAccessExpression(e)?he.isIdentifier(e.expression)&&e.expression.text==="test":!1}extractDefineChecksumTestArgs(e){let r=e.arguments;if(r.length<2)return;let n=r[0],i=r[1];if(!n||!i)return;let s=this.extractStringLiteral(n),o=this.extractStringLiteral(i);if(s&&o)return{testTitle:s,checksumTestId:o}}extractStringLiteral(e){if(he.isStringLiteral(e)||he.isNoSubstitutionTemplateLiteral(e))return e.text}},_o=class{static{a(this,"ChecksumTestIdExtractor")}constructor(e){this.strategies=e??[new yo,new go]}extract(e,r){for(let n of this.strategies){let i=n.extract(e,r);if(i)return i}}};var op=new _o;var Gi=a((t,e)=>typeof t=="string"?t:(console.warn(`[checksum] Test title in ${e??"<unknown file>"} is not a string (got ${typeof t}) \u2014 coercing. The title must be test()'s FIRST argument, e.g. test(defineChecksumTest("Title", "ID"), { tag: ["@bug"] }, fn); spreading it into the options object turns the title into an object and breaks tags/annotations for this test.`),JSON.stringify(t)),"coerceTestTitle");function Vi(t,e){return e.pwTestIdToChecksumTestId[t.playwrightTestId]||(t.filePath!==void 0?op.extract(t.filePath,t.title):void 0)}a(Vi,"resolveChecksumTestId");var wo=a((t,e)=>Object.values(e[t]??{}).some(r=>r.autoRecoveryMetadata?.data?.autoRecovered),"isAutoRecovered"),bo=a(t=>typeof t=="number"&&!isNaN(t)?t:0,"getStat");function Eo(t,e,r){let n=[],i=0,s=0,o=bo(e.expected)+bo(e.flaky),c=bo(e.unexpected);for(let l of t){let u=bw(l,r);n.push(u),u.recovered&&s++,u.bug&&(i++,u.outcome==="expected"||u.outcome==="flaky"?o--:u.outcome==="unexpected"&&c--)}return{passed:o,failed:c,bug:i,recovered:s,tests:n}}a(Eo,"computeReportStats");function bw(t,e){let r=Vi({playwrightTestId:t.playwrightTestId,filePath:t.filePath,title:t.title},e),n=ww(t),i=Ew(t.annotations),s=wo(t.playwrightTestId,e.playwrightIdToMetadata),o=Tw(r,t,e),c=e.toRelativeFilePath(t.filePath);return{checksumTestId:r,playwrightTestId:t.playwrightTestId,success:t.ok,recovered:s,bug:n,annotations:i,tags:t.tags,outcome:t.outcome,variantKey:ho(t.filePath,t.titlePath,t.title),...t.filePath!==void 0?{filePath:t.filePath}:{},...c!==void 0?{relativeFilePath:c}:{},...t.projectName?{project:t.projectName}:{},...t.errorMessage?{errorMessage:t.errorMessage}:{},...o!==void 0?{usingChecksumTestIdPlaceholder:o}:{}}}a(bw,"rowToTestWithMetadata");function cp(t,e){let r=t.files,n=a(c=>{let u=Vi({playwrightTestId:c.testId,filePath:c.location.file,title:c.title},e)??`${c.location.file}::${c.title}`,d=ho(c.location.file,c.path??[],c.title);return`${u}::${c.projectName}::${d}`},"keyFor"),i=new Map;for(let c of r)for(let l of c.tests)i.set(n(l),l);let s=new Set(i.values()),o={total:0,expected:0,unexpected:0,flaky:0,skipped:0};for(let c of r){c.tests=c.tests.filter(l=>s.has(l));for(let l of c.tests)o.total++,l.outcome==="expected"?o.expected++:l.outcome==="unexpected"?o.unexpected++:l.outcome==="flaky"?o.flaky++:o.skipped++}t.files=r.filter(c=>c.tests.length>0),t.stats={...t.stats,...o}}a(cp,"dedupeReportByChecksumTestId");var ww=a(t=>t.tags.includes("bug")||t.annotations.some(e=>e.type==="bug")||t.title.includes("@bug"),"detectBug"),Ew=a(t=>t.filter(e=>!!e?.type).map(e=>({type:e.type,description:e.description||""})),"normalizeAnnotations"),Tw=a((t,e,r)=>{if(r.checksumTestIdToUsingPlaceholder)return r.pwTestIdToChecksumTestId[e.playwrightTestId]&&r.checksumTestIdToUsingPlaceholder[t]||!1},"computeUsingPlaceholder");var lp=a((t,e,r)=>{if(!t)return;let n=r||e,i;if((0,Wr.isAbsolute)(t))i=t;else{let s=(0,Wr.dirname)(e);i=(0,Wr.resolve)(s,t)}return i.replace(n+"/","")},"toRelativeFilePath");var up=require("node:util");var qr=8*1024,Sn=`
158
+ \u2026 [truncated]`,vw=/[\u001b\u0080-\u009f]/g;function To(t){let e=t.replaceAll("\0","");return Sw((0,up.stripVTControlCharacters)(e))}a(To,"sanitizeTestErrorMessage");function Sw(t){return t.replace(vw,"")}a(Sw,"removeResidualVTControls");function Wi(t){let e=To(t);if(Buffer.byteLength(e,"utf8")<=qr)return{value:e,truncated:!1};let r=qr-Buffer.byteLength(Sn,"utf8"),n="",i=0;for(let s of e){let o=Buffer.byteLength(s,"utf8");if(i+o>r)break;n+=s,i+=o}return{value:n+Sn,truncated:!0}}a(Wi,"boundTestErrorMessage");var fp=require("node:crypto");var xw=new Set(["failed","timedOut","interrupted"]),vo=new WeakMap;function pp(){let t={messages:new Map,ambiguousKeys:new Set,truncatedCount:0,identityConflictCount:0};return vo.set(t,new Map),t}a(pp,"createErrorDetailIndex");function mp(t,e){try{let r=Iw(t);if(!r||Aw(r.tests))return!1;for(let n of r.tests){if(!Kr(n))continue;let i=bp(n.projectName),s=n.testId;if(i===void 0||!qi(s))continue;let o=Cw(n);if(!o)continue;let c=Ow(o);c.truncated&&(e.truncatedCount+=1),Pw(e,_p(r.fileId,i,s),c.value,Mw(o))}return!0}catch{return!1}}a(mp,"addTestFileErrorDetails");function hp(t){return Kr(t)&&Object.prototype.hasOwnProperty.call(t,"fileId")&&Object.prototype.hasOwnProperty.call(t,"tests")}a(hp,"isTestFileErrorDetailCandidate");function gp(t,e,r,n){let i=bp(r);if(!qi(e)||i===void 0||!qi(n))return;let s=_p(e,i,n);if(!t.ambiguousKeys.has(s))return t.messages.get(s)}a(gp,"getTestErrorMessage");function Iw(t){if(!Kr(t))return;let e=t.fileId,r=t.tests;if(!(!qi(e)||!Array.isArray(r)))return{fileId:e,tests:r}}a(Iw,"parseTestFile");function Aw(t){return t.length>0&&!t.some(Kr)}a(Aw,"hasOnlyMalformedTests");function Cw(t){let e=t.results;if(!Array.isArray(e))return;let r=e.at(-1);if(!Kr(r))return;let n=r.status;if(typeof n!="string"||!xw.has(n))return;let i=r.errors;if(Array.isArray(i))for(let s of i){let o=Rw(s);if(o)return o}}a(Cw,"extractFinalErrorDetail");function Rw(t){if(typeof t=="string"){let n=yp(t);return n?{message:n}:void 0}if(!Kr(t))return;let e=dp(t.message,t.value),r=dp(t.codeframe,t.snippet);return e?!r||e.includes(r)?{message:e}:{message:e,frame:r}:r?{frame:r}:void 0}a(Rw,"normalizeError");function Ow(t){let{message:e,frame:r}=t;if(!e)return Wi(r??"");if(!r)return Wi(e);let n=Buffer.byteLength(e,"utf8");if(n>qr)return Wi(e);let i=`
61
159
 
62
- `,i=Buffer.byteLength(s,"utf8"),a=Buffer.byteLength(r,"utf8");if(n+i+a<=or)return{value:`${e}${s}${r}`,truncated:!1};let c=i+Buffer.byteLength(Gr,"utf8"),l=or-n;if(l<c)return{value:e,truncated:!0};let u=oT(r,l-c);return{value:`${e}${s}${u}${Gr}`,truncated:!0}}o(aT,"boundNormalizedErrorDetail");function oT(t,e){let r="",n=0;for(let s of t){let i=Buffer.byteLength(s,"utf8");if(n+i>e)break;r+=s,n+=i}return r}o(oT,"utf8Prefix");function cT(t){let e=(0,Lp.createHash)("sha256");return t.message&&e.update(t.message,"utf8"),t.message&&t.frame&&e.update(`
160
+ `,s=Buffer.byteLength(i,"utf8"),o=Buffer.byteLength(r,"utf8");if(n+s+o<=qr)return{value:`${e}${i}${r}`,truncated:!1};let c=s+Buffer.byteLength(Sn,"utf8"),l=qr-n;if(l<c)return{value:e,truncated:!0};let u=kw(r,l-c);return{value:`${e}${i}${u}${Sn}`,truncated:!0}}a(Ow,"boundNormalizedErrorDetail");function kw(t,e){let r="",n=0;for(let i of t){let s=Buffer.byteLength(i,"utf8");if(n+s>e)break;r+=i,n+=s}return r}a(kw,"utf8Prefix");function Mw(t){let e=(0,fp.createHash)("sha256");return t.message&&e.update(t.message,"utf8"),t.message&&t.frame&&e.update(`
63
161
 
64
- `,"utf8"),t.frame&&e.update(t.frame,"utf8"),e.digest("hex")}o(cT,"digestNormalizedErrorDetail");function Bp(t){let e=Pa(t);return e.trim().length===0?"":e.replace(/^(?:[^\S\r\n]*(?:\r\n|\r|\n))+/u,"").replace(/(?:(?:\r\n|\r|\n)[^\S\r\n]*)+$/u,"")}o(Bp,"normalizeErrorText");function lT(t,e,r,n){if(t.ambiguousKeys.has(e))return;let s=La.get(t);if(s||(s=new Map,La.set(t,s)),t.messages.get(e)===void 0){t.messages.set(e,r),s.set(e,n);return}s.get(e)!==n&&(t.messages.delete(e),s.delete(e),t.ambiguousKeys.add(e),t.identityConflictCount+=1)}o(lT,"addErrorDetail");function jp(t,e,r){return JSON.stringify([t,e,r])}o(jp,"createIdentityKey");function Pp(...t){for(let e of t){if(typeof e!="string")continue;let r=Bp(e);if(r)return r}}o(Pp,"firstMeaningfulString");function cr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}o(cr,"isRecord");function Hp(t){return t==null||t===""?"":typeof t=="string"?t:void 0}o(Hp,"normalizeProjectName");function fs(t){return typeof t=="string"&&t.length>0}o(fs,"isNonEmptyString");var uT=o(t=>Number.isSafeInteger(t)&&t>=0?Math.min(t,8388608):0,"effectiveErrorDetailsPayloadBudgetBytes"),dT=o(t=>Buffer.byteLength(`,"errorMessage":${JSON.stringify(t)}`,"utf8"),"serializedErrorMessagePropertyBytes");function Gp(t,e=8388608){let r=uT(e),n=0,s=t.tests?.map(i=>{if(i.errorMessage===void 0)return i;let a=dT(i.errorMessage);if(a<=r)return r-=a,i;n+=1;let c={...i};return delete c.errorMessage,c});return{stats:{...t,...s!==void 0?{tests:s}:{}},omittedCount:n}}o(Gp,"applyErrorDetailsPayloadBudget");var zp=o(t=>Df.includes(t),"isPayloadTag"),pT=o((t,e)=>t.files.flatMap(r=>r.tests.map(n=>{let s=e?Fp(e,r.fileId,n.projectName,n.testId):void 0;return{playwrightTestId:n.testId,ok:!!n.ok,outcome:n.outcome,title:n.title,titlePath:n.path??[],filePath:n.location?.file,...n.projectName?{projectName:n.projectName}:{},tags:n.tags??[],annotations:n.annotations??[],...s?{errorMessage:s}:{}}})),"htmlReportToRows"),ps=class t{constructor(e,r,n,s={},i={},a,c,l,u={}){this.reportHTMLFilePath=e;this.testRunUUID=r;this.pwTestIdToChecksumTestId=n;this.playwrightIdToMetadata=s;this.channel=a;this.checksumTestIdToUsingPlaceholder=u;this.supportVideo=!1;this.config={hosted:!0,assetsBaseURL:"https://api.checksum.ai/api/test-runs"};this.config={...this.config,...i},this.checksumRoot=c||(0,Ht.dirname)((0,Ht.dirname)(e)),this.projectRoot=l||this.checksumRoot}static{o(this,"PlaywrightReportProcessor")}static{this.templateCache=null}async process(){let e=0;try{e=(0,ye.statSync)(this.reportHTMLFilePath)?.size||0,this.channel.debug(`Report HTML file size approximately ${e} bytes`)}catch(i){this.channel.debug(`Failed to retrieve file size for ${this.reportHTMLFilePath}`,i)}let r=(0,Ht.join)((0,qp.tmpdir)(),`pw-report-${(0,Kp.randomUUID)()}.zip`),n=o(()=>{try{(0,ye.existsSync)(r)&&(0,ye.unlinkSync)(r)}catch{}},"cleanupFile"),s={sigterm:o(()=>{n(),process.exit(143)},"sigterm"),sigint:o(()=>{n(),process.exit(130)},"sigint"),exit:n};process.once("SIGTERM",s.sigterm),process.once("SIGINT",s.sigint),process.once("exit",s.exit);try{this.channel.debug("Extracting base64 to temp ZIP file...");let i=Date.now();await this.extractBase64ToFile(r);let a=Date.now()-i;this.channel.debug("Modifying ZIP file...");let c=Date.now(),l=this.modifyZipFile(r),u=Date.now()-c;this.channel.debug("Writing output HTML...");let d=Date.now();await this.writeOutputWithStreamedZip(r);let p=Date.now()-d;return{report_html_bytes:e,extract_ms:a,modify_ms:u,write_ms:p,entry_count:l.entryCount,json_entry_count:l.jsonEntryCount,largest_entry_bytes:l.largestEntryBytes,largest_entry_name:l.largestEntryName,error_details_extracted:l.errorDetailsExtracted,error_details_truncated:l.errorDetailsTruncated,error_detail_parse_failures:l.errorDetailParseFailures,error_detail_identity_conflicts:l.errorDetailIdentityConflicts,error_details_payload_budget_omitted:l.errorDetailsPayloadBudgetOmitted}}finally{process.removeListener("SIGTERM",s.sigterm),process.removeListener("SIGINT",s.sigint),process.removeListener("exit",s.exit);try{(0,ye.existsSync)(r)&&(0,ye.unlinkSync)(r)}catch{this.channel.debug(`Failed to cleanup temp file: ${r}`)}}}async extractBase64ToFile(e){return new Promise((r,n)=>{let s=!1,i=!1,a=!1,c=[],l=0,u=(0,ye.createWriteStream)(e);u.on("error",g=>{if(!i){i=!0;try{_.destroyed||_.destroy(),p.end()}catch{}n(g)}});let d=o(()=>{if(l<4)return;let g=c.join("");c.length=0,a||(g=g.replace("data:application/zip;base64,",""),a=!0);let y=Math.floor(g.length/4)*4,E=g.slice(0,y),w=g.slice(y);if(w.length>0?(c.push(w),l=w.length):l=0,E.length>0){let S=Buffer.from(E,"base64");u.write(S)}},"flushBuffer"),p=new Vp.Parser({onopentag:o((g,y)=>{zp(g)&&y.id==="playwrightReportBase64"&&(s=!0)},"onopentag"),ontext:o(g=>{s&&(c.push(g),l+=g.length,l>1024*1024&&d())},"ontext"),onclosetag:o(g=>{if(zp(g)&&s&&!i){if(i=!0,l>0){let y=c.join("");if(a||(y=y.replace("data:application/zip;base64,","")),y.length>0){let E=Buffer.from(y,"base64");u.write(E)}}try{_.destroyed||_.destroy()}catch{}u.end(()=>r())}},"onclosetag"),onerror:o(g=>{if(!i){i=!0;try{p.end(),_.destroyed||_.destroy(),u.destroyed||u.destroy()}catch{}n(g)}},"onerror")}),_=(0,ye.createReadStream)(this.reportHTMLFilePath,{encoding:"utf8"});_.on("data",g=>p.write(g.toString())),_.on("end",()=>{if(p.end(),!i){i=!0;try{u.destroyed||u.destroy()}catch{}n(new Error("Could not find playwrightReportBase64 in HTML"))}}),_.on("error",g=>{if(!i){i=!0;try{p.end(),u.destroyed||u.destroy()}catch{}n(g)}})})}modifyZipFile(e){let r=new Wp.default(e),n=r.getEntries(),s=Dp(),i,a,c=0,l=0,u=0,d="";for(let _ of n){if(_.isDirectory||!_.entryName.endsWith(".json"))continue;let g=_.getData().toString("utf8");if(l+=1,g.length>u&&(u=g.length,d=_.entryName),_.entryName==="report.json")i=JSON.parse(g),a=_;else{let y=this.replaceAttachmentPaths(g);_.setData(Buffer.from(y,"utf8"));try{let E=JSON.parse(y);Up(E)&&!$p(E,s)&&(c+=1)}catch{c+=1}}}if(!i||!a)throw new Error("report.json not found in ZIP file");this.config.dedupeByChecksumTestId&&Np(i,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId}),this.handleReportJSON(i),this.report=i;let p=this.extractStats(i,s);return a.setData(Buffer.from(JSON.stringify(i),"utf8")),r.writeZip(e),{entryCount:n.length,jsonEntryCount:l,largestEntryBytes:u,largestEntryName:d,errorDetailsExtracted:s.messages.size,errorDetailsTruncated:s.truncatedCount,errorDetailParseFailures:c,errorDetailIdentityConflicts:s.identityConflictCount,errorDetailsPayloadBudgetOmitted:p}}replaceAttachmentPaths(e){return e.replace(/"path"\s*:\s*"([^"]+)"/g,(r,n)=>n.startsWith("http://")||n.startsWith("https://")?r:`"path":"${this.makeAttachmentPath(n)}"`)}async writeOutputWithStreamedZip(e){let r=this.getTemplate(),n=this.getProcessedFilePath(),s=n.replace(".html",".backup.html");(0,ye.copyFileSync)(n,s);let i=(0,ye.createWriteStream)(n);await new Promise((a,c)=>{i.on("error",c),i.write(r),i.write($f+"data:application/zip;base64,");let l=(0,ye.createReadStream)(e,{highWaterMark:3*1024*1024});l.on("data",u=>{let p=(typeof u=="string"?Buffer.from(u):u).toString("base64");i.write(p)||l.pause()}),i.on("drain",()=>{l.resume()}),l.on("end",()=>{i.write(Uf),i.end(()=>a())}),l.on("error",u=>{try{i.destroyed||i.destroy()}catch{}c(u)}),i.on("error",u=>{try{l.destroyed||l.destroy()}catch{}c(u)})})}testHasTrace(e,r){try{if(!this.report)return!0;let n=Object.keys(this.pwTestIdToChecksumTestId??{}).find(i=>this.pwTestIdToChecksumTestId[i]===e);if(!n)return!0;let s=o(i=>i.some(a=>a.attachments?.some(c=>c.name==="trace")),"hasTrace");for(let i of this.report.files)for(let a of i.tests)if(a.testId===n&&a.projectName===r&&s(a.results))return!0;return!1}catch(n){return this.channel.debug("Failed to check if test has trace, assuming trace exists",n),!0}}getProcessedFilePath(){return this.reportHTMLFilePath}getTemplate(){return t.templateCache||(t.templateCache=(0,ye.readFileSync)(cs.playwrightReporter.htmlReportTemplatePath,"utf-8")),t.templateCache}getReportsStats(){return this.stats}extractStats(e,r){if(!e.stats)return 0;let n=ka(pT(e,r),e.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:o(i=>Mp(i,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}),s=Gp(n,this.config.errorDetailsPayloadBudgetBytes??8388608);return this.stats=s.stats,s.omittedCount}makeAttachmentPath(e){return this.config.hosted?`${this.config.assetsBaseURL}/${this.testRunUUID}/report-data-file-url?fileName=${(0,Ht.basename)(e)}`:e}handleReportJSON(e){let r={},n=o(s=>{let i=s.testId,a=this.playwrightIdToMetadata[i];a&&(r[i]=a);let c=us({playwrightTestId:s.testId,filePath:s.location?.file,title:s.title},{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId});c!==void 0&&(s.checksumTestId=c),s.results.forEach(l=>{this.processAttachments(l.attachments)})},"getChecksumMetadataForPWTestId");e.files.forEach(s=>{s.tests.forEach(n)}),e.checksumMetadata=r}processAttachments(e){if(e.forEach(r=>this.updateAttachment(r)),!this.supportVideo){let r=e.findIndex(n=>n.name==="video");r!==-1&&e.splice(r,1)}}updateAttachment(e){e.path&&(e.path=this.makeAttachmentPath(e.path))}};var Da={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},mT={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",hard_assertion:void 0,soft_assertion:void 0,recovery:void 0,scroll:void 0},eG=Object.fromEntries(Object.entries(mT).map(t=>t.reverse())),hT={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},tG=Object.fromEntries(Object.entries(hT).map(t=>t.reverse()));var rG={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},nG={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var bs=require("fs"),fm=require("path"),pm=require("stream");var Zp=o(t=>{if(t.error!=null)return"ERROR";let e=t.status_code;if(typeof e=="number"&&e>=500)return"ERROR";let r=t.exit_code;return typeof r=="number"&&r!==0?"ERROR":"INFO"},"severityFor");var $a=require("fs");var Jp="\x1B[31m",gT="\x1B[33m",yT="\x1B[32m",_T="\x1B[36m",bT="\x1B[2m",ET="\x1B[1m",zr="\x1B[0m",wT=o(()=>{let t=process.env.WIDE_EVENT_PRETTY;return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),TT=new Set(["severity","message","kind","timestamp","_startedAtMs"]),vT=o(t=>{let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="bigint")return n.toString();if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n})},"safeStringify"),ST=o(t=>t==="ERROR"||t==="CRITICAL"?Jp:t==="WARNING"?gT:yT,"colorForSeverity"),IT=o(t=>{let e=String(t.severity??"INFO"),r=`${ST(e)}${e.padEnd(5)}${zr}`,n=t.kind?`${_T}${t.kind}${zr}`:"",s=String(t.message??""),i=t.error&&typeof t.error=="object"?(()=>{let d=t.error;return` ${Jp}${d.type??"Error"}: ${d.message??""}${zr}`})():"",a=["outcome","test_suite_run_id","status"],c=Object.entries(t).filter(([d,p])=>!TT.has(d)&&p!=null&&d!=="error"&&typeof p!="object"),l=o(d=>{let p=a.indexOf(d);return p===-1?a.length:p},"rank"),u=c.sort(([d],[p])=>l(d)-l(p)).slice(0,8).map(([d,p])=>`${bT}${d}=${zr}${p}`).join(" ");return[r,ET+n+zr,s,u,i].filter(d=>d&&d.trim()!=="").join(" ")},"formatPretty"),xT=o(t=>{let e=t.trace_id;if(typeof e!="string"||e==="")return t;let r=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return r?{...t,"logging.googleapis.com/trace":`projects/${r}/traces/${e}`}:t},"withGcpTraceField"),Yp=o(t=>{let e=wT()?IT(t):vT(xT(t));(0,$a.writeSync)(1,e+`
65
- `)},"emitEvent");var Xp=o(t=>{(0,$a.writeSync)(2,t.endsWith(`
162
+ `,"utf8"),t.frame&&e.update(t.frame,"utf8"),e.digest("hex")}a(Mw,"digestNormalizedErrorDetail");function yp(t){let e=To(t);return e.trim().length===0?"":e.replace(/^(?:[^\S\r\n]*(?:\r\n|\r|\n))+/u,"").replace(/(?:(?:\r\n|\r|\n)[^\S\r\n]*)+$/u,"")}a(yp,"normalizeErrorText");function Pw(t,e,r,n){if(t.ambiguousKeys.has(e))return;let i=vo.get(t);if(i||(i=new Map,vo.set(t,i)),t.messages.get(e)===void 0){t.messages.set(e,r),i.set(e,n);return}i.get(e)!==n&&(t.messages.delete(e),i.delete(e),t.ambiguousKeys.add(e),t.identityConflictCount+=1)}a(Pw,"addErrorDetail");function _p(t,e,r){return JSON.stringify([t,e,r])}a(_p,"createIdentityKey");function dp(...t){for(let e of t){if(typeof e!="string")continue;let r=yp(e);if(r)return r}}a(dp,"firstMeaningfulString");function Kr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}a(Kr,"isRecord");function bp(t){return t==null||t===""?"":typeof t=="string"?t:void 0}a(bp,"normalizeProjectName");function qi(t){return typeof t=="string"&&t.length>0}a(qi,"isNonEmptyString");var Nw=a(t=>Number.isSafeInteger(t)&&t>=0?Math.min(t,8388608):0,"effectiveErrorDetailsPayloadBudgetBytes"),Lw=a(t=>Buffer.byteLength(`,"errorMessage":${JSON.stringify(t)}`,"utf8"),"serializedErrorMessagePropertyBytes");function wp(t,e=8388608){let r=Nw(e),n=0,i=t.tests?.map(s=>{if(s.errorMessage===void 0)return s;let o=Lw(s.errorMessage);if(o<=r)return r-=o,s;n+=1;let c={...s};return delete c.errorMessage,c});return{stats:{...t,...i!==void 0?{tests:i}:{}},omittedCount:n}}a(wp,"applyErrorDetailsPayloadBudget");var Ep=a(t=>bf.includes(t),"isPayloadTag"),Uw=a((t,e)=>t.files.flatMap(r=>r.tests.map(n=>{let i=e?gp(e,r.fileId,n.projectName,n.testId):void 0;return{playwrightTestId:n.testId,ok:!!n.ok,outcome:n.outcome,title:Gi(n.title,n.location.file),titlePath:n.path??[],filePath:n.location.file,...n.projectName?{projectName:n.projectName}:{},tags:n.tags??[],annotations:n.annotations??[],...i?{errorMessage:i}:{}}})),"htmlReportToRows"),Ki=class t{constructor(e,r,n,i={},s={},o,c,l,u={}){this.reportHTMLFilePath=e;this.testRunUUID=r;this.pwTestIdToChecksumTestId=n;this.playwrightIdToMetadata=i;this.channel=o;this.checksumTestIdToUsingPlaceholder=u;this.supportVideo=!1;this.config={hosted:!0,assetsBaseURL:"https://api.checksum.ai/api/test-runs"};this.config={...this.config,...s},this.checksumRoot=c||(0,pr.dirname)((0,pr.dirname)(e)),this.projectRoot=l||this.checksumRoot}static{a(this,"PlaywrightReportProcessor")}static{this.templateCache=null}async process(){let e=0;try{e=(0,be.statSync)(this.reportHTMLFilePath).size||0,this.channel.debug(`Report HTML file size approximately ${e} bytes`)}catch(s){this.channel.debug(`Failed to retrieve file size for ${this.reportHTMLFilePath}`,s)}let r=(0,pr.join)((0,Sp.tmpdir)(),`pw-report-${(0,xp.randomUUID)()}.zip`),n=a(()=>{try{(0,be.existsSync)(r)&&(0,be.unlinkSync)(r)}catch{}},"cleanupFile"),i={sigterm:a(()=>{n(),process.exit(143)},"sigterm"),sigint:a(()=>{n(),process.exit(130)},"sigint"),exit:n};process.once("SIGTERM",i.sigterm),process.once("SIGINT",i.sigint),process.once("exit",i.exit);try{this.channel.debug("Extracting base64 to temp ZIP file...");let s=Date.now();await this.extractBase64ToFile(r);let o=Date.now()-s;this.channel.debug("Modifying ZIP file...");let c=Date.now(),l=this.modifyZipFile(r),u=Date.now()-c;this.channel.debug("Writing output HTML...");let d=Date.now();await this.writeOutputWithStreamedZip(r);let f=Date.now()-d;return{report_html_bytes:e,extract_ms:o,modify_ms:u,write_ms:f,entry_count:l.entryCount,json_entry_count:l.jsonEntryCount,largest_entry_bytes:l.largestEntryBytes,largest_entry_name:l.largestEntryName,error_details_extracted:l.errorDetailsExtracted,error_details_truncated:l.errorDetailsTruncated,error_detail_parse_failures:l.errorDetailParseFailures,error_detail_identity_conflicts:l.errorDetailIdentityConflicts,error_details_payload_budget_omitted:l.errorDetailsPayloadBudgetOmitted}}finally{process.removeListener("SIGTERM",i.sigterm),process.removeListener("SIGINT",i.sigint),process.removeListener("exit",i.exit);try{(0,be.existsSync)(r)&&(0,be.unlinkSync)(r)}catch{this.channel.debug(`Failed to cleanup temp file: ${r}`)}}}async extractBase64ToFile(e){return new Promise((r,n)=>{let i=!1,s=!1,o=!1,c=[],l=0,u=(0,be.createWriteStream)(e);u.on("error",h=>{if(!s){s=!0;try{y.destroyed||y.destroy(),f.end()}catch{}n(h)}});let d=a(()=>{if(l<4)return;let h=c.join("");c.length=0,o||(h=h.replace("data:application/zip;base64,",""),o=!0);let g=Math.floor(h.length/4)*4,b=h.slice(0,g),w=h.slice(g);if(w.length>0?(c.push(w),l=w.length):l=0,b.length>0){let v=Buffer.from(b,"base64");u.write(v)}},"flushBuffer"),f=new Tp.Parser({onopentag:a((h,g)=>{Ep(h)&&g.id==="playwrightReportBase64"&&(i=!0)},"onopentag"),ontext:a(h=>{i&&(c.push(h),l+=h.length,l>1024*1024&&d())},"ontext"),onclosetag:a(h=>{if(Ep(h)&&i&&!s){if(s=!0,l>0){let g=c.join("");if(o||(g=g.replace("data:application/zip;base64,","")),g.length>0){let b=Buffer.from(g,"base64");u.write(b)}}try{y.destroyed||y.destroy()}catch{}u.end(()=>r())}},"onclosetag"),onerror:a(h=>{if(!s){s=!0;try{f.end(),y.destroyed||y.destroy(),u.destroyed||u.destroy()}catch{}n(h)}},"onerror")}),y=(0,be.createReadStream)(this.reportHTMLFilePath,{encoding:"utf8"});y.on("data",h=>f.write(h.toString())),y.on("end",()=>{if(f.end(),!s){s=!0;try{u.destroyed||u.destroy()}catch{}n(new Error("Could not find playwrightReportBase64 in HTML"))}}),y.on("error",h=>{if(!s){s=!0;try{f.end(),u.destroyed||u.destroy()}catch{}n(h)}})})}modifyZipFile(e){let r=new vp.default(e),n=r.getEntries(),i=pp(),s,o,c=0,l=0,u=0,d="";for(let y of n){if(y.isDirectory||!y.entryName.endsWith(".json"))continue;let h=y.getData().toString("utf8");if(l+=1,h.length>u&&(u=h.length,d=y.entryName),y.entryName==="report.json")s=JSON.parse(h),o=y;else{let g=this.replaceAttachmentPaths(h);y.setData(Buffer.from(g,"utf8"));try{let b=JSON.parse(g);hp(b)&&!mp(b,i)&&(c+=1)}catch{c+=1}}}if(!s||!o)throw new Error("report.json not found in ZIP file");this.config.dedupeByChecksumTestId&&cp(s,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId}),this.handleReportJSON(s),this.report=s;let f=this.extractStats(s,i);return o.setData(Buffer.from(JSON.stringify(s),"utf8")),r.writeZip(e),{entryCount:n.length,jsonEntryCount:l,largestEntryBytes:u,largestEntryName:d,errorDetailsExtracted:i.messages.size,errorDetailsTruncated:i.truncatedCount,errorDetailParseFailures:c,errorDetailIdentityConflicts:i.identityConflictCount,errorDetailsPayloadBudgetOmitted:f}}replaceAttachmentPaths(e){return e.replace(/"path"\s*:\s*"([^"]+)"/g,(r,n)=>n.startsWith("http://")||n.startsWith("https://")?r:`"path":"${this.makeAttachmentPath(n)}"`)}async writeOutputWithStreamedZip(e){let r=this.getTemplate(),n=this.getProcessedFilePath(),i=n.replace(".html",".backup.html");(0,be.copyFileSync)(n,i);let s=(0,be.createWriteStream)(n);await new Promise((o,c)=>{s.on("error",c),s.write(r),s.write(wf+"data:application/zip;base64,");let l=(0,be.createReadStream)(e,{highWaterMark:3*1024*1024});l.on("data",u=>{let f=(typeof u=="string"?Buffer.from(u):u).toString("base64");s.write(f)||l.pause()}),s.on("drain",()=>{l.resume()}),l.on("end",()=>{s.write(Ef),s.end(()=>o())}),l.on("error",u=>{try{s.destroyed||s.destroy()}catch{}c(u)}),s.on("error",u=>{try{l.destroyed||l.destroy()}catch{}c(u)})})}testHasTrace(e,r){try{if(!this.report)return!0;let n=Object.keys(this.pwTestIdToChecksumTestId??{}).find(s=>this.pwTestIdToChecksumTestId[s]===e);if(!n)return!0;let i=a(s=>s.some(o=>o.attachments?.some(c=>c.name==="trace")),"hasTrace");for(let s of this.report.files)for(let o of s.tests)if(o.testId===n&&o.projectName===r&&i(o.results))return!0;return!1}catch(n){return this.channel.debug("Failed to check if test has trace, assuming trace exists",n),!0}}getProcessedFilePath(){return this.reportHTMLFilePath}getTemplate(){return t.templateCache||(t.templateCache=(0,be.readFileSync)(Hi.playwrightReporter.htmlReportTemplatePath,"utf-8")),t.templateCache}getReportsStats(){return this.stats}extractStats(e,r){if(!e.stats)return 0;let n=Eo(Uw(e,r),e.stats,{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId,playwrightIdToMetadata:this.playwrightIdToMetadata,checksumTestIdToUsingPlaceholder:this.checksumTestIdToUsingPlaceholder,toRelativeFilePath:a(s=>lp(s,this.checksumRoot,this.projectRoot),"toRelativeFilePath")}),i=wp(n,this.config.errorDetailsPayloadBudgetBytes??8388608);return this.stats=i.stats,i.omittedCount}makeAttachmentPath(e){return this.config.hosted?`${this.config.assetsBaseURL}/${this.testRunUUID}/report-data-file-url?fileName=${(0,pr.basename)(e)}`:e}handleReportJSON(e){let r={},n=a(i=>{let s=i.testId,o=this.playwrightIdToMetadata[s];o&&(r[s]=o),i.title=Gi(i.title,i.location.file);let c=Vi({playwrightTestId:i.testId,filePath:i.location.file,title:i.title},{pwTestIdToChecksumTestId:this.pwTestIdToChecksumTestId});c!==void 0&&(i.checksumTestId=c),i.results.forEach(l=>{this.processAttachments(l.attachments)})},"getChecksumMetadataForPWTestId");e.files.forEach(i=>{i.tests.forEach(n)}),e.checksumMetadata=r}processAttachments(e){if(e.forEach(r=>this.updateAttachment(r)),!this.supportVideo){let r=e.findIndex(n=>n.name==="video");r!==-1&&e.splice(r,1)}}updateAttachment(e){e.path&&(e.path=this.makeAttachmentPath(e.path))}};var So={trace:"application/zip","trace-backup-file":"application/zip",har:"application/zip",report:"text/html","rrweb-recording":"application/json"},$w={click:"click",fill:"input",click_and_type:"click_and_type",clear_and_type:"clear_and_type",double_click:"double_click",drag_and_drop:"drag_and_drop",hover:"hover",navigate:"navigation",keystroke:"keystroke",selectoption:"selectoption",upload_files:"upload_files",wait:"wait",get_more_items:"get_more_items",reset:void 0,save:void 0,fail:void 0,finish:void 0,dismiss_modal:void 0,vision_help:void 0,switch_tab:"switch_tab",expand_interactable_elements:void 0,approve_release:void 0,logout_and_login:"logout_and_login",canvas_click:"canvas_click",native_accept:"native_accept",native_dismiss:"native_dismiss",hard_assertion:void 0,soft_assertion:void 0,recovery:void 0,scroll:void 0},nz=Object.fromEntries(Object.entries($w).map(t=>t.reverse())),Fw={goto:"navigation",click:"click",dblclick:"double_click",dragTo:"drag_and_drop",check:"check",uncheck:"uncheck",fill:"input",hover:"hover",selectOption:"selectoption",waitForTimeout:"wait","keyboard.press":"keystroke",setInputFiles:"upload_files",getPage:"switch_tab",reauthenticate:"logout_and_login",canvasClick:"canvas_click"},iz=Object.fromEntries(Object.entries(Fw).map(t=>t.reverse()));var sz={input:[1,2],selectoption:[1,2],keystroke:[1,2],wait:[1,2],navigation:[1,2],click:[0,1],double_click:[0,1],drag_and_drop:[1,2],upload_files:[1,2],canvas_click:[1,2],logout_and_login:[1],login:[1,2],click_and_type:[1,2],clear_and_type:[1,2],check:[0,1],uncheck:[0,1],hover:[0,1]},az={input:1,selectoption:1,keystroke:1,wait:-1,navigation:1,click:0,double_click:0,drag_and_drop:1,upload_files:1,canvas_click:-1,logout_and_login:-1,login:1,click_and_type:0,clear_and_type:0,check:0,uncheck:0,hover:0,native_accept:-1,native_dismiss:-1};var es=require("fs"),zp=require("path"),Gp=require("stream");var Ip=a(t=>{if(t.error!=null)return"ERROR";let e=t.status_code;if(typeof e=="number"&&e>=500)return"ERROR";let r=t.exit_code;return typeof r=="number"&&r!==0?"ERROR":"INFO"},"severityFor");var xo=require("fs");var Ap="\x1B[31m",Bw="\x1B[33m",jw="\x1B[32m",Hw="\x1B[36m",zw="\x1B[2m",Gw="\x1B[1m",xn="\x1B[0m",Vw=a(()=>{let t=process.env.WIDE_EVENT_PRETTY;return t==="true"||t==="1"?!0:t==="false"||t==="0"?!1:process.stdout.isTTY?!0:process.env.APP_ENV==="local"},"shouldPretty"),Ww=new Set(["severity","message","kind","timestamp","_startedAtMs"]),qw=a(t=>{let e=new WeakSet;return JSON.stringify(t,(r,n)=>{if(typeof n=="bigint")return n.toString();if(typeof n=="object"&&n!==null){if(e.has(n))return"[Circular]";e.add(n)}return n})},"safeStringify"),Kw=a(t=>t==="ERROR"||t==="CRITICAL"?Ap:t==="WARNING"?Bw:jw,"colorForSeverity"),Jw=a(t=>{let e=String(t.severity??"INFO"),r=`${Kw(e)}${e.padEnd(5)}${xn}`,n=t.kind?`${Hw}${t.kind}${xn}`:"",i=String(t.message??""),s=t.error&&typeof t.error=="object"?(()=>{let d=t.error;return` ${Ap}${d.type??"Error"}: ${d.message??""}${xn}`})():"",o=["outcome","test_suite_run_id","status"],c=Object.entries(t).filter(([d,f])=>!Ww.has(d)&&f!=null&&d!=="error"&&typeof f!="object"),l=a(d=>{let f=o.indexOf(d);return f===-1?o.length:f},"rank"),u=c.sort(([d],[f])=>l(d)-l(f)).slice(0,8).map(([d,f])=>`${zw}${d}=${xn}${f}`).join(" ");return[r,Gw+n+xn,i,u,s].filter(d=>d&&d.trim()!=="").join(" ")},"formatPretty"),Zw=a(t=>{let e=t.trace_id;if(typeof e!="string"||e==="")return t;let r=process.env.GCP_PROJECT_ID||process.env.GOOGLE_CLOUD_PROJECT;return r?{...t,"logging.googleapis.com/trace":`projects/${r}/traces/${e}`}:t},"withGcpTraceField"),Cp=a(t=>{let e=Vw()?Jw(t):qw(Zw(t));(0,xo.writeSync)(1,e+`
163
+ `)},"emitEvent");var Rp=a(t=>{(0,xo.writeSync)(2,t.endsWith(`
66
164
  `)?t:`${t}
67
- `)},"writeStderrLine");var AT=o(t=>{let e=t.kind??"event",r=t.outcome?` ${t.outcome}`:"",n=typeof t.duration_ms=="number"?` ${t.duration_ms}ms`:"";return`${e}${r}${n}`.trim()},"defaultMessage"),CT=o((t,e,r)=>{let n=Date.now(),s={timestamp:new Date().toISOString(),kind:t,...e},i=!1,a={set(c){return Object.assign(s,c),a},emit(c){i||(i=!0,c&&Object.assign(s,c),s.duration_ms===void 0&&(s.duration_ms=Date.now()-n),r(s))}};return a},"startHandle"),RT=o((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??AT,n=t.label??"[wide-event]",s=t.sink??(c=>Yp(c)),i=o(c=>{if(!e(c))return;let l={severity:Zp(c),message:c.message??r(c),...c};try{s(l)}catch(u){try{Xp(`${n} emit failed: ${String(u)}`)}catch{}}},"emit");return{emit:i,emitWideEvent:o((c,l={})=>{i({timestamp:new Date().toISOString(),kind:c,...l})},"emitWideEvent"),wideEvent:o((c,l={})=>CT(c,l,i),"wideEvent"),configureSink:o(c=>{s=c},"configureSink")}},"createWideEvents"),Qp=o(t=>t==="true"||t==="1","truthy"),em=o(()=>Qp(process.env.CHECKSUM_WIDE_EVENTS)||Qp(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),Ua=RT({decide:o(()=>em(),"decide")}),Fa=Ua.configureSink,lr=o((t,e={})=>Ua.wideEvent(t,e),"wideEvent"),Gt=o((t,e={})=>{Ua.emitWideEvent(t,e)},"emitWideEvent"),et=o(t=>t instanceof Error?{type:t.name,message:t.message}:{type:"UnknownError",message:String(t)},"toErrorField");async function tm(t,e){let r;try{r=await t.json()}catch{r=void 0}return OT({ok:t.ok,status:t.status,body:r},e)}o(tm,"assertOkJson");function OT(t,e){let r=t.body&&typeof t.body=="object"?t.body:void 0;if(!t.ok){let s=NT(r?.message);throw MT(new Error(`${e.resource} failed (HTTP ${t.status})`+(s?`: ${s}`:".")),t.status)}if(!r)throw new Error(`${e.resource} (HTTP ${t.status}) returned a non-object body; expected JSON.`);let n=(e.requiredFields??[]).filter(s=>!r[s]);if(n.length>0)throw new Error(`${e.resource} (HTTP ${t.status}) response is missing required field${n.length>1?"s":""}: ${n.join(", ")}.`);return r}o(OT,"assertJsonBody");function NT(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e=="string").join("; "):""}o(NT,"extractMessage");function MT(t,e){return Object.assign(t,{status:e})}o(MT,"withStatus");var ms=o(t=>typeof t=="number"&&t>=400&&t<500&&t!==408&&t!==429,"isNonRetryableStatus");var hs={uploadTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_TIMEOUT_MS",fallback:6e5,min:5e3,max:36e5},noProgressAbortMs:{env:"CHECKSUM_RUNTIME_UPLOAD_NO_PROGRESS_MS",fallback:6e4,min:5e3,max:6e5},assetDeadlineMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ASSET_DEADLINE_MS",fallback:12e5,min:3e4,max:54e5},maxAttempts:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_ATTEMPTS",fallback:6,min:1,max:20},stallTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_STALL_TIMEOUT_MS",fallback:6e5,min:3e4,max:36e5},minProgressBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_MIN_PROGRESS_BYTES",fallback:65536,min:1,max:67108864},finalizeBudgetMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_BUDGET_MS",fallback:18e5,min:6e4,max:54e5},finalizeCeilingMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_CEILING_MS",fallback:24e5,min:12e4,max:72e5},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},watchTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_WATCH_TIMEOUT_MS",fallback:12e4,min:5e3,max:18e5},ipcTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_IPC_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},onEndFlushTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ONEND_FLUSH_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},resumableChunkBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_RESUMABLE_CHUNK_BYTES",fallback:8388608,min:262144,max:268435456},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},bodyTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_BODY_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},maxConcurrentUploads:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_CONCURRENT",fallback:15,min:1,max:64}};function kT(t,e,r,n){if(t===void 0||t.trim()==="")return e;let s=Number(t);return Number.isInteger(s)?Math.min(n,Math.max(r,s)):e}o(kT,"clampEnvInt");var PT=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function LT(t){let e={...t},r=[];for(let[n,s,i]of PT)for(let a of s){let c=Math.floor(e[n]*i);e[a]>c&&(r.push(`${hs[a].env} (${e[a]}ms) exceeds its bound under ${hs[n].env} (${e[n]}ms); using ${c}ms`),e[a]=c)}return{tunables:e,warnings:r}}o(LT,"coerceScopeHierarchy");function Ba(t){let e={};for(let r of Object.keys(hs)){let n=hs[r];e[r]=kT(t[n.env],n.fallback,n.min,n.max)}return e.resumableChunkBytes=Math.max(1,Math.floor(e.resumableChunkBytes/262144))*262144,LT(e)}o(Ba,"resolveUploadTunablesDetailed");function DT(t){return Ba(t).tunables}o(DT,"resolveUploadTunables");var rm=DT({});var nm=new WeakMap,ja=new WeakMap;function sm(t,e){t.loadedBytes=0,t.committedBytes??=0,t.lastProgress=e,nm.set(t,t.committedBytes),ja.set(t,0)}o(sm,"beginUpload");function Ha(t){t.loadedBytes=0,ja.set(t,0)}o(Ha,"resetAttemptBytes");var im=o(t=>(e,r,n,s)=>{let i=t.get(e)??0;return r-i<n?!1:(e.lastProgress=s,t.set(e,r),!0)},"stamperFor"),$T=im(ja),UT=im(nm);function Ga(t,e,r,n){return t.loadedBytes=e,$T(t,e,r,n)}o(Ga,"recordSent");function za(t,e,r,n){let s=Math.max(t.committedBytes??0,e);return t.committedBytes=s,UT(t,s,r,n)}o(za,"recordCommitted");var ys=require("fs"),om=require("stream");function gs(t,{baseMs:e,capMs:r,random:n=Math.random}){let s=Math.min(r,e*2**(t-1));return s/2+n()*(s/2)}o(gs,"jitteredBackoffMs");async function ur(t){await t.body?.cancel().catch(()=>{})}o(ur,"drainBody");var qa=o(t=>t===200||t===201,"isStored"),cm=o(t=>t===308,"isResumeIncomplete"),FT=o(t=>t===404||t===410,"isSessionGoneStatus"),lm=o((t,e)=>{let r=t?.match(/bytes=0-(\d+)/);return r?Number(r[1])+1:e},"nextOffsetFromRange"),BT=o((t,e,r)=>e<=t?`bytes */${r}`:`bytes ${t}-${e-1}/${r}`,"contentRangeFor");function jT(t,e,r){let n=e,s=new TransformStream({transform(i,a){n+=i.byteLength,r?.(n),a.enqueue(i)}});return om.Readable.toWeb(t).pipeThrough(s)}o(jT,"countingBody");var tt=class extends Error{constructor(r,n){super(r);this.status=n;this.name="ResumableUploadError"}static{o(this,"ResumableUploadError")}},um=o(t=>t instanceof tt?t.status:void 0,"statusOf"),HT=o(t=>{let e=um(t);return e!==void 0&&FT(e)},"isSessionGone"),GT=o(t=>ms(um(t)),"isPermanent");async function zT(t,e,r,n){let s=await r(t,{method:"POST",headers:{"x-goog-resumable":"start","Content-Type":e,"Content-Length":"0"},signal:n});if(await ur(s),!qa(s.status))throw new tt(`resumable init failed with status ${s.status}`,s.status);let i=s.headers.get("Location");if(!i)throw new tt("resumable init returned no Location");return i}o(zT,"initResumableSession");async function VT(t,e,r,n){let s=await r(t,{method:"PUT",headers:{"Content-Range":`bytes */${e}`},signal:n});if(await ur(s),qa(s.status))return{done:!0,offset:e};if(!cm(s.status))throw new tt(`offset query failed with status ${s.status}`,s.status);return{done:!1,offset:lm(s.headers.get("Range"),0)}}o(VT,"queryCommittedOffset");async function am(t,e,{offset:r,endExclusive:n},s){let i=Math.max(0,(0,ys.statSync)(t.filePath).size-r),a=Math.min(Math.max(0,n-r),i),c=r+a,l=a>0?(0,ys.createReadStream)(t.filePath,{start:r,end:c-1}):void 0;try{let u={method:"PUT",headers:{"Content-Range":BT(r,c,t.size),"Content-Length":String(a)},duplex:"half",signal:s,...l?{body:jT(l,r,t.onSent)}:{}},d=await t.fetchImpl(e,u);if(await ur(d),qa(d.status))return{stored:!0,committed:t.size};if(cm(d.status))return{stored:!1,committed:lm(d.headers.get("Range"),r)};throw new tt(`resumable PUT failed with status ${d.status}`,d.status)}finally{l?.destroy()}}o(am,"putChunk");async function WT(t,e,r,n){let s=r;for(;s<t.size;){let a=Math.min(s+t.chunkSizeBytes,t.size),{stored:c,committed:l}=await am(t,e,{offset:s,endExclusive:a},n);if(c){t.onCommitted?.(t.size);return}if(l<=s)throw new tt("resumable PUT made no forward progress");s=l,t.onCommitted?.(s)}let{stored:i}=await am(t,e,{offset:t.size,endExclusive:t.size},n);if(!i)throw new tt("resumable upload did not finalize");t.onCommitted?.(t.size)}o(WT,"sendFrom");async function qT(t,e,r){if(e.url)return e.url;if(!t.target.initUrl)throw new tt("no resumable target provided");return e.url=await zT(t.target.initUrl,t.contentType,t.fetchImpl,r),e.used=!1,e.url}o(qT,"openSession");async function KT(t,e,r,n){if(!r)return 0;let s=await VT(e,t.size,t.fetchImpl,n);if(!s.done)return t.onCommitted?.(s.offset),s.offset}o(KT,"resumePoint");async function ZT(t,e,r){let n=await qT(t,e,r),s=await KT(t,n,e.used,r);if(e.used=!0,s===void 0){t.onCommitted?.(t.size);return}await WT(t,n,s,r)}o(ZT,"runAttempt");function JT(t,e,r){return HT(t)&&e.target.initUrl?(r.url=void 0,r.used=!1,"retry"):GT(t)?"stop":"retry"}o(JT,"afterFailure");async function dm(t){let e={url:t.target.sessionUrl,used:!1},r;for(let n=1;n<=t.maxAttempts&&!(t.now()>=t.deadlineAt);n++)try{await ZT(t,e,t.makeSignal());return}catch(s){if(r=s,JT(s,t,e)==="stop"||n>=t.maxAttempts)break;await t.sleep(gs(n,{baseMs:1e3,capMs:16e3,...t.random?{random:t.random}:{}}))}throw r instanceof Error?r:new tt(`resumable upload failed: ${String(r)}`)}o(dm,"uploadResumable");var YT=o(t=>{let e=t;if(e?.name==="TimeoutError")return"timeout";if(e?.name==="AbortError")return"no_progress_abort";let r=e?.cause?.code;if(r==="UND_ERR_CONNECT_TIMEOUT"||r==="UND_ERR_HEADERS_TIMEOUT"||r==="UND_ERR_BODY_TIMEOUT")return"timeout";if(typeof r=="string"&&r.length>0)return`network_error:${r}`;let n=typeof e?.message=="string"?e.message:"";return n.startsWith("Upload failed with status")?"http_error":n.startsWith("get-upload-url")?"signed_url_error":n.includes("No upload URL")?"signed_url_missing":"network_error"},"classifyUploadError"),XT=o(t=>Math.max(1e3,Math.min(1e4,Math.floor(t/4))),"noProgressPollMs"),_s=class{constructor(e,r,n,s,i=!1,a={start:o(u=>{},"start"),complete:o(u=>{},"complete"),error:o((u,d)=>{},"error")},c,l={}){this.apiBaseURL=e;this.apiKey=r;this.uploadTimeout=n;this.makeGetUploadUrlAPIPath=s;this.isolationMode=i;this.reporter=a;this.sessionId=c;this.SIGNED_URL_TIMEOUT_MS=3e4;this.tunables=l.tunables??rm,this.fetchImpl=l.fetchImpl??globalThis.fetch,this.now=l.now??Date.now,this.MAX_ATTEMPTS=this.tunables.maxAttempts,this.PUT_NO_PROGRESS_ABORT_MS=this.tunables.noProgressAbortMs,this.ASSET_DEADLINE_MS=this.tunables.assetDeadlineMs,this.MIN_PROGRESS_BYTES=this.tunables.minProgressBytes}static{o(this,"TestAssetUploader")}async uploadAsset(e){if(e.uploadStarted=!0,this.isolationMode){e.lastProgress=Date.now(),e.loadedBytes=0,e.sizeBytes=100,e.response=new Promise(a=>{setTimeout(()=>{e.complete=!0,e.lastProgress=Date.now(),e.loadedBytes=100,a({statusCode:200,ok:!0,body:"OK"})},10)});return}let{path:r}=e.info,n=this.now()+this.ASSET_DEADLINE_MS,s=lr("asset_upload",{test_suite_run_id:this.sessionId,asset_type:e.info.type,file_name:e.info.fileName??(0,fm.basename)(r),test_id:e.info.testId,project:e.info.project}),i=[];try{let c=(0,bs.statSync)(r).size;e.sizeBytes=c,sm(e,this.now()),s.set({size_bytes:c}),this.reporter.start(r);let l;for(let u=1;u<=this.MAX_ATTEMPTS&&!(this.now()>=n);u++){let d={attempt:u};try{let p=this.now();if(await this.getSignedURLForUpload(e),d.signed_url_ms=this.now()-p,!e.uploadURL)throw new Error("No upload URL returned");let _=this.now();d.resumable=e.resumable===!0,e.resumable?await this.putResumable(e,r,c,n):await this.putWithWatchdog(e,r,c),d.put_ms=this.now()-_,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,i.push(d),this.reporter.complete(r),e.complete=!0,s.emit({outcome:"success",attempt_count:i.length,attempts:i,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes});return}catch(p){l=p,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,d.failure_reason=YT(p),d.error=et(p);let _=ms(p?.status);d.non_retryable=_,delete e.uploadURL;let g=_?"non_retryable":e.resumable?"resumable_owns_retries":u>=this.MAX_ATTEMPTS?"max_attempts":this.now()>=n?"asset_deadline":void 0;if(d.retry_stop_reason=g,i.push(d),g)break;await this.backoff(u,n)}}this.reporter.error(r,l),e.error=!0,s.emit({outcome:"error",attempt_count:i.length,attempts:i,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,deadline_exceeded:this.now()>=n,error:et(l)})}catch(a){this.reporter.error(r,a),e.error=!0,s.emit({outcome:"error",failure_reason:"pre_upload",attempt_count:i.length,attempts:i,error:et(a)})}}async putWithWatchdog(e,r,n){let s=e.uploadURL;if(!s)throw new Error("No upload URL returned");let i=new AbortController,a=this.uploadTimeout??void 0;Ha(e);let c=this.armNoProgressWatchdog(e,()=>i.abort()),l=a!==void 0?setTimeout(()=>i.abort(new DOMException("upload attempt timeout","TimeoutError")),a):void 0,u=(0,bs.createReadStream)(r),d=0,p=this.MIN_PROGRESS_BYTES,_=this.now,g=new TransformStream({transform(w,S){d+=w.byteLength,e.sizeBytes=n,Ga(e,d,p,_()),S.enqueue(w)}}),y=pm.Readable.toWeb(u).pipeThrough(g),E={method:"PUT",headers:{"Content-Type":Da[e.info.type]??""},body:y,duplex:"half",signal:i.signal};try{let w=await this.fetchImpl(s,E);if(!w.ok)throw await ur(w),Object.assign(new Error(`Upload failed with status ${w.status}`),{status:w.status});za(e,n,this.MIN_PROGRESS_BYTES,this.now()),e.response=Promise.resolve(await w.text())}finally{clearInterval(c),clearTimeout(l),u.destroy()}}armNoProgressWatchdog(e,r){let n=-1,s=this.now();return setInterval(()=>{let i=Math.max(e.loadedBytes??0,e.committedBytes??0);i>n?(n=i,s=this.now()):this.now()-s>this.PUT_NO_PROGRESS_ABORT_MS&&r()},XT(this.PUT_NO_PROGRESS_ABORT_MS))}async putResumable(e,r,n,s){let i=e.uploadURL;if(!i)throw new Error("No upload URL returned");Ha(e);let a=this.uploadTimeout??this.tunables.uploadTimeoutMs,c,l,u=o(()=>(clearInterval(l),c=new AbortController,l=this.armNoProgressWatchdog(e,()=>c?.abort()),c.signal),"armAttempt");try{await dm({target:{initUrl:i},filePath:r,size:n,contentType:Da[e.info.type]??"",fetchImpl:this.fetchImpl,makeSignal:o(()=>AbortSignal.any([u(),AbortSignal.timeout(a)]),"makeSignal"),maxAttempts:this.MAX_ATTEMPTS,deadlineAt:s,chunkSizeBytes:this.tunables.resumableChunkBytes,now:this.now,sleep:o(d=>new Promise(p=>setTimeout(p,d)),"sleep"),onSent:o(d=>Ga(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onSent"),onCommitted:o(d=>za(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onCommitted")})}finally{clearInterval(l)}e.response=Promise.resolve("OK")}async backoff(e,r){let n=gs(e,{baseMs:1e3,capMs:16e3}),s=Math.max(0,Math.min(n,r-this.now()));s>0&&await new Promise(i=>setTimeout(i,s))}async getSignedURLForUpload(e){let r=new AbortController,n=setTimeout(()=>r.abort(),this.SIGNED_URL_TIMEOUT_MS);try{let s=JSON.stringify(e.info),i=`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(e)}`,a={Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},c=await this.fetchImpl(i,{method:"POST",headers:a,body:s,signal:r.signal}),{url:l,resumable:u}=await tm(c,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=l,e.resumable=u===!0}catch(s){throw delete e.uploadURL,s}finally{clearTimeout(n)}}};function Es(t,e,r=Date.now()){let n=t.filter(i=>!i.complete&&!i.error);if(n.length===0)return!1;let s=n.reduce((i,a)=>Math.max(i,a.lastProgress??0),0);return s>0&&r-s>e}o(Es,"isUploadStalled");function ws(t,e,r){return t!==void 0&&r-t>e}o(ws,"hasElapsedSinceTestEnd");function mm(t,e,r){return ws(e.testRunEndTime,e.finalizeBudgetMs,r)?!0:t===void 0?!1:t.complete||t.error?!0:Es([t],e.stallTimeoutMs,r)}o(mm,"shouldStopWaitingForReport");function hm(t){return t.abandonedAssets.length===0}o(hm,"mayCleanUpSources");function QT(t,e,r){if((e.length===0||Es(t.assets,t.stallTimeoutMs,r))&&ws(t.testRunEndTime,t.finalizeBudgetMs,r))return"budget";if(ws(t.testRunEndTime,t.finalizeCeilingMs,r))return"budget-ceiling"}o(QT,"backstopReason");function gm(t,e){let r=t.assets.filter(i=>!i.complete&&!i.error),n=o(i=>({reason:i,abandonedAssets:r}),"decide"),s=QT(t,r,e);if(s!==void 0)return n(s);if(!(t.processingInProgress||!t.doneWaitingForReport)&&!(r.length>0&&!Es(t.assets,t.stallTimeoutMs,e))&&!(t.pendingWatchCount>0&&!ws(t.testRunEndTime,t.watchTimeoutMs,e)))return r.length>0?n("stall"):t.pendingWatchCount>0?n("watch-timeout"):n("complete")}o(gm,"decideFinalize");var ym=require("module");var ev=(0,ym.createRequire)(__filename);function _m(t){let e,r;try{e=ev("undici"),r=new e.Agent({connect:{timeout:t.connectTimeoutMs},headersTimeout:t.headersTimeoutMs,bodyTimeout:t.bodyTimeoutMs,keepAliveTimeout:1e4,keepAliveMaxTimeout:3e4})}catch(s){return Gt("monitor_dispatcher_unavailable",{outcome:"error",error:et(s)}),process.emitWarning("@checksum-ai/runtime: undici dispatcher unavailable; upload timeouts fall back to the platform defaults",{detail:String(s)}),globalThis.fetch}let n=e.fetch;return(s,i)=>{let a={...i,dispatcher:r};return n(s,a)}}o(_m,"createMonitorFetch");var Ka=class{static{o(this,"CLIChannel")}constructor(){}sendToCLI(...e){let r=`{trm}${e.map(n=>n.toString()).join(`,
165
+ `)},"writeStderrLine");var Yw=a(t=>{let e=t.kind??"event",r=t.outcome?` ${t.outcome}`:"",n=typeof t.duration_ms=="number"?` ${t.duration_ms}ms`:"";return`${e}${r}${n}`.trim()},"defaultMessage"),Xw=a((t,e,r)=>{let n=Date.now(),i={timestamp:new Date().toISOString(),kind:t,...e},s=!1,o={set(c){return Object.assign(i,c),o},emit(c){s||(s=!0,c&&Object.assign(i,c),i.duration_ms===void 0&&(i.duration_ms=Date.now()-n),r(i))}};return o},"startHandle"),Qw=a((t={})=>{let e=t.decide??(()=>!0),r=t.deriveMessage??Yw,n=t.label??"[wide-event]",i=t.sink??(c=>Cp(c)),s=a(c=>{if(!e(c))return;let l={severity:Ip(c),message:c.message??r(c),...c};try{i(l)}catch(u){try{Rp(`${n} emit failed: ${String(u)}`)}catch{}}},"emit");return{emit:s,emitWideEvent:a((c,l={})=>{s({timestamp:new Date().toISOString(),kind:c,...l})},"emitWideEvent"),wideEvent:a((c,l={})=>Xw(c,l,s),"wideEvent"),configureSink:a(c=>{i=c},"configureSink")}},"createWideEvents"),Op=a(t=>t==="true"||t==="1","truthy"),kp=a(()=>Op(process.env.CHECKSUM_WIDE_EVENTS)||Op(process.env.WIDE_EVENT_PRETTY),"wideEventsEnabled"),Io=Qw({decide:a(()=>kp(),"decide")}),Ao=Io.configureSink,Jr=a((t,e={})=>Io.wideEvent(t,e),"wideEvent"),mr=a((t,e={})=>{Io.emitWideEvent(t,e)},"emitWideEvent"),tt=a(t=>t instanceof Error?{type:t.name,message:t.message}:{type:"UnknownError",message:String(t)},"toErrorField");async function Mp(t,e){let r;try{r=await t.json()}catch{r=void 0}return e0({ok:t.ok,status:t.status,body:r},e)}a(Mp,"assertOkJson");function e0(t,e){let r=t.body&&typeof t.body=="object"?t.body:void 0;if(!t.ok){let i=t0(r?.message);throw r0(new Error(`${e.resource} failed (HTTP ${t.status})`+(i?`: ${i}`:".")),t.status)}if(!r)throw new Error(`${e.resource} (HTTP ${t.status}) returned a non-object body; expected JSON.`);let n=(e.requiredFields??[]).filter(i=>!r[i]);if(n.length>0)throw new Error(`${e.resource} (HTTP ${t.status}) response is missing required field${n.length>1?"s":""}: ${n.join(", ")}.`);return r}a(e0,"assertJsonBody");function t0(t){return typeof t=="string"?t:Array.isArray(t)?t.filter(e=>typeof e=="string").join("; "):""}a(t0,"extractMessage");function r0(t,e){return Object.assign(t,{status:e})}a(r0,"withStatus");var Ji=a(t=>typeof t=="number"&&t>=400&&t<500&&t!==408&&t!==429,"isNonRetryableStatus");var Zi={uploadTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_TIMEOUT_MS",fallback:6e5,min:5e3,max:36e5},noProgressAbortMs:{env:"CHECKSUM_RUNTIME_UPLOAD_NO_PROGRESS_MS",fallback:6e4,min:5e3,max:6e5},assetDeadlineMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ASSET_DEADLINE_MS",fallback:12e5,min:3e4,max:54e5},maxAttempts:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_ATTEMPTS",fallback:6,min:1,max:20},stallTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_STALL_TIMEOUT_MS",fallback:6e5,min:3e4,max:36e5},minProgressBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_MIN_PROGRESS_BYTES",fallback:65536,min:1,max:67108864},finalizeBudgetMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_BUDGET_MS",fallback:18e5,min:6e4,max:54e5},finalizeCeilingMs:{env:"CHECKSUM_RUNTIME_UPLOAD_FINALIZE_CEILING_MS",fallback:24e5,min:12e4,max:72e5},cliHardCapMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CLI_HARD_CAP_MS",fallback:27e5,min:12e4,max:72e5},watchTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_WATCH_TIMEOUT_MS",fallback:12e4,min:5e3,max:18e5},ipcTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_IPC_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},onEndFlushTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_ONEND_FLUSH_TIMEOUT_MS",fallback:5e3,min:500,max:6e4},resumableChunkBytes:{env:"CHECKSUM_RUNTIME_UPLOAD_RESUMABLE_CHUNK_BYTES",fallback:8388608,min:262144,max:268435456},connectTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_CONNECT_TIMEOUT_MS",fallback:1e4,min:1e3,max:6e4},headersTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_HEADERS_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},bodyTimeoutMs:{env:"CHECKSUM_RUNTIME_UPLOAD_BODY_TIMEOUT_MS",fallback:3e5,min:5e3,max:18e5},maxConcurrentUploads:{env:"CHECKSUM_RUNTIME_UPLOAD_MAX_CONCURRENT",fallback:15,min:1,max:64}};function n0(t,e,r,n){if(t===void 0||t.trim()==="")return e;let i=Number(t);return Number.isInteger(i)?Math.min(n,Math.max(r,i)):e}a(n0,"clampEnvInt");var i0=[["cliHardCapMs",["finalizeCeilingMs"],.9],["finalizeCeilingMs",["finalizeBudgetMs"],1],["finalizeBudgetMs",["stallTimeoutMs","assetDeadlineMs","watchTimeoutMs"],1],["assetDeadlineMs",["uploadTimeoutMs"],1],["uploadTimeoutMs",["noProgressAbortMs"],.5]];function s0(t){let e={...t},r=[];for(let[n,i,s]of i0)for(let o of i){let c=Math.floor(e[n]*s);e[o]>c&&(r.push(`${Zi[o].env} (${e[o]}ms) exceeds its bound under ${Zi[n].env} (${e[n]}ms); using ${c}ms`),e[o]=c)}return{tunables:e,warnings:r}}a(s0,"coerceScopeHierarchy");function Co(t){let e={};for(let r of Object.keys(Zi)){let n=Zi[r];e[r]=n0(t[n.env],n.fallback,n.min,n.max)}return e.resumableChunkBytes=Math.max(1,Math.floor(e.resumableChunkBytes/262144))*262144,s0(e)}a(Co,"resolveUploadTunablesDetailed");function a0(t){return Co(t).tunables}a(a0,"resolveUploadTunables");var Pp=a0({});var Np=new WeakMap,Ro=new WeakMap;function Lp(t,e){t.loadedBytes=0,t.committedBytes??=0,t.lastProgress=e,Np.set(t,t.committedBytes),Ro.set(t,0)}a(Lp,"beginUpload");function Oo(t){t.loadedBytes=0,Ro.set(t,0)}a(Oo,"resetAttemptBytes");var Dp=a(t=>(e,r,n,i)=>{let s=t.get(e)??0;return r-s<n?!1:(e.lastProgress=i,t.set(e,r),!0)},"stamperFor"),o0=Dp(Ro),c0=Dp(Np);function ko(t,e,r,n){return t.loadedBytes=e,o0(t,e,r,n)}a(ko,"recordSent");function Mo(t,e,r,n){let i=Math.max(t.committedBytes??0,e);return t.committedBytes=i,c0(t,i,r,n)}a(Mo,"recordCommitted");var Xi=require("fs"),$p=require("stream");function Yi(t,{baseMs:e,capMs:r,random:n=Math.random}){let i=Math.min(r,e*2**(t-1));return i/2+n()*(i/2)}a(Yi,"jitteredBackoffMs");async function Zr(t){await t.body?.cancel().catch(()=>{})}a(Zr,"drainBody");var Lo=a(t=>t===200||t===201,"isStored"),Fp=a(t=>t===308,"isResumeIncomplete"),l0=a(t=>t===404||t===410,"isSessionGoneStatus"),Bp=a((t,e)=>{let r=t?.match(/bytes=0-(\d+)/);return r?Number(r[1])+1:e},"nextOffsetFromRange"),u0=a((t,e,r)=>e<=t?`bytes */${r}`:`bytes ${t}-${e-1}/${r}`,"contentRangeFor");function d0(t,e,r){let n=e,i=new TransformStream({transform(s,o){n+=s.byteLength,r?.(n),o.enqueue(s)}});return $p.Readable.toWeb(t).pipeThrough(i)}a(d0,"countingBody");var rt=class extends Error{constructor(r,n){super(r);this.status=n;this.name="ResumableUploadError"}static{a(this,"ResumableUploadError")}},jp=a(t=>t instanceof rt?t.status:void 0,"statusOf"),f0=a(t=>{let e=jp(t);return e!==void 0&&l0(e)},"isSessionGone"),p0=a(t=>Ji(jp(t)),"isPermanent");async function m0(t,e,r,n){let i=await r(t,{method:"POST",headers:{"x-goog-resumable":"start","Content-Type":e,"Content-Length":"0"},signal:n});if(await Zr(i),!Lo(i.status))throw new rt(`resumable init failed with status ${i.status}`,i.status);let s=i.headers.get("Location");if(!s)throw new rt("resumable init returned no Location");return s}a(m0,"initResumableSession");async function h0(t,e,r,n){let i=await r(t,{method:"PUT",headers:{"Content-Range":`bytes */${e}`},signal:n});if(await Zr(i),Lo(i.status))return{done:!0,offset:e};if(!Fp(i.status))throw new rt(`offset query failed with status ${i.status}`,i.status);return{done:!1,offset:Bp(i.headers.get("Range"),0)}}a(h0,"queryCommittedOffset");async function Up(t,e,{offset:r,endExclusive:n},i){let s=Math.max(0,(0,Xi.statSync)(t.filePath).size-r),o=Math.min(Math.max(0,n-r),s),c=r+o,l=o>0?(0,Xi.createReadStream)(t.filePath,{start:r,end:c-1}):void 0;try{let u={method:"PUT",headers:{"Content-Range":u0(r,c,t.size),"Content-Length":String(o)},duplex:"half",signal:i,...l?{body:d0(l,r,t.onSent)}:{}},d=await t.fetchImpl(e,u);if(await Zr(d),Lo(d.status))return{stored:!0,committed:t.size};if(Fp(d.status))return{stored:!1,committed:Bp(d.headers.get("Range"),r)};throw new rt(`resumable PUT failed with status ${d.status}`,d.status)}finally{l?.destroy()}}a(Up,"putChunk");async function g0(t,e,r,n){let i=r;for(;i<t.size;){let o=Math.min(i+t.chunkSizeBytes,t.size),{stored:c,committed:l}=await Up(t,e,{offset:i,endExclusive:o},n);if(c){t.onCommitted?.(t.size);return}if(l<=i)throw new rt("resumable PUT made no forward progress");i=l,t.onCommitted?.(i)}let{stored:s}=await Up(t,e,{offset:t.size,endExclusive:t.size},n);if(!s)throw new rt("resumable upload did not finalize");t.onCommitted?.(t.size)}a(g0,"sendFrom");async function y0(t,e,r){if(e.url)return e.url;if(!t.target.initUrl)throw new rt("no resumable target provided");return e.url=await m0(t.target.initUrl,t.contentType,t.fetchImpl,r),e.used=!1,e.url}a(y0,"openSession");async function _0(t,e,r,n){if(!r)return 0;let i=await h0(e,t.size,t.fetchImpl,n);if(!i.done)return t.onCommitted?.(i.offset),i.offset}a(_0,"resumePoint");async function b0(t,e,r){let n=await y0(t,e,r),i=await _0(t,n,e.used,r);if(e.used=!0,i===void 0){t.onCommitted?.(t.size);return}await g0(t,n,i,r)}a(b0,"runAttempt");function w0(t,e,r){return f0(t)&&e.target.initUrl?(r.url=void 0,r.used=!1,"retry"):p0(t)?"stop":"retry"}a(w0,"afterFailure");async function Hp(t){let e={url:t.target.sessionUrl,used:!1},r;for(let n=1;n<=t.maxAttempts&&!(t.now()>=t.deadlineAt);n++)try{await b0(t,e,t.makeSignal());return}catch(i){if(r=i,w0(i,t,e)==="stop"||n>=t.maxAttempts)break;await t.sleep(Yi(n,{baseMs:1e3,capMs:16e3,...t.random?{random:t.random}:{}}))}throw r instanceof Error?r:new rt(`resumable upload failed: ${String(r)}`)}a(Hp,"uploadResumable");var E0=a(t=>{if(typeof t!="object"||t===null)return"network_error";let e="name"in t&&typeof t.name=="string"?t.name:"";if(e==="TimeoutError")return"timeout";if(e==="AbortError")return"no_progress_abort";let r="cause"in t?t.cause:void 0,n=typeof r=="object"&&r!==null&&"code"in r&&typeof r.code=="string"?r.code:void 0;if(n==="UND_ERR_CONNECT_TIMEOUT"||n==="UND_ERR_HEADERS_TIMEOUT"||n==="UND_ERR_BODY_TIMEOUT")return"timeout";if(n!==void 0&&n.length>0)return`network_error:${n}`;let i="message"in t&&typeof t.message=="string"?t.message:"";return i.startsWith("Upload failed with status")?"http_error":i.startsWith("get-upload-url")?"signed_url_error":i.includes("No upload URL")?"signed_url_missing":"network_error"},"classifyUploadError"),T0=a(t=>Math.max(1e3,Math.min(1e4,Math.floor(t/4))),"noProgressPollMs"),Qi=class{constructor(e,r,n,i,s=!1,o={start:a(u=>{},"start"),complete:a(u=>{},"complete"),error:a((u,d)=>{},"error")},c,l={}){this.apiBaseURL=e;this.apiKey=r;this.uploadTimeout=n;this.makeGetUploadUrlAPIPath=i;this.isolationMode=s;this.reporter=o;this.sessionId=c;this.SIGNED_URL_TIMEOUT_MS=3e4;this.tunables=l.tunables??Pp,this.fetchImpl=l.fetchImpl??globalThis.fetch,this.now=l.now??Date.now,this.MAX_ATTEMPTS=this.tunables.maxAttempts,this.PUT_NO_PROGRESS_ABORT_MS=this.tunables.noProgressAbortMs,this.ASSET_DEADLINE_MS=this.tunables.assetDeadlineMs,this.MIN_PROGRESS_BYTES=this.tunables.minProgressBytes}static{a(this,"TestAssetUploader")}async uploadAsset(e){if(e.uploadStarted=!0,this.isolationMode){e.lastProgress=Date.now(),e.loadedBytes=0,e.sizeBytes=100,e.response=new Promise(o=>{setTimeout(()=>{e.complete=!0,e.lastProgress=Date.now(),e.loadedBytes=100,o({statusCode:200,ok:!0,body:"OK"})},10)});return}let{path:r}=e.info,n=this.now()+this.ASSET_DEADLINE_MS,i=Jr("asset_upload",{test_suite_run_id:this.sessionId,asset_type:e.info.type,file_name:e.info.fileName??(0,zp.basename)(r),test_id:e.info.testId,project:e.info.project}),s=[];try{let c=(0,es.statSync)(r).size;e.sizeBytes=c,Lp(e,this.now()),i.set({size_bytes:c}),this.reporter.start(r);let l;for(let u=1;u<=this.MAX_ATTEMPTS&&!(this.now()>=n);u++){let d={attempt:u};try{let f=this.now();if(await this.getSignedURLForUpload(e),d.signed_url_ms=this.now()-f,!e.uploadURL)throw new Error("No upload URL returned");let y=this.now();d.resumable=e.resumable===!0,e.resumable?await this.putResumable(e,r,c,n):await this.putWithWatchdog(e,r,c),d.put_ms=this.now()-y,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,s.push(d),this.reporter.complete(r),e.complete=!0,i.emit({outcome:"success",attempt_count:s.length,attempts:s,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes});return}catch(f){l=f,d.loaded_bytes=e.loadedBytes,d.committed_bytes=e.committedBytes,d.failure_reason=E0(f),d.error=tt(f);let y=Ji(typeof f=="object"&&f!==null&&"status"in f?f.status:void 0);d.non_retryable=y,delete e.uploadURL;let h=y?"non_retryable":e.resumable?"resumable_owns_retries":u>=this.MAX_ATTEMPTS?"max_attempts":this.now()>=n?"asset_deadline":void 0;if(d.retry_stop_reason=h,s.push(d),h)break;await this.backoff(u,n)}}this.reporter.error(r,l),e.error=!0,i.emit({outcome:"error",attempt_count:s.length,attempts:s,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,deadline_exceeded:this.now()>=n,error:tt(l)})}catch(o){this.reporter.error(r,o),e.error=!0,i.emit({outcome:"error",failure_reason:"pre_upload",attempt_count:s.length,attempts:s,error:tt(o)})}}async putWithWatchdog(e,r,n){let i=e.uploadURL;if(!i)throw new Error("No upload URL returned");let s=new AbortController,o=this.uploadTimeout??void 0;Oo(e);let c=this.armNoProgressWatchdog(e,()=>s.abort()),l=o!==void 0?setTimeout(()=>s.abort(new DOMException("upload attempt timeout","TimeoutError")),o):void 0,u=(0,es.createReadStream)(r),d=0,f=this.MIN_PROGRESS_BYTES,y=this.now,h=new TransformStream({transform(w,v){d+=w.byteLength,e.sizeBytes=n,ko(e,d,f,y()),v.enqueue(w)}}),g=Gp.Readable.toWeb(u).pipeThrough(h),b={method:"PUT",headers:{"Content-Type":So[e.info.type]??""},body:g,duplex:"half",signal:s.signal};try{let w=await this.fetchImpl(i,b);if(!w.ok)throw await Zr(w),Object.assign(new Error(`Upload failed with status ${w.status}`),{status:w.status});Mo(e,n,this.MIN_PROGRESS_BYTES,this.now()),e.response=Promise.resolve(await w.text())}finally{clearInterval(c),clearTimeout(l),u.destroy()}}armNoProgressWatchdog(e,r){let n=-1,i=this.now();return setInterval(()=>{let s=Math.max(e.loadedBytes??0,e.committedBytes??0);s>n?(n=s,i=this.now()):this.now()-i>this.PUT_NO_PROGRESS_ABORT_MS&&r()},T0(this.PUT_NO_PROGRESS_ABORT_MS))}async putResumable(e,r,n,i){let s=e.uploadURL;if(!s)throw new Error("No upload URL returned");Oo(e);let o=this.uploadTimeout??this.tunables.uploadTimeoutMs,c,l,u=a(()=>(clearInterval(l),c=new AbortController,l=this.armNoProgressWatchdog(e,()=>c?.abort()),c.signal),"armAttempt");try{await Hp({target:{initUrl:s},filePath:r,size:n,contentType:So[e.info.type]??"",fetchImpl:this.fetchImpl,makeSignal:a(()=>AbortSignal.any([u(),AbortSignal.timeout(o)]),"makeSignal"),maxAttempts:this.MAX_ATTEMPTS,deadlineAt:i,chunkSizeBytes:this.tunables.resumableChunkBytes,now:this.now,sleep:a(d=>new Promise(f=>setTimeout(f,d)),"sleep"),onSent:a(d=>ko(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onSent"),onCommitted:a(d=>Mo(e,d,this.MIN_PROGRESS_BYTES,this.now()),"onCommitted")})}finally{clearInterval(l)}e.response=Promise.resolve("OK")}async backoff(e,r){let n=Yi(e,{baseMs:1e3,capMs:16e3}),i=Math.max(0,Math.min(n,r-this.now()));i>0&&await new Promise(s=>setTimeout(s,i))}async getSignedURLForUpload(e){let r=new AbortController,n=setTimeout(()=>r.abort(),this.SIGNED_URL_TIMEOUT_MS);try{let i=JSON.stringify(e.info),s=`${this.apiBaseURL}/${this.makeGetUploadUrlAPIPath(e)}`,o={Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.apiKey},c=await this.fetchImpl(s,{method:"POST",headers:o,body:i,signal:r.signal}),{url:l,resumable:u}=await Mp(c,{resource:"get-upload-url",requiredFields:["url"]});e.uploadURL=l,e.resumable=u===!0}catch(i){throw delete e.uploadURL,i}finally{clearTimeout(n)}}};function ts(t,e,r=Date.now()){let n=t.filter(s=>!s.complete&&!s.error);if(n.length===0)return!1;let i=n.reduce((s,o)=>Math.max(s,o.lastProgress??0),0);return i>0&&r-i>e}a(ts,"isUploadStalled");function rs(t,e,r){return t!==void 0&&r-t>e}a(rs,"hasElapsedSinceTestEnd");function Vp(t,e,r){return rs(e.testRunEndTime,e.finalizeBudgetMs,r)?!0:t===void 0?!1:t.complete||t.error?!0:ts([t],e.stallTimeoutMs,r)}a(Vp,"shouldStopWaitingForReport");function Wp(t){return t.abandonedAssets.length===0}a(Wp,"mayCleanUpSources");function v0(t,e,r){if((e.length===0||ts(t.assets,t.stallTimeoutMs,r))&&rs(t.testRunEndTime,t.finalizeBudgetMs,r))return"budget";if(rs(t.testRunEndTime,t.finalizeCeilingMs,r))return"budget-ceiling"}a(v0,"backstopReason");function qp(t,e){let r=t.assets.filter(s=>!s.complete&&!s.error),n=a(s=>({reason:s,abandonedAssets:r}),"decide"),i=v0(t,r,e);if(i!==void 0)return n(i);if(!(t.processingInProgress||!t.doneWaitingForReport)&&!(r.length>0&&!ts(t.assets,t.stallTimeoutMs,e))&&!(t.pendingWatchCount>0&&!rs(t.testRunEndTime,t.watchTimeoutMs,e)))return r.length>0?n("stall"):t.pendingWatchCount>0?n("watch-timeout"):n("complete")}a(qp,"decideFinalize");var Kp=require("module");var S0=(0,Kp.createRequire)(__filename);function Jp(t){let e,r;try{e=S0("undici"),r=new e.Agent({connect:{timeout:t.connectTimeoutMs},headersTimeout:t.headersTimeoutMs,bodyTimeout:t.bodyTimeoutMs,keepAliveTimeout:1e4,keepAliveMaxTimeout:3e4})}catch(i){return mr("monitor_dispatcher_unavailable",{outcome:"error",error:tt(i)}),process.emitWarning("@checksum-ai/runtime: undici dispatcher unavailable; upload timeouts fall back to the platform defaults",{detail:String(i)}),globalThis.fetch}let n=e.fetch;return(i,s)=>{let o={...s,dispatcher:r};return n(i,o)}}a(Jp,"createMonitorFetch");var Do=class{static{a(this,"CLIChannel")}constructor(){}sendToCLI(...e){let r=`{trm}${e.map(n=>n.toString()).join(`,
68
166
  `)}{/trm}`;process.stdout.write(`${r}
69
- `)}event(e,r){return new Promise(n=>{let s=r?`${e}=${r}`:e;setTimeout(()=>{this.sendToCLI(`monitor:${s}`),n(!0)},100)})}trace(e,r){let n=r?`${e}=${JSON.stringify(r)}`:e;setTimeout(()=>{this.sendToCLI(`trace:${n}`)},100)}log(e){return this.event("log",e)}debug(...e){this.sendToCLI(e)}wideEvent(e){let r=Buffer.from(JSON.stringify(e),"utf-8").toString("base64");this.sendToCLI(`wideevent:${r}`)}},Ts=class{constructor(e,r=!1){this.config=e;this.isolationMode=r;this.tunablesResolution=Ba(process.env);this.tunables=this.tunablesResolution.tunables;this.MAX_UPLOADS=this.tunables.maxConcurrentUploads;this.MONITOR_INTERVAL=2500;this.UPLOAD_TIMEOUT=this.tunables.uploadTimeoutMs;this.UPLOAD_STALL_TIMEOUT=this.tunables.stallTimeoutMs;this.WATCH_TIMEOUT=this.tunables.watchTimeoutMs;this.FINALIZE_BUDGET=this.tunables.finalizeBudgetMs;this.FINALIZE_CEILING=this.tunables.finalizeCeilingMs;this.SHUTDOWN_FLUSH_TIMEOUT=2e3;this.assets=[];this.watchAssets=[];this.processingPaths=new Set;this.doneWaitingForReport=!1;this.processingInProgress=!1;this.pwTestIdToChecksumTestId={};this.checksumTestIdToUsingPlaceholder={};this.progressFlushInFlight=!1;this.stallEventEmitted=!1;this.channel=new Ka,Fa(n=>this.channel.wideEvent(n)),this.testAssetUploader=new _s(e.apiURL,e.apiKey,this.UPLOAD_TIMEOUT,()=>`client-api/test-runs/${this.config.sessionId}/get-upload-url`,this.isolationMode,{start:o(n=>this.channel.trace("Upload Start",{filename:n}),"start"),complete:o(n=>{if(!this.reportAsset||n!==this.reportAsset.info.path)try{(0,oe.unlinkSync)(n),this.channel.debug(`[TestAssetUploader] Deleted file after successful upload: ${n}`)}catch(s){this.channel.debug(`[TestAssetUploader] Failed to delete file after upload: ${n}`,s)}this.channel.trace("Upload Complete",{filename:n})},"complete"),error:o((n,s)=>this.channel.trace("Upload Failed",{filename:n,error:s}),"error")},e.sessionId,{fetchImpl:_m(this.tunables),tunables:this.tunables}),this.uploadMonitorInterval=setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL);for(let n of this.tunablesResolution.warnings)this.channel.debug(`[upload-tunables] ${n}`),Gt("upload_tunable_coerced",{warning:n});this.listenForMessages(),this.startServer()}static{o(this,"TestRunMonitor")}listenForMessages(){process.stdin.on("data",e=>{(async()=>{let r=e.toString().trim();if(!r.startsWith("cli:"))return;let[n,s]=r.substring(4).split("=");switch(this.channel.debug("Received message from CLI "+n+" "+s),n){case"report":if(this.testRunEndTime=Date.now(),s!=="false")try{let i=Buffer.from(s??"","base64").toString("utf-8"),a=JSON.parse(i);await this.handleReport(a)}catch(i){this.channel.debug("Error JSON parsing report payload, continue without report. Error: "+this.stringify(i)),this.stopWaitingForReport("failed")}else this.stopWaitingForReport("not-requested");this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})()})}async readMetadataFile(e){try{let r=await(0,Em.readFile)(e,"utf-8");return JSON.parse(r)}catch(r){return this.channel.trace("Runtime Error",`Error reading checksum metadata file ${e}: ${r.message}`),{}}}async serveReport(e){try{let r=(0,De.dirname)(e);await this.channel.log("Serving report in browser: "+r);let n=cs.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,bm.execSync)(n,{encoding:"utf8",stdio:"pipe"}),await this.channel.log("Success: Report opened in browser")}catch(r){await this.channel.log(`Error serving report in browser: ${r.message}`),r.stderr&&await this.channel.log(r.stderr.toString())}}async handleReport(e){let{reportPath:r,pathToChecksumMetadata:n,didFail:s,openReportCriteria:i,checksumRoot:a,projectRoot:c,isUploadReport:l,dedupeByChecksumTestId:u}=e;this.channel.debug(`Handling report ${this.isolationMode?"(isolation mode)":""}`+r),this.uploadReportData((0,De.dirname)(r),l);let d=lr("report_processing",{test_suite_run_id:this.config.sessionId,report_path:r,isolation_mode:this.isolationMode,is_upload_report:!!l});try{let p=await this.readMetadataFile(n),_=new ps(r,this.config.sessionId,this.pwTestIdToChecksumTestId,p,{hosted:!this.isolationMode,...u?{dedupeByChecksumTestId:u}:{}},this.channel,a,c,this.checksumTestIdToUsingPlaceholder),g=this.initAsset({type:"report",path:""});this.reportAsset=g;try{let w=await _.process();g.info.path=_.getProcessedFilePath(),d.set({processed_path:g.info.path,...w}),this.uploadAsset(g)}catch(w){this.channel.debug("Error processing report, "+w.message),g.error=!0,d.set({error:et(w)})}let y=_.getReportsStats();this.stats=y,Lf(d,g.error?"error":"success",y),this.channel.debug("Checking watch assets");let E=this.watchAssets.filter(w=>!(w.type!=="trace"||_.testHasTrace(w.testId??"",w.project??"")));E.length>0&&(this.channel.debug("Removed watch assets - "),this.channel.debug(JSON.stringify(E.map(w=>w.path)))),this.watchAssets=this.watchAssets.filter(w=>w.type!=="trace"||_.testHasTrace(w.testId??"",w.project??""))}catch(p){this.channel.debug("Error processing report, "+this.stringify(p)),this.reportAsset&&(this.reportAsset.error=!0),d.emit({outcome:"error",error:et(p)})}finally{if((i==="always"||i==="on-failure"&&s)&&await this.serveReport(r),n&&(0,oe.existsSync)(n))try{(0,oe.unlinkSync)(n)}catch(_){console.error(`Error deleting checksum metadata file ${n}: ${_.message}`)}}}async uploadReportData(e,r){let n=(0,De.join)(e,"data");try{let s=(0,oe.readdirSync)(n),i=r?[".webm"]:[".zip",".webm"],a=s.filter(c=>!i.includes((0,De.extname)(c)));this.channel.debug("Preparing to upload report data files,"+a);for(let c of a)this.channel.debug("Uploading report data file,"+c),this.addAsset({type:"report-data-file",fileName:c,path:`${n}/${c}`})}catch(s){this.channel.debug(`Error reading/adding report data files from dir ${n}`+s.message)}}shutdown(){clearInterval(this.uploadMonitorInterval);try{this.server?.closeAllConnections?.(),this.server?.close?.()}catch{}this.channel.debug("Received shutdown message from CLI"),process.stdout.write("",()=>process.exit(0)),setTimeout(()=>process.exit(0),this.SHUTDOWN_FLUSH_TIMEOUT).unref()}async monitorUploadsCompletion(){let e=Date.now();!this.doneWaitingForReport&&mm(this.reportAsset,{testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET},e)&&this.settleReport();let r=gm({assets:this.assets,processingInProgress:this.processingInProgress,doneWaitingForReport:this.doneWaitingForReport,pendingWatchCount:this.watchAssets.length,testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,watchTimeoutMs:this.WATCH_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET,finalizeCeilingMs:this.FINALIZE_CEILING},e);if(!r){await As(1e3),this.monitorUploadsCompletion();return}this.finalizeRun(r,e)}stopWaitingForReport(e){this.doneWaitingForReport=!0,this.reportOutcome=e}reportAssetOutcome(){return this.reportAsset?.complete?"uploaded":this.reportAsset?.error?"failed":"abandoned"}settleReport(){this.stopWaitingForReport(this.reportAssetOutcome());let e="";try{let r=JSON.stringify(this.stats??{}),n=`checksum-stats-${(0,Vr.randomBytes)(8).toString("hex")}.json`;e=(0,De.join)((0,Sm.tmpdir)(),n),(0,oe.writeFileSync)(e,r,"utf-8"),this.channel.debug(`Stats written to temporary file: ${e}`)}catch(r){this.channel.debug("Error writing stats to file"),this.channel.log(`[monitorUploadsCompletion] Error writing stats to file: ${r.message}`)}this.channel.event("report-complete",`${this.reportOutcome==="uploaded"?"true":"false"}:${e}`)}finalizeRun(e,r){e.reason==="stall"&&this.emitStallDetected(e.abandonedAssets,r),e.abandonedAssets.forEach(a=>{a.error=!0});let n=this.assets.some(a=>a.error)?"uploads-complete-with-errors":"uploads-complete",s=this.assets.filter(a=>a.error);Gt("uploads_completion",{test_suite_run_id:this.config.sessionId,outcome:s.length>0?"error":"success",decision:n,total_assets:this.assets.length,completed:this.assets.filter(a=>a.complete).length,errored:s.length,stalled:e.abandonedAssets.length>0,stalled_count:e.abandonedAssets.length,finalize_reason:e.reason,finalize_budget_ms:this.FINALIZE_BUDGET,finalize_ceiling_ms:this.FINALIZE_CEILING,watch_remaining:this.watchAssets.length,report_outcome:this.reportOutcome,upload_finalize_ms:this.testRunEndTime?r-this.testRunEndTime:void 0,errored_assets:s.map(a=>this.assetSnapshot(a,r))});let i=n==="uploads-complete"?{}:{uploadErrors:s.map(a=>{try{return JSON.stringify(a)}catch{return a.info.path}}),watchAssets:this.watchAssets,testRunEndTime:this.testRunEndTime,now:r,finalizeReason:e.reason,abandonedAssets:e.abandonedAssets.map(a=>this.assetSnapshot(a,r))};if(hm(e))try{this.cleanUp()}catch(a){this.channel.debug("cleanUp failed (ignored): "+a?.message)}else this.channel.debug(`skipping cleanUp: ${e.abandonedAssets.length} asset(s) abandoned (${e.reason})`);this.channel.event(n,JSON.stringify(i))}assetSnapshot(e,r){return{file_name:e.info.fileName??(0,De.basename)(e.info.path),asset_type:e.info.type,test_id:e.info.testId,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,last_progress_age_ms:e.lastProgress?r-e.lastProgress:void 0}}cleanUp(){let e;for(let r of this.assets)if(r.info.type==="rrweb-recording"){e=(0,De.dirname)(r.info.path);break}e&&(0,oe.rmSync)(e,{recursive:!0,force:!0})}emitStallDetected(e,r){this.channel.log("Uploads are stalled"),!this.stallEventEmitted&&(this.stallEventEmitted=!0,Gt("upload_stall_detected",{test_suite_run_id:this.config.sessionId,outcome:"error",timeout_ms:this.UPLOAD_STALL_TIMEOUT,total_assets:this.assets.length,pending_count:e.length,pending_assets:e.map(n=>this.assetSnapshot(n,r))}))}async startServer(){let e=await this.acquirePortNumber();this.channel.event("port",e.toString()),this.server=(0,Tm.createServer)((r,n)=>{let s=o(a=>{n.writeHead(400,{"Content-Type":"text/plain"}),n.end(a)},"returnErrorWithMessage");if(r.method!=="POST"){n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Method not allowed");return}let i="";r.on("data",a=>{i+=a.toString()}),r.on("end",()=>{let a;try{a=JSON.parse(i)}catch{s("Invalid body");return}let{type:c,payload:l,watch:u}=a;switch(this.channel.debug(`Server received message, ${c}, ${this.stringify(l)}`),c){case"asset":if(!l.path||!l.type){s("Missing arguments");return}u?this.watchAsset(l):this.processAsset(l);break;case"testInfo":if(!l.pwTestId||!l.checksumTestId){s("Missing arguments");return}this.pwTestIdToChecksumTestId[l.pwTestId]=l.checksumTestId,l.usingChecksumTestIdPlaceholder!==void 0&&(this.checksumTestIdToUsingPlaceholder[l.checksumTestId]=l.usingChecksumTestIdPlaceholder);break;case"checksumTestMetadata":{let d=l;if(!d.checksumTestId||!l.data){s("Missing arguments");return}this.channel.event("checksumTestMetadata",JSON.stringify({...d}));break}case"testStats":break;case"playwrightConfig":this.channel.event("playwrightConfig",JSON.stringify(l));break;case"runProgress":this.forwardProgress(l);break;default:s("Invalid message type");return}n.writeHead(200,{"Content-Type":"text/plain"}),n.end("OK")})}),this.server.listen(e)}forwardProgress(e){this.latestProgress=e,!this.progressFlushInFlight&&this.flushProgress()}async flushProgress(){this.progressFlushInFlight=!0;try{for(;this.latestProgress;){let e=this.latestProgress;this.latestProgress=void 0,await this.patchProgress(e)}}finally{this.progressFlushInFlight=!1}}async patchProgress(e){if(this.isolationMode)return;let r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{await fetch(`${this.config.apiURL}/client-api/test-runs/${this.config.sessionId}/progress`,{method:"PATCH",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:JSON.stringify({progress:e}),signal:r.signal})}catch(s){this.channel.debug("Failed to send run progress: "+s?.message)}finally{clearTimeout(n)}}stringify(e){try{return JSON.stringify(e)}catch{return"message"in e?e.message:e}}monitorUploads(){let{totalSizeBytes:e,totalUploadedBytes:r}=this.calculateUploadProgress();if(e>0&&!this.isolationMode){let i=(r/e*100).toFixed(2);this.channel.event("upload-progress",i)}let n=this.assets.filter(i=>!i.uploadStarted);if(n.length===0)return;let s=o(()=>this.assets.filter(i=>i.uploadStarted&&!i.complete&&!i.error).length,"getNumOfActiveUploads");if(!(s()>=this.MAX_UPLOADS))for(;n.length>0&&s()<this.MAX_UPLOADS;){let i=n.pop();if(i===void 0)break;this.uploadAsset(i)}}calculateUploadProgress(){let e=this.assets.reduce((n,{sizeBytes:s})=>n+(s??0),0),r=Math.min(e,this.assets.reduce((n,{loadedBytes:s})=>n+(s??0),0));return{totalSizeBytes:e,totalUploadedBytes:r}}getUploadLogMessage(e){switch(e.info.type){case"report":return"Uploading report";case"har":return`Uploading har file for test ${e.info.testId}`;case"trace":return`Uploading trace file for test ${e.info.testId}`;case"esra":return`Uploading metadata file for test ${e.info.testId}`;case"test-files":return`Uploading auto-healed test code for file ${e.info.path}`;default:return}}async uploadAsset(e){try{e.uploadStarted=!0;let r=this.getUploadLogMessage(e);r&&!this.isolationMode&&this.channel.event("log",r),await this.testAssetUploader.uploadAsset(e)}catch(r){e.error=!0,this.channel.debug("Error uploading asset"+this.stringify(r)),this.channel.trace("Upload Failed",{asset:e.info.fileName,error:String(r)})}}watchAsset(e){if(this.watchAssets.some(n=>n.path===e.path)){this.channel.debug(`Already watching file ${e.path}, skipping duplicate`);return}this.channel.debug("Watching file "+e.path),this.watchAssets.push({...e,addedAt:Date.now()});let r=o(async()=>{await this.waitForFileComplete(e.path)&&(this.processAsset(e),this.watchAssets=this.watchAssets.filter(s=>s.path!==e.path))},"waitForCompletion");if((0,oe.existsSync)(e.path))r();else{let n=(0,De.dirname)(e.path),s=(0,De.basename)(e.path),i=!1,a=(0,oe.watch)(n,(c,l)=>{(async()=>{if(!(l!==s||i))try{this.channel.debug("Watched file changed "+e.path),i=!0,await r()}finally{a.close()}})()})}}waitForFileComplete(e,r=1e3,n=6e4,s=1){return new Promise(i=>{let a=Date.now(),c=0,l=s,u=o(()=>{if(!(0,oe.existsSync)(e)){this.channel.debug(`Asset required for upload doesn't exist anymore ${e}`),i(!1);return}let d=(0,oe.statSync)(e).size;if(d===c){if(l>0){this.channel.debug(`File size has not changed, verifying stabilization, ${e}, size: ${d}, equalSizeValidationCountLeft: ${l}`),l--,setTimeout(u,r);return}this.channel.debug(`File size has not changed, stabilization verified, ${e}, size: ${d}`),i(!0);return}if(this.channel.debug(`File size changed, waiting for stabilization, ${e}, previous size: ${c}, current size: ${d}`),Date.now()-a>n){this.channel.debug(`Asset required for upload is taking over ${n} ms to write to disk ${e}`),i(!0);return}c=d,setTimeout(u,r)},"checkFile");u()})}processAsset(e){switch(e.type){case"trace":return this.processTrace(e.path,e.testId);case"har":return this.processHar();case"rrweb-recording":case"esra":case"test-files":return this.addAsset(e);default:return}}async processHar(){}async calculateFileSha1Streaming(e){let r=(0,Vr.createHash)("sha1"),n=(0,oe.createReadStream)(e);return await(0,wm.pipeline)(n,r),r.digest("hex")}async processTrace(e,r){if(this.processingPaths.has(e)){this.channel.debug(`Trace file ${e} already being processed, skipping`);return}this.processingPaths.add(e);let n;try{this.processingInProgress=!0,await As(1e3),n=lr("trace_processing",{test_suite_run_id:this.config.sessionId,test_id:r});let s=e;if(!this.isolationMode){this.channel.debug(`Preparing trace for upload (testId: ${r})...`),s=e.replace(".zip",".actual.zip"),(0,oe.renameSync)(e,s);let c="checksum-playwright-trace:"+Date.now().toString()+(0,Vr.randomBytes)(1024).toString("hex");(0,oe.writeFileSync)(e,c)}let a=await o(async()=>await this.calculateFileSha1Streaming(e)+(0,De.extname)(e),"makePlaywrightHTMLReporterName")();this.channel.debug(`Trace file for test ${r} has been manipulated with file name ${a}, sending for upload...`),this.addAsset({type:"report-data-file",path:s,...r!==void 0?{testId:r}:{},fileName:a}),n?.emit({outcome:"success",file_name:a})}catch(s){let i=String(s);this.channel.debug("Error processing trace file"+i),this.channel.trace("Trace Processing Error",{error:i}),n?.emit({outcome:"error",error:et(s)})}finally{this.processingPaths.delete(e),this.processingInProgress=!1}}addAsset(e){this.channel.debug("Adding file "+e.path);let r=this.initAsset(e);return this.assets.push(r),r}initAsset(e){return{complete:!1,error:!1,info:e,removeAfterUpload:e.type==="rrweb-recording"}}async acquirePortNumber(){return new Promise((e,r)=>{let n=vm.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let s=n.address().port;n.close(()=>{e(s)})})})}},Im;try{Im=JSON.parse(process.argv[2]??"")}catch(t){console.error("Error starting test run monitor",t),process.exit(1)}new Ts(Im,process.argv?.[3]==="isolated");0&&(module.exports={TestRunMonitor});
167
+ `)}event(e,r){return new Promise(n=>{let i=r?`${e}=${r}`:e;setTimeout(()=>{this.sendToCLI(`monitor:${i}`),n(!0)},100)})}trace(e,r){let n=r?`${e}=${JSON.stringify(r)}`:e;setTimeout(()=>{this.sendToCLI(`trace:${n}`)},100)}log(e){return this.event("log",e)}debug(...e){this.sendToCLI(e)}wideEvent(e){let r=Buffer.from(JSON.stringify(e),"utf-8").toString("base64");this.sendToCLI(`wideevent:${r}`)}},ns=class{constructor(e,r=!1){this.config=e;this.isolationMode=r;this.tunablesResolution=Co(process.env);this.tunables=this.tunablesResolution.tunables;this.MAX_UPLOADS=this.tunables.maxConcurrentUploads;this.MONITOR_INTERVAL=2500;this.UPLOAD_TIMEOUT=this.tunables.uploadTimeoutMs;this.UPLOAD_STALL_TIMEOUT=this.tunables.stallTimeoutMs;this.WATCH_TIMEOUT=this.tunables.watchTimeoutMs;this.FINALIZE_BUDGET=this.tunables.finalizeBudgetMs;this.FINALIZE_CEILING=this.tunables.finalizeCeilingMs;this.SHUTDOWN_FLUSH_TIMEOUT=2e3;this.assets=[];this.watchAssets=[];this.processingPaths=new Set;this.doneWaitingForReport=!1;this.processingInProgress=!1;this.pwTestIdToChecksumTestId={};this.checksumTestIdToUsingPlaceholder={};this.progressFlushInFlight=!1;this.stallEventEmitted=!1;this.channel=new Do,Ao(n=>this.channel.wideEvent(n)),this.testAssetUploader=new Qi(e.apiURL,e.apiKey,this.UPLOAD_TIMEOUT,()=>`client-api/test-runs/${this.config.sessionId}/get-upload-url`,this.isolationMode,{start:a(n=>this.channel.trace("Upload Start",{filename:n}),"start"),complete:a(n=>{if(!this.reportAsset||n!==this.reportAsset.info.path)try{(0,ce.unlinkSync)(n),this.channel.debug(`[TestAssetUploader] Deleted file after successful upload: ${n}`)}catch(i){this.channel.debug(`[TestAssetUploader] Failed to delete file after upload: ${n}`,i)}this.channel.trace("Upload Complete",{filename:n})},"complete"),error:a((n,i)=>this.channel.trace("Upload Failed",{filename:n,error:i}),"error")},e.sessionId,{fetchImpl:Jp(this.tunables),tunables:this.tunables}),this.uploadMonitorInterval=setInterval(this.monitorUploads.bind(this),this.MONITOR_INTERVAL);for(let n of this.tunablesResolution.warnings)this.channel.debug(`[upload-tunables] ${n}`),mr("upload_tunable_coerced",{warning:n});this.listenForMessages(),this.startServer()}static{a(this,"TestRunMonitor")}listenForMessages(){process.stdin.on("data",e=>{(async()=>{let r=e.toString().trim();if(!r.startsWith("cli:"))return;let[n,i]=r.substring(4).split("=");switch(this.channel.debug("Received message from CLI "+n+" "+i),n){case"report":if(this.testRunEndTime=Date.now(),i!=="false")try{let s=Buffer.from(i??"","base64").toString("utf-8"),o=JSON.parse(s);await this.handleReport(o)}catch(s){this.channel.debug("Error JSON parsing report payload, continue without report. Error: "+this.stringify(s)),this.stopWaitingForReport("failed")}else this.stopWaitingForReport("not-requested");this.monitorUploadsCompletion();break;case"shutdown":this.shutdown();break}})()})}async readMetadataFile(e){try{let r=await(0,Yp.readFile)(e,"utf-8");return JSON.parse(r)}catch(r){return this.channel.trace("Runtime Error",`Error reading checksum metadata file ${e}: ${r.message}`),{}}}async serveReport(e){try{let r=(0,Be.dirname)(e);await this.channel.log("Serving report in browser: "+r);let n=Hi.isRepoMode?`yarn playwright show-report ${r}`:`npx playwright show-report ${r}`;(0,Zp.execSync)(n,{encoding:"utf8",stdio:"pipe"}),await this.channel.log("Success: Report opened in browser")}catch(r){await this.channel.log(`Error serving report in browser: ${r.message}`),r.stderr&&await this.channel.log(r.stderr.toString())}}async handleReport(e){let{reportPath:r,pathToChecksumMetadata:n,didFail:i,openReportCriteria:s,checksumRoot:o,projectRoot:c,isUploadReport:l,dedupeByChecksumTestId:u}=e;this.channel.debug(`Handling report ${this.isolationMode?"(isolation mode)":""}`+r),this.uploadReportData((0,Be.dirname)(r),l);let d=Jr("report_processing",{test_suite_run_id:this.config.sessionId,report_path:r,isolation_mode:this.isolationMode,is_upload_report:!!l});try{let f=await this.readMetadataFile(n),y=new Ki(r,this.config.sessionId,this.pwTestIdToChecksumTestId,f,{hosted:!this.isolationMode,...u?{dedupeByChecksumTestId:u}:{}},this.channel,o,c,this.checksumTestIdToUsingPlaceholder),h=this.initAsset({type:"report",path:""});this.reportAsset=h;try{let w=await y.process();h.info.path=y.getProcessedFilePath(),d.set({processed_path:h.info.path,...w}),this.uploadAsset(h)}catch(w){this.channel.debug("Error processing report, "+w.message),h.error=!0,d.set({error:tt(w)})}let g=y.getReportsStats();this.stats=g,_f(d,h.error?"error":"success",g),this.channel.debug("Checking watch assets");let b=this.watchAssets.filter(w=>!(w.type!=="trace"||y.testHasTrace(w.testId??"",w.project??"")));b.length>0&&(this.channel.debug("Removed watch assets - "),this.channel.debug(JSON.stringify(b.map(w=>w.path)))),this.watchAssets=this.watchAssets.filter(w=>w.type!=="trace"||y.testHasTrace(w.testId??"",w.project??""))}catch(f){this.channel.debug("Error processing report, "+this.stringify(f)),this.reportAsset&&(this.reportAsset.error=!0),d.emit({outcome:"error",error:tt(f)})}finally{if((s==="always"||s==="on-failure"&&i)&&await this.serveReport(r),n&&(0,ce.existsSync)(n))try{(0,ce.unlinkSync)(n)}catch(y){console.error(`Error deleting checksum metadata file ${n}: ${y.message}`)}}}async uploadReportData(e,r){let n=(0,Be.join)(e,"data");try{let i=(0,ce.readdirSync)(n),s=r?[".webm"]:[".zip",".webm"],o=i.filter(c=>!s.includes((0,Be.extname)(c)));this.channel.debug("Preparing to upload report data files,"+o);for(let c of o)this.channel.debug("Uploading report data file,"+c),this.addAsset({type:"report-data-file",fileName:c,path:`${n}/${c}`})}catch(i){this.channel.debug(`Error reading/adding report data files from dir ${n}`+i.message)}}shutdown(){clearInterval(this.uploadMonitorInterval);try{this.server?.closeAllConnections?.(),this.server?.close?.()}catch{}this.channel.debug("Received shutdown message from CLI"),process.stdout.write("",()=>process.exit(0)),setTimeout(()=>process.exit(0),this.SHUTDOWN_FLUSH_TIMEOUT).unref()}async monitorUploadsCompletion(){let e=Date.now();!this.doneWaitingForReport&&Vp(this.reportAsset,{testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET},e)&&this.settleReport();let r=qp({assets:this.assets,processingInProgress:this.processingInProgress,doneWaitingForReport:this.doneWaitingForReport,pendingWatchCount:this.watchAssets.length,testRunEndTime:this.testRunEndTime,stallTimeoutMs:this.UPLOAD_STALL_TIMEOUT,watchTimeoutMs:this.WATCH_TIMEOUT,finalizeBudgetMs:this.FINALIZE_BUDGET,finalizeCeilingMs:this.FINALIZE_CEILING},e);if(!r){await cs(1e3),this.monitorUploadsCompletion();return}this.finalizeRun(r,e)}stopWaitingForReport(e){this.doneWaitingForReport=!0,this.reportOutcome=e}reportAssetOutcome(){return this.reportAsset?.complete?"uploaded":this.reportAsset?.error?"failed":"abandoned"}settleReport(){this.stopWaitingForReport(this.reportAssetOutcome());let e="";try{let r=JSON.stringify(this.stats??{}),n=`checksum-stats-${(0,In.randomBytes)(8).toString("hex")}.json`;e=(0,Be.join)((0,tm.tmpdir)(),n),(0,ce.writeFileSync)(e,r,"utf-8"),this.channel.debug(`Stats written to temporary file: ${e}`)}catch(r){this.channel.debug("Error writing stats to file"),this.channel.log(`[monitorUploadsCompletion] Error writing stats to file: ${r.message}`)}this.channel.event("report-complete",`${this.reportOutcome==="uploaded"?"true":"false"}:${e}`)}finalizeRun(e,r){e.reason==="stall"&&this.emitStallDetected(e.abandonedAssets,r),e.abandonedAssets.forEach(o=>{o.error=!0});let n=this.assets.some(o=>o.error)?"uploads-complete-with-errors":"uploads-complete",i=this.assets.filter(o=>o.error);mr("uploads_completion",{test_suite_run_id:this.config.sessionId,outcome:i.length>0?"error":"success",decision:n,total_assets:this.assets.length,completed:this.assets.filter(o=>o.complete).length,errored:i.length,stalled:e.abandonedAssets.length>0,stalled_count:e.abandonedAssets.length,finalize_reason:e.reason,finalize_budget_ms:this.FINALIZE_BUDGET,finalize_ceiling_ms:this.FINALIZE_CEILING,watch_remaining:this.watchAssets.length,report_outcome:this.reportOutcome,upload_finalize_ms:this.testRunEndTime?r-this.testRunEndTime:void 0,errored_assets:i.map(o=>this.assetSnapshot(o,r))});let s=n==="uploads-complete"?{}:{uploadErrors:i.map(o=>{try{return JSON.stringify(o)}catch{return o.info.path}}),watchAssets:this.watchAssets,testRunEndTime:this.testRunEndTime,now:r,finalizeReason:e.reason,abandonedAssets:e.abandonedAssets.map(o=>this.assetSnapshot(o,r))};if(Wp(e))try{this.cleanUp()}catch(o){this.channel.debug("cleanUp failed (ignored): "+o?.message)}else this.channel.debug(`skipping cleanUp: ${e.abandonedAssets.length} asset(s) abandoned (${e.reason})`);this.channel.event(n,JSON.stringify(s))}assetSnapshot(e,r){return{file_name:e.info.fileName??(0,Be.basename)(e.info.path),asset_type:e.info.type,test_id:e.info.testId,loaded_bytes:e.loadedBytes,committed_bytes:e.committedBytes,size_bytes:e.sizeBytes,last_progress_age_ms:e.lastProgress?r-e.lastProgress:void 0}}cleanUp(){let e;for(let r of this.assets)if(r.info.type==="rrweb-recording"){e=(0,Be.dirname)(r.info.path);break}e&&(0,ce.rmSync)(e,{recursive:!0,force:!0})}emitStallDetected(e,r){this.channel.log("Uploads are stalled"),!this.stallEventEmitted&&(this.stallEventEmitted=!0,mr("upload_stall_detected",{test_suite_run_id:this.config.sessionId,outcome:"error",timeout_ms:this.UPLOAD_STALL_TIMEOUT,total_assets:this.assets.length,pending_count:e.length,pending_assets:e.map(n=>this.assetSnapshot(n,r))}))}async startServer(){let e=await this.acquirePortNumber();this.channel.event("port",e.toString()),this.server=(0,Qp.createServer)((r,n)=>{let i=a(o=>{n.writeHead(400,{"Content-Type":"text/plain"}),n.end(o)},"returnErrorWithMessage");if(r.method!=="POST"){n.writeHead(404,{"Content-Type":"text/plain"}),n.end("Method not allowed");return}let s="";r.on("data",o=>{s+=o.toString()}),r.on("end",()=>{let o;try{o=JSON.parse(s)}catch{i("Invalid body");return}let{type:c,payload:l,watch:u}=o;switch(this.channel.debug(`Server received message, ${c}, ${this.stringify(l)}`),c){case"asset":if(!l.path||!l.type){i("Missing arguments");return}u?this.watchAsset(l):this.processAsset(l);break;case"testInfo":if(!l.pwTestId||!l.checksumTestId){i("Missing arguments");return}this.pwTestIdToChecksumTestId[l.pwTestId]=l.checksumTestId,l.usingChecksumTestIdPlaceholder!==void 0&&(this.checksumTestIdToUsingPlaceholder[l.checksumTestId]=l.usingChecksumTestIdPlaceholder);break;case"checksumTestMetadata":{let d=l;if(!d.checksumTestId||!l.data){i("Missing arguments");return}this.channel.event("checksumTestMetadata",JSON.stringify({...d}));break}case"testStats":break;case"playwrightConfig":this.channel.event("playwrightConfig",JSON.stringify(l));break;case"runProgress":this.forwardProgress(l);break;default:i("Invalid message type");return}n.writeHead(200,{"Content-Type":"text/plain"}),n.end("OK")})}),this.server.listen(e)}forwardProgress(e){this.latestProgress=e,!this.progressFlushInFlight&&this.flushProgress()}async flushProgress(){this.progressFlushInFlight=!0;try{for(;this.latestProgress;){let e=this.latestProgress;this.latestProgress=void 0,await this.patchProgress(e)}}finally{this.progressFlushInFlight=!1}}async patchProgress(e){if(this.isolationMode)return;let r=new AbortController,n=setTimeout(()=>r.abort(),3e4);try{await fetch(`${this.config.apiURL}/client-api/test-runs/${this.config.sessionId}/progress`,{method:"PATCH",headers:{Accept:"application/json","Content-Type":"application/json",ChecksumAppCode:this.config.apiKey},body:JSON.stringify({progress:e}),signal:r.signal})}catch(i){this.channel.debug("Failed to send run progress: "+i?.message)}finally{clearTimeout(n)}}stringify(e){try{return JSON.stringify(e)}catch{return"message"in e?e.message:e}}monitorUploads(){let{totalSizeBytes:e,totalUploadedBytes:r}=this.calculateUploadProgress();if(e>0&&!this.isolationMode){let s=(r/e*100).toFixed(2);this.channel.event("upload-progress",s)}let n=this.assets.filter(s=>!s.uploadStarted);if(n.length===0)return;let i=a(()=>this.assets.filter(s=>s.uploadStarted&&!s.complete&&!s.error).length,"getNumOfActiveUploads");if(!(i()>=this.MAX_UPLOADS))for(;n.length>0&&i()<this.MAX_UPLOADS;){let s=n.pop();if(s===void 0)break;this.uploadAsset(s)}}calculateUploadProgress(){let e=this.assets.reduce((n,{sizeBytes:i})=>n+(i??0),0),r=Math.min(e,this.assets.reduce((n,{loadedBytes:i})=>n+(i??0),0));return{totalSizeBytes:e,totalUploadedBytes:r}}getUploadLogMessage(e){switch(e.info.type){case"report":return"Uploading report";case"har":return`Uploading har file for test ${e.info.testId}`;case"trace":return`Uploading trace file for test ${e.info.testId}`;case"esra":return`Uploading metadata file for test ${e.info.testId}`;case"test-files":return`Uploading auto-healed test code for file ${e.info.path}`;default:return}}async uploadAsset(e){try{e.uploadStarted=!0;let r=this.getUploadLogMessage(e);r&&!this.isolationMode&&this.channel.event("log",r),await this.testAssetUploader.uploadAsset(e)}catch(r){e.error=!0,this.channel.debug("Error uploading asset"+this.stringify(r)),this.channel.trace("Upload Failed",{asset:e.info.fileName,error:String(r)})}}watchAsset(e){if(this.watchAssets.some(n=>n.path===e.path)){this.channel.debug(`Already watching file ${e.path}, skipping duplicate`);return}this.channel.debug("Watching file "+e.path),this.watchAssets.push({...e,addedAt:Date.now()});let r=a(async()=>{await this.waitForFileComplete(e.path)&&(this.processAsset(e),this.watchAssets=this.watchAssets.filter(i=>i.path!==e.path))},"waitForCompletion");if((0,ce.existsSync)(e.path))r();else{let n=(0,Be.dirname)(e.path),i=(0,Be.basename)(e.path),s=!1,o=(0,ce.watch)(n,(c,l)=>{(async()=>{if(!(l!==i||s))try{this.channel.debug("Watched file changed "+e.path),s=!0,await r()}finally{o.close()}})()})}}waitForFileComplete(e,r=1e3,n=6e4,i=1){return new Promise(s=>{let o=Date.now(),c=0,l=i,u=a(()=>{if(!(0,ce.existsSync)(e)){this.channel.debug(`Asset required for upload doesn't exist anymore ${e}`),s(!1);return}let d=(0,ce.statSync)(e).size;if(d===c){if(l>0){this.channel.debug(`File size has not changed, verifying stabilization, ${e}, size: ${d}, equalSizeValidationCountLeft: ${l}`),l--,setTimeout(u,r);return}this.channel.debug(`File size has not changed, stabilization verified, ${e}, size: ${d}`),s(!0);return}if(this.channel.debug(`File size changed, waiting for stabilization, ${e}, previous size: ${c}, current size: ${d}`),Date.now()-o>n){this.channel.debug(`Asset required for upload is taking over ${n} ms to write to disk ${e}`),s(!0);return}c=d,setTimeout(u,r)},"checkFile");u()})}processAsset(e){switch(e.type){case"trace":return this.processTrace(e.path,e.testId);case"har":return this.processHar();case"rrweb-recording":case"esra":case"test-files":return this.addAsset(e);default:return}}async processHar(){}async calculateFileSha1Streaming(e){let r=(0,In.createHash)("sha1"),n=(0,ce.createReadStream)(e);return await(0,Xp.pipeline)(n,r),r.digest("hex")}async processTrace(e,r){if(this.processingPaths.has(e)){this.channel.debug(`Trace file ${e} already being processed, skipping`);return}this.processingPaths.add(e);let n;try{this.processingInProgress=!0,await cs(1e3),n=Jr("trace_processing",{test_suite_run_id:this.config.sessionId,test_id:r});let i=e;if(!this.isolationMode){this.channel.debug(`Preparing trace for upload (testId: ${r})...`),i=e.replace(".zip",".actual.zip"),(0,ce.renameSync)(e,i);let c="checksum-playwright-trace:"+Date.now().toString()+(0,In.randomBytes)(1024).toString("hex");(0,ce.writeFileSync)(e,c)}let o=await a(async()=>await this.calculateFileSha1Streaming(e)+(0,Be.extname)(e),"makePlaywrightHTMLReporterName")();this.channel.debug(`Trace file for test ${r} has been manipulated with file name ${o}, sending for upload...`),this.addAsset({type:"report-data-file",path:i,...r!==void 0?{testId:r}:{},fileName:o}),n.emit({outcome:"success",file_name:o})}catch(i){let s=String(i);this.channel.debug("Error processing trace file"+s),this.channel.trace("Trace Processing Error",{error:s}),n?.emit({outcome:"error",error:tt(i)})}finally{this.processingPaths.delete(e),this.processingInProgress=!1}}addAsset(e){this.channel.debug("Adding file "+e.path);let r=this.initAsset(e);return this.assets.push(r),r}initAsset(e){return{complete:!1,error:!1,info:e,removeAfterUpload:e.type==="rrweb-recording"}}async acquirePortNumber(){return new Promise((e,r)=>{let n=em.createServer();n.unref(),n.on("error",r),n.listen(0,()=>{let i=n.address().port;n.close(()=>{e(i)})})})}},rm;try{rm=JSON.parse(process.argv[2]??"")}catch(t){console.error("Error starting test run monitor",t),process.exit(1)}new ns(rm,process.argv[3]==="isolated");0&&(module.exports={TestRunMonitor});
70
168
  /*! Bundled license information:
71
169
 
72
170
  @langchain/core/dist/utils/js-sha256/hash.js: